Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization/3.3/TtpOrchestratorNode5.cs @ 14600

Last change on this file since 14600 was 14598, checked in by jkarder, 8 years ago

#2205: worked on optimization networks

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