Changeset 14601 for branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization.TravelingThief
- Timestamp:
- 01/24/17 09:31:29 (8 years ago)
- Location:
- branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization.TravelingThief
- Files:
-
- 10 added
- 3 copied
- 6 moved
Legend:
- Unmodified
- Added
- Removed
-
branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization.TravelingThief/3.3/Problems/BinaryKnapsackProblem.cs
r14598 r14601 1 using System; 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 22 using System; 2 23 using HeuristicLab.Common; 3 24 using HeuristicLab.Core; … … 8 29 using HeuristicLab.Problems.Binary; 9 30 10 namespace HeuristicLab.Networks.IntegratedOptimization {31 namespace HeuristicLab.Networks.IntegratedOptimization.TravelingThief { 11 32 [Item("Binary Knapsack Problem (BKSP)", "Represents a problem whose objective is to maximize the number of true values.")] 12 33 [Creatable(CreatableAttribute.Categories.CombinatorialProblems, Priority = 999)] -
branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization.TravelingThief/3.3/Problems/LootProfitProblem.cs
r14598 r14601 1 using System; 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 2 22 using System.Collections.Generic; 3 23 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 24 using HeuristicLab.Common; 25 using HeuristicLab.Core; 26 using HeuristicLab.Encodings.BinaryVectorEncoding; 27 using HeuristicLab.Encodings.PermutationEncoding; 28 using HeuristicLab.Optimization; 29 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 30 using HeuristicLab.Problems.Binary; 31 using HeuristicLab.Problems.TravelingSalesman; 6 32 7 namespace HeuristicLab.Networks.IntegratedOptimization.Problems { 8 class LootProfitProblem { 33 namespace HeuristicLab.Networks.IntegratedOptimization.TravelingThief { 34 [Item("Loot Profit Problem", "Represents a problem whose objective is to optimize a TTP loot for fixed TTP tour.")] 35 [Creatable(CreatableAttribute.Categories.Problems, Priority = 999)] 36 [StorableClass] 37 public class LootProfitProblem : BinaryProblem { 38 public override bool Maximization { 39 get { return true; } 40 } 41 42 [Storable] 43 public TravelingSalesmanProblem Tsp { get; set; } 44 [Storable] 45 public BinaryKnapsackProblem Ksp { get; set; } 46 [Storable] 47 public Permutation FixedTspSolution { get; set; } 48 [Storable] 49 public int[] Availability { get; set; } 50 [Storable] 51 public double RentingRatio { get; set; } 52 [Storable] 53 public double MinSpeed { get; set; } 54 [Storable] 55 public double MaxSpeed { get; set; } 56 57 [StorableConstructor] 58 protected LootProfitProblem(bool deserializing) : base(deserializing) { } 59 protected LootProfitProblem(LootProfitProblem original, Cloner cloner) : base(original, cloner) { 60 Tsp = cloner.Clone(original.Tsp); 61 Ksp = cloner.Clone(original.Ksp); 62 FixedTspSolution = cloner.Clone(original.FixedTspSolution); 63 Availability = original.Availability != null ? (int[])original.Availability.Clone() : null; 64 RentingRatio = original.RentingRatio; 65 MinSpeed = original.MinSpeed; 66 MaxSpeed = original.MaxSpeed; 67 } 68 public LootProfitProblem() : base() { 69 Encoding.Length = 5; 70 } 71 72 public override IDeepCloneable Clone(Cloner cloner) { 73 return new LootProfitProblem(this, cloner); 74 } 75 76 public override double Evaluate(BinaryVector vector, IRandom random) { 77 return TtpUtils.EvaluateTtp(Tsp, FixedTspSolution.ToArray(), 78 Ksp, vector.ToArray(), 79 Availability, RentingRatio, MinSpeed, MaxSpeed); 80 } 81 82 public override IEnumerable<Individual> GetNeighbors(Individual individual, IRandom random) { 83 while (true) { 84 var neighbor = individual.Copy(); 85 SinglePositionBitflipManipulator.Apply(random, neighbor.BinaryVector()); break; 86 yield return neighbor; 87 } 88 } 9 89 } 10 90 } -
branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization.TravelingThief/3.3/Problems/TourProfitProblem.cs
r14598 r14601 1 using System.Collections.Generic; 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 22 using System.Collections.Generic; 2 23 using System.Linq; 3 24 using HeuristicLab.Common; … … 9 30 using HeuristicLab.Problems.TravelingSalesman; 10 31 11 namespace HeuristicLab.Networks.IntegratedOptimization {32 namespace HeuristicLab.Networks.IntegratedOptimization.TravelingThief { 12 33 [Item("Tour Profit Problem", "Represents a problem whose objective is to optimize a TTP tour for fixed TTP loot.")] 13 34 [Creatable(CreatableAttribute.Categories.Problems, Priority = 999)] … … 53 74 54 75 public override double Evaluate(Individual individual, IRandom random) { 55 return TtpUtils.EvaluateTtp(Tsp, individual.Permutation(). CloneAsArray(),56 Ksp, FixedKspSolution. CloneAsArray(),76 return TtpUtils.EvaluateTtp(Tsp, individual.Permutation().ToArray(), 77 Ksp, FixedKspSolution.ToArray(), 57 78 Availability, RentingRatio, MinSpeed, MaxSpeed); 58 79 } -
branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization.TravelingThief/3.3/TtpImporter.cs
r14598 r14601 2 2 using HeuristicLab.Data; 3 3 4 namespace HeuristicLab.Networks.IntegratedOptimization {4 namespace HeuristicLab.Networks.IntegratedOptimization.TravelingThief { 5 5 public static class TtpImporter { 6 6 public static void ImportTtpInstance(string filePath, out DoubleMatrix tspCoordinates, -
branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization.TravelingThief/3.3/TtpNetwork1.cs
r14600 r14601 1 using System; 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 22 using System; 2 23 using System.Collections.Generic; 3 24 using HeuristicLab.Algorithms.CMAEvolutionStrategy; … … 11 32 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 12 33 13 namespace HeuristicLab.Networks.IntegratedOptimization {14 [Item("TtpNetwork 5", "An optimization network for the TTP.")]34 namespace HeuristicLab.Networks.IntegratedOptimization.TravelingThief { 35 [Item("TtpNetwork1", "Version 1 of a TTP optimization network.")] 15 36 [Creatable("Optimization Networks")] 16 37 [StorableClass] 17 // standard ttp 18 // cmaes variegates ksp values (factors) 19 // 1) init cmaes (length = ksp.values.length) 20 // 2) start cmaes 21 // 3) evaluate vector as follows: 22 // 4) change ksp values (mult by factor in vector) 23 // 5) best ksp 24 // 6) best tsp for ksp selection 25 // 7) return ttp quality 26 public sealed class TtpNetwork5 : Network, IOptimizer { 38 public sealed class TtpNetwork1 : Network, IOptimizer { 27 39 #region Nodes 28 public TtpOrchestratorNode 5Orchestrator {29 get { return (TtpOrchestratorNode 5)Nodes["Orchestrator"]; }40 public TtpOrchestratorNode1 Orchestrator { 41 get { return (TtpOrchestratorNode1)Nodes["Orchestrator"]; } 30 42 } 31 43 … … 44 56 45 57 [StorableConstructor] 46 private TtpNetwork 5(bool deserializing) : base(deserializing) { }47 private TtpNetwork 5(TtpNetwork5original, Cloner cloner) : base(original, cloner) {58 private TtpNetwork1(bool deserializing) : base(deserializing) { } 59 private TtpNetwork1(TtpNetwork1 original, Cloner cloner) : base(original, cloner) { 48 60 RegisterEvents(); 49 61 } … … 59 71 } 60 72 61 public TtpNetwork 5() : base("TtpNetwork5") {62 var orchestratorNode = new TtpOrchestratorNode 5("Orchestrator");73 public TtpNetwork1() : base("TtpNetwork1") { 74 var orchestratorNode = new TtpOrchestratorNode1("Orchestrator"); 63 75 Nodes.Add(orchestratorNode); 64 76 … … 70 82 orchestratorNode.MetaSolverOrchestrationPort.ConnectedPort = metaSolverNode.OrchestrationPort; 71 83 Nodes.Add(metaSolverNode); 72 73 //var tspSolverNode = new OrchestratedAlgorithmNode("TspSolver");74 //var osga = new OffspringSelectionGeneticAlgorithm();75 //osga.Problem = new TourProfitProblem();76 //osga.ComparisonFactorLowerBound.Value = 1.0;77 //osga.ComparisonFactorModifier = null;78 //osga.ComparisonFactorUpperBound.Value = 1.0;79 //var crossover = (MultiPermutationCrossover)(osga.Crossover = osga.CrossoverParameter.ValidValues.First(x => x is MultiPermutationCrossover));80 //foreach (var c in crossover.Operators)81 // crossover.Operators.SetItemCheckedState(c, c is CosaCrossover || c is OrderCrossover2 || c is PartiallyMatchedCrossover);82 //osga.MaximumSelectionPressure.Value = 200;83 //osga.Mutator = osga.MutatorParameter.ValidValues.First(x => x is MultiPermutationManipulator);84 //osga.PopulationSize.Value = 200;85 //osga.Selector = osga.SelectorParameter.ValidValues.First(x => x is RandomSelector);86 //tspSolverNode.Algorithm = osga;87 //orchestratorNode.TspSolverOrchestrationPort.ConnectedPort = tspSolverNode.OrchestrationPort;88 //Nodes.Add(tspSolverNode);89 84 90 85 var tspSolverNode = new OrchestratedAlgorithmNode("TspSolver"); … … 109 104 IntValue kspCapacity; IntArray kspItemWeights; IntArray kspItemValues; 110 105 IntArray ttpAvailability; DoubleValue ttpMinSpeed; DoubleValue ttpMaxSpeed; DoubleValue ttpRentingRatio; 111 TtpImporter.ImportTtpInstance(@"ttp-instances\berlin52-ttp\berlin52_n51_uncorr -similar-weights_05.ttp",106 TtpImporter.ImportTtpInstance(@"ttp-instances\berlin52-ttp\berlin52_n51_uncorr_01.ttp", 112 107 out tspCoordinates, 113 108 out kspCapacity, out kspItemValues, out kspItemWeights, … … 133 128 134 129 public override IDeepCloneable Clone(Cloner cloner) { 135 return new TtpNetwork 5(this, cloner);130 return new TtpNetwork1(this, cloner); 136 131 } 137 132 -
branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization.TravelingThief/3.3/TtpNetwork3.cs
r14598 r14601 1 //using HeuristicLab.Algorithms.CMAEvolutionStrategy; 2 //using HeuristicLab.Algorithms.LocalSearch; 3 //using HeuristicLab.Algorithms.ParameterlessPopulationPyramid; 4 //using HeuristicLab.Common; 5 //using HeuristicLab.Core; 6 //using HeuristicLab.Core.Networks; 7 //using HeuristicLab.Data; 8 //using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 9 10 //namespace HeuristicLab.Networks.IntegratedOptimization { 11 // [Item("TtpNetwork3", "An optimization network for the TTP.")] 12 // [Creatable("Optimization Networks")] 13 // [StorableClass] 14 // // standard ttp 15 // // cmaes variegates ksp values and tsp coordinates 16 // // 1) init cmaes (length = ksp.values.length) 17 // // 2) start cmaes 18 // // 3) evaluate vector as follows: 19 // // 4) change ksp values and tsp coordinates (mult by factor in vector) 20 // // 5) best ksp 21 // // 6) best tsp 22 // // 7) return ttp quality 23 // public sealed class TtpNetwork3 : Network { 24 // [StorableConstructor] 25 // private TtpNetwork3(bool deserializing) : base(deserializing) { } 26 // private TtpNetwork3(TtpNetwork3 original, Cloner cloner) : base(original, cloner) { } 27 // public TtpNetwork3() : base("TtpNetwork3") { 28 // var orchestratorNode = new TtpOrchestratorNode3(); 29 // Nodes.Add(orchestratorNode); 30 31 // var metaSolverNode = new OrchestratedAlgorithmNode("MetaSolver"); 32 // var cmaes = new CMAEvolutionStrategy(); 33 // cmaes.MaximumEvaluatedSolutions = 3000; 34 // cmaes.Engine = new ParallelEngine.ParallelEngine(); 35 // metaSolverNode.Algorithm = cmaes; 36 // orchestratorNode.MetaSolverOrchestrationPort.ConnectedPort = metaSolverNode.OrchestrationPort; 37 // Nodes.Add(metaSolverNode); 38 39 // var tspSolverNode = new OrchestratedAlgorithmNode("TspSolver") { CloneAlgorithm = true }; 40 // var ls = new LocalSearch(); 41 // ls.Problem = orchestratorNode.TspParameter.Value; 42 // ls.MaximumIterations.Value = 100; 43 // tspSolverNode.Algorithm = ls; 44 // orchestratorNode.TspSolverOrchestrationPort.ConnectedPort = tspSolverNode.OrchestrationPort; 45 // Nodes.Add(tspSolverNode); 46 47 // var kspSolverNode = new OrchestratedAlgorithmNode("KspSolver") { CloneAlgorithm = true }; 48 // var p3 = new ParameterlessPopulationPyramid(); 49 // p3.Problem = orchestratorNode.KspParameter.Value; 50 // p3.MaximumRuntime = 3; 51 // kspSolverNode.Algorithm = p3; 52 // orchestratorNode.KspSolverOrchestrationPort.ConnectedPort = kspSolverNode.OrchestrationPort; 53 // Nodes.Add(kspSolverNode); 54 55 // #region Import 56 // DoubleMatrix tspCoordinates; 57 // IntValue kspCapacity; IntArray kspItemWeights; IntArray kspItemValues; 58 // IntArray ttpAvailability; DoubleValue ttpMinSpeed; DoubleValue ttpMaxSpeed; DoubleValue ttpRentingRatio; 59 // TtpImporter.ImportTtpInstance(@"ttp-instances\berlin52-ttp\berlin52_n51_uncorr_01.ttp", 60 // out tspCoordinates, 61 // out kspCapacity, out kspItemValues, out kspItemWeights, 62 // out ttpAvailability, out ttpMinSpeed, out ttpMaxSpeed, out ttpRentingRatio); 63 64 // var tsp = orchestratorNode.TspParameter.Value; 65 // tsp.Coordinates = tspCoordinates; 66 67 // var ksp = orchestratorNode.KspParameter.Value; 68 // ksp.KnapsackCapacity = kspCapacity; 69 // ksp.Encoding.Length = kspItemValues.Length; 70 // ksp.Values = kspItemValues; 71 // ksp.Weights = kspItemWeights; 72 73 // orchestratorNode.AvailabilityParameter.Value = ttpAvailability; 74 // orchestratorNode.MinSpeedParameter.Value = ttpMinSpeed; 75 // orchestratorNode.MaxSpeedParameter.Value = ttpMaxSpeed; 76 // orchestratorNode.RentingRatioParameter.Value = ttpRentingRatio; 77 // #endregion 78 // } 79 80 // public override IDeepCloneable Clone(Cloner cloner) { 81 // return new TtpNetwork3(this, cloner); 82 // } 83 // } 84 //} 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 22 using System; 23 using System.Collections.Generic; 24 using HeuristicLab.Algorithms.CMAEvolutionStrategy; 25 using HeuristicLab.Algorithms.LocalSearch; 26 using HeuristicLab.Algorithms.ParameterlessPopulationPyramid; 27 using HeuristicLab.Common; 28 using HeuristicLab.Core; 29 using HeuristicLab.Core.Networks; 30 using HeuristicLab.Data; 31 using HeuristicLab.Optimization; 32 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 33 34 namespace HeuristicLab.Networks.IntegratedOptimization.TravelingThief { 35 [Item("TtpNetwork3", "Version 3 of a TTP optimization network.")] 36 [Creatable("Optimization Networks")] 37 [StorableClass] 38 public sealed class TtpNetwork3 : Network, IOptimizer { 39 #region Nodes 40 public TtpOrchestratorNode1 Orchestrator { 41 get { return (TtpOrchestratorNode1)Nodes["Orchestrator"]; } 42 } 43 44 public OrchestratedAlgorithmNode MetaSolver { 45 get { return (OrchestratedAlgorithmNode)Nodes["MetaSolver"]; } 46 } 47 48 public OrchestratedAlgorithmNode TspSolver { 49 get { return (OrchestratedAlgorithmNode)Nodes["TspSolver"]; } 50 } 51 52 public OrchestratedAlgorithmNode KspSolver { 53 get { return (OrchestratedAlgorithmNode)Nodes["KspSolver"]; } 54 } 55 #endregion 56 57 [StorableConstructor] 58 private TtpNetwork3(bool deserializing) : base(deserializing) { } 59 private TtpNetwork3(TtpNetwork3 original, Cloner cloner) : base(original, cloner) { 60 RegisterEvents(); 61 } 62 63 private void RegisterEvents() { 64 MetaSolver.Algorithm.ExecutionStateChanged += OnExecutionStateChanged; 65 MetaSolver.Algorithm.ExecutionTimeChanged += OnExecutionTimeChanged; 66 MetaSolver.Algorithm.Prepared += OnPrepared; 67 MetaSolver.Algorithm.Started += OnStarted; 68 MetaSolver.Algorithm.Paused += OnPaused; 69 MetaSolver.Algorithm.Stopped += OnStopped; 70 MetaSolver.Algorithm.ExceptionOccurred += OnExceptionOccurred; 71 } 72 73 public TtpNetwork3() : base("TtpNetwork3") { 74 var orchestratorNode = new TtpOrchestratorNode3("Orchestrator"); 75 Nodes.Add(orchestratorNode); 76 77 var metaSolverNode = new OrchestratedAlgorithmNode("MetaSolver"); 78 var cmaes = new CMAEvolutionStrategy(); 79 cmaes.Problem = new VariegationProblem(); 80 cmaes.MaximumGenerations = 80; 81 metaSolverNode.Algorithm = cmaes; 82 orchestratorNode.MetaSolverOrchestrationPort.ConnectedPort = metaSolverNode.OrchestrationPort; 83 Nodes.Add(metaSolverNode); 84 85 var tspSolverNode = new OrchestratedAlgorithmNode("TspSolver"); 86 var ls = new LocalSearch(); 87 ls.Problem = orchestratorNode.KspParameter.Value; 88 ls.MaximumIterations.Value = 100; 89 ls.SampleSize.Value = 2000; 90 tspSolverNode.Algorithm = ls; 91 orchestratorNode.TspSolverOrchestrationPort.ConnectedPort = tspSolverNode.OrchestrationPort; 92 Nodes.Add(tspSolverNode); 93 94 var kspSolverNode = new OrchestratedAlgorithmNode("KspSolver"); 95 var p3 = new ParameterlessPopulationPyramid(); 96 p3.Problem = orchestratorNode.KspParameter.Value; 97 p3.MaximumRuntime = 3; 98 kspSolverNode.Algorithm = p3; 99 orchestratorNode.KspSolverOrchestrationPort.ConnectedPort = kspSolverNode.OrchestrationPort; 100 Nodes.Add(kspSolverNode); 101 102 #region Import 103 DoubleMatrix tspCoordinates; 104 IntValue kspCapacity; IntArray kspItemWeights; IntArray kspItemValues; 105 IntArray ttpAvailability; DoubleValue ttpMinSpeed; DoubleValue ttpMaxSpeed; DoubleValue ttpRentingRatio; 106 TtpImporter.ImportTtpInstance(@"ttp-instances\berlin52-ttp\berlin52_n51_uncorr_01.ttp", 107 out tspCoordinates, 108 out kspCapacity, out kspItemValues, out kspItemWeights, 109 out ttpAvailability, out ttpMinSpeed, out ttpMaxSpeed, out ttpRentingRatio); 110 111 var tsp = orchestratorNode.TspParameter.Value; 112 tsp.Coordinates = tspCoordinates; 113 114 var ksp = orchestratorNode.KspParameter.Value; 115 ksp.KnapsackCapacity = kspCapacity; 116 ksp.Encoding.Length = kspItemValues.Length; 117 ksp.Values = kspItemValues; 118 ksp.Weights = kspItemWeights; 119 120 orchestratorNode.AvailabilityParameter.Value = ttpAvailability; 121 orchestratorNode.MinSpeedParameter.Value = ttpMinSpeed; 122 orchestratorNode.MaxSpeedParameter.Value = ttpMaxSpeed; 123 orchestratorNode.RentingRatioParameter.Value = ttpRentingRatio; 124 #endregion 125 126 RegisterEvents(); 127 } 128 129 public override IDeepCloneable Clone(Cloner cloner) { 130 return new TtpNetwork3(this, cloner); 131 } 132 133 [StorableHook(HookType.AfterDeserialization)] 134 private void AfterDeserialization() { 135 RegisterEvents(); 136 } 137 138 #region IOptimizer Members 139 public RunCollection Runs { get { return MetaSolver.Algorithm.Runs; } } 140 public IEnumerable<IOptimizer> NestedOptimizers { get { yield break; } } 141 public ExecutionState ExecutionState { get { return MetaSolver.Algorithm.ExecutionState; } } 142 public TimeSpan ExecutionTime { get { return MetaSolver.Algorithm.ExecutionTime; } } 143 144 public void Prepare(bool clearRuns) { Prepare(); } 145 public void Prepare() { Orchestrator.Prepare(); } 146 public void Start() { 147 if (MetaSolver.Algorithm.ExecutionState == ExecutionState.Prepared) 148 Orchestrator.Prepare(); 149 Orchestrator.StartAsync(); 150 } 151 public void Pause() { Orchestrator.Pause(); } 152 public void Stop() { Orchestrator.Stop(); } 153 #endregion 154 155 private void OnExecutionStateChanged(object sender, EventArgs e) { OnExecutionStateChanged(); } 156 private void OnExecutionTimeChanged(object sender, EventArgs e) { OnExecutionTimeChanged(); } 157 private void OnPrepared(object sender, EventArgs e) { OnPrepared(); } 158 private void OnStarted(object sender, EventArgs e) { OnStarted(); } 159 private void OnPaused(object sender, EventArgs e) { OnPaused(); } 160 private void OnStopped(object sender, EventArgs e) { OnStopped(); } 161 private void OnExceptionOccurred(object sender, EventArgs<Exception> e) { OnExceptionOccurred(e.Value); } 162 163 public event EventHandler ExecutionStateChanged; 164 private void OnExecutionStateChanged() { 165 var handler = ExecutionStateChanged; 166 if (handler != null) handler(this, EventArgs.Empty); 167 } 168 169 public event EventHandler ExecutionTimeChanged; 170 private void OnExecutionTimeChanged() { 171 var handler = ExecutionTimeChanged; 172 if (handler != null) handler(this, EventArgs.Empty); 173 } 174 175 public event EventHandler Prepared; 176 private void OnPrepared() { 177 var handler = Prepared; 178 if (handler != null) handler(this, EventArgs.Empty); 179 } 180 181 public event EventHandler Started; 182 private void OnStarted() { 183 var handler = Started; 184 if (handler != null) handler(this, EventArgs.Empty); 185 } 186 187 public event EventHandler Paused; 188 private void OnPaused() { 189 var handler = Paused; 190 if (handler != null) handler(this, EventArgs.Empty); 191 } 192 193 public event EventHandler Stopped; 194 private void OnStopped() { 195 var handler = Stopped; 196 if (handler != null) handler(this, EventArgs.Empty); 197 } 198 199 public event EventHandler<EventArgs<Exception>> ExceptionOccurred; 200 private void OnExceptionOccurred(Exception exception) { 201 var handler = ExceptionOccurred; 202 if (handler != null) handler(this, new EventArgs<Exception>(exception)); 203 } 204 } 205 } -
branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization.TravelingThief/3.3/TtpOrchestratorNode1.cs
r14600 r14601 1 using System; 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 22 using System; 2 23 using System.Collections.Generic; 3 24 using System.Linq; … … 17 38 using HeuristicLab.Problems.TravelingSalesman; 18 39 19 namespace HeuristicLab.Networks.IntegratedOptimization {20 [Item("TtpOrchestratorNode 5", "An abstract base class for an orchestrator node for the TTP.")]40 namespace HeuristicLab.Networks.IntegratedOptimization.TravelingThief { 41 [Item("TtpOrchestratorNode1", "Orchestrator for TTP optimization network version 1.")] 21 42 [StorableClass] 22 public sealed class TtpOrchestratorNode 5: OrchestratorNode {43 public sealed class TtpOrchestratorNode1 : OrchestratorNode { 23 44 #region Constants 24 45 private const string TspParameterName = "TSP"; … … 34 55 #endregion 35 56 36 [Storable]37 57 private ResultCollection tspResults, kspResults; 38 58 … … 96 116 97 117 [StorableConstructor] 98 private TtpOrchestratorNode 5(bool deserializing) : base(deserializing) { }99 private TtpOrchestratorNode 5(TtpOrchestratorNode5original, Cloner cloner) : base(original, cloner) {118 private TtpOrchestratorNode1(bool deserializing) : base(deserializing) { } 119 private TtpOrchestratorNode1(TtpOrchestratorNode1 original, Cloner cloner) : base(original, cloner) { 100 120 RegisterEvents(); 101 121 } 102 public TtpOrchestratorNode 5() : this("TtpOrchestratorNode5") { }103 public TtpOrchestratorNode 5(string name) : base(name) {122 public TtpOrchestratorNode1() : this("TtpOrchestratorNode1") { } 123 public TtpOrchestratorNode1(string name) : base(name) { 104 124 #region Configure Parameters 105 125 Parameters.Add(new ValueParameter<IntValue>(IterationsParameterName, new IntValue(20))); … … 125 145 126 146 public override IDeepCloneable Clone(Cloner cloner) { 127 return new TtpOrchestratorNode 5(this, cloner);147 return new TtpOrchestratorNode1(this, cloner); 128 148 } 129 149 … … 230 250 var bestKspQuality = KnapsackEvaluator.Apply(bestKspSolution, kspCapacity, kspPenalty, kspWeights, kspValues).Quality; 231 251 var loot = new KnapsackSolution(bestKspSolution, bestKspQuality, kspCapacity, kspWeights, kspValues); 232 kspResults.Add(new Result("Best KSP Solution", loot));233 252 234 253 var tspMsg = TspSolverOrchestrationPort.PrepareMessage(); -
branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization.TravelingThief/3.3/TtpOrchestratorNode3.cs
r14598 r14601 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("TtpOrchestratorNode3", "An abstract base class for an orchestrator node for the TTP.")] 22 // [StorableClass] 23 // public sealed class TtpOrchestratorNode3 : 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 TtpOrchestratorNode3(bool deserializing) : base(deserializing) { } 118 // private TtpOrchestratorNode3(TtpOrchestratorNode3 original, Cloner cloner) : base(original, cloner) { } 119 // public TtpOrchestratorNode3() : this("TtpOrchestratorNode3") { } 120 // public TtpOrchestratorNode3(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 TtpOrchestratorNode3(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 + 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 // int fi = 0; 196 197 // var ksp = (BinaryKnapsackProblem)KspParameter.Value.Clone(); 198 // while (fi < ksp.Values.Length) { 199 // ksp.Values[fi] = (int)Math.Ceiling(ksp.Values[fi] * factors[fi]); 200 // ++fi; 201 // } 202 203 // var kspMsg = KspSolverOrchestrationPort.PrepareMessage(); 204 // kspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Start); 205 // kspMsg["Problem"] = ksp; 206 // KspSolverOrchestrationPort.SendMessage(kspMsg); 207 208 // var kspResults = kspThreadResults[Thread.CurrentThread.ManagedThreadId]; 209 // var bestKspSolution = (BinaryVector)kspResults["Best Solution"].Value; 210 // var kspCapacity = (IntValue)KspParameter.Value.KnapsackCapacity.Clone(); 211 // var kspPenalty = new DoubleValue(0.0); 212 // var kspWeights = (IntArray)KspParameter.Value.Weights.Clone(); 213 // var kspValues = (IntArray)KspParameter.Value.Values.Clone(); 214 // var bestKspQuality = KnapsackEvaluator.Apply(bestKspSolution, kspCapacity, kspPenalty, kspWeights, kspValues).Quality; 215 // var loot = new KnapsackSolution(bestKspSolution, bestKspQuality, kspCapacity, kspWeights, kspValues); 216 // kspResults.Add(new Result("Best KSP Solution", loot)); 217 218 // var tsp = (TravelingSalesmanProblem)TspParameter.Value.Clone(); 219 // for (int j = 0; j < tsp.Coordinates.Rows; j++) { 220 // tsp.Coordinates[j, 0] = (int)Math.Ceiling(tsp.Coordinates[j, 0] * factors[fi + j * 2]); 221 // tsp.Coordinates[j, 1] = (int)Math.Ceiling(tsp.Coordinates[j, 1] * factors[fi + j * 2 + 1]); 222 // } 223 224 // var tspMsg = TspSolverOrchestrationPort.PrepareMessage(); 225 // tspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Start); 226 // tspMsg["Problem"] = tsp; 227 // TspSolverOrchestrationPort.SendMessage(tspMsg); 228 229 // var tspResults = tspThreadResults[Thread.CurrentThread.ManagedThreadId]; 230 // var tour = (PathTSPTour)tspResults["Best TSP Solution"].Value; 231 // tour.Coordinates = (DoubleMatrix)TspParameter.Value.Coordinates.Clone(); 232 // tour.Quality.Value = TSPCoordinatesPathEvaluator.Apply(new TSPEuclideanPathEvaluator(), tour.Coordinates, tour.Permutation); 233 234 // #region Analyze 235 // double objectiveValue = EvaluateTtp(TspParameter.Value, tour.Permutation.ToArray(), KspParameter.Value, loot.BinaryVector.ToArray()); 236 // ((DoubleValue)message["Quality"]).Value = objectiveValue; 237 238 // var ttpResults = new ResultCollection(); 239 // ttpResults.Add(new Result("Quality", new DoubleValue(objectiveValue))); 240 // ttpResults.Add(new Result("Tour", tour)); 241 // ttpResults.Add(new Result("Loot", loot)); 242 243 // lock (locker) { 244 // TtpResults.Add(ttpResults); 245 // TspResults.Add(tspResults); 246 // KspResults.Add(kspResults); 247 248 // IResult bestQuality; 249 // if (!Results.TryGetValue("Best TTP Quality", out bestQuality)) { 250 // Results.Add(new Result("Best TTP Quality", new DoubleValue(objectiveValue))); 251 // Results.Add(new Result("Best Tour", tour)); 252 // Results.Add(new Result("Best Loot", loot)); 253 // } else if (((DoubleValue)bestQuality.Value).Value < objectiveValue) { 254 // ((DoubleValue)bestQuality.Value).Value = objectiveValue; 255 // Results["Best Tour"].Value = tour; 256 // Results["Best Loot"].Value = loot; 257 // } 258 // } 259 // #endregion 260 // } 261 // #endregion 262 263 // #region TspSolver Message Handling 264 // private void TspSolverOrchestrationPortMessage(IMessage message) { 265 // var results = (ResultCollection)message["Results"]; 266 // if (results.ContainsKey("Best TSP Solution")) { 267 // tspThreadResults[Thread.CurrentThread.ManagedThreadId] = results; 268 // } 269 // } 270 271 // private void TspSolverEvaluationPortMessage(IMessage message) { } 272 // #endregion 273 274 // #region KspSolver Message Handling 275 // private void KspSolverOrchestrationPortMessage(IMessage message) { 276 // var results = (ResultCollection)message["Results"]; 277 // if (results.ContainsKey("Best Solution")) { 278 // kspThreadResults[Thread.CurrentThread.ManagedThreadId] = results; 279 // } 280 // } 281 282 // private void KspSolverEvaluationPortMessage(IMessage message) { } 283 // #endregion 284 285 // #region Helpers 286 // private double EvaluateTtp(TravelingSalesmanProblem tsp, int[] tour, BinaryKnapsackProblem ksp, bool[] loot) { 287 // bool feasible; 288 // return EvaluateTtp(tsp, tour, ksp, loot, out feasible); 289 // } 290 291 // private double EvaluateTtp(TravelingSalesmanProblem tsp, int[] tour, BinaryKnapsackProblem ksp, bool[] loot, out bool feasible) { 292 // double collectedWeight = 0.0; 293 // double objectiveValue = 0.0; 294 // double infeasibleBaseLine = -1000000.0; 295 // double speedCoefficient = (MaxSpeedParameter.Value.Value - MinSpeedParameter.Value.Value) / ksp.KnapsackCapacity.Value; 296 297 // int hideoutIdx = 0; 298 // while (tour[hideoutIdx] != 0) hideoutIdx++; 299 // int cityIdx = (hideoutIdx + 1) % tour.Length; 300 // int lastCityIdx = hideoutIdx; 301 302 // while (cityIdx != hideoutIdx) { 303 // double oldCollectedWeight = collectedWeight; 304 // var availableItems = AvailabilityParameter.Value.Select((c, i) => new { CityIdx = c, ItemIdx = i }).Where(x => x.CityIdx == tour[cityIdx]); 305 306 // foreach (var item in availableItems) { 307 // if (!loot[item.ItemIdx]) continue; 308 // collectedWeight += ksp.Weights[item.ItemIdx]; 309 // objectiveValue += ksp.Values[item.ItemIdx]; 310 // } 311 312 // objectiveValue -= Distance(tsp.Coordinates.CloneAsMatrix(), tour[lastCityIdx], tour[cityIdx]) * RentingRatioParameter.Value.Value / 313 // (MaxSpeedParameter.Value.Value - speedCoefficient * oldCollectedWeight); 314 // lastCityIdx = cityIdx; 315 // cityIdx = (cityIdx + 1) % tour.Length; 316 // } 317 318 // objectiveValue -= Distance(tsp.Coordinates.CloneAsMatrix(), tour[lastCityIdx], tour[hideoutIdx]) * RentingRatioParameter.Value.Value / 319 // (MaxSpeedParameter.Value.Value - speedCoefficient * collectedWeight); 320 321 // feasible = collectedWeight <= ksp.KnapsackCapacity.Value; 322 // if (!feasible) objectiveValue = infeasibleBaseLine - collectedWeight; 323 324 // return objectiveValue; 325 // } 326 327 // private double Distance(double[,] coords, int fromIdx, int toIdx) { 328 // double fromX = coords[fromIdx, 0], fromY = coords[fromIdx, 1], 329 // toX = coords[toIdx, 0], toY = coords[toIdx, 1]; 330 // return (int)Math.Ceiling(Math.Sqrt((toX - fromX) * (toX - fromX) + (toY - fromY) * (toY - fromY))); 331 // } 332 // #endregion 333 334 // #region Event Handlers 335 // private void MetaSolverOrchestrationPort_ConnectedPortChanged(object sender, EventArgs e) { 336 // if (MetaSolverOrchestrationPort.ConnectedPort == null) return; 337 338 // var node = MetaSolverOrchestrationPort.ConnectedPort.Parent as OrchestratedAlgorithmNode; 339 // if (node == null) return; 340 341 // var hook = new HookOperator { Name = "Meta Eval Hook" }; 342 // hook.Parameters.Add(new LookupParameter<RealVector>("RealVector") { Hidden = true }); 343 // hook.Parameters.Add(new LookupParameter<DoubleValue>("Quality") { Hidden = true }); 344 // node.EvalHook = hook; 345 346 // node.OrchestrationPort.CloneParametersFromPort(MetaSolverOrchestrationPort); 347 // node.EvaluationPort.CloneParametersFromPort(MetaSolverEvaluationPort); 348 // node.EvaluationPort.ConnectedPort = MetaSolverEvaluationPort; 349 // } 350 351 // private void TspSolverOrchestrationPort_ConnectedPortChanged(object sender, EventArgs e) { 352 // if (TspSolverOrchestrationPort.ConnectedPort == null) return; 353 354 // var node = TspSolverOrchestrationPort.ConnectedPort.Parent as OrchestratedAlgorithmNode; 355 // if (node == null) return; 356 357 // var hook = new HookOperator { Name = "TSP Eval Hook" }; 358 // hook.Parameters.Add(new LookupParameter<Permutation>("TSPTour") { Hidden = true }); 359 // hook.Parameters.Add(new LookupParameter<DoubleValue>("TSPTourLength") { Hidden = true }); 360 // node.EvalHook = hook; 361 362 // node.OrchestrationPort.CloneParametersFromPort(TspSolverOrchestrationPort); 363 // node.EvaluationPort.CloneParametersFromPort(TspSolverEvaluationPort); 364 // node.EvaluationPort.ConnectedPort = TspSolverEvaluationPort; 365 // } 366 367 // private void KspSolverOrchestrationPort_ConnectedPortChanged(object sender, EventArgs e) { 368 // if (KspSolverOrchestrationPort.ConnectedPort == null) return; 369 370 // var node = KspSolverOrchestrationPort.ConnectedPort.Parent as OrchestratedAlgorithmNode; 371 // if (node == null) return; 372 373 // var hook = new HookOperator { Name = "KSP Eval Hook" }; 374 // hook.Parameters.Add(new LookupParameter<BinaryVector>("KnapsackSolution") { Hidden = true }); 375 // hook.Parameters.Add(new LookupParameter<DoubleValue>("Quality") { Hidden = true }); 376 // node.EvalHook = hook; 377 378 // node.OrchestrationPort.CloneParametersFromPort(KspSolverOrchestrationPort); 379 // node.EvaluationPort.CloneParametersFromPort(KspSolverEvaluationPort); 380 // node.EvaluationPort.ConnectedPort = KspSolverEvaluationPort; 381 // } 382 // #endregion 383 // } 384 //} 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 22 using System; 23 using System.Collections.Generic; 24 using System.Linq; 25 using System.Threading; 26 using HeuristicLab.Common; 27 using HeuristicLab.Core; 28 using HeuristicLab.Core.Networks; 29 using HeuristicLab.Data; 30 using HeuristicLab.Encodings.BinaryVectorEncoding; 31 using HeuristicLab.Encodings.PermutationEncoding; 32 using HeuristicLab.Encodings.RealVectorEncoding; 33 using HeuristicLab.Operators; 34 using HeuristicLab.Optimization; 35 using HeuristicLab.Parameters; 36 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 37 using HeuristicLab.Problems.Knapsack; 38 using HeuristicLab.Problems.TravelingSalesman; 39 40 namespace 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 TspParameterName = "TSP"; 46 private const string KspParameterName = "KSP"; 47 private const string AvailabilityParameterName = "Availability"; 48 private const string MinSpeedParameterName = "MinSpeed"; 49 private const string MaxSpeedParameterName = "MaxSpeed"; 50 private const string RentingRatioParameterName = "RentingRatio"; 51 private const string IterationsParameterName = "Iterations"; 52 private const string MetaSolverName = "MetaSolver"; 53 private const string TspSolverName = "TspSolver"; 54 private const string KspSolverName = "KspSolver"; 55 #endregion 56 57 private ResultCollection tspResults, kspResults; 58 59 private CancellationTokenSource cts; 60 61 #region Parameters 62 public IValueParameter<IntValue> IterationsParameter { 63 get { return (IValueParameter<IntValue>)Parameters[IterationsParameterName]; } 64 } 65 66 public IValueParameter<TravelingSalesmanProblem> TspParameter { 67 get { return (IValueParameter<TravelingSalesmanProblem>)Parameters[TspParameterName]; } 68 } 69 70 public IValueParameter<BinaryKnapsackProblem> KspParameter { 71 get { return (IValueParameter<BinaryKnapsackProblem>)Parameters[KspParameterName]; } 72 } 73 74 public IValueParameter<IntArray> AvailabilityParameter { 75 get { return (IValueParameter<IntArray>)Parameters[AvailabilityParameterName]; } 76 } 77 78 public IValueParameter<DoubleValue> MinSpeedParameter { 79 get { return (IValueParameter<DoubleValue>)Parameters[MinSpeedParameterName]; } 80 } 81 82 public IValueParameter<DoubleValue> MaxSpeedParameter { 83 get { return (IValueParameter<DoubleValue>)Parameters[MaxSpeedParameterName]; } 84 } 85 86 public IValueParameter<DoubleValue> RentingRatioParameter { 87 get { return (IValueParameter<DoubleValue>)Parameters[RentingRatioParameterName]; } 88 } 89 #endregion 90 91 #region Ports 92 public IMessagePort MetaSolverOrchestrationPort { 93 get { return (IMessagePort)Ports[MetaSolverName + OrchestrationPortNameSuffix]; } 94 } 95 96 public IMessagePort MetaSolverEvaluationPort { 97 get { return (IMessagePort)Ports[MetaSolverName + EvaluationPortNameSuffix]; } 98 } 99 100 public IMessagePort TspSolverOrchestrationPort { 101 get { return (IMessagePort)Ports[TspSolverName + OrchestrationPortNameSuffix]; } 102 } 103 104 public IMessagePort TspSolverEvaluationPort { 105 get { return (IMessagePort)Ports[TspSolverName + EvaluationPortNameSuffix]; } 106 } 107 108 public IMessagePort KspSolverOrchestrationPort { 109 get { return (IMessagePort)Ports[KspSolverName + OrchestrationPortNameSuffix]; } 110 } 111 112 public IMessagePort KspSolverEvaluationPort { 113 get { return (IMessagePort)Ports[KspSolverName + EvaluationPortNameSuffix]; } 114 } 115 #endregion 116 117 [StorableConstructor] 118 private TtpOrchestratorNode3(bool deserializing) : base(deserializing) { } 119 private TtpOrchestratorNode3(TtpOrchestratorNode3 original, Cloner cloner) : base(original, cloner) { 120 RegisterEvents(); 121 } 122 public TtpOrchestratorNode3() : this("TtpOrchestratorNode3") { } 123 public TtpOrchestratorNode3(string name) : base(name) { 124 #region Configure Parameters 125 Parameters.Add(new ValueParameter<IntValue>(IterationsParameterName, new IntValue(20))); 126 Parameters.Add(new ValueParameter<TravelingSalesmanProblem>(TspParameterName, new TravelingSalesmanProblem())); 127 Parameters.Add(new ValueParameter<BinaryKnapsackProblem>(KspParameterName, new BinaryKnapsackProblem())); 128 Parameters.Add(new ValueParameter<IntArray>(AvailabilityParameterName)); 129 Parameters.Add(new ValueParameter<DoubleValue>(MinSpeedParameterName, new DoubleValue(0.1))); 130 Parameters.Add(new ValueParameter<DoubleValue>(MaxSpeedParameterName, new DoubleValue(1.0))); 131 Parameters.Add(new ValueParameter<DoubleValue>(RentingRatioParameterName, new DoubleValue(0.5))); 132 #endregion 133 134 #region Configure Ports 135 AddOrchestrationPort<VariegationProblem>(MetaSolverName); 136 AddEvaluationPort<RealVector>(MetaSolverName, "RealVector", "Quality"); 137 AddOrchestrationPort<TravelingSalesmanProblem>(TspSolverName); 138 AddEvaluationPort<Permutation>(TspSolverName, "TSPTour", "TSPTourLength"); 139 AddOrchestrationPort<BinaryKnapsackProblem>(KspSolverName); 140 AddEvaluationPort<BinaryVector>(KspSolverName, "KnapsackSolution", "Quality"); 141 142 RegisterEvents(); 143 #endregion 144 } 145 146 public override IDeepCloneable Clone(Cloner cloner) { 147 return new TtpOrchestratorNode3(this, cloner); 148 } 149 150 [StorableHook(HookType.AfterDeserialization)] 151 private void AfterDeserialization() { 152 RegisterEvents(); 153 } 154 155 private void RegisterEvents() { 156 MetaSolverOrchestrationPort.ConnectedPortChanged += MetaSolverOrchestrationPort_ConnectedPortChanged; 157 TspSolverOrchestrationPort.ConnectedPortChanged += TspSolverOrchestrationPort_ConnectedPortChanged; 158 KspSolverOrchestrationPort.ConnectedPortChanged += KspSolverOrchestrationPort_ConnectedPortChanged; 159 } 160 161 public override void Prepare() { 162 Results.Clear(); 163 164 var metaMsg = MetaSolverOrchestrationPort.PrepareMessage(); 165 metaMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Prepare | OrchestrationMessage.QualityAdaption); 166 var problem = new VariegationProblem(); 167 problem.Encoding.Length = KspParameter.Value.Length + TspParameter.Value.Coordinates.Rows * 2; 168 problem.Encoding.Bounds = new DoubleMatrix(new[,] { { -1.0, 1.0 } }); 169 metaMsg["Problem"] = problem; 170 MetaSolverOrchestrationPort.SendMessage(metaMsg); 171 } 172 173 public override void Start() { 174 cts = new CancellationTokenSource(); 175 176 try { 177 var metaMsg = MetaSolverOrchestrationPort.PrepareMessage(); 178 metaMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Start); 179 MetaSolverOrchestrationPort.SendMessage(metaMsg); 180 } catch (Exception e) { } 181 } 182 183 public override void Pause() { 184 cts.Cancel(); 185 186 var metaMsg = MetaSolverOrchestrationPort.PrepareMessage(); 187 metaMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Pause); 188 MetaSolverOrchestrationPort.SendMessage(metaMsg); 189 190 var tspMsg = TspSolverOrchestrationPort.PrepareMessage(); 191 tspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Stop); 192 TspSolverOrchestrationPort.SendMessage(tspMsg); 193 194 var kspMsg = KspSolverOrchestrationPort.PrepareMessage(); 195 kspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Stop); 196 KspSolverOrchestrationPort.SendMessage(kspMsg); 197 } 198 199 public override void Stop() { 200 cts.Cancel(); 201 202 var metaMsg = MetaSolverOrchestrationPort.PrepareMessage(); 203 metaMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Stop); 204 MetaSolverOrchestrationPort.SendMessage(metaMsg); 205 206 var tspMsg = TspSolverOrchestrationPort.PrepareMessage(); 207 tspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Stop); 208 TspSolverOrchestrationPort.SendMessage(tspMsg); 209 210 var kspMsg = KspSolverOrchestrationPort.PrepareMessage(); 211 kspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Stop); 212 KspSolverOrchestrationPort.SendMessage(kspMsg); 213 } 214 215 protected override void ProcessMessage(IMessage message, IMessagePort port, CancellationToken token) { 216 var messageActions = new Dictionary<IMessagePort, Action<IMessage>>(); 217 messageActions.Add(MetaSolverOrchestrationPort, MetaSolverOrchestrationPortMessage); 218 messageActions.Add(MetaSolverEvaluationPort, MetaSolverEvaluationPortMessage); 219 messageActions.Add(TspSolverOrchestrationPort, TspSolverOrchestrationPortMessage); 220 messageActions.Add(TspSolverEvaluationPort, TspSolverEvaluationPortMessage); 221 messageActions.Add(KspSolverOrchestrationPort, KspSolverOrchestrationPortMessage); 222 messageActions.Add(KspSolverEvaluationPort, KspSolverEvaluationPortMessage); 223 224 messageActions[port](message); 225 226 base.ProcessMessage(message, port, token); 227 } 228 229 #region MetaSolver Message Handling 230 private void MetaSolverOrchestrationPortMessage(IMessage message) { } 231 232 private void MetaSolverEvaluationPortMessage(IMessage message) { 233 var factors = (RealVector)message["RealVector"]; 234 int fi = 0; 235 236 var ksp = (BinaryKnapsackProblem)KspParameter.Value.Clone(); 237 while (fi < ksp.Values.Length) { 238 ksp.Values[fi] = (int)Math.Ceiling(ksp.Values[fi] * factors[fi]); 239 ++fi; 240 } 241 242 var kspMsg = KspSolverOrchestrationPort.PrepareMessage(); 243 kspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Prepare | OrchestrationMessage.Start); 244 kspMsg["Problem"] = ksp; 245 KspSolverOrchestrationPort.SendMessage(kspMsg); 246 cts.Token.ThrowIfCancellationRequested(); 247 248 var bestKspSolution = (BinaryVector)kspResults["Best Solution"].Value; 249 var kspCapacity = (IntValue)KspParameter.Value.KnapsackCapacity.Clone(); 250 var kspPenalty = new DoubleValue(0.0); 251 var kspWeights = (IntArray)KspParameter.Value.Weights.Clone(); 252 var kspValues = (IntArray)KspParameter.Value.Values.Clone(); 253 var bestKspQuality = KnapsackEvaluator.Apply(bestKspSolution, kspCapacity, kspPenalty, kspWeights, kspValues).Quality; 254 var loot = new KnapsackSolution(bestKspSolution, bestKspQuality, kspCapacity, kspWeights, kspValues); 255 256 var tsp = (TravelingSalesmanProblem)TspParameter.Value.Clone(); 257 for (int j = 0; j < tsp.Coordinates.Rows; j++) { 258 tsp.Coordinates[j, 0] = (int)Math.Ceiling(tsp.Coordinates[j, 0] * factors[fi + j * 2]); 259 tsp.Coordinates[j, 1] = (int)Math.Ceiling(tsp.Coordinates[j, 1] * factors[fi + j * 2 + 1]); 260 } 261 262 var tspMsg = TspSolverOrchestrationPort.PrepareMessage(); 263 tspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Prepare | OrchestrationMessage.Start); 264 var tpp = new TourProfitProblem { 265 Tsp = (TravelingSalesmanProblem)TspParameter.Value.Clone(), 266 Ksp = (BinaryKnapsackProblem)KspParameter.Value.Clone(), 267 FixedKspSolution = bestKspSolution, 268 Availability = AvailabilityParameter.Value.ToArray(), 269 RentingRatio = RentingRatioParameter.Value.Value, 270 MinSpeed = MinSpeedParameter.Value.Value, 271 MaxSpeed = MaxSpeedParameter.Value.Value 272 }; 273 tpp.Encoding.Length = TspParameter.Value.Coordinates.Rows; 274 tspMsg["Problem"] = tpp; 275 TspSolverOrchestrationPort.SendMessage(tspMsg); 276 cts.Token.ThrowIfCancellationRequested(); 277 278 var bestTspSolution = (Permutation)tspResults["Best TSP Solution"].Value; 279 var coordinates = (DoubleMatrix)TspParameter.Value.Coordinates.Clone(); 280 var tour = new PathTSPTour(coordinates, bestTspSolution, new DoubleValue(TSPCoordinatesPathEvaluator.Apply(new TSPEuclideanPathEvaluator(), coordinates, bestTspSolution))); 281 282 #region Analyze 283 double objectiveValue = TtpUtils.EvaluateTtp(TspParameter.Value, tour.Permutation.ToArray(), KspParameter.Value, loot.BinaryVector.ToArray(), 284 AvailabilityParameter.Value.ToArray(), RentingRatioParameter.Value.Value, MinSpeedParameter.Value.Value, MaxSpeedParameter.Value.Value); 285 ((DoubleValue)message["Quality"]).Value = objectiveValue; 286 287 IResult bestQuality; 288 if (!Results.TryGetValue("Best TTP Quality", out bestQuality)) { 289 Results.Add(new Result("Best TTP Quality", new DoubleValue(objectiveValue))); 290 Results.Add(new Result("Best Tour", tour)); 291 Results.Add(new Result("Best Loot", loot)); 292 } else if (((DoubleValue)bestQuality.Value).Value < objectiveValue) { 293 ((DoubleValue)bestQuality.Value).Value = objectiveValue; 294 Results["Best Tour"].Value = tour; 295 Results["Best Loot"].Value = loot; 296 } 297 #endregion 298 } 299 #endregion 300 301 #region TspSolver Message Handling 302 private void TspSolverOrchestrationPortMessage(IMessage message) { 303 var results = (ResultCollection)message["Results"]; 304 if (results.ContainsKey("Best TSP Solution")) { 305 tspResults = results; 306 } 307 } 308 309 private void TspSolverEvaluationPortMessage(IMessage message) { } 310 #endregion 311 312 #region KspSolver Message Handling 313 private void KspSolverOrchestrationPortMessage(IMessage message) { 314 var results = (ResultCollection)message["Results"]; 315 if (results.ContainsKey("Best Solution")) { 316 kspResults = results; 317 } 318 } 319 320 private void KspSolverEvaluationPortMessage(IMessage message) { } 321 #endregion 322 323 #region Event Handlers 324 private void MetaSolverOrchestrationPort_ConnectedPortChanged(object sender, EventArgs e) { 325 if (MetaSolverOrchestrationPort.ConnectedPort == null) return; 326 327 var node = MetaSolverOrchestrationPort.ConnectedPort.Parent as OrchestratedAlgorithmNode; 328 if (node == null) return; 329 330 var hook = new HookOperator { Name = "Meta Eval Hook" }; 331 hook.Parameters.Add(new LookupParameter<RealVector>("RealVector") { Hidden = true }); 332 hook.Parameters.Add(new LookupParameter<DoubleValue>("Quality") { Hidden = true }); 333 node.EvalHook = hook; 334 335 node.OrchestrationPort.CloneParametersFromPort(MetaSolverOrchestrationPort); 336 node.EvaluationPort.CloneParametersFromPort(MetaSolverEvaluationPort); 337 node.EvaluationPort.ConnectedPort = MetaSolverEvaluationPort; 338 } 339 340 private void TspSolverOrchestrationPort_ConnectedPortChanged(object sender, EventArgs e) { 341 if (TspSolverOrchestrationPort.ConnectedPort == null) return; 342 343 var node = TspSolverOrchestrationPort.ConnectedPort.Parent as OrchestratedAlgorithmNode; 344 if (node == null) return; 345 346 var hook = new HookOperator { Name = "TSP Eval Hook" }; 347 hook.Parameters.Add(new LookupParameter<Permutation>("TSPTour") { Hidden = true }); 348 hook.Parameters.Add(new LookupParameter<DoubleValue>("TSPTourLength") { Hidden = true }); 349 node.EvalHook = hook; 350 351 node.OrchestrationPort.CloneParametersFromPort(TspSolverOrchestrationPort); 352 node.EvaluationPort.CloneParametersFromPort(TspSolverEvaluationPort); 353 node.EvaluationPort.ConnectedPort = TspSolverEvaluationPort; 354 } 355 356 private void KspSolverOrchestrationPort_ConnectedPortChanged(object sender, EventArgs e) { 357 if (KspSolverOrchestrationPort.ConnectedPort == null) return; 358 359 var node = KspSolverOrchestrationPort.ConnectedPort.Parent as OrchestratedAlgorithmNode; 360 if (node == null) return; 361 362 var hook = new HookOperator { Name = "KSP Eval Hook" }; 363 hook.Parameters.Add(new LookupParameter<BinaryVector>("KnapsackSolution") { Hidden = true }); 364 hook.Parameters.Add(new LookupParameter<DoubleValue>("Quality") { Hidden = true }); 365 node.EvalHook = hook; 366 367 node.OrchestrationPort.CloneParametersFromPort(KspSolverOrchestrationPort); 368 node.EvaluationPort.CloneParametersFromPort(KspSolverEvaluationPort); 369 node.EvaluationPort.ConnectedPort = KspSolverEvaluationPort; 370 } 371 #endregion 372 } 373 } -
branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization.TravelingThief/3.3/TtpUtils.cs
r14598 r14601 3 3 using HeuristicLab.Problems.TravelingSalesman; 4 4 5 namespace HeuristicLab.Networks.IntegratedOptimization {5 namespace HeuristicLab.Networks.IntegratedOptimization.TravelingThief { 6 6 public static class TtpUtils { 7 7 public static double EvaluateTtp(TravelingSalesmanProblem tsp, int[] tour, BinaryKnapsackProblem ksp, bool[] loot, int[] availability, double rentingRatio, double minSpeed, double maxSpeed) {
Note: See TracChangeset
for help on using the changeset viewer.