Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization.TravelingThief/3.3/TtpOrchestratorNode2.cs @ 14601

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

#2205: worked on optimization networks

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