Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization/3.3/TtpOrchestratorNode4.cs @ 14592

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

#2205: worked on optimization networks

  • added projects for integrated optimization (orchestration)
File size: 17.4 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("TtpOrchestratorNode4", "An abstract base class for an orchestrator node for the TTP.")]
22  [StorableClass]
23  public sealed class TtpOrchestratorNode4 : 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 TtpOrchestratorNode4(bool deserializing) : base(deserializing) { }
118    private TtpOrchestratorNode4(TtpOrchestratorNode4 original, Cloner cloner) : base(original, cloner) { }
119    public TtpOrchestratorNode4() : this("TtpOrchestratorNode4") { }
120    public TtpOrchestratorNode4(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 TtpOrchestratorNode4(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 = 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
196      var tsp = (TravelingSalesmanProblem)TspParameter.Value.Clone();
197      for (int j = 0; j < tsp.Coordinates.Rows; j++) {
198        tsp.Coordinates[j, 0] = (int)Math.Ceiling(tsp.Coordinates[j, 0] * factors[j * 2]);
199        tsp.Coordinates[j, 1] = (int)Math.Ceiling(tsp.Coordinates[j, 1] * factors[j * 2 + 1]);
200      }
201
202      var tspMsg = TspSolverOrchestrationPort.PrepareMessage();
203      tspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Start);
204      tspMsg["Problem"] = tsp;
205      TspSolverOrchestrationPort.SendMessage(tspMsg);
206
207      var tspResults = tspThreadResults[Thread.CurrentThread.ManagedThreadId];
208      var tour = (PathTSPTour)tspResults["Best TSP Solution"].Value;
209      tour.Coordinates = (DoubleMatrix)TspParameter.Value.Coordinates.Clone();
210      tour.Quality.Value = TSPCoordinatesPathEvaluator.Apply(new TSPEuclideanPathEvaluator(), tour.Coordinates, tour.Permutation);
211
212      var kspMsg = KspSolverOrchestrationPort.PrepareMessage();
213      kspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Start);
214      kspMsg["Problem"] = (BinaryKnapsackProblem)KspParameter.Value.Clone();
215      KspSolverOrchestrationPort.SendMessage(kspMsg);
216
217      var kspResults = kspThreadResults[Thread.CurrentThread.ManagedThreadId];
218      var bestKspSolution = (BinaryVector)kspResults["Best Solution"].Value;
219      var kspCapacity = (IntValue)KspParameter.Value.KnapsackCapacity.Clone();
220      var kspPenalty = new DoubleValue(0.0);
221      var kspWeights = (IntArray)KspParameter.Value.Weights.Clone();
222      var kspValues = (IntArray)KspParameter.Value.Values.Clone();
223      var bestKspQuality = KnapsackEvaluator.Apply(bestKspSolution, kspCapacity, kspPenalty, kspWeights, kspValues).Quality;
224      var loot = new KnapsackSolution(bestKspSolution, bestKspQuality, kspCapacity, kspWeights, kspValues);
225      kspResults.Add(new Result("Best KSP Solution", loot));
226
227      #region Analyze
228      double objectiveValue = EvaluateTtp(TspParameter.Value, tour.Permutation.ToArray(), KspParameter.Value, loot.BinaryVector.ToArray());
229      ((DoubleValue)message["Quality"]).Value = objectiveValue;
230
231      var ttpResults = new ResultCollection();
232      ttpResults.Add(new Result("Quality", new DoubleValue(objectiveValue)));
233      ttpResults.Add(new Result("Tour", tour));
234      ttpResults.Add(new Result("Loot", loot));
235
236      lock (locker) {
237        TtpResults.Add(ttpResults);
238        TspResults.Add(tspResults);
239        KspResults.Add(kspResults);
240
241        IResult bestQuality;
242        if (!Results.TryGetValue("Best TTP Quality", out bestQuality)) {
243          Results.Add(new Result("Best TTP Quality", new DoubleValue(objectiveValue)));
244          Results.Add(new Result("Best Tour", tour));
245          Results.Add(new Result("Best Loot", loot));
246        } else if (((DoubleValue)bestQuality.Value).Value < objectiveValue) {
247          ((DoubleValue)bestQuality.Value).Value = objectiveValue;
248          Results["Best Tour"].Value = tour;
249          Results["Best Loot"].Value = loot;
250        }
251      }
252      #endregion
253    }
254    #endregion
255
256    #region TspSolver Message Handling
257    private void TspSolverOrchestrationPortMessage(IMessage message) {
258      var results = (ResultCollection)message["Results"];
259      if (results.ContainsKey("Best TSP Solution")) {
260        tspThreadResults[Thread.CurrentThread.ManagedThreadId] = results;
261      }
262    }
263
264    private void TspSolverEvaluationPortMessage(IMessage message) { }
265    #endregion
266
267    #region KspSolver Message Handling
268    private void KspSolverOrchestrationPortMessage(IMessage message) {
269      var results = (ResultCollection)message["Results"];
270      if (results.ContainsKey("Best Solution")) {
271        kspThreadResults[Thread.CurrentThread.ManagedThreadId] = results;
272      }
273    }
274
275    private void KspSolverEvaluationPortMessage(IMessage message) { }
276    #endregion
277
278    #region Helpers
279    private double EvaluateTtp(TravelingSalesmanProblem tsp, int[] tour, BinaryKnapsackProblem ksp, bool[] loot) {
280      bool feasible;
281      return EvaluateTtp(tsp, tour, ksp, loot, out feasible);
282    }
283
284    private double EvaluateTtp(TravelingSalesmanProblem tsp, int[] tour, BinaryKnapsackProblem ksp, bool[] loot, out bool feasible) {
285      double collectedWeight = 0.0;
286      double objectiveValue = 0.0;
287      double infeasibleBaseLine = -1000000.0;
288      double speedCoefficient = (MaxSpeedParameter.Value.Value - MinSpeedParameter.Value.Value) / ksp.KnapsackCapacity.Value;
289
290      int hideoutIdx = 0;
291      while (tour[hideoutIdx] != 0) hideoutIdx++;
292      int cityIdx = (hideoutIdx + 1) % tour.Length;
293      int lastCityIdx = hideoutIdx;
294
295      while (cityIdx != hideoutIdx) {
296        double oldCollectedWeight = collectedWeight;
297        var availableItems = AvailabilityParameter.Value.Select((c, i) => new { CityIdx = c, ItemIdx = i }).Where(x => x.CityIdx == tour[cityIdx]);
298
299        foreach (var item in availableItems) {
300          if (!loot[item.ItemIdx]) continue;
301          collectedWeight += ksp.Weights[item.ItemIdx];
302          objectiveValue += ksp.Values[item.ItemIdx];
303        }
304
305        objectiveValue -= Distance(tsp.Coordinates.CloneAsMatrix(), tour[lastCityIdx], tour[cityIdx]) * RentingRatioParameter.Value.Value /
306                          (MaxSpeedParameter.Value.Value - speedCoefficient * oldCollectedWeight);
307        lastCityIdx = cityIdx;
308        cityIdx = (cityIdx + 1) % tour.Length;
309      }
310
311      objectiveValue -= Distance(tsp.Coordinates.CloneAsMatrix(), tour[lastCityIdx], tour[hideoutIdx]) * RentingRatioParameter.Value.Value /
312                        (MaxSpeedParameter.Value.Value - speedCoefficient * collectedWeight);
313
314      feasible = collectedWeight <= ksp.KnapsackCapacity.Value;
315      if (!feasible) objectiveValue = infeasibleBaseLine - collectedWeight;
316
317      return objectiveValue;
318    }
319
320    private double Distance(double[,] coords, int fromIdx, int toIdx) {
321      double fromX = coords[fromIdx, 0], fromY = coords[fromIdx, 1],
322             toX = coords[toIdx, 0], toY = coords[toIdx, 1];
323      return (int)Math.Ceiling(Math.Sqrt((toX - fromX) * (toX - fromX) + (toY - fromY) * (toY - fromY)));
324    }
325    #endregion
326
327    #region Event Handlers
328    private void MetaSolverOrchestrationPort_ConnectedPortChanged(object sender, EventArgs e) {
329      if (MetaSolverOrchestrationPort.ConnectedPort == null) return;
330
331      var node = MetaSolverOrchestrationPort.ConnectedPort.Parent as OrchestratedAlgorithmNode;
332      if (node == null) return;
333
334      var hook = new HookOperator { Name = "Meta Eval Hook" };
335      hook.Parameters.Add(new LookupParameter<RealVector>("RealVector") { Hidden = true });
336      hook.Parameters.Add(new LookupParameter<DoubleValue>("Quality") { Hidden = true });
337      node.EvalHook = hook;
338
339      node.OrchestrationPort.CloneParametersFromPort(MetaSolverOrchestrationPort);
340      node.EvaluationPort.CloneParametersFromPort(MetaSolverEvaluationPort);
341      node.EvaluationPort.ConnectedPort = MetaSolverEvaluationPort;
342    }
343
344    private void TspSolverOrchestrationPort_ConnectedPortChanged(object sender, EventArgs e) {
345      if (TspSolverOrchestrationPort.ConnectedPort == null) return;
346
347      var node = TspSolverOrchestrationPort.ConnectedPort.Parent as OrchestratedAlgorithmNode;
348      if (node == null) return;
349
350      var hook = new HookOperator { Name = "TSP Eval Hook" };
351      hook.Parameters.Add(new LookupParameter<Permutation>("TSPTour") { Hidden = true });
352      hook.Parameters.Add(new LookupParameter<DoubleValue>("TSPTourLength") { Hidden = true });
353      node.EvalHook = hook;
354
355      node.OrchestrationPort.CloneParametersFromPort(TspSolverOrchestrationPort);
356      node.EvaluationPort.CloneParametersFromPort(TspSolverEvaluationPort);
357      node.EvaluationPort.ConnectedPort = TspSolverEvaluationPort;
358    }
359
360    private void KspSolverOrchestrationPort_ConnectedPortChanged(object sender, EventArgs e) {
361      if (KspSolverOrchestrationPort.ConnectedPort == null) return;
362
363      var node = KspSolverOrchestrationPort.ConnectedPort.Parent as OrchestratedAlgorithmNode;
364      if (node == null) return;
365
366      var hook = new HookOperator { Name = "KSP Eval Hook" };
367      hook.Parameters.Add(new LookupParameter<BinaryVector>("KnapsackSolution") { Hidden = true });
368      hook.Parameters.Add(new LookupParameter<DoubleValue>("Quality") { Hidden = true });
369      node.EvalHook = hook;
370
371      node.OrchestrationPort.CloneParametersFromPort(KspSolverOrchestrationPort);
372      node.EvaluationPort.CloneParametersFromPort(KspSolverEvaluationPort);
373      node.EvaluationPort.ConnectedPort = KspSolverEvaluationPort;
374    }
375    #endregion
376  }
377}
Note: See TracBrowser for help on using the repository browser.