Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2499: added code from HeuristicLab.BioBoost.Views (from private repository) nothing much has been changed

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