Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2205: worked on optimization networks

  • updated ttp networks (1, 2, 3)
  • added lrp network (1)
  • fixed plugin dependencies
File size: 18.7 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("TtpOrchestratorNode3", "Orchestrator for TTP optimization network version 3.")]
42  [StorableClass]
43  public sealed class TtpOrchestratorNode3 : OrchestratorNode {
44    #region Constants
45    private const string InstanceParameterName = "Instance";
46    private const string TspParameterName = "TSP";
47    private const string KspParameterName = "KSP";
48    private const string AvailabilityParameterName = "Availability";
49    private const string MinSpeedParameterName = "MinSpeed";
50    private const string MaxSpeedParameterName = "MaxSpeed";
51    private const string RentingRatioParameterName = "RentingRatio";
52    private const string MetaSolverName = "MetaSolver";
53    private const string TspSolverName = "TspSolver";
54    private const string KspSolverName = "KspSolver";
55    #endregion
56
57    private CancellationTokenSource cts;
58    private ResultCollection tspResults, kspResults;
59
60    [Storable]
61    double[,] tspCoordinates;
62    [Storable]
63    TtpUtils.DistanceType distanceType;
64    [Storable]
65    int kspCapacity;
66    [Storable]
67    int[] kspItemWeights, kspItemValues, ttpAvailability;
68    [Storable]
69    double ttpMinSpeed, ttpMaxSpeed, ttpRentingRatio;
70
71    #region Parameters
72    public IFixedValueParameter<TextFileValue> InstanceParameter {
73      get { return (IFixedValueParameter<TextFileValue>)Parameters[InstanceParameterName]; }
74    }
75
76    public IValueParameter<TravelingSalesmanProblem> TspParameter {
77      get { return (IValueParameter<TravelingSalesmanProblem>)Parameters[TspParameterName]; }
78    }
79
80    public IValueParameter<BinaryKnapsackProblem> KspParameter {
81      get { return (IValueParameter<BinaryKnapsackProblem>)Parameters[KspParameterName]; }
82    }
83
84    public IValueParameter<IntArray> AvailabilityParameter {
85      get { return (IValueParameter<IntArray>)Parameters[AvailabilityParameterName]; }
86    }
87
88    public IValueParameter<DoubleValue> MinSpeedParameter {
89      get { return (IValueParameter<DoubleValue>)Parameters[MinSpeedParameterName]; }
90    }
91
92    public IValueParameter<DoubleValue> MaxSpeedParameter {
93      get { return (IValueParameter<DoubleValue>)Parameters[MaxSpeedParameterName]; }
94    }
95
96    public IValueParameter<DoubleValue> RentingRatioParameter {
97      get { return (IValueParameter<DoubleValue>)Parameters[RentingRatioParameterName]; }
98    }
99    #endregion
100
101    #region Ports
102    public IMessagePort MetaSolverOrchestrationPort {
103      get { return (IMessagePort)Ports[MetaSolverName + OrchestrationPortNameSuffix]; }
104    }
105
106    public IMessagePort MetaSolverEvaluationPort {
107      get { return (IMessagePort)Ports[MetaSolverName + EvaluationPortNameSuffix]; }
108    }
109
110    public IMessagePort TspSolverOrchestrationPort {
111      get { return (IMessagePort)Ports[TspSolverName + OrchestrationPortNameSuffix]; }
112    }
113
114    public IMessagePort TspSolverEvaluationPort {
115      get { return (IMessagePort)Ports[TspSolverName + EvaluationPortNameSuffix]; }
116    }
117
118    public IMessagePort KspSolverOrchestrationPort {
119      get { return (IMessagePort)Ports[KspSolverName + OrchestrationPortNameSuffix]; }
120    }
121
122    public IMessagePort KspSolverEvaluationPort {
123      get { return (IMessagePort)Ports[KspSolverName + EvaluationPortNameSuffix]; }
124    }
125    #endregion
126
127    [StorableConstructor]
128    private TtpOrchestratorNode3(bool deserializing) : base(deserializing) { }
129    private TtpOrchestratorNode3(TtpOrchestratorNode3 original, Cloner cloner) : base(original, cloner) {
130      tspCoordinates = (double[,])original.tspCoordinates.Clone();
131      kspCapacity = original.kspCapacity;
132      kspItemWeights = (int[])original.kspItemWeights.Clone();
133      kspItemValues = (int[])original.kspItemValues.Clone();
134      ttpAvailability = (int[])original.ttpAvailability.Clone();
135      ttpMinSpeed = original.ttpMinSpeed;
136      ttpMaxSpeed = original.ttpMaxSpeed;
137      ttpRentingRatio = original.ttpRentingRatio;
138
139      RegisterEvents();
140    }
141    public TtpOrchestratorNode3() : this("TtpOrchestratorNode3") { }
142    public TtpOrchestratorNode3(string name) : base(name) {
143      #region Configure Parameters
144      Parameters.Add(new FixedValueParameter<TextFileValue>(InstanceParameterName));
145      Parameters.Add(new ValueParameter<TravelingSalesmanProblem>(TspParameterName, new TravelingSalesmanProblem()));
146      Parameters.Add(new ValueParameter<BinaryKnapsackProblem>(KspParameterName, new BinaryKnapsackProblem()));
147      Parameters.Add(new ValueParameter<IntArray>(AvailabilityParameterName));
148      Parameters.Add(new ValueParameter<DoubleValue>(MinSpeedParameterName, new DoubleValue(0.1)));
149      Parameters.Add(new ValueParameter<DoubleValue>(MaxSpeedParameterName, new DoubleValue(1.0)));
150      Parameters.Add(new ValueParameter<DoubleValue>(RentingRatioParameterName, new DoubleValue(0.5)));
151      #endregion
152
153      #region Configure Ports
154      AddOrchestrationPort<VariegationProblem>(MetaSolverName);
155      AddEvaluationPort<RealVector>(MetaSolverName, "RealVector", "Quality");
156      AddOrchestrationPort<TravelingSalesmanProblem>(TspSolverName);
157      AddEvaluationPort<Permutation>(TspSolverName, "TSPTour", "TSPTourLength");
158      AddOrchestrationPort<BinaryKnapsackProblem>(KspSolverName);
159      AddEvaluationPort<BinaryVector>(KspSolverName, "KnapsackSolution", "Quality");
160
161      RegisterEvents();
162      #endregion
163    }
164
165    public override IDeepCloneable Clone(Cloner cloner) {
166      return new TtpOrchestratorNode3(this, cloner);
167    }
168
169    [StorableHook(HookType.AfterDeserialization)]
170    private void AfterDeserialization() {
171      RegisterEvents();
172    }
173
174    private void RegisterEvents() {
175      InstanceParameter.Value.ToStringChanged += InstanceParameter_Value_ToStringChanged;
176      MetaSolverOrchestrationPort.ConnectedPortChanged += MetaSolverOrchestrationPort_ConnectedPortChanged;
177      TspSolverOrchestrationPort.ConnectedPortChanged += TspSolverOrchestrationPort_ConnectedPortChanged;
178      KspSolverOrchestrationPort.ConnectedPortChanged += KspSolverOrchestrationPort_ConnectedPortChanged;
179    }
180
181    private void InstanceParameter_Value_ToStringChanged(object sender, EventArgs e) {
182      string filePath = InstanceParameter.Value.Value;
183      TtpUtils.Import(filePath, out tspCoordinates, out distanceType,
184                                out kspCapacity, out kspItemValues, out kspItemWeights,
185                                out ttpAvailability, out ttpMinSpeed, out ttpMaxSpeed, out ttpRentingRatio);
186
187      var tsp = TspParameter.Value;
188      tsp.Coordinates = new DoubleMatrix(tspCoordinates);
189
190      var ksp = KspParameter.Value;
191      ksp.KnapsackCapacity.Value = kspCapacity;
192      ksp.Encoding.Length = kspItemValues.Length;
193      ksp.Values = new IntArray(kspItemValues);
194      ksp.Weights = new IntArray(kspItemWeights);
195
196      AvailabilityParameter.Value = new IntArray(ttpAvailability);
197      MinSpeedParameter.Value.Value = ttpMinSpeed;
198      MaxSpeedParameter.Value.Value = ttpMaxSpeed;
199      RentingRatioParameter.Value.Value = ttpRentingRatio;
200    }
201
202    public override void Prepare() {
203      Results.Clear();
204
205      var metaMsg = MetaSolverOrchestrationPort.PrepareMessage();
206      metaMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Prepare | OrchestrationMessage.QualityAdaption);
207      var problem = new VariegationProblem();
208      problem.Encoding.Length = KspParameter.Value.Length + TspParameter.Value.Coordinates.Rows * 2;
209      problem.Encoding.Bounds = new DoubleMatrix(new[,] { { -1.0, 1.0 } });
210      metaMsg["Problem"] = problem;
211      MetaSolverOrchestrationPort.SendMessage(metaMsg);
212    }
213
214    public override void Start() {
215      cts = new CancellationTokenSource();
216
217      try {
218        var metaMsg = MetaSolverOrchestrationPort.PrepareMessage();
219        metaMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Start);
220        MetaSolverOrchestrationPort.SendMessage(metaMsg);
221      } catch (Exception e) { }
222    }
223
224    public override void Pause() {
225      cts.Cancel();
226
227      var metaMsg = MetaSolverOrchestrationPort.PrepareMessage();
228      metaMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Pause);
229      MetaSolverOrchestrationPort.SendMessage(metaMsg);
230
231      var tspMsg = TspSolverOrchestrationPort.PrepareMessage();
232      tspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Stop);
233      TspSolverOrchestrationPort.SendMessage(tspMsg);
234
235      var kspMsg = KspSolverOrchestrationPort.PrepareMessage();
236      kspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Stop);
237      KspSolverOrchestrationPort.SendMessage(kspMsg);
238    }
239
240    public override void Stop() {
241      cts.Cancel();
242
243      var metaMsg = MetaSolverOrchestrationPort.PrepareMessage();
244      metaMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Stop);
245      MetaSolverOrchestrationPort.SendMessage(metaMsg);
246
247      var tspMsg = TspSolverOrchestrationPort.PrepareMessage();
248      tspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Stop);
249      TspSolverOrchestrationPort.SendMessage(tspMsg);
250
251      var kspMsg = KspSolverOrchestrationPort.PrepareMessage();
252      kspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Stop);
253      KspSolverOrchestrationPort.SendMessage(kspMsg);
254    }
255
256    protected override void ProcessMessage(IMessage message, IMessagePort port, CancellationToken token) {
257      var messageActions = new Dictionary<IMessagePort, Action<IMessage>>();
258      messageActions.Add(MetaSolverOrchestrationPort, MetaSolverOrchestrationPortMessage);
259      messageActions.Add(MetaSolverEvaluationPort, MetaSolverEvaluationPortMessage);
260      messageActions.Add(TspSolverOrchestrationPort, TspSolverOrchestrationPortMessage);
261      messageActions.Add(TspSolverEvaluationPort, TspSolverEvaluationPortMessage);
262      messageActions.Add(KspSolverOrchestrationPort, KspSolverOrchestrationPortMessage);
263      messageActions.Add(KspSolverEvaluationPort, KspSolverEvaluationPortMessage);
264
265      messageActions[port](message);
266
267      base.ProcessMessage(message, port, token);
268    }
269
270    #region MetaSolver Message Handling
271    private void MetaSolverOrchestrationPortMessage(IMessage message) { }
272
273    private void MetaSolverEvaluationPortMessage(IMessage message) {
274      var factors = (RealVector)message["RealVector"];
275      int fi = 0;
276
277      var ksp = (BinaryKnapsackProblem)KspParameter.Value.Clone();
278      while (fi < ksp.Values.Length) {
279        ksp.Values[fi] = (int)Math.Ceiling(ksp.Values[fi] * factors[fi]);
280        ++fi;
281      }
282
283      var kspMsg = KspSolverOrchestrationPort.PrepareMessage();
284      kspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Prepare | OrchestrationMessage.Start);
285      kspMsg["Problem"] = ksp;
286      KspSolverOrchestrationPort.SendMessage(kspMsg);
287      cts.Token.ThrowIfCancellationRequested();
288
289      var bestKspSolution = (BinaryVector)kspResults["Best Solution"].Value.Clone();
290      var kspCapacity = (IntValue)KspParameter.Value.KnapsackCapacity.Clone();
291      var kspPenalty = new DoubleValue(0.0);
292      var kspWeights = (IntArray)KspParameter.Value.Weights.Clone();
293      var kspValues = (IntArray)KspParameter.Value.Values.Clone();
294      var bestKspQuality = KnapsackEvaluator.Apply(bestKspSolution, kspCapacity, kspPenalty, kspWeights, kspValues).Quality;
295      var loot = new KnapsackSolution(bestKspSolution, bestKspQuality, kspCapacity, kspWeights, kspValues);
296
297      var tsp = (TravelingSalesmanProblem)TspParameter.Value.Clone();
298      for (int j = 0; j < tsp.Coordinates.Rows; j++) {
299        tsp.Coordinates[j, 0] = (int)Math.Ceiling(tsp.Coordinates[j, 0] * factors[fi + j * 2]);
300        tsp.Coordinates[j, 1] = (int)Math.Ceiling(tsp.Coordinates[j, 1] * factors[fi + j * 2 + 1]);
301      }
302
303      var tspMsg = TspSolverOrchestrationPort.PrepareMessage();
304      tspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Prepare | OrchestrationMessage.Start);
305      var tpp = new TourProfitProblem {
306        Tsp = (TravelingSalesmanProblem)TspParameter.Value.Clone(),
307        Ksp = (BinaryKnapsackProblem)KspParameter.Value.Clone(),
308        FixedKspSolution = bestKspSolution,
309        Availability = AvailabilityParameter.Value.ToArray(),
310        RentingRatio = RentingRatioParameter.Value.Value,
311        MinSpeed = MinSpeedParameter.Value.Value,
312        MaxSpeed = MaxSpeedParameter.Value.Value,
313        DistanceType = distanceType
314      };
315      tpp.Encoding.Length = TspParameter.Value.Coordinates.Rows;
316      tspMsg["Problem"] = tpp;
317      TspSolverOrchestrationPort.SendMessage(tspMsg);
318      cts.Token.ThrowIfCancellationRequested();
319
320      var bestTspSolution = (Permutation)tspResults["Best TSP Solution"].Value.Clone();
321      var coordinates = (DoubleMatrix)TspParameter.Value.Coordinates.Clone();
322      var tour = new PathTSPTour(coordinates, bestTspSolution, new DoubleValue(TSPCoordinatesPathEvaluator.Apply(new TSPEuclideanPathEvaluator(), coordinates, bestTspSolution)));
323
324      #region Analyze
325      double objectiveValue = TtpUtils.Evaluate(TspParameter.Value, tour.Permutation.ToArray(), KspParameter.Value, loot.BinaryVector.ToArray(),
326        AvailabilityParameter.Value.ToArray(), RentingRatioParameter.Value.Value, MinSpeedParameter.Value.Value, MaxSpeedParameter.Value.Value, distanceType);
327      ((DoubleValue)message["Quality"]).Value = objectiveValue;
328
329      IResult bestQuality;
330      if (!Results.TryGetValue("Best TTP Quality", out bestQuality)) {
331        Results.Add(new Result("Best TTP Quality", new DoubleValue(objectiveValue)));
332        Results.Add(new Result("Best Tour", tour));
333        Results.Add(new Result("Best Loot", loot));
334      } else if (((DoubleValue)bestQuality.Value).Value < objectiveValue) {
335        ((DoubleValue)bestQuality.Value).Value = objectiveValue;
336        Results["Best Tour"].Value = tour;
337        Results["Best Loot"].Value = loot;
338      }
339      #endregion
340    }
341    #endregion
342
343    #region TspSolver Message Handling
344    private void TspSolverOrchestrationPortMessage(IMessage message) {
345      var results = (ResultCollection)message["Results"];
346      if (results.ContainsKey("Best TSP Solution")) {
347        tspResults = results;
348      }
349    }
350
351    private void TspSolverEvaluationPortMessage(IMessage message) { }
352    #endregion
353
354    #region KspSolver Message Handling
355    private void KspSolverOrchestrationPortMessage(IMessage message) {
356      var results = (ResultCollection)message["Results"];
357      if (results.ContainsKey("Best Solution")) {
358        kspResults = results;
359      }
360    }
361
362    private void KspSolverEvaluationPortMessage(IMessage message) { }
363    #endregion
364
365    #region Event Handlers
366    private void MetaSolverOrchestrationPort_ConnectedPortChanged(object sender, EventArgs e) {
367      if (MetaSolverOrchestrationPort.ConnectedPort == null) return;
368
369      var node = MetaSolverOrchestrationPort.ConnectedPort.Parent as OrchestratedAlgorithmNode;
370      if (node == null) return;
371
372      var hook = new HookOperator { Name = "Meta Eval Hook" };
373      hook.Parameters.Add(new LookupParameter<RealVector>("RealVector") { Hidden = true });
374      hook.Parameters.Add(new LookupParameter<DoubleValue>("Quality") { Hidden = true });
375      node.EvalHook = hook;
376
377      node.OrchestrationPort.CloneParametersFromPort(MetaSolverOrchestrationPort);
378      node.EvaluationPort.CloneParametersFromPort(MetaSolverEvaluationPort);
379      node.EvaluationPort.ConnectedPort = MetaSolverEvaluationPort;
380    }
381
382    private void TspSolverOrchestrationPort_ConnectedPortChanged(object sender, EventArgs e) {
383      if (TspSolverOrchestrationPort.ConnectedPort == null) return;
384
385      var node = TspSolverOrchestrationPort.ConnectedPort.Parent as OrchestratedAlgorithmNode;
386      if (node == null) return;
387
388      var hook = new HookOperator { Name = "TSP Eval Hook" };
389      hook.Parameters.Add(new LookupParameter<Permutation>("TSPTour") { Hidden = true });
390      hook.Parameters.Add(new LookupParameter<DoubleValue>("TSPTourLength") { Hidden = true });
391      node.EvalHook = hook;
392
393      node.OrchestrationPort.CloneParametersFromPort(TspSolverOrchestrationPort);
394      node.EvaluationPort.CloneParametersFromPort(TspSolverEvaluationPort);
395      node.EvaluationPort.ConnectedPort = TspSolverEvaluationPort;
396    }
397
398    private void KspSolverOrchestrationPort_ConnectedPortChanged(object sender, EventArgs e) {
399      if (KspSolverOrchestrationPort.ConnectedPort == null) return;
400
401      var node = KspSolverOrchestrationPort.ConnectedPort.Parent as OrchestratedAlgorithmNode;
402      if (node == null) return;
403
404      var hook = new HookOperator { Name = "KSP Eval Hook" };
405      hook.Parameters.Add(new LookupParameter<BinaryVector>("KnapsackSolution") { Hidden = true });
406      hook.Parameters.Add(new LookupParameter<DoubleValue>("Quality") { Hidden = true });
407      node.EvalHook = hook;
408
409      node.OrchestrationPort.CloneParametersFromPort(KspSolverOrchestrationPort);
410      node.EvaluationPort.CloneParametersFromPort(KspSolverEvaluationPort);
411      node.EvaluationPort.ConnectedPort = KspSolverEvaluationPort;
412    }
413    #endregion
414  }
415}
Note: See TracBrowser for help on using the repository browser.