Free cookie consent management tool by TermsFeed Policy Generator

source: addons/HeuristicLab.Problems.BioBoost/HeuristicLab.Problems.BioBoost.Views/3.3/MenuItems/CreateBioBoostExperimentMenuItem.cs @ 17104

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

#2845: adapted BioBoost addon

File size: 10.9 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.Core;
23using HeuristicLab.Data;
24using HeuristicLab.MainForm;
25using HeuristicLab.Optimization;
26using HeuristicLab.Optimizer;
27using System;
28using System.Collections.Generic;
29using System.Linq;
30using System.Text.RegularExpressions;
31using HeuristicLab.BioBoost.Data;
32using HeuristicLab.BioBoost.Evaluators;
33using HeuristicLab.BioBoost.Operators.Mutation;
34using HeuristicLab.BioBoost.ProblemDescription;
35using HeuristicLab.BioBoost.Utils;
36using HeuristicLab.Encodings.IntegerVectorEncoding;
37using HeuristicLab.Parameters;
38using MenuItem = HeuristicLab.MainForm.WindowsForms.MenuItem;
39
40
41namespace HeuristicLab.BioBoost.Views {
42  internal sealed class CreateBioBoostExperimentMenuItem : MenuItem, IOptimizerUserInterfaceItemProvider {
43    public override string Name {
44      get { return "Create BioBoost Experiment"; }
45    }
46
47    public override IEnumerable<string> Structure {
48      get { return new string[] { "&Edit" }; }
49    }
50
51    public override int Position {
52      get { return 1450; }
53    }
54
55    protected override void OnToolStripItemSet(EventArgs e) {
56      ToolStripItem.Enabled = false;
57    }
58
59    protected override void OnActiveViewChanged(object sender, EventArgs e) {
60      IContentView activeView = MainFormManager.MainForm.ActiveView as IContentView;
61      if (activeView == null) {
62        ToolStripItem.Enabled = false;
63        return;
64      }
65
66      var content = activeView.Content;
67      var algorithm = content as IAlgorithm;
68
69      ToolStripItem.Enabled = algorithm != null && algorithm.Problem is BioBoostProblem;
70    }
71
72    private enum Pathway { FP, CP, HTC };
73    private enum Region { BI, SK, BS, SE, SW, C, S, EU };
74    private enum Price { Cheap, Medium, Expensive };
75    private enum Implementation { Narrow, Normal, Broad };
76
77    private int nValues(Type t) { return Enum.GetValues(t).Length; }
78
79    public override void Execute() {
80      IContentView activeView = (IContentView)MainFormManager.MainForm.ActiveView;
81      var progress = Progress.Show(activeView.Content, "Generating Algorithm Configurations");
82      int n = nValues(typeof (Pathway))*nValues(typeof (Region))*nValues(typeof (Price))* nValues(typeof (Implementation));
83      int count = 0;
84      progress.ProgressValue = 1.0*count/n;
85      var alg = activeView.Content as IAlgorithm;
86
87      Action<IContentView> action = view => {
88        var optimizers = new List<IOptimizer>();
89        foreach (Region r in Enum.GetValues(typeof (Region))) {
90          var x = new Experiment("BioBoost final experiment " + r);
91          foreach (Pathway pw in Enum.GetValues(typeof (Pathway))) {
92            foreach (Price p in Enum.GetValues(typeof (Price))) {
93              foreach (Implementation i in Enum.GetValues(typeof (Implementation))) {
94                x.Optimizers.Add(CreateConfiguration(alg, pw, r, p, i, true));
95                progress.ProgressValue = 1.0*(++count)/n;
96                //x.Optimizers.Add(CreateConfiguration(alg, pw, r, p, i, false));
97                //progress.Start(string.Format("{0}/{1}", count, n));
98              }
99            }
100          }
101          var br = new BatchRun("BioBoost final batch run " + r);
102          br.Repetitions = 3;
103          br.Optimizer = x;
104          optimizers.Add(br);
105        }
106        progress.Finish();
107        foreach (var opt in optimizers)
108          MainFormManager.MainForm.ShowContent(opt);
109      };
110
111
112      action.BeginInvoke(activeView, delegate(IAsyncResult result) {
113        try {
114          action.EndInvoke(result);
115        } catch (SystemException e) {
116          var dialog = new PluginInfrastructure.ErrorDialog(e);
117          dialog.ShowDialog();
118        }
119        Progress.Hide(activeView.Content);
120      }, null);
121
122    }
123
124    private static IAlgorithm CreateConfiguration(IAlgorithm alg, Pathway pw, Region r, Price p, Implementation i, bool limitedDistanceInit) {
125      alg = (IAlgorithm) alg.Clone();
126      var problem = alg.Problem as BioBoostProblem;
127      var problemData = problem.ProblemData;
128
129      switch (r) {
130        case Region.BI: problemData.KeepRegions(new Regex("^(UK|IE)")); break; // BI (British Islands)
131        case Region.SK: problemData.KeepRegions(new Regex("^(SE|FI)")); break; // SK (Scandinavia)
132        case Region.BS: problemData.KeepRegions(new Regex("^(EE|LV|LT)")); break; // BS (Baltic States)
133        case Region.SE: problemData.KeepRegions(new Regex("^(BG|RO|EL|MK)")); break; // SE (South East Europe)
134        case Region.SW: problemData.KeepRegions(new Regex("^(ES|PT|FR|NL|BE|LU)")); break; //SW (South West Europe)
135        case Region.C: problemData.KeepRegions(new Regex("^(DE|DK|PL|CZ|SK)")); break; // C (Central Europe)
136        case Region.S: problemData.KeepRegions(new Regex("^(AT|SI|HU|IT|HR)")); break; // S (South Central)
137        case Region.EU: /* don't remove anything */ break;
138      }
139
140      string feedstock = null;
141      string carrier = null;
142      string finalProduct = null;
143      switch (pw) {
144        case Pathway.FP: feedstock = "Straw"; carrier = "Biosyncrude"; finalProduct = "TransportFuel"; break;
145        case Pathway.CP: feedstock = "ForestryResidues"; carrier = "Biooil"; finalProduct = "TransportFuel"; break;
146        case Pathway.HTC: feedstock = "MunicipalWaste"; carrier = "Biocoal"; finalProduct = "ElectricityOut"; break;
147      }
148      SetPathway(problemData, feedstock, carrier, finalProduct);
149
150      switch (p) {
151        case Price.Cheap: ScaleFeedstockPrice(problemData, feedstock, 0.75); break;
152        case Price.Medium: ScaleFeedstockPrice(problemData, feedstock, 1); break;
153        case Price.Expensive:  ScaleFeedstockPrice(problemData, feedstock, 1.5); break;
154      }
155
156      double alpha = 1;
157      bool plantKiller = false;
158      switch (i) {
159        case Implementation.Narrow: alpha = 1; plantKiller = true; break;
160        case Implementation.Normal: alpha = 1; plantKiller = false; break;
161        case Implementation.Broad: alpha = 0.5; plantKiller = false; break;
162      }
163      ((MonolithicEvaluator) problem.Evaluator).AlphaParameter.Value = new DoubleValue(alpha);
164      var mutationOperators = ((MultiMutator) NavigateItem(alg, "Mutator")).Operators;
165      mutationOperators.SetItemCheckedState(mutationOperators.First(op => op.Name == "PlantKiller"), plantKiller);
166
167      if (limitedDistanceInit) {
168        Choose( (ConstrainedValueParameter<IIntegerVectorCreator>) NavigateParameter(problem, "SolutionCreator", "IntegerVectorCreator"), "LimitedDistanceTransportTargetCreator");
169        Set((IParameterizedItem) NavigateItem(problem, "SolutionCreator", "IntegerVectorCreator"), "TournamentSize", 20);
170      } else {
171        Choose((ConstrainedValueParameter<IIntegerVectorCreator>) NavigateParameter(problem, "SolutionCreator", "IntegerVectorCreator"), "UniformRandomIntegerVectorCreator");
172      }
173
174      // adjust generations
175      int n = problem.NRegions;
176      Set(alg, "MaximumGenerations", n*n);
177
178      alg.Name = string.Format("BioBoost 11a final {0} {1} {2} {3} {4} {5}Gen", pw, r, p, i, limitedDistanceInit ? "LimitedDistanceInit" : "", n*n);
179      return alg;
180    }
181
182    private static void ScaleFeedstockPrice(BioBoostProblemData problemData, string feedstockName, double scale) {
183      Scale((Product) NavigateItem(problemData, "DataItems", "Product: " + feedstockName), "Price", scale);
184      Scale((Product) NavigateItem(problemData, "DataItems", "Product: " + feedstockName), "MaxPrice", scale);
185    }
186
187    private static void SetPathway(BioBoostProblemData problemData, string feedstock, string carrier, string finalProduct) {
188      CheckOnly(problemData, "Utilizations", feedstock);
189      CheckOnly(problemData, "TransportTargets", feedstock, carrier);
190      CheckOnly(problemData, "FinalProducts", finalProduct);
191      var potentials = problemData.FeedstockPotentials.Select(p => p.Name).ToHashSet();
192      foreach (var p in potentials) {
193        if (p != feedstock + "Potentials") {
194          problemData.FeedstockPotentials.Remove(p);
195        }
196      }
197      foreach (var p in problemData.Products) {
198        if (potentials.Contains(p.Label + "Potentials") && p.Label != feedstock)
199          problemData.DataItems.Remove(p);
200      }
201    }
202
203
204    private static void Set(IParameterizedItem item, string name, double value) { ((IValueParameter<DoubleValue>)item.Parameters[name]).Value = new DoubleValue(value); }
205    private static void Set(IParameterizedItem item, string name, int value) { ((IValueParameter<IntValue>)item.Parameters[name]).Value = new IntValue(value); }
206
207    private static void Scale(IParameterizedItem item, string name, double scale) {
208      var value = ((IValueParameter<DoubleValue>) item.Parameters[name]).Value.Value;
209      ((IValueParameter<DoubleValue>)item.Parameters[name]).Value = new DoubleValue(value*scale);
210    }
211
212    private static void CheckOnly(IParameterizedItem item, string name, params string[] values) {
213      var valueSet = new HashSet<string>(values);
214      var parameters = ((ValueParameter<CheckedItemList<StringValue>>) item.Parameters[name]).Value;
215      foreach (var i in parameters) {
216        parameters.SetItemCheckedState(i, valueSet.Contains(i.Value));
217      }
218    }
219
220    private static IItem NavigateItem(IItem item, params string[] path) {
221      for (int i = 0; i < path.Length; i++) {
222        if (item is IParameterizedItem) {
223          item = ((IValueParameter) ((IParameterizedItem) item).Parameters[path[i]]).Value;
224        } else if (item is ItemCollection<DataItem>) {
225          item = ((ItemCollection<DataItem>) item).First(x => x.ToString() == path[i]);
226        }
227      }
228      return item;
229    }
230
231    private static IItem NavigateParameter(IItem item, params string[] path) {
232      for (int i = 0; i < path.Length; i++) {
233        item = ((IParameterizedItem) item).Parameters[path[i]];
234        if (i < path.Length-1)
235          item = ((IValueParameter) item).Value;
236      }
237      return item;
238    }
239
240    private static void Choose<T>(ConstrainedValueParameter<T> param, string valueName) where T : class, IItem {
241      param.Value = param.ValidValues.First(v => v.ItemName == valueName);
242    }
243
244  }
245}
Note: See TracBrowser for help on using the repository browser.