Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 14604 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: 20.9 KB
Line 
1//using System;
2//using System.Collections.Concurrent;
3//using System.Collections.Generic;
4//using System.Linq;
5//using System.Threading;
6//using HeuristicLab.Common;
7//using HeuristicLab.Core;
8//using HeuristicLab.Core.Networks;
9//using HeuristicLab.Data;
10//using HeuristicLab.Encodings.BinaryVectorEncoding;
11//using HeuristicLab.Encodings.PermutationEncoding;
12//using HeuristicLab.Encodings.RealVectorEncoding;
13//using HeuristicLab.Operators;
14//using HeuristicLab.Optimization;
15//using HeuristicLab.Parameters;
16//using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
17//using HeuristicLab.Problems.Knapsack;
18//using HeuristicLab.Problems.TravelingSalesman;
19
20//namespace HeuristicLab.Networks.IntegratedOptimization {
21//  [Item("TtpOrchestratorNode2", "An abstract base class for an orchestrator node for the TTP.")]
22//  [StorableClass]
23//  public sealed class TtpOrchestratorNode2 : 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 IMessagePort MetaSolverOrchestrationPort {
78//      get { return (IMessagePort)Ports[MetaSolverName + OrchestrationPortNameSuffix]; }
79//    }
80
81//    public IMessagePort MetaSolverEvaluationPort {
82//      get { return (IMessagePort)Ports[MetaSolverName + EvaluationPortNameSuffix]; }
83//    }
84
85//    public IMessagePort TspSolverOrchestrationPort {
86//      get { return (IMessagePort)Ports[TspSolverName + OrchestrationPortNameSuffix]; }
87//    }
88
89//    public IMessagePort TspSolverEvaluationPort {
90//      get { return (IMessagePort)Ports[TspSolverName + EvaluationPortNameSuffix]; }
91//    }
92
93//    public IMessagePort KspSolverOrchestrationPort {
94//      get { return (IMessagePort)Ports[KspSolverName + OrchestrationPortNameSuffix]; }
95//    }
96
97//    public IMessagePort KspSolverEvaluationPort {
98//      get { return (IMessagePort)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 TtpOrchestratorNode2(bool deserializing) : base(deserializing) { }
118//    private TtpOrchestratorNode2(TtpOrchestratorNode2 original, Cloner cloner) : base(original, cloner) { }
119//    public TtpOrchestratorNode2() : this("TtpOrchestratorNode2") { }
120//    public TtpOrchestratorNode2(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 TtpOrchestratorNode2(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 = KspParameter.Value.Length;
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 ksp = (BinaryKnapsackProblem)KspParameter.Value.Clone();
197//      for (int i = 0; i < factors.Length; i++)
198//        ksp.Values[i] = (int)Math.Ceiling(ksp.Values[i] * factors[i]);
199
200//      var kspMsg = KspSolverOrchestrationPort.PrepareMessage();
201//      kspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Start);
202//      kspMsg["Problem"] = ksp;
203//      KspSolverOrchestrationPort.SendMessage(kspMsg);
204
205//      var kspResults = kspThreadResults[Thread.CurrentThread.ManagedThreadId];
206//      var bestKspSolution = (BinaryVector)kspResults["Best Solution"].Value;
207//      var kspCapacity = (IntValue)KspParameter.Value.KnapsackCapacity.Clone();
208//      var kspPenalty = new DoubleValue(0.0);
209//      var kspWeights = (IntArray)KspParameter.Value.Weights.Clone();
210//      var kspValues = (IntArray)KspParameter.Value.Values.Clone();
211//      var bestKspQuality = KnapsackEvaluator.Apply(bestKspSolution, kspCapacity, kspPenalty, kspWeights, kspValues).Quality;
212//      var loot = new KnapsackSolution(bestKspSolution, bestKspQuality, kspCapacity, kspWeights, kspValues);
213//      kspResults.Add(new Result("Best KSP Solution", loot));
214
215//      var tspMsg = TspSolverOrchestrationPort.PrepareMessage();
216//      tspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Start);
217//      tspMsg["Problem"] = ReduceTsp(bestKspSolution.ToArray());
218//      TspSolverOrchestrationPort.SendMessage(tspMsg);
219
220//      var tspResults = tspThreadResults[Thread.CurrentThread.ManagedThreadId];
221//      var tour = (PathTSPTour)tspResults["Best TSP Solution"].Value;
222//      tour.Coordinates = (DoubleMatrix)TspParameter.Value.Coordinates.Clone();
223//      tour.Quality.Value = TSPCoordinatesPathEvaluator.Apply(new TSPEuclideanPathEvaluator(), tour.Coordinates, tour.Permutation);
224
225//      #region Analyze
226//      int[] cityMapping = MapCities(loot.BinaryVector.ToArray());
227//      double objectiveValue = EvaluateTtp(TspParameter.Value, tour.Permutation.Select(x => cityMapping[x]).ToArray(), KspParameter.Value, loot.BinaryVector.ToArray());
228//      ((DoubleValue)message["Quality"]).Value = objectiveValue;
229
230//      var ttpResults = new ResultCollection();
231//      ttpResults.Add(new Result("Quality", new DoubleValue(objectiveValue)));
232//      ttpResults.Add(new Result("Tour", tour));
233//      ttpResults.Add(new Result("Loot", loot));
234
235//      lock (locker) {
236//        TtpResults.Add(ttpResults);
237//        TspResults.Add(tspResults);
238//        KspResults.Add(kspResults);
239
240//        IResult bestQuality;
241//        if (!Results.TryGetValue("Best TTP Quality", out bestQuality)) {
242//          Results.Add(new Result("Best TTP Quality", new DoubleValue(objectiveValue)));
243//          Results.Add(new Result("Best Tour", tour));
244//          Results.Add(new Result("Best Loot", loot));
245//        } else if (((DoubleValue)bestQuality.Value).Value < objectiveValue) {
246//          ((DoubleValue)bestQuality.Value).Value = objectiveValue;
247//          Results["Best Tour"].Value = tour;
248//          Results["Best Loot"].Value = loot;
249//        }
250//      }
251//      #endregion
252//    }
253//    #endregion
254
255//    #region TspSolver Message Handling
256//    private void TspSolverOrchestrationPortMessage(IMessage message) {
257//      var results = (ResultCollection)message["Results"];
258//      if (results.ContainsKey("Best TSP Solution")) {
259//        tspThreadResults[Thread.CurrentThread.ManagedThreadId] = results;
260//      }
261//    }
262
263//    private void TspSolverEvaluationPortMessage(IMessage message) { }
264//    #endregion
265
266//    #region KspSolver Message Handling
267//    private void KspSolverOrchestrationPortMessage(IMessage message) {
268//      var results = (ResultCollection)message["Results"];
269//      if (results.ContainsKey("Best Solution")) {
270//        kspThreadResults[Thread.CurrentThread.ManagedThreadId] = results;
271//      }
272//    }
273
274//    private void KspSolverEvaluationPortMessage(IMessage message) { }
275//    #endregion
276
277//    #region Helpers
278//    private TravelingSalesmanProblem ReduceTsp(bool[] selectedItems) {
279//      var selection = MapCities(selectedItems);
280//      var problem = (TravelingSalesmanProblem)TspParameter.Value.Clone();
281//      var originalCoordinates = problem.Coordinates;
282
283//      var coordinates = new DoubleMatrix(selection.Length, 2);
284//      for (int i = 0; i < selection.Length; i++) {
285//        coordinates[i, 0] = originalCoordinates[selection[i], 0];
286//        coordinates[i, 1] = originalCoordinates[selection[i], 1];
287//      }
288//      problem.Coordinates = coordinates;
289//      return problem;
290//    }
291
292//    #region Commented VariegateKsp
293//    /*
294//    private BinaryKnapsackProblem VariegateKsp(TravelingSalesmanProblem tsp, int[] tour, BinaryKnapsackProblem ksp, bool[] loot) {
295//      int[] cities = Enumerable.Range(0, TspParameter.Value.SolutionCreator.LengthParameter.Value.Value).ToArray();
296//      int[] cityMapping = MapCities(loot);
297//      int[] deselectedCities = cities.Except(cityMapping).ToArray();
298//      double quality = EvaluateTtp(tsp, tour.Select(x => cityMapping[x]).ToArray(), ksp, loot);
299
300//      var increase = new HashSet<int>();
301
302//      foreach (var dc in deselectedCities) {
303//        var availableItems = AvailabilityParameter.Value.Select((c, i) => new { CityIdx = c, ItemIdx = i }).Where(x => x.CityIdx == dc).ToArray();
304//        if (!availableItems.Any()) continue;
305
306//        // build new loot
307//        bool[] newLoot = (bool[])loot.Clone();
308//        newLoot[availableItems[0].ItemIdx] = true;
309
310//        // build new ksp
311//        var newKsp = (BinaryKnapsackProblem)ksp.Clone();
312//        int avgValue = (int)Math.Round(availableItems.Average(x => newKsp.Values[x.ItemIdx]));
313//        int avgWeight = (int)Math.Round(availableItems.Average(x => newKsp.Weights[x.ItemIdx]));
314//        newKsp.Values[availableItems[0].ItemIdx] = avgValue;
315//        newKsp.Weights[availableItems[0].ItemIdx] = avgWeight;
316
317//        bool better = false;
318//        for (int i = 1; i < cityMapping.Length; i++) {
319//          // evaluate
320//          var newCityMapping = (int[])cityMapping.Clone();
321//          newCityMapping[i] = dc;
322//          double q = EvaluateTtp(tsp, tour.Select(x => newCityMapping[x]).ToArray(), newKsp, newLoot);
323//          if (q > quality) {
324//            better = true;
325//            break;
326//          }
327//        }
328
329//        if (better)
330//          foreach (var item in availableItems)
331//            increase.Add(item.ItemIdx);
332//      }
333
334//      var result = (BinaryKnapsackProblem)ksp.Clone();
335//      if (increase.Any()) {
336//        // increase values by 5 %
337//        foreach (var itemIndex in increase)
338//          result.Values[itemIndex] = (int)Math.Ceiling(result.Values[itemIndex] * 1.05);
339//      }
340//      return result;
341//    }
342//    */
343//    #endregion
344
345//    private double EvaluateTtp(TravelingSalesmanProblem tsp, int[] tour, BinaryKnapsackProblem ksp, bool[] loot) {
346//      bool feasible;
347//      return EvaluateTtp(tsp, tour, ksp, loot, out feasible);
348//    }
349
350//    private double EvaluateTtp(TravelingSalesmanProblem tsp, int[] tour, BinaryKnapsackProblem ksp, bool[] loot, out bool feasible) {
351//      double collectedWeight = 0.0;
352//      double objectiveValue = 0.0;
353//      double infeasibleBaseLine = -1000000.0;
354//      double speedCoefficient = (MaxSpeedParameter.Value.Value - MinSpeedParameter.Value.Value) / ksp.KnapsackCapacity.Value;
355
356//      int hideoutIdx = 0;
357//      while (tour[hideoutIdx] != 0) hideoutIdx++;
358//      int cityIdx = (hideoutIdx + 1) % tour.Length;
359//      int lastCityIdx = hideoutIdx;
360
361//      while (cityIdx != hideoutIdx) {
362//        double oldCollectedWeight = collectedWeight;
363//        var availableItems = AvailabilityParameter.Value.Select((c, i) => new { CityIdx = c, ItemIdx = i }).Where(x => x.CityIdx == tour[cityIdx]);
364
365//        foreach (var item in availableItems) {
366//          if (!loot[item.ItemIdx]) continue;
367//          collectedWeight += ksp.Weights[item.ItemIdx];
368//          objectiveValue += ksp.Values[item.ItemIdx];
369//        }
370
371//        objectiveValue -= Distance(tsp.Coordinates.CloneAsMatrix(), tour[lastCityIdx], tour[cityIdx]) * RentingRatioParameter.Value.Value /
372//                          (MaxSpeedParameter.Value.Value - speedCoefficient * oldCollectedWeight);
373//        lastCityIdx = cityIdx;
374//        cityIdx = (cityIdx + 1) % tour.Length;
375//      }
376
377//      objectiveValue -= Distance(tsp.Coordinates.CloneAsMatrix(), tour[lastCityIdx], tour[hideoutIdx]) * RentingRatioParameter.Value.Value /
378//                        (MaxSpeedParameter.Value.Value - speedCoefficient * collectedWeight);
379
380//      feasible = collectedWeight <= ksp.KnapsackCapacity.Value;
381//      if (!feasible) objectiveValue = infeasibleBaseLine - collectedWeight;
382
383//      return objectiveValue;
384//    }
385
386//    private int[] MapCities(bool[] loot) {
387//      var map = new HashSet<int> { 0 };
388//      for (int i = 0; i < loot.Length; i++)
389//        if (loot[i]) map.Add(AvailabilityParameter.Value[i]);
390//      return map.OrderBy(x => x).ToArray();
391//    }
392
393//    private double Distance(double[,] coords, int fromIdx, int toIdx) {
394//      double fromX = coords[fromIdx, 0], fromY = coords[fromIdx, 1],
395//             toX = coords[toIdx, 0], toY = coords[toIdx, 1];
396//      return (int)Math.Ceiling(Math.Sqrt((toX - fromX) * (toX - fromX) + (toY - fromY) * (toY - fromY)));
397//    }
398//    #endregion
399
400//    #region Event Handlers
401//    private void MetaSolverOrchestrationPort_ConnectedPortChanged(object sender, EventArgs e) {
402//      if (MetaSolverOrchestrationPort.ConnectedPort == null) return;
403
404//      var node = MetaSolverOrchestrationPort.ConnectedPort.Parent as OrchestratedAlgorithmNode;
405//      if (node == null) return;
406
407//      var hook = new HookOperator { Name = "Meta Eval Hook" };
408//      hook.Parameters.Add(new LookupParameter<RealVector>("RealVector") { Hidden = true });
409//      hook.Parameters.Add(new LookupParameter<DoubleValue>("Quality") { Hidden = true });
410//      node.EvalHook = hook;
411
412//      node.OrchestrationPort.CloneParametersFromPort(MetaSolverOrchestrationPort);
413//      node.EvaluationPort.CloneParametersFromPort(MetaSolverEvaluationPort);
414//      node.EvaluationPort.ConnectedPort = MetaSolverEvaluationPort;
415//    }
416
417//    private void TspSolverOrchestrationPort_ConnectedPortChanged(object sender, EventArgs e) {
418//      if (TspSolverOrchestrationPort.ConnectedPort == null) return;
419
420//      var node = TspSolverOrchestrationPort.ConnectedPort.Parent as OrchestratedAlgorithmNode;
421//      if (node == null) return;
422
423//      var hook = new HookOperator { Name = "TSP Eval Hook" };
424//      hook.Parameters.Add(new LookupParameter<Permutation>("TSPTour") { Hidden = true });
425//      hook.Parameters.Add(new LookupParameter<DoubleValue>("TSPTourLength") { Hidden = true });
426//      node.EvalHook = hook;
427
428//      node.OrchestrationPort.CloneParametersFromPort(TspSolverOrchestrationPort);
429//      node.EvaluationPort.CloneParametersFromPort(TspSolverEvaluationPort);
430//      node.EvaluationPort.ConnectedPort = TspSolverEvaluationPort;
431//    }
432
433//    private void KspSolverOrchestrationPort_ConnectedPortChanged(object sender, EventArgs e) {
434//      if (KspSolverOrchestrationPort.ConnectedPort == null) return;
435
436//      var node = KspSolverOrchestrationPort.ConnectedPort.Parent as OrchestratedAlgorithmNode;
437//      if (node == null) return;
438
439//      var hook = new HookOperator { Name = "KSP Eval Hook" };
440//      hook.Parameters.Add(new LookupParameter<BinaryVector>("KnapsackSolution") { Hidden = true });
441//      hook.Parameters.Add(new LookupParameter<DoubleValue>("Quality") { Hidden = true });
442//      node.EvalHook = hook;
443
444//      node.OrchestrationPort.CloneParametersFromPort(KspSolverOrchestrationPort);
445//      node.EvaluationPort.CloneParametersFromPort(KspSolverEvaluationPort);
446//      node.EvaluationPort.ConnectedPort = KspSolverEvaluationPort;
447//    }
448//    #endregion
449//  }
450//}
Note: See TracBrowser for help on using the repository browser.