Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2205_OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization.TravelingThief/3.3/TtpOrchestratorNode.cs @ 17215

Last change on this file since 17215 was 14653, checked in by jkarder, 8 years ago

#2205: worked on optimization networks

  • improved ttp evaluation
File size: 14.5 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.Threading;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Core.Networks;
28using HeuristicLab.Data;
29using HeuristicLab.Encodings.RealVectorEncoding;
30using HeuristicLab.Operators;
31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33using HeuristicLab.Problems.TravelingSalesman;
34
35namespace HeuristicLab.Networks.IntegratedOptimization.TravelingThief {
36  [Item("TtpOrchestratorNode", "An abstract base class for orchestrators used in TTP optimization networks.")]
37  [StorableClass]
38  public abstract class TtpOrchestratorNode : OrchestratorNode {
39    #region Constants
40    protected const string InstanceParameterName = "Instance";
41    protected const string TspParameterName = "TSP";
42    protected const string KspParameterName = "KSP";
43    protected const string AvailabilityParameterName = "Availability";
44    protected const string MinSpeedParameterName = "MinSpeed";
45    protected const string MaxSpeedParameterName = "MaxSpeed";
46    protected const string RentingRatioParameterName = "RentingRatio";
47    protected const string MetaSolverName = "MetaSolver";
48    protected const string TspSolverName = "TspSolver";
49    protected const string KspSolverName = "KspSolver";
50    protected const string OrchestrationPortNameSuffix = "OrchestrationPort";
51    protected const string EvaluationPortNameSuffix = "EvaluationPort";
52    #endregion
53
54    protected CancellationTokenSource cts;
55
56    [Storable]
57    protected double[,] tspCoordinates = new double[0, 0];
58    [Storable]
59    protected TtpUtils.DistanceType distanceType;
60    [Storable]
61    protected int kspCapacity;
62    [Storable]
63    protected int[] kspItemWeights = new int[0], kspItemValues = new int[0], ttpAvailability = new int[0];
64    [Storable]
65    protected double ttpMinSpeed, ttpMaxSpeed, ttpRentingRatio;
66
67    #region Parameters
68    public IFixedValueParameter<TextFileValue> InstanceParameter {
69      get { return (IFixedValueParameter<TextFileValue>)Parameters[InstanceParameterName]; }
70    }
71
72    public IValueParameter<TravelingSalesmanProblem> TspParameter {
73      get { return (IValueParameter<TravelingSalesmanProblem>)Parameters[TspParameterName]; }
74    }
75
76    public IValueParameter<BinaryKnapsackProblem> KspParameter {
77      get { return (IValueParameter<BinaryKnapsackProblem>)Parameters[KspParameterName]; }
78    }
79
80    public IValueParameter<IntArray> AvailabilityParameter {
81      get { return (IValueParameter<IntArray>)Parameters[AvailabilityParameterName]; }
82    }
83
84    public IValueParameter<DoubleValue> MinSpeedParameter {
85      get { return (IValueParameter<DoubleValue>)Parameters[MinSpeedParameterName]; }
86    }
87
88    public IValueParameter<DoubleValue> MaxSpeedParameter {
89      get { return (IValueParameter<DoubleValue>)Parameters[MaxSpeedParameterName]; }
90    }
91
92    public IValueParameter<DoubleValue> RentingRatioParameter {
93      get { return (IValueParameter<DoubleValue>)Parameters[RentingRatioParameterName]; }
94    }
95    #endregion
96
97    #region Ports
98    public IMessagePort MetaSolverOrchestrationPort {
99      get { return (IMessagePort)Ports[MetaSolverName + OrchestrationPortNameSuffix]; }
100      protected set {
101        string portName = MetaSolverName + OrchestrationPortNameSuffix;
102        if (Ports.ContainsKey(portName))
103          throw new InvalidOperationException(portName + " already set.");
104        Ports.Add(value);
105        value.ConnectedPortChanged += MetaSolverOrchestrationPort_ConnectedPortChanged;
106      }
107    }
108
109    public IMessagePort MetaSolverEvaluationPort {
110      get { return (IMessagePort)Ports[MetaSolverName + EvaluationPortNameSuffix]; }
111      protected set {
112        string portName = MetaSolverName + EvaluationPortNameSuffix;
113        if (Ports.ContainsKey(portName))
114          throw new InvalidOperationException(portName + " already set.");
115        Ports.Add(value);
116      }
117    }
118
119    public IMessagePort TspSolverOrchestrationPort {
120      get { return (IMessagePort)Ports[TspSolverName + OrchestrationPortNameSuffix]; }
121      protected set {
122        string portName = TspSolverName + OrchestrationPortNameSuffix;
123        if (Ports.ContainsKey(portName))
124          throw new InvalidOperationException(portName + " already set.");
125        Ports.Add(value);
126        value.ConnectedPortChanged += TspSolverOrchestrationPort_ConnectedPortChanged;
127      }
128    }
129
130    public IMessagePort TspSolverEvaluationPort {
131      get { return (IMessagePort)Ports[TspSolverName + EvaluationPortNameSuffix]; }
132      protected set {
133        string portName = TspSolverName + EvaluationPortNameSuffix;
134        if (Ports.ContainsKey(portName))
135          throw new InvalidOperationException(portName + " already set.");
136        Ports.Add(value);
137      }
138    }
139
140    public IMessagePort KspSolverOrchestrationPort {
141      get { return (IMessagePort)Ports[KspSolverName + OrchestrationPortNameSuffix]; }
142      protected set {
143        string portName = KspSolverName + OrchestrationPortNameSuffix;
144        if (Ports.ContainsKey(portName))
145          throw new InvalidOperationException(portName + " already set.");
146        Ports.Add(value);
147        value.ConnectedPortChanged += KspSolverOrchestrationPort_ConnectedPortChanged;
148      }
149    }
150
151    public IMessagePort KspSolverEvaluationPort {
152      get { return (IMessagePort)Ports[KspSolverName + EvaluationPortNameSuffix]; }
153      protected set {
154        string portName = KspSolverName + EvaluationPortNameSuffix;
155        if (Ports.ContainsKey(portName))
156          throw new InvalidOperationException(portName + " already set.");
157        Ports.Add(value);
158      }
159    }
160    #endregion
161
162    [StorableConstructor]
163    protected TtpOrchestratorNode(bool deserializing) : base(deserializing) { }
164    protected TtpOrchestratorNode(TtpOrchestratorNode original, Cloner cloner) : base(original, cloner) {
165      tspCoordinates = (double[,])original.tspCoordinates.Clone();
166      kspCapacity = original.kspCapacity;
167      kspItemWeights = (int[])original.kspItemWeights.Clone();
168      kspItemValues = (int[])original.kspItemValues.Clone();
169      ttpAvailability = (int[])original.ttpAvailability.Clone();
170      ttpMinSpeed = original.ttpMinSpeed;
171      ttpMaxSpeed = original.ttpMaxSpeed;
172      ttpRentingRatio = original.ttpRentingRatio;
173
174      RegisterEvents();
175    }
176    protected TtpOrchestratorNode() : this("TtpOrchestratorNode") { }
177    protected TtpOrchestratorNode(string name) : base(name) {
178      Parameters.Add(new FixedValueParameter<TextFileValue>(InstanceParameterName));
179      Parameters.Add(new ValueParameter<TravelingSalesmanProblem>(TspParameterName, new TravelingSalesmanProblem()));
180      Parameters.Add(new ValueParameter<BinaryKnapsackProblem>(KspParameterName, new BinaryKnapsackProblem()));
181      Parameters.Add(new ValueParameter<IntArray>(AvailabilityParameterName));
182      Parameters.Add(new ValueParameter<DoubleValue>(MinSpeedParameterName, new DoubleValue(0.1)));
183      Parameters.Add(new ValueParameter<DoubleValue>(MaxSpeedParameterName, new DoubleValue(1.0)));
184      Parameters.Add(new ValueParameter<DoubleValue>(RentingRatioParameterName, new DoubleValue(0.5)));
185
186      InstanceParameter.Value.ToStringChanged += InstanceParameter_Value_ToStringChanged;
187    }
188
189    [StorableHook(HookType.AfterDeserialization)]
190    private void AfterDeserialization() {
191      RegisterEvents();
192    }
193
194    private void RegisterEvents() {
195      InstanceParameter.Value.ToStringChanged += InstanceParameter_Value_ToStringChanged;
196      MetaSolverOrchestrationPort.ConnectedPortChanged += MetaSolverOrchestrationPort_ConnectedPortChanged;
197      TspSolverOrchestrationPort.ConnectedPortChanged += TspSolverOrchestrationPort_ConnectedPortChanged;
198      KspSolverOrchestrationPort.ConnectedPortChanged += KspSolverOrchestrationPort_ConnectedPortChanged;
199    }
200
201    private void InstanceParameter_Value_ToStringChanged(object sender, EventArgs e) {
202      string filePath = InstanceParameter.Value.Value;
203      TtpUtils.Import(filePath, out tspCoordinates, out distanceType,
204                                out kspCapacity, out kspItemValues, out kspItemWeights,
205                                out ttpAvailability, out ttpMinSpeed, out ttpMaxSpeed, out ttpRentingRatio);
206
207      var tsp = TspParameter.Value;
208      tsp.Coordinates = new DoubleMatrix(tspCoordinates);
209      tsp.DistanceMatrix = new DistanceMatrix(TtpUtils.GetDistances(tsp.Coordinates, distanceType));
210
211      var ksp = KspParameter.Value;
212      ksp.KnapsackCapacity.Value = kspCapacity;
213      ksp.Encoding.Length = kspItemValues.Length;
214      ksp.Values = new IntArray(kspItemValues);
215      ksp.Weights = new IntArray(kspItemWeights);
216
217      AvailabilityParameter.Value = new IntArray(ttpAvailability);
218      MinSpeedParameter.Value.Value = ttpMinSpeed;
219      MaxSpeedParameter.Value.Value = ttpMaxSpeed;
220      RentingRatioParameter.Value.Value = ttpRentingRatio;
221
222      Prepare();
223    }
224
225    protected virtual void MetaSolverOrchestrationPort_ConnectedPortChanged(object sender, EventArgs e) {
226      if (MetaSolverOrchestrationPort.ConnectedPort == null) return;
227
228      var node = MetaSolverOrchestrationPort.ConnectedPort.Parent as OrchestratedAlgorithmNode;
229      if (node == null) return;
230
231      var hook = new HookOperator { Name = "Meta Eval Hook" };
232      hook.Parameters.Add(new LookupParameter<RealVector>("RealVector") { Hidden = true });
233      hook.Parameters.Add(new LookupParameter<DoubleValue>("Quality") { Hidden = true });
234      node.EvalHook = hook;
235
236      node.OrchestrationPort.CloneParametersFromPort(MetaSolverOrchestrationPort);
237      node.EvaluationPort.CloneParametersFromPort(MetaSolverEvaluationPort);
238      node.EvaluationPort.ConnectedPort = MetaSolverEvaluationPort;
239    }
240
241    protected virtual void TspSolverOrchestrationPort_ConnectedPortChanged(object sender, EventArgs e) {
242      if (TspSolverOrchestrationPort.ConnectedPort == null) return;
243
244      var node = TspSolverOrchestrationPort.ConnectedPort.Parent as OrchestratedAlgorithmNode;
245      if (node == null) return;
246
247      node.OrchestrationPort.CloneParametersFromPort(TspSolverOrchestrationPort);
248    }
249
250    protected virtual void KspSolverOrchestrationPort_ConnectedPortChanged(object sender, EventArgs e) {
251      if (KspSolverOrchestrationPort.ConnectedPort == null) return;
252
253      var node = KspSolverOrchestrationPort.ConnectedPort.Parent as OrchestratedAlgorithmNode;
254      if (node == null) return;
255
256      node.OrchestrationPort.CloneParametersFromPort(KspSolverOrchestrationPort);
257    }
258
259    public override void Prepare(bool clearRuns = false) {
260      Results.Clear();
261    }
262
263    public override void Start() {
264      cts = new CancellationTokenSource();
265
266      var metaMsg = MetaSolverOrchestrationPort.PrepareMessage();
267      metaMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Start);
268      MetaSolverOrchestrationPort.SendMessage(metaMsg);
269    }
270
271    public override void Pause() {
272      cts.Cancel();
273
274      var metaMsg = MetaSolverOrchestrationPort.PrepareMessage();
275      metaMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Pause);
276      MetaSolverOrchestrationPort.SendMessage(metaMsg);
277
278      var tspMsg = TspSolverOrchestrationPort.PrepareMessage();
279      tspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Stop);
280      TspSolverOrchestrationPort.SendMessage(tspMsg);
281
282      var kspMsg = KspSolverOrchestrationPort.PrepareMessage();
283      kspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Stop);
284      KspSolverOrchestrationPort.SendMessage(kspMsg);
285    }
286
287    public override void Stop() {
288      cts.Cancel();
289
290      var metaMsg = MetaSolverOrchestrationPort.PrepareMessage();
291      metaMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Stop);
292      MetaSolverOrchestrationPort.SendMessage(metaMsg);
293
294      var tspMsg = TspSolverOrchestrationPort.PrepareMessage();
295      tspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Stop);
296      TspSolverOrchestrationPort.SendMessage(tspMsg);
297
298      var kspMsg = KspSolverOrchestrationPort.PrepareMessage();
299      kspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Stop);
300      KspSolverOrchestrationPort.SendMessage(kspMsg);
301    }
302
303    protected override void ProcessMessage(IMessage message, IMessagePort port, CancellationToken token) {
304      var messageActions = new Dictionary<IMessagePort, Action<IMessage>>();
305      messageActions.Add(MetaSolverOrchestrationPort, MetaSolverOrchestrationPortMessage);
306      messageActions.Add(MetaSolverEvaluationPort, MetaSolverEvaluationPortMessage);
307      messageActions.Add(TspSolverOrchestrationPort, TspSolverOrchestrationPortMessage);
308      messageActions.Add(KspSolverOrchestrationPort, KspSolverOrchestrationPortMessage);
309
310      messageActions[port](message);
311
312      base.ProcessMessage(message, port, token);
313    }
314
315    #region MetaSolver Message Handling
316    protected virtual void MetaSolverOrchestrationPortMessage(IMessage message) { }
317
318    protected virtual void MetaSolverEvaluationPortMessage(IMessage message) { }
319    #endregion
320
321    #region TspSolver Message Handling
322    protected virtual void TspSolverOrchestrationPortMessage(IMessage message) { }
323
324    protected virtual void TspSolverEvaluationPortMessage(IMessage message) { }
325    #endregion
326
327    #region KspSolver Message Handling
328    protected virtual void KspSolverOrchestrationPortMessage(IMessage message) { }
329
330    private void KspSolverEvaluationPortMessage(IMessage message) { }
331    #endregion
332  }
333}
Note: See TracBrowser for help on using the repository browser.