Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.BioBoost/HeuristicLab.Problems.BioBoost.Views/3.3/MenuItems/CreateBioBoostExperimentMenuItem.cs @ 13074

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

#2499: added license header and removed unused usings

File size: 11.0 KB
RevLine 
[13074]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
[13072]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 mainForm = ((MainForm.WindowsForms.MainForm) MainFormManager.MainForm);
82      var progress = mainForm.AddOperationProgressToContent(activeView.Content, "Generating Algorithm Configurations");
83      int n = nValues(typeof (Pathway))*nValues(typeof (Region))*nValues(typeof (Price))* nValues(typeof (Implementation));
84      int count = 0;
85      progress.Start();
86      progress.ProgressValue = 1.0*count/n;
87      var alg = activeView.Content as IAlgorithm;
88
89      Action<IContentView> action = view => {
90        var optimizers = new List<IOptimizer>();
91        foreach (Region r in Enum.GetValues(typeof (Region))) {
92          var x = new Experiment("BioBoost final experiment " + r);
93          foreach (Pathway pw in Enum.GetValues(typeof (Pathway))) {
94            foreach (Price p in Enum.GetValues(typeof (Price))) {
95              foreach (Implementation i in Enum.GetValues(typeof (Implementation))) {
96                x.Optimizers.Add(CreateConfiguration(alg, pw, r, p, i, true));
97                progress.ProgressValue = 1.0*(++count)/n;
98                //x.Optimizers.Add(CreateConfiguration(alg, pw, r, p, i, false));
99                //progress.Start(string.Format("{0}/{1}", count, n));
100              }
101            }
102          }
103          var br = new BatchRun("BioBoost final batch run " + r);
104          br.Repetitions = 3;
105          br.Optimizer = x;
106          optimizers.Add(br);
107        }
108        progress.Finish();
109        foreach (var opt in optimizers)
110          MainFormManager.MainForm.ShowContent(opt);
111      };
112
113
114      action.BeginInvoke(activeView, delegate(IAsyncResult result) {
115        try {
116          action.EndInvoke(result);
117        } catch (SystemException e) {
118          var dialog = new PluginInfrastructure.ErrorDialog(e);
119          dialog.ShowDialog();
120        }
121        mainForm.RemoveOperationProgressFromContent(activeView.Content);
122      }, null);
123
124    }
125
126    private static IAlgorithm CreateConfiguration(IAlgorithm alg, Pathway pw, Region r, Price p, Implementation i, bool limitedDistanceInit) {
127      alg = (IAlgorithm) alg.Clone();
128      var problem = alg.Problem as BioBoostProblem;
129      var problemData = problem.ProblemData;
130
131      switch (r) {
132        case Region.BI: problemData.KeepRegions(new Regex("^(UK|IE)")); break; // BI (British Islands)
133        case Region.SK: problemData.KeepRegions(new Regex("^(SE|FI)")); break; // SK (Scandinavia)
134        case Region.BS: problemData.KeepRegions(new Regex("^(EE|LV|LT)")); break; // BS (Baltic States)
135        case Region.SE: problemData.KeepRegions(new Regex("^(BG|RO|EL|MK)")); break; // SE (South East Europe)
136        case Region.SW: problemData.KeepRegions(new Regex("^(ES|PT|FR|NL|BE|LU)")); break; //SW (South West Europe)
137        case Region.C: problemData.KeepRegions(new Regex("^(DE|DK|PL|CZ|SK)")); break; // C (Central Europe)
138        case Region.S: problemData.KeepRegions(new Regex("^(AT|SI|HU|IT|HR)")); break; // S (South Central)
139        case Region.EU: /* don't remove anything */ break;
140      }
141
142      string feedstock = null;
143      string carrier = null;
144      string finalProduct = null;
145      switch (pw) {
146        case Pathway.FP: feedstock = "Straw"; carrier = "Biosyncrude"; finalProduct = "TransportFuel"; break;
147        case Pathway.CP: feedstock = "ForestryResidues"; carrier = "Biooil"; finalProduct = "TransportFuel"; break;
148        case Pathway.HTC: feedstock = "MunicipalWaste"; carrier = "Biocoal"; finalProduct = "ElectricityOut"; break;
149      }
150      SetPathway(problemData, feedstock, carrier, finalProduct);
151
152      switch (p) {
153        case Price.Cheap: ScaleFeedstockPrice(problemData, feedstock, 0.75); break;
154        case Price.Medium: ScaleFeedstockPrice(problemData, feedstock, 1); break;
155        case Price.Expensive:  ScaleFeedstockPrice(problemData, feedstock, 1.5); break;
156      }
157
158      double alpha = 1;
159      bool plantKiller = false;
160      switch (i) {
161        case Implementation.Narrow: alpha = 1; plantKiller = true; break;
162        case Implementation.Normal: alpha = 1; plantKiller = false; break;
163        case Implementation.Broad: alpha = 0.5; plantKiller = false; break;
164      }
165      ((MonolithicEvaluator) problem.Evaluator).AlphaParameter.Value = new DoubleValue(alpha);
166      var mutationOperators = ((MultiMutator) NavigateItem(alg, "Mutator")).Operators;
167      mutationOperators.SetItemCheckedState(mutationOperators.First(op => op.Name == "PlantKiller"), plantKiller);
168
169      if (limitedDistanceInit) {
170        Choose( (ConstrainedValueParameter<IIntegerVectorCreator>) NavigateParameter(problem, "SolutionCreator", "IntegerVectorCreator"), "LimitedDistanceTransportTargetCreator");
171        Set((IParameterizedItem) NavigateItem(problem, "SolutionCreator", "IntegerVectorCreator"), "TournamentSize", 20);
172      } else {
173        Choose((ConstrainedValueParameter<IIntegerVectorCreator>) NavigateParameter(problem, "SolutionCreator", "IntegerVectorCreator"), "UniformRandomIntegerVectorCreator");
174      }
175
176      // adjust generations
177      int n = problem.NRegions;
178      Set(alg, "MaximumGenerations", n*n);
179
180      alg.Name = string.Format("BioBoost 11a final {0} {1} {2} {3} {4} {5}Gen", pw, r, p, i, limitedDistanceInit ? "LimitedDistanceInit" : "", n*n);
181      return alg;
182    }
183
184    private static void ScaleFeedstockPrice(BioBoostProblemData problemData, string feedstockName, double scale) {
185      Scale((Product) NavigateItem(problemData, "DataItems", "Product: " + feedstockName), "Price", scale);
186      Scale((Product) NavigateItem(problemData, "DataItems", "Product: " + feedstockName), "MaxPrice", scale);
187    }
188
189    private static void SetPathway(BioBoostProblemData problemData, string feedstock, string carrier, string finalProduct) {
190      CheckOnly(problemData, "Utilizations", feedstock);
191      CheckOnly(problemData, "TransportTargets", feedstock, carrier);
192      CheckOnly(problemData, "FinalProducts", finalProduct);
193      var potentials = problemData.FeedstockPotentials.Select(p => p.Name).ToHashSet();
194      foreach (var p in potentials) {
195        if (p != feedstock + "Potentials") {
196          problemData.FeedstockPotentials.Remove(p);
197        }
198      }
199      foreach (var p in problemData.Products) {
200        if (potentials.Contains(p.Label + "Potentials") && p.Label != feedstock)
201          problemData.DataItems.Remove(p);
202      }
203    }
204
205
206    private static void Set(IParameterizedItem item, string name, double value) { ((IValueParameter<DoubleValue>)item.Parameters[name]).Value = new DoubleValue(value); }
207    private static void Set(IParameterizedItem item, string name, int value) { ((IValueParameter<IntValue>)item.Parameters[name]).Value = new IntValue(value); }
208
209    private static void Scale(IParameterizedItem item, string name, double scale) {
210      var value = ((IValueParameter<DoubleValue>) item.Parameters[name]).Value.Value;
211      ((IValueParameter<DoubleValue>)item.Parameters[name]).Value = new DoubleValue(value*scale);
212    }
213
214    private static void CheckOnly(IParameterizedItem item, string name, params string[] values) {
215      var valueSet = new HashSet<string>(values);
216      var parameters = ((ValueParameter<CheckedItemList<StringValue>>) item.Parameters[name]).Value;
217      foreach (var i in parameters) {
218        parameters.SetItemCheckedState(i, valueSet.Contains(i.Value));
219      }
220    }
221
222    private static IItem NavigateItem(IItem item, params string[] path) {
223      for (int i = 0; i < path.Length; i++) {
224        if (item is IParameterizedItem) {
225          item = ((IValueParameter) ((IParameterizedItem) item).Parameters[path[i]]).Value;
226        } else if (item is ItemCollection<DataItem>) {
227          item = ((ItemCollection<DataItem>) item).First(x => x.ToString() == path[i]);
228        }
229      }
230      return item;
231    }
232
233    private static IItem NavigateParameter(IItem item, params string[] path) {
234      for (int i = 0; i < path.Length; i++) {
235        item = ((IParameterizedItem) item).Parameters[path[i]];
236        if (i < path.Length-1)
237          item = ((IValueParameter) item).Value;
238      }
239      return item;
240    }
241
242    private static void Choose<T>(ConstrainedValueParameter<T> param, string valueName) where T : class, IItem {
243      param.Value = param.ValidValues.First(v => v.ItemName == valueName);
244    }
245
246  }
247}
Note: See TracBrowser for help on using the repository browser.