Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization/3.3/TtpOrchestratorNode3.cs @ 14586

Last change on this file since 14586 was 14586, checked in by jkarder, 7 years ago

#2205: worked on optimization networks

  • added projects for integrated optimization (orchestration)
File size: 17.6 KB
Line 
1using System;
2using System.Collections.Concurrent;
3using System.Collections.Generic;
4using System.Linq;
5using System.Threading;
6using HeuristicLab.Common;
7using HeuristicLab.Core;
8using HeuristicLab.Core.Networks;
9using HeuristicLab.Data;
10using HeuristicLab.Encodings.BinaryVectorEncoding;
11using HeuristicLab.Encodings.PermutationEncoding;
12using HeuristicLab.Encodings.RealVectorEncoding;
13using HeuristicLab.Operators;
14using HeuristicLab.Optimization;
15using HeuristicLab.Parameters;
16using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
17using HeuristicLab.Problems.Knapsack;
18using HeuristicLab.Problems.TravelingSalesman;
19
20namespace HeuristicLab.Networks.IntegratedOptimization {
21  [Item("TtpOrchestratorNode3", "An abstract base class for an orchestrator node for the TTP.")]
22  [StorableClass]
23  public sealed class TtpOrchestratorNode3 : OrchestratorNode {
24    #region Constants
25    private const string TspParameterName = "TSP";
26    private const string KspParameterName = "KSP";
27    private const string AvailabilityParameterName = "Availability";
28    private const string MinSpeedParameterName = "MinSpeed";
29    private const string MaxSpeedParameterName = "MaxSpeed";
30    private const string RentingRatioParameterName = "RentingRatio";
31    private const string IterationsParameterName = "Iterations";
32    private const string MetaSolverName = "MetaSolver";
33    private const string TspSolverName = "TspSolver";
34    private const string KspSolverName = "KspSolver";
35    private const string TspResultsResultName = "TspResults";
36    private const string KspResultsResultName = "KspResults";
37    private const string TtpResultsResultName = "TtpResults";
38    #endregion
39
40    #region Thread Results
41    private object locker = new object();
42    private ConcurrentDictionary<int, ResultCollection> tspThreadResults = new ConcurrentDictionary<int, ResultCollection>();
43    private ConcurrentDictionary<int, ResultCollection> kspThreadResults = new ConcurrentDictionary<int, ResultCollection>();
44    #endregion
45
46    #region Parameters
47    public IValueParameter<IntValue> IterationsParameter {
48      get { return (IValueParameter<IntValue>)Parameters[IterationsParameterName]; }
49    }
50
51    public IValueParameter<TravelingSalesmanProblem> TspParameter {
52      get { return (IValueParameter<TravelingSalesmanProblem>)Parameters[TspParameterName]; }
53    }
54
55    public IValueParameter<BinaryKnapsackProblem> KspParameter {
56      get { return (IValueParameter<BinaryKnapsackProblem>)Parameters[KspParameterName]; }
57    }
58
59    public IValueParameter<IntArray> AvailabilityParameter {
60      get { return (IValueParameter<IntArray>)Parameters[AvailabilityParameterName]; }
61    }
62
63    public IValueParameter<DoubleValue> MinSpeedParameter {
64      get { return (IValueParameter<DoubleValue>)Parameters[MinSpeedParameterName]; }
65    }
66
67    public IValueParameter<DoubleValue> MaxSpeedParameter {
68      get { return (IValueParameter<DoubleValue>)Parameters[MaxSpeedParameterName]; }
69    }
70
71    public IValueParameter<DoubleValue> RentingRatioParameter {
72      get { return (IValueParameter<DoubleValue>)Parameters[RentingRatioParameterName]; }
73    }
74    #endregion
75
76    #region Ports
77    public IConfigurationPort MetaSolverOrchestrationPort {
78      get { return (IConfigurationPort)Ports[MetaSolverName + OrchestrationPortNameSuffix]; }
79    }
80
81    public IConfigurationPort MetaSolverEvaluationPort {
82      get { return (IConfigurationPort)Ports[MetaSolverName + EvaluationPortNameSuffix]; }
83    }
84
85    public IConfigurationPort TspSolverOrchestrationPort {
86      get { return (IConfigurationPort)Ports[TspSolverName + OrchestrationPortNameSuffix]; }
87    }
88
89    public IConfigurationPort TspSolverEvaluationPort {
90      get { return (IConfigurationPort)Ports[TspSolverName + EvaluationPortNameSuffix]; }
91    }
92
93    public IConfigurationPort KspSolverOrchestrationPort {
94      get { return (IConfigurationPort)Ports[KspSolverName + OrchestrationPortNameSuffix]; }
95    }
96
97    public IConfigurationPort KspSolverEvaluationPort {
98      get { return (IConfigurationPort)Ports[KspSolverName + EvaluationPortNameSuffix]; }
99    }
100    #endregion
101
102    #region Results
103    public ItemList<ResultCollection> TspResults {
104      get { return (ItemList<ResultCollection>)Results[TspResultsResultName].Value; }
105    }
106
107    public ItemList<ResultCollection> KspResults {
108      get { return (ItemList<ResultCollection>)Results[KspResultsResultName].Value; }
109    }
110
111    public ItemList<ResultCollection> TtpResults {
112      get { return (ItemList<ResultCollection>)Results[TtpResultsResultName].Value; }
113    }
114    #endregion
115
116    [StorableConstructor]
117    private TtpOrchestratorNode3(bool deserializing) : base(deserializing) { }
118    private TtpOrchestratorNode3(TtpOrchestratorNode3 original, Cloner cloner) : base(original, cloner) { }
119    public TtpOrchestratorNode3() : this("TtpOrchestratorNode3") { }
120    public TtpOrchestratorNode3(string name) : base(name) {
121      #region Configure Parameters
122      Parameters.Add(new ValueParameter<IntValue>(IterationsParameterName, new IntValue(20)));
123      Parameters.Add(new ValueParameter<TravelingSalesmanProblem>(TspParameterName, new TravelingSalesmanProblem()));
124      Parameters.Add(new ValueParameter<BinaryKnapsackProblem>(KspParameterName, new BinaryKnapsackProblem()));
125      Parameters.Add(new ValueParameter<IntArray>(AvailabilityParameterName));
126      Parameters.Add(new ValueParameter<DoubleValue>(MinSpeedParameterName, new DoubleValue(0.1)));
127      Parameters.Add(new ValueParameter<DoubleValue>(MaxSpeedParameterName, new DoubleValue(1.0)));
128      Parameters.Add(new ValueParameter<DoubleValue>(RentingRatioParameterName, new DoubleValue(0.5)));
129      #endregion
130
131      #region Configure Ports
132      AddOrchestrationPort<VariegationProblem>(MetaSolverName);
133      AddEvaluationPort<RealVector>(MetaSolverName, "RealVector", "Quality");
134      AddOrchestrationPort<TravelingSalesmanProblem>(TspSolverName);
135      AddEvaluationPort<Permutation>(TspSolverName, "TSPTour", "TSPTourLength");
136      AddOrchestrationPort<BinaryKnapsackProblem>(KspSolverName);
137      AddEvaluationPort<BinaryVector>(KspSolverName, "KnapsackSolution", "Quality");
138
139      MetaSolverOrchestrationPort.ConnectedPortChanged += MetaSolverOrchestrationPort_ConnectedPortChanged;
140      TspSolverOrchestrationPort.ConnectedPortChanged += TspSolverOrchestrationPort_ConnectedPortChanged;
141      KspSolverOrchestrationPort.ConnectedPortChanged += KspSolverOrchestrationPort_ConnectedPortChanged;
142      #endregion
143    }
144
145    public override IDeepCloneable Clone(Cloner cloner) {
146      return new TtpOrchestratorNode3(this, cloner);
147    }
148
149    public override void Prepare() {
150      tspThreadResults.Clear();
151      kspThreadResults.Clear();
152      Results.Clear();
153      Results.Add(new Result(TspResultsResultName, new ItemList<ResultCollection>()));
154      Results.Add(new Result(KspResultsResultName, new ItemList<ResultCollection>()));
155      Results.Add(new Result(TtpResultsResultName, new ItemList<ResultCollection>()));
156    }
157
158    public override void Start() {
159      var metaMsg = MetaSolverOrchestrationPort.PrepareMessage();
160      metaMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.QualityAdaption);
161      var problem = new VariegationProblem();
162      problem.Encoding.Length = KspParameter.Value.Length + TspParameter.Value.Coordinates.Rows * 2;
163      problem.Encoding.Bounds = new DoubleMatrix(new[,] { { -1.0, 1.0 } });
164      metaMsg["Problem"] = problem;
165      MetaSolverOrchestrationPort.SendMessage(metaMsg);
166    }
167
168    public override void Pause() {
169      throw new NotImplementedException();
170    }
171
172    public override void Stop() {
173      throw new NotImplementedException();
174    }
175
176    protected override void ProcessMessage(IMessage message, IMessagePort port, CancellationToken token) {
177      var messageActions = new Dictionary<IMessagePort, Action<IMessage>>();
178      messageActions.Add(MetaSolverOrchestrationPort, MetaSolverOrchestrationPortMessage);
179      messageActions.Add(MetaSolverEvaluationPort, MetaSolverEvaluationPortMessage);
180      messageActions.Add(TspSolverOrchestrationPort, TspSolverOrchestrationPortMessage);
181      messageActions.Add(TspSolverEvaluationPort, TspSolverEvaluationPortMessage);
182      messageActions.Add(KspSolverOrchestrationPort, KspSolverOrchestrationPortMessage);
183      messageActions.Add(KspSolverEvaluationPort, KspSolverEvaluationPortMessage);
184
185      messageActions[port](message);
186
187      base.ProcessMessage(message, port, token);
188    }
189
190    #region MetaSolver Message Handling
191    private void MetaSolverOrchestrationPortMessage(IMessage message) { }
192
193    private void MetaSolverEvaluationPortMessage(IMessage message) {
194      var factors = (RealVector)message["RealVector"];
195      int fi = 0;
196
197      var ksp = (BinaryKnapsackProblem)KspParameter.Value.Clone();
198      while (fi < ksp.Values.Length) {
199        ksp.Values[fi] = (int)Math.Ceiling(ksp.Values[fi] * factors[fi]);
200        ++fi;
201      }
202
203      var kspMsg = KspSolverOrchestrationPort.PrepareMessage();
204      kspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Start);
205      kspMsg["Problem"] = ksp;
206      KspSolverOrchestrationPort.SendMessage(kspMsg);
207
208      var kspResults = kspThreadResults[Thread.CurrentThread.ManagedThreadId];
209      var bestKspSolution = (BinaryVector)kspResults["Best Solution"].Value;
210      var kspCapacity = (IntValue)KspParameter.Value.KnapsackCapacity.Clone();
211      var kspPenalty = new DoubleValue(0.0);
212      var kspWeights = (IntArray)KspParameter.Value.Weights.Clone();
213      var kspValues = (IntArray)KspParameter.Value.Values.Clone();
214      var bestKspQuality = KnapsackEvaluator.Apply(bestKspSolution, kspCapacity, kspPenalty, kspWeights, kspValues).Quality;
215      var loot = new KnapsackSolution(bestKspSolution, bestKspQuality, kspCapacity, kspWeights, kspValues);
216      kspResults.Add(new Result("Best KSP Solution", loot));
217
218      var tsp = (TravelingSalesmanProblem)TspParameter.Value.Clone();
219      for (int j = 0; j < tsp.Coordinates.Rows; j++) {
220        tsp.Coordinates[j, 0] = (int)Math.Ceiling(tsp.Coordinates[j, 0] * factors[fi + j * 2]);
221        tsp.Coordinates[j, 1] = (int)Math.Ceiling(tsp.Coordinates[j, 1] * factors[fi + j * 2 + 1]);
222      }
223
224      var tspMsg = TspSolverOrchestrationPort.PrepareMessage();
225      tspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Start);
226      tspMsg["Problem"] = tsp;
227      TspSolverOrchestrationPort.SendMessage(tspMsg);
228
229      var tspResults = tspThreadResults[Thread.CurrentThread.ManagedThreadId];
230      var tour = (PathTSPTour)tspResults["Best TSP Solution"].Value;
231      tour.Coordinates = (DoubleMatrix)TspParameter.Value.Coordinates.Clone();
232      tour.Quality.Value = TSPCoordinatesPathEvaluator.Apply(new TSPEuclideanPathEvaluator(), tour.Coordinates, tour.Permutation);
233
234      #region Analyze
235      double objectiveValue = EvaluateTtp(TspParameter.Value, tour.Permutation.ToArray(), KspParameter.Value, loot.BinaryVector.ToArray());
236      ((DoubleValue)message["Quality"]).Value = objectiveValue;
237
238      var ttpResults = new ResultCollection();
239      ttpResults.Add(new Result("Quality", new DoubleValue(objectiveValue)));
240      ttpResults.Add(new Result("Tour", tour));
241      ttpResults.Add(new Result("Loot", loot));
242
243      lock (locker) {
244        TtpResults.Add(ttpResults);
245        TspResults.Add(tspResults);
246        KspResults.Add(kspResults);
247
248        IResult bestQuality;
249        if (!Results.TryGetValue("Best TTP Quality", out bestQuality)) {
250          Results.Add(new Result("Best TTP Quality", new DoubleValue(objectiveValue)));
251          Results.Add(new Result("Best Tour", tour));
252          Results.Add(new Result("Best Loot", loot));
253        } else if (((DoubleValue)bestQuality.Value).Value < objectiveValue) {
254          ((DoubleValue)bestQuality.Value).Value = objectiveValue;
255          Results["Best Tour"].Value = tour;
256          Results["Best Loot"].Value = loot;
257        }
258      }
259      #endregion
260    }
261    #endregion
262
263    #region TspSolver Message Handling
264    private void TspSolverOrchestrationPortMessage(IMessage message) {
265      var results = (ResultCollection)message["Results"];
266      if (results.ContainsKey("Best TSP Solution")) {
267        tspThreadResults[Thread.CurrentThread.ManagedThreadId] = results;
268      }
269    }
270
271    private void TspSolverEvaluationPortMessage(IMessage message) { }
272    #endregion
273
274    #region KspSolver Message Handling
275    private void KspSolverOrchestrationPortMessage(IMessage message) {
276      var results = (ResultCollection)message["Results"];
277      if (results.ContainsKey("Best Solution")) {
278        kspThreadResults[Thread.CurrentThread.ManagedThreadId] = results;
279      }
280    }
281
282    private void KspSolverEvaluationPortMessage(IMessage message) { }
283    #endregion
284
285    #region Helpers
286    private double EvaluateTtp(TravelingSalesmanProblem tsp, int[] tour, BinaryKnapsackProblem ksp, bool[] loot) {
287      bool feasible;
288      return EvaluateTtp(tsp, tour, ksp, loot, out feasible);
289    }
290
291    private double EvaluateTtp(TravelingSalesmanProblem tsp, int[] tour, BinaryKnapsackProblem ksp, bool[] loot, out bool feasible) {
292      double collectedWeight = 0.0;
293      double objectiveValue = 0.0;
294      double infeasibleBaseLine = -1000000.0;
295      double speedCoefficient = (MaxSpeedParameter.Value.Value - MinSpeedParameter.Value.Value) / ksp.KnapsackCapacity.Value;
296
297      int hideoutIdx = 0;
298      while (tour[hideoutIdx] != 0) hideoutIdx++;
299      int cityIdx = (hideoutIdx + 1) % tour.Length;
300      int lastCityIdx = hideoutIdx;
301
302      while (cityIdx != hideoutIdx) {
303        double oldCollectedWeight = collectedWeight;
304        var availableItems = AvailabilityParameter.Value.Select((c, i) => new { CityIdx = c, ItemIdx = i }).Where(x => x.CityIdx == tour[cityIdx]);
305
306        foreach (var item in availableItems) {
307          if (!loot[item.ItemIdx]) continue;
308          collectedWeight += ksp.Weights[item.ItemIdx];
309          objectiveValue += ksp.Values[item.ItemIdx];
310        }
311
312        objectiveValue -= Distance(tsp.Coordinates.CloneAsMatrix(), tour[lastCityIdx], tour[cityIdx]) * RentingRatioParameter.Value.Value /
313                          (MaxSpeedParameter.Value.Value - speedCoefficient * oldCollectedWeight);
314        lastCityIdx = cityIdx;
315        cityIdx = (cityIdx + 1) % tour.Length;
316      }
317
318      objectiveValue -= Distance(tsp.Coordinates.CloneAsMatrix(), tour[lastCityIdx], tour[hideoutIdx]) * RentingRatioParameter.Value.Value /
319                        (MaxSpeedParameter.Value.Value - speedCoefficient * collectedWeight);
320
321      feasible = collectedWeight <= ksp.KnapsackCapacity.Value;
322      if (!feasible) objectiveValue = infeasibleBaseLine - collectedWeight;
323
324      return objectiveValue;
325    }
326
327    private double Distance(double[,] coords, int fromIdx, int toIdx) {
328      double fromX = coords[fromIdx, 0], fromY = coords[fromIdx, 1],
329             toX = coords[toIdx, 0], toY = coords[toIdx, 1];
330      return (int)Math.Ceiling(Math.Sqrt((toX - fromX) * (toX - fromX) + (toY - fromY) * (toY - fromY)));
331    }
332    #endregion
333
334    #region Event Handlers
335    private void MetaSolverOrchestrationPort_ConnectedPortChanged(object sender, EventArgs e) {
336      if (MetaSolverOrchestrationPort.ConnectedPort == null) return;
337
338      var node = MetaSolverOrchestrationPort.ConnectedPort.Parent as OrchestratedAlgorithmNode;
339      if (node == null) return;
340
341      var hook = new HookOperator { Name = "Meta Eval Hook" };
342      hook.Parameters.Add(new LookupParameter<RealVector>("RealVector") { Hidden = true });
343      hook.Parameters.Add(new LookupParameter<DoubleValue>("Quality") { Hidden = true });
344      node.EvalHook = hook;
345
346      node.OrchestrationPort.CloneParametersFromPort(MetaSolverOrchestrationPort);
347      node.EvaluationPort.CloneParametersFromPort(MetaSolverEvaluationPort);
348      node.EvaluationPort.ConnectedPort = MetaSolverEvaluationPort;
349    }
350
351    private void TspSolverOrchestrationPort_ConnectedPortChanged(object sender, EventArgs e) {
352      if (TspSolverOrchestrationPort.ConnectedPort == null) return;
353
354      var node = TspSolverOrchestrationPort.ConnectedPort.Parent as OrchestratedAlgorithmNode;
355      if (node == null) return;
356
357      var hook = new HookOperator { Name = "TSP Eval Hook" };
358      hook.Parameters.Add(new LookupParameter<Permutation>("TSPTour") { Hidden = true });
359      hook.Parameters.Add(new LookupParameter<DoubleValue>("TSPTourLength") { Hidden = true });
360      node.EvalHook = hook;
361
362      node.OrchestrationPort.CloneParametersFromPort(TspSolverOrchestrationPort);
363      node.EvaluationPort.CloneParametersFromPort(TspSolverEvaluationPort);
364      node.EvaluationPort.ConnectedPort = TspSolverEvaluationPort;
365    }
366
367    private void KspSolverOrchestrationPort_ConnectedPortChanged(object sender, EventArgs e) {
368      if (KspSolverOrchestrationPort.ConnectedPort == null) return;
369
370      var node = KspSolverOrchestrationPort.ConnectedPort.Parent as OrchestratedAlgorithmNode;
371      if (node == null) return;
372
373      var hook = new HookOperator { Name = "KSP Eval Hook" };
374      hook.Parameters.Add(new LookupParameter<BinaryVector>("KnapsackSolution") { Hidden = true });
375      hook.Parameters.Add(new LookupParameter<DoubleValue>("Quality") { Hidden = true });
376      node.EvalHook = hook;
377
378      node.OrchestrationPort.CloneParametersFromPort(KspSolverOrchestrationPort);
379      node.EvaluationPort.CloneParametersFromPort(KspSolverEvaluationPort);
380      node.EvaluationPort.ConnectedPort = KspSolverEvaluationPort;
381    }
382    #endregion
383  }
384}
Note: See TracBrowser for help on using the repository browser.