Changeset 14598
- Timestamp:
- 01/23/17 14:49:07 (8 years ago)
- Location:
- branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization/3.3
- Files:
-
- 13 edited
Legend:
- Unmodified
- Added
- Removed
-
branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization/3.3/OrchestratedAlgorithmNode.cs
r14586 r14598 23 23 24 24 #region Ports 25 public I ConfigurationPort OrchestrationPort {26 get { return (I ConfigurationPort)Ports[OrchestrationPortName]; }25 public IMessagePort OrchestrationPort { 26 get { return (IMessagePort)Ports[OrchestrationPortName]; } 27 27 } 28 public I ConfigurationPort EvaluationPort {29 get { return (I ConfigurationPort)Ports[EvaluationPortName]; }28 public IMessagePort EvaluationPort { 29 get { return (IMessagePort)Ports[EvaluationPortName]; } 30 30 } 31 31 #endregion … … 42 42 } 43 43 44 [Storable]45 public bool CloneAlgorithm { get; set; }46 47 44 [StorableConstructor] 48 45 protected OrchestratedAlgorithmNode(bool deserializing) : base(deserializing) { } 49 46 protected OrchestratedAlgorithmNode(OrchestratedAlgorithmNode original, Cloner cloner) : base(original, cloner) { 50 CloneAlgorithm = original.CloneAlgorithm;51 47 EvalHook = cloner.Clone(original.EvalHook); 52 53 OrchestrationPort.MessageReceived += OrchestrationPort_MessageReceived; 48 RegisterEvents(); 54 49 } 55 50 public OrchestratedAlgorithmNode() : this("OrchestratedAlgorithmNode") { } 56 51 public OrchestratedAlgorithmNode(string name) : base(name) { 57 #region Configure Ports 58 #region OrchestrationPort 59 var orchestrationPort = new ConfigurationPort(OrchestrationPortName); 60 orchestrationPort.MessageReceived += OrchestrationPort_MessageReceived; 52 var orchestrationPort = new MessagePort(OrchestrationPortName); 61 53 Ports.Add(orchestrationPort); 62 #endregion63 54 64 #region EvaluationPort 65 var evaluationPort = new ConfigurationPort(EvaluationPortName); 55 var evaluationPort = new MessagePort(EvaluationPortName); 66 56 Ports.Add(evaluationPort); 67 #endregion 68 #endregion57 58 RegisterEvents(); 69 59 } 70 60 … … 75 65 [StorableHook(HookType.AfterDeserialization)] 76 66 private void AfterDeserialization() { 67 RegisterEvents(); 68 } 69 70 private void RegisterEvents() { 77 71 OrchestrationPort.MessageReceived += OrchestrationPort_MessageReceived; 78 72 } … … 81 75 private void OrchestrationPort_MessageReceived(object sender, EventArgs<IMessage, CancellationToken> e) { 82 76 var message = ((EnumValue<OrchestrationMessage>)e.Value["OrchestrationMessage"]).Value; 83 IAlgorithm alg = null;84 77 78 #region Prepare 85 79 if (message.HasFlag(OrchestrationMessage.Prepare)) { 86 // TODO: what if CloneAlgorithm == true? 87 IMessageValue problemMsgVal; 88 if (e.Value.Values.TryGetValue("Problem", out problemMsgVal)) { 89 alg = CloneAlgorithm ? (IAlgorithm)Algorithm.Clone() : Algorithm; 90 var prob = (IHeuristicOptimizationProblem)problemMsgVal.Value.Clone(); 80 switch (Algorithm.ExecutionState) { 81 case ExecutionState.Prepared: 82 case ExecutionState.Paused: 83 case ExecutionState.Stopped: 84 IMessageValue problemMsgVal; 85 if (e.Value.Values.TryGetValue("Problem", out problemMsgVal)) { 86 var prob = (IHeuristicOptimizationProblem)problemMsgVal.Value.Clone(); 91 87 92 if (message.HasFlag(OrchestrationMessage.QualityAdaption)) {93 var instEval = prob.Evaluator as InstrumentedOperator;94 if (instEval != null && EvalHook != null) instEval.AfterExecutionOperators.Add(EvalHook);95 }88 if (message.HasFlag(OrchestrationMessage.QualityAdaption)) { 89 var instEval = prob.Evaluator as InstrumentedOperator; 90 if (instEval != null && EvalHook != null) instEval.AfterExecutionOperators.Add(EvalHook); 91 } 96 92 97 var parameters = new Dictionary<string, IItem>(); 98 alg.CollectParameterValues(parameters); 99 var entry = parameters.SingleOrDefault(x => x.Value is IMultiAnalyzer); 100 var checkedStates = new Dictionary<Type, bool>(); 101 if (entry.Key != null) { 102 var multiAnalyzer = entry.Value as IMultiAnalyzer; 103 foreach (var analyzer in multiAnalyzer.Operators) 104 checkedStates.Add(analyzer.GetType(), multiAnalyzer.Operators.ItemChecked(analyzer)); 105 } 93 IParameter analyzerParameter = null; 94 IMultiAnalyzer multiAnalyzer = null; 95 var checkedStates = new Dictionary<Type, bool>(); 96 if (Algorithm.Parameters.TryGetValue("Analyzer", out analyzerParameter)) { 97 multiAnalyzer = analyzerParameter.ActualValue as IMultiAnalyzer; 98 foreach (var item in multiAnalyzer.Operators) 99 checkedStates.Add(item.GetType(), multiAnalyzer.Operators.ItemChecked(item)); 100 } 106 101 107 alg.Problem = prob;102 Algorithm.Problem = prob; 108 103 109 if (entry.Key != null) { 110 var multiAnalyzer = entry.Value as IMultiAnalyzer; 111 foreach (var state in checkedStates) { 112 var analyzer = multiAnalyzer.Operators.Single(x => x.GetType() == state.Key); 113 multiAnalyzer.Operators.SetItemCheckedState(analyzer, state.Value); 104 if (multiAnalyzer != null) { 105 if (Algorithm.Parameters.TryGetValue("Analyzer", out analyzerParameter)) { 106 multiAnalyzer = analyzerParameter.ActualValue as IMultiAnalyzer; 107 if (multiAnalyzer != null && checkedStates.Any()) { 108 foreach (var analyzer in multiAnalyzer.Operators) { 109 bool checkedState; 110 checkedStates.TryGetValue(analyzer.GetType(), out checkedState); 111 multiAnalyzer.Operators.SetItemCheckedState(analyzer, checkedState); 112 } 113 } 114 } 115 } 116 117 Algorithm.Prepare(); 114 118 } 115 } 116 117 alg.Prepare(); 119 break; 118 120 } 119 121 } 122 #endregion 120 123 124 #region Start 121 125 if (message.HasFlag(OrchestrationMessage.Start)) { 122 // TODO: what if CloneAlgorithm == true? 123 StartAlgorithm(alg ?? (CloneAlgorithm ? (IAlgorithm)Algorithm.Clone() : Algorithm)); 126 switch (Algorithm.ExecutionState) { 127 case ExecutionState.Prepared: 128 case ExecutionState.Paused: 129 var trigger = new ManualResetEvent(false); 130 Exception ex = null; 124 131 125 if (sendResultMessage) { 126 var msg = OrchestrationPort.PrepareMessage(); 127 msg["Results"] = (ResultCollection)alg.Results.Clone(); 128 OrchestrationPort.SendMessage(msg); 129 } else sendResultMessage = true; 132 EventHandler onStopped = null; 133 EventHandler<EventArgs<Exception>> onExceptionOccurred = null; 134 Algorithm.Stopped += onStopped = (src, args) => { 135 Algorithm.Stopped -= onStopped; 136 Algorithm.ExceptionOccurred -= onExceptionOccurred; 137 trigger.Set(); 138 }; 139 Algorithm.ExceptionOccurred += onExceptionOccurred = (src, args) => { 140 Algorithm.Stopped -= onStopped; 141 Algorithm.ExceptionOccurred -= onExceptionOccurred; 142 ex = args.Value; 143 trigger.Set(); 144 }; 145 146 Algorithm.Start(); 147 trigger.WaitOne(); 148 149 if (ex != null) throw ex; 150 151 if (sendResultMessage) { 152 var msg = OrchestrationPort.PrepareMessage(); 153 msg["Results"] = (ResultCollection)Algorithm.Results.Clone(); 154 OrchestrationPort.SendMessage(msg); 155 } else sendResultMessage = true; 156 break; 157 } 130 158 } 159 #endregion 131 160 161 #region Pause 132 162 if (message.HasFlag(OrchestrationMessage.Pause)) { 133 // TODO: what if CloneAlgorithm == true? 134 sendResultMessage = false; 135 (alg ?? (CloneAlgorithm ? (IAlgorithm)Algorithm.Clone() : Algorithm)).Pause(); 163 if (Algorithm.ExecutionState == ExecutionState.Started) { 164 sendResultMessage = false; 165 try { 166 Algorithm.Pause(); 167 } catch (InvalidOperationException) { 168 // ExecutionState might have changed since we accepted the message 169 } 170 } 136 171 } 172 #endregion 137 173 174 #region Stop 138 175 if (message.HasFlag(OrchestrationMessage.Stop)) { 139 // TODO: what if CloneAlgorithm == true? 140 (alg ?? (CloneAlgorithm ? (IAlgorithm)Algorithm.Clone() : Algorithm)).Stop(); 176 switch (Algorithm.ExecutionState) { 177 case ExecutionState.Started: 178 case ExecutionState.Paused: 179 try { 180 Algorithm.Stop(); 181 } catch (InvalidOperationException) { 182 // ExecutionState might have changed since we accepted the message 183 } catch (NullReferenceException) { 184 // BasicAlgorithm might have stopped since we accepted the message 185 // CancellationTokenSource is null in this case 186 } 187 break; 188 } 141 189 } 142 } 143 144 private void StartAlgorithm(IAlgorithm a) { 145 var trigger = new ManualResetEvent(false); 146 Exception ex = null; 147 a.Stopped += (src, e) => { trigger.Set(); }; 148 a.ExceptionOccurred += (src, e) => { ex = e.Value; trigger.Set(); }; 149 a.Prepare(); 150 a.Start(); 151 trigger.WaitOne(); 152 if (ex != null) throw ex; 190 #endregion 153 191 } 154 192 #endregion -
branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization/3.3/OrchestratorNode.cs
r14586 r14598 39 39 } 40 40 41 #region Parameters42 //public IValueParameter<EnumValue<OrchestrationMessage>> OrchestrationMessageParameter {43 // get { return (IValueParameter<EnumValue<OrchestrationMessage>>)Parameters[OrchestrationMessageParameterName]; }44 //}45 #endregion46 47 41 [StorableConstructor] 48 42 protected OrchestratorNode(bool deserializing) : base(deserializing) { } … … 51 45 parameters = cloner.Clone(original.parameters); 52 46 readOnlyParameters = null; 47 RegisterEvents(); 53 48 } 49 54 50 protected OrchestratorNode() : base("OrchestratorNode") { 55 51 results = new ResultCollection(); … … 71 67 } 72 68 69 [StorableHook(HookType.AfterDeserialization)] 70 private void AfterDeserialization() { 71 RegisterEvents(); 72 } 73 74 private void RegisterEvents() { 75 foreach (var p in Ports) RegisterPortEvents(p); 76 } 77 73 78 protected void AddOrchestrationPort<T>(string solverName) 74 79 where T : class, IProblem { 75 var orchestrationPort = new ConfigurationPort(solverName + OrchestrationPortNameSuffix);80 var orchestrationPort = new MessagePort(solverName + OrchestrationPortNameSuffix); 76 81 orchestrationPort.Parameters.Add(new PortParameter<EnumValue<OrchestrationMessage>>("OrchestrationMessage") { 77 82 Type = PortParameterType.Output … … 87 92 88 93 protected void AddEvaluationPort<T>(string solverName, string solutionName, string qualityName) where T : class, IItem { 89 var evaluationPort = new ConfigurationPort(solverName + EvaluationPortNameSuffix);94 var evaluationPort = new MessagePort(solverName + EvaluationPortNameSuffix); 90 95 evaluationPort.Parameters.Add(new PortParameter<T>(solutionName) { 91 96 Type = PortParameterType.Input -
branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization/3.3/Plugin.cs.frame
r14586 r14598 28 28 [Plugin("HeuristicLab.Networks.IntegratedOptimization", "3.3.14.$WCREV$")] 29 29 [PluginFile("HeuristicLab.Networks.IntegratedOptimization-3.3.dll", PluginFileType.Assembly)] 30 [PluginDependency("HeuristicLab.Algorithms.CMAEvolutionStrategy", "3.4")] 31 [PluginDependency("HeuristicLab.Algorithms.GeneticAlgorithm", "3.3")] 32 [PluginDependency("HeuristicLab.Algorithms.LocalSearch", "3.3")] 33 [PluginDependency("HeuristicLab.Algorithms.OffspringSelectionGeneticAlgorithm", "3.3")] 34 [PluginDependency("HeuristicLab.Algorithms.ParameterlessPopulationPyramid", "3.3")] 35 [PluginDependency("HeuristicLab.Algorithms.SimulatedAnnealing", "3.3")] 36 [PluginDependency("HeuristicLab.Algorithms.TabuSearch", "3.3")] 37 [PluginDependency("HeuristicLab.Analysis", "3.3")] 38 [PluginDependency("HeuristicLab.Collections", "3.3")] 39 [PluginDependency("HeuristicLab.Common", "3.3")] 40 [PluginDependency("HeuristicLab.Core", "3.3")] 41 [PluginDependency("HeuristicLab.Data", "3.3")] 42 [PluginDependency("HeuristicLab.Encodings.BinaryVectorEncoding", "3.3")] 43 [PluginDependency("HeuristicLab.Encodings.IntegerVectorEncoding", "3.3")] 44 [PluginDependency("HeuristicLab.Encodings.PermutationEncoding", "3.3")] 45 [PluginDependency("HeuristicLab.Encodings.RealVectorEncoding", "3.3")] 46 [PluginDependency("HeuristicLab.Networks", "3.3")] 47 [PluginDependency("HeuristicLab.Operators", "3.3")] 48 [PluginDependency("HeuristicLab.Optimization", "3.3")] 49 [PluginDependency("HeuristicLab.ParallelEngine", "3.3")] 50 [PluginDependency("HeuristicLab.Parameters", "3.3")] 51 [PluginDependency("HeuristicLab.Problems.Binary", "3.3")] 52 [PluginDependency("HeuristicLab.Problems.Instances", "3.3")] 53 [PluginDependency("HeuristicLab.Problems.Knapsack", "3.3")] 54 [PluginDependency("HeuristicLab.Problems.TravelingSalesman", "3.3")] 55 [PluginDependency("HeuristicLab.Random", "3.3")] 56 [PluginDependency("HeuristicLab.Scripting", "3.3")] 57 [PluginDependency("HeuristicLab.Selection", "3.3")] 30 58 public class HeuristicLabNetworksIntegratedOptimizationPlugin : PluginBase { 31 59 } -
branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization/3.3/Problems/TourProfitProblem.cs
r14586 r14598 18 18 } 19 19 20 [Storable] 20 21 public TravelingSalesmanProblem Tsp { get; set; } 22 [Storable] 21 23 public BinaryKnapsackProblem Ksp { get; set; } 24 [Storable] 22 25 public BinaryVector FixedKspSolution { get; set; } 26 [Storable] 23 27 public int[] Availability { get; set; } 28 [Storable] 24 29 public double RentingRatio { get; set; } 30 [Storable] 25 31 public double MinSpeed { get; set; } 32 [Storable] 26 33 public double MaxSpeed { get; set; } 27 34 … … 52 59 53 60 public override IEnumerable<Individual> GetNeighbors(Individual individual, IRandom random) { 54 foreach (var move in ExhaustiveInversionMoveGenerator.Generate(individual.Permutation())) {61 while (true) { 55 62 var neighbor = individual.Copy(); 56 InversionManipulator.Apply(neighbor.Permutation(), move.Index1, move.Index2); 63 switch (random.Next(7)) { 64 case 0: InsertionManipulator.Apply(random, neighbor.Permutation()); break; 65 case 1: InversionManipulator.Apply(random, neighbor.Permutation()); break; 66 case 2: ScrambleManipulator.Apply(random, neighbor.Permutation()); break; 67 case 3: Swap2Manipulator.Apply(random, neighbor.Permutation()); break; 68 case 4: Swap3Manipulator.Apply(random, neighbor.Permutation()); break; 69 case 5: TranslocationInversionManipulator.Apply(random, neighbor.Permutation()); break; 70 case 6: TranslocationManipulator.Apply(random, neighbor.Permutation()); break; 71 } 57 72 yield return neighbor; 58 73 } -
branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization/3.3/TtpNetwork2.cs
r14586 r14598 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;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 9 10 namespace HeuristicLab.Networks.IntegratedOptimization {11 [Item("TtpNetwork2", "An optimization network for the TTP.")]12 [Creatable("Optimization Networks")]13 [StorableClass]14 // partial ttp15 // cmaes variegates ksp values (factors)16 // 1) init cmaes (length = ksp.values.length)17 // 2) start cmaes18 // 3) evaluate vector as follows:19 // 4) change ksp values (mult by factor in vector)20 // 5) best ksp21 // 6) best reduced tsp22 // 7) return ttp quality23 public sealed class TtpNetwork2 : Network {24 [StorableConstructor]25 private TtpNetwork2(bool deserializing) : base(deserializing) { }26 private TtpNetwork2(TtpNetwork2 original, Cloner cloner) : base(original, cloner) { }27 public TtpNetwork2() : base("TtpNetwork2") {28 var orchestratorNode = new TtpOrchestratorNode2();29 Nodes.Add(orchestratorNode);10 //namespace HeuristicLab.Networks.IntegratedOptimization { 11 // [Item("TtpNetwork2", "An optimization network for the TTP.")] 12 // [Creatable("Optimization Networks")] 13 // [StorableClass] 14 // // partial ttp 15 // // cmaes variegates ksp values (factors) 16 // // 1) init cmaes (length = ksp.values.length) 17 // // 2) start cmaes 18 // // 3) evaluate vector as follows: 19 // // 4) change ksp values (mult by factor in vector) 20 // // 5) best ksp 21 // // 6) best reduced tsp 22 // // 7) return ttp quality 23 // public sealed class TtpNetwork2 : Network { 24 // [StorableConstructor] 25 // private TtpNetwork2(bool deserializing) : base(deserializing) { } 26 // private TtpNetwork2(TtpNetwork2 original, Cloner cloner) : base(original, cloner) { } 27 // public TtpNetwork2() : base("TtpNetwork2") { 28 // var orchestratorNode = new TtpOrchestratorNode2(); 29 // Nodes.Add(orchestratorNode); 30 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);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 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);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 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);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 54 55 #region Import56 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);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 63 64 var tsp = orchestratorNode.TspParameter.Value;65 tsp.Coordinates = tspCoordinates;64 // var tsp = orchestratorNode.TspParameter.Value; 65 // tsp.Coordinates = tspCoordinates; 66 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;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 72 73 orchestratorNode.AvailabilityParameter.Value = ttpAvailability;74 orchestratorNode.MinSpeedParameter.Value = ttpMinSpeed;75 orchestratorNode.MaxSpeedParameter.Value = ttpMaxSpeed;76 orchestratorNode.RentingRatioParameter.Value = ttpRentingRatio;77 #endregion78 }73 // orchestratorNode.AvailabilityParameter.Value = ttpAvailability; 74 // orchestratorNode.MinSpeedParameter.Value = ttpMinSpeed; 75 // orchestratorNode.MaxSpeedParameter.Value = ttpMaxSpeed; 76 // orchestratorNode.RentingRatioParameter.Value = ttpRentingRatio; 77 // #endregion 78 // } 79 79 80 public override IDeepCloneable Clone(Cloner cloner) {81 return new TtpNetwork2(this, cloner);82 }83 }84 }80 // public override IDeepCloneable Clone(Cloner cloner) { 81 // return new TtpNetwork2(this, cloner); 82 // } 83 // } 84 //} -
branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization/3.3/TtpNetwork3.cs
r14586 r14598 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;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 9 10 namespace HeuristicLab.Networks.IntegratedOptimization {11 [Item("TtpNetwork3", "An optimization network for the TTP.")]12 [Creatable("Optimization Networks")]13 [StorableClass]14 // standard ttp15 // cmaes variegates ksp values and tsp coordinates16 // 1) init cmaes (length = ksp.values.length)17 // 2) start cmaes18 // 3) evaluate vector as follows:19 // 4) change ksp values and tsp coordinates (mult by factor in vector)20 // 5) best ksp21 // 6) best tsp22 // 7) return ttp quality23 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);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 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);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 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);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 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);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 54 55 #region Import56 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);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 63 64 var tsp = orchestratorNode.TspParameter.Value;65 tsp.Coordinates = tspCoordinates;64 // var tsp = orchestratorNode.TspParameter.Value; 65 // tsp.Coordinates = tspCoordinates; 66 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;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 72 73 orchestratorNode.AvailabilityParameter.Value = ttpAvailability;74 orchestratorNode.MinSpeedParameter.Value = ttpMinSpeed;75 orchestratorNode.MaxSpeedParameter.Value = ttpMaxSpeed;76 orchestratorNode.RentingRatioParameter.Value = ttpRentingRatio;77 #endregion78 }73 // orchestratorNode.AvailabilityParameter.Value = ttpAvailability; 74 // orchestratorNode.MinSpeedParameter.Value = ttpMinSpeed; 75 // orchestratorNode.MaxSpeedParameter.Value = ttpMaxSpeed; 76 // orchestratorNode.RentingRatioParameter.Value = ttpRentingRatio; 77 // #endregion 78 // } 79 79 80 public override IDeepCloneable Clone(Cloner cloner) {81 return new TtpNetwork3(this, cloner);82 }83 }84 }80 // public override IDeepCloneable Clone(Cloner cloner) { 81 // return new TtpNetwork3(this, cloner); 82 // } 83 // } 84 //} -
branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization/3.3/TtpNetwork4.cs
r14586 r14598 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;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 9 10 namespace HeuristicLab.Networks.IntegratedOptimization {11 [Item("TtpNetwork4", "An optimization network for the TTP.")]12 [Creatable("Optimization Networks")]13 [StorableClass]14 // standard ttp15 // cmaes variegates tsp coordinates16 // 1) init cmaes (length = ksp.values.length)17 // 2) start cmaes18 // 3) evaluate vector as follows:19 // 4) change tsp coordinates (mult by factor in vector)20 // 5) best tsp21 // 6) best ksp22 // 7) return ttp quality23 public sealed class TtpNetwork4 : Network {24 [StorableConstructor]25 private TtpNetwork4(bool deserializing) : base(deserializing) { }26 private TtpNetwork4(TtpNetwork4 original, Cloner cloner) : base(original, cloner) { }27 public TtpNetwork4() : base("TtpNetwork4") {28 var orchestratorNode = new TtpOrchestratorNode4();29 Nodes.Add(orchestratorNode);10 //namespace HeuristicLab.Networks.IntegratedOptimization { 11 // [Item("TtpNetwork4", "An optimization network for the TTP.")] 12 // [Creatable("Optimization Networks")] 13 // [StorableClass] 14 // // standard ttp 15 // // cmaes variegates tsp coordinates 16 // // 1) init cmaes (length = ksp.values.length) 17 // // 2) start cmaes 18 // // 3) evaluate vector as follows: 19 // // 4) change tsp coordinates (mult by factor in vector) 20 // // 5) best tsp 21 // // 6) best ksp 22 // // 7) return ttp quality 23 // public sealed class TtpNetwork4 : Network { 24 // [StorableConstructor] 25 // private TtpNetwork4(bool deserializing) : base(deserializing) { } 26 // private TtpNetwork4(TtpNetwork4 original, Cloner cloner) : base(original, cloner) { } 27 // public TtpNetwork4() : base("TtpNetwork4") { 28 // var orchestratorNode = new TtpOrchestratorNode4(); 29 // Nodes.Add(orchestratorNode); 30 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);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 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);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 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);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 54 55 #region Import56 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);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 63 64 var tsp = orchestratorNode.TspParameter.Value;65 tsp.Coordinates = tspCoordinates;64 // var tsp = orchestratorNode.TspParameter.Value; 65 // tsp.Coordinates = tspCoordinates; 66 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;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 72 73 orchestratorNode.AvailabilityParameter.Value = ttpAvailability;74 orchestratorNode.MinSpeedParameter.Value = ttpMinSpeed;75 orchestratorNode.MaxSpeedParameter.Value = ttpMaxSpeed;76 orchestratorNode.RentingRatioParameter.Value = ttpRentingRatio;77 #endregion78 }73 // orchestratorNode.AvailabilityParameter.Value = ttpAvailability; 74 // orchestratorNode.MinSpeedParameter.Value = ttpMinSpeed; 75 // orchestratorNode.MaxSpeedParameter.Value = ttpMaxSpeed; 76 // orchestratorNode.RentingRatioParameter.Value = ttpRentingRatio; 77 // #endregion 78 // } 79 79 80 public override IDeepCloneable Clone(Cloner cloner) {81 return new TtpNetwork4(this, cloner);82 }83 }84 }80 // public override IDeepCloneable Clone(Cloner cloner) { 81 // return new TtpNetwork4(this, cloner); 82 // } 83 // } 84 //} -
branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization/3.3/TtpNetwork5.cs
r14586 r14598 1 1 using System; 2 2 using System.Collections.Generic; 3 using System.Linq;4 3 using HeuristicLab.Algorithms.CMAEvolutionStrategy; 5 using HeuristicLab.Algorithms. OffspringSelectionGeneticAlgorithm;4 using HeuristicLab.Algorithms.LocalSearch; 6 5 using HeuristicLab.Algorithms.ParameterlessPopulationPyramid; 7 6 using HeuristicLab.Common; … … 9 8 using HeuristicLab.Core.Networks; 10 9 using HeuristicLab.Data; 11 using HeuristicLab.Encodings.PermutationEncoding;12 10 using HeuristicLab.Optimization; 13 11 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 14 using HeuristicLab.Selection;15 12 16 13 namespace HeuristicLab.Networks.IntegratedOptimization { … … 48 45 [StorableConstructor] 49 46 private TtpNetwork5(bool deserializing) : base(deserializing) { } 50 private TtpNetwork5(TtpNetwork5 original, Cloner cloner) : base(original, cloner) { } 47 private TtpNetwork5(TtpNetwork5 original, Cloner cloner) : base(original, cloner) { 48 RegisterEvents(); 49 } 50 51 private void RegisterEvents() { 52 MetaSolver.Algorithm.ExecutionStateChanged += OnExecutionStateChanged; 53 MetaSolver.Algorithm.ExecutionTimeChanged += OnExecutionTimeChanged; 54 MetaSolver.Algorithm.Prepared += OnPrepared; 55 MetaSolver.Algorithm.Started += OnStarted; 56 MetaSolver.Algorithm.Paused += OnPaused; 57 MetaSolver.Algorithm.Stopped += OnStopped; 58 MetaSolver.Algorithm.ExceptionOccurred += OnExceptionOccurred; 59 } 60 51 61 public TtpNetwork5() : base("TtpNetwork5") { 52 62 var orchestratorNode = new TtpOrchestratorNode5("Orchestrator"); … … 55 65 var metaSolverNode = new OrchestratedAlgorithmNode("MetaSolver"); 56 66 var cmaes = new CMAEvolutionStrategy(); 67 cmaes.Problem = new VariegationProblem(); 57 68 cmaes.MaximumGenerations = 80; 58 cmaes.Engine = new ParallelEngine.ParallelEngine();59 69 metaSolverNode.Algorithm = cmaes; 60 70 orchestratorNode.MetaSolverOrchestrationPort.ConnectedPort = metaSolverNode.OrchestrationPort; 61 71 Nodes.Add(metaSolverNode); 62 72 63 var tspSolverNode = new OrchestratedAlgorithmNode("TspSolver") { CloneAlgorithm = true }; 64 var osga = new OffspringSelectionGeneticAlgorithm(); 65 osga.Problem = new TourProfitProblem(); 66 osga.ComparisonFactorLowerBound.Value = 1.0; 67 osga.ComparisonFactorModifier = null; 68 osga.ComparisonFactorUpperBound.Value = 1.0; 69 var crossover = (MultiPermutationCrossover)(osga.Crossover = osga.CrossoverParameter.ValidValues.First(x => x is MultiPermutationCrossover)); 70 foreach (var c in crossover.Operators) 71 crossover.Operators.SetItemCheckedState(c, c is CosaCrossover || c is OrderCrossover2 || c is PartiallyMatchedCrossover); 72 osga.MaximumSelectionPressure.Value = 200; 73 osga.Mutator = osga.MutatorParameter.ValidValues.First(x => x is MultiPermutationManipulator); 74 osga.PopulationSize.Value = 200; 75 osga.Selector = osga.SelectorParameter.ValidValues.First(x => x is RandomSelector); 76 tspSolverNode.Algorithm = osga; 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 90 var tspSolverNode = new OrchestratedAlgorithmNode("TspSolver"); 91 var ls = new LocalSearch(); 92 ls.Problem = new TourProfitProblem(); 93 ls.MaximumIterations.Value = 100; 94 ls.SampleSize.Value = 2000; 95 tspSolverNode.Algorithm = ls; 77 96 orchestratorNode.TspSolverOrchestrationPort.ConnectedPort = tspSolverNode.OrchestrationPort; 78 97 Nodes.Add(tspSolverNode); 79 98 80 var kspSolverNode = new OrchestratedAlgorithmNode("KspSolver") { CloneAlgorithm = true };99 var kspSolverNode = new OrchestratedAlgorithmNode("KspSolver"); 81 100 var p3 = new ParameterlessPopulationPyramid(); 82 101 p3.Problem = orchestratorNode.KspParameter.Value; … … 109 128 orchestratorNode.RentingRatioParameter.Value = ttpRentingRatio; 110 129 #endregion 111 } 112 113 public event EventHandler ExecutionStateChanged; 114 public event EventHandler ExecutionTimeChanged; 115 public event EventHandler Prepared; 116 public event EventHandler Started; 117 public event EventHandler Paused; 118 public event EventHandler Stopped; 119 public event EventHandler<EventArgs<Exception>> ExceptionOccurred; 130 131 RegisterEvents(); 132 } 120 133 121 134 public override IDeepCloneable Clone(Cloner cloner) { … … 123 136 } 124 137 138 [StorableHook(HookType.AfterDeserialization)] 139 private void AfterDeserialization() { 140 RegisterEvents(); 141 } 142 125 143 #region IOptimizer Members 126 144 public RunCollection Runs { get { return MetaSolver.Algorithm.Runs; } } 127 128 145 public IEnumerable<IOptimizer> NestedOptimizers { get { yield break; } } 129 130 146 public ExecutionState ExecutionState { get { return MetaSolver.Algorithm.ExecutionState; } } 131 132 147 public TimeSpan ExecutionTime { get { return MetaSolver.Algorithm.ExecutionTime; } } 133 148 134 public void Prepare(bool clearRuns) { MetaSolver.Algorithm.Prepare(clearRuns); } 135 149 public void Prepare(bool clearRuns) { Prepare(); } 136 150 public void Prepare() { Orchestrator.Prepare(); } 137 138 public void Start() { Orchestrator.Start(); } 139 140 public void Pause() { Orchestrator.Stop(); } 141 151 public void Start() { 152 if (MetaSolver.Algorithm.ExecutionState == ExecutionState.Prepared) 153 Orchestrator.Prepare(); 154 Orchestrator.StartAsync(); 155 } 156 public void Pause() { Orchestrator.Pause(); } 142 157 public void Stop() { Orchestrator.Stop(); } 143 158 #endregion 159 160 private void OnExecutionStateChanged(object sender, EventArgs e) { OnExecutionStateChanged(); } 161 private void OnExecutionTimeChanged(object sender, EventArgs e) { OnExecutionTimeChanged(); } 162 private void OnPrepared(object sender, EventArgs e) { OnPrepared(); } 163 private void OnStarted(object sender, EventArgs e) { OnStarted(); } 164 private void OnPaused(object sender, EventArgs e) { OnPaused(); } 165 private void OnStopped(object sender, EventArgs e) { OnStopped(); } 166 private void OnExceptionOccurred(object sender, EventArgs<Exception> e) { OnExceptionOccurred(e.Value); } 167 168 public event EventHandler ExecutionStateChanged; 169 private void OnExecutionStateChanged() { 170 var handler = ExecutionStateChanged; 171 if (handler != null) handler(this, EventArgs.Empty); 172 } 173 174 public event EventHandler ExecutionTimeChanged; 175 private void OnExecutionTimeChanged() { 176 var handler = ExecutionTimeChanged; 177 if (handler != null) handler(this, EventArgs.Empty); 178 } 179 180 public event EventHandler Prepared; 181 private void OnPrepared() { 182 var handler = Prepared; 183 if (handler != null) handler(this, EventArgs.Empty); 184 } 185 186 public event EventHandler Started; 187 private void OnStarted() { 188 var handler = Started; 189 if (handler != null) handler(this, EventArgs.Empty); 190 } 191 192 public event EventHandler Paused; 193 private void OnPaused() { 194 var handler = Paused; 195 if (handler != null) handler(this, EventArgs.Empty); 196 } 197 198 public event EventHandler Stopped; 199 private void OnStopped() { 200 var handler = Stopped; 201 if (handler != null) handler(this, EventArgs.Empty); 202 } 203 204 public event EventHandler<EventArgs<Exception>> ExceptionOccurred; 205 private void OnExceptionOccurred(Exception exception) { 206 var handler = ExceptionOccurred; 207 if (handler != null) handler(this, new EventArgs<Exception>(exception)); 208 } 144 209 } 145 210 } -
branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization/3.3/TtpOrchestratorNode1.cs
r14586 r14598 70 70 71 71 // #region Ports 72 // public I ConfigurationPort TspSolverOrchestrationPort {73 // get { return (I ConfigurationPort)Ports[TspSolverName + OrchestrationPortNameSuffix]; }74 // } 75 76 // public I ConfigurationPort TspSolverEvaluationPort {77 // get { return (I ConfigurationPort)Ports[TspSolverName + EvaluationPortNameSuffix]; }78 // } 79 80 // public I ConfigurationPort KspSolverOrchestrationPort {81 // get { return (I ConfigurationPort)Ports[KspSolverName + OrchestrationPortNameSuffix]; }82 // } 83 84 // public I ConfigurationPort KspSolverEvaluationPort {85 // get { return (I ConfigurationPort)Ports[KspSolverName + EvaluationPortNameSuffix]; }72 // public IMessagePort TspSolverOrchestrationPort { 73 // get { return (IMessagePort)Ports[TspSolverName + OrchestrationPortNameSuffix]; } 74 // } 75 76 // public IMessagePort TspSolverEvaluationPort { 77 // get { return (IMessagePort)Ports[TspSolverName + EvaluationPortNameSuffix]; } 78 // } 79 80 // public IMessagePort KspSolverOrchestrationPort { 81 // get { return (IMessagePort)Ports[KspSolverName + OrchestrationPortNameSuffix]; } 82 // } 83 84 // public IMessagePort KspSolverEvaluationPort { 85 // get { return (IMessagePort)Ports[KspSolverName + EvaluationPortNameSuffix]; } 86 86 // } 87 87 // #endregion -
branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization/3.3/TtpOrchestratorNode2.cs
r14586 r14598 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 Constants25 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 #endregion39 40 #region Thread Results41 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 #endregion45 46 #region Parameters47 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 #endregion75 76 #region Ports77 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 #endregion101 102 #region Results103 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 #endregion115 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 Parameters122 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 #endregion130 131 #region Configure Ports132 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 #endregion143 }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 Handling191 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 Analyze226 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 #endregion252 }253 #endregion254 255 #region TspSolver Message Handling256 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 #endregion265 266 #region KspSolver Message Handling267 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 #endregion276 277 #region Helpers278 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 VariegateKsp293 /*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 loot307 bool[] newLoot = (bool[])loot.Clone();308 newLoot[availableItems[0].ItemIdx] = true;309 310 // build new ksp311 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 // evaluate320 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 #endregion344 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 #endregion399 400 #region Event Handlers401 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 #endregion449 }450 }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 //} -
branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization/3.3/TtpOrchestratorNode3.cs
r14586 r14598 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 Constants25 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 #endregion39 40 #region Thread Results41 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 #endregion45 46 #region Parameters47 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 #endregion75 76 #region Ports77 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 #endregion101 102 #region Results103 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 #endregion115 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 Parameters122 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 #endregion130 131 #region Configure Ports132 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 #endregion143 }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 Handling191 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 Analyze235 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 #endregion260 }261 #endregion262 263 #region TspSolver Message Handling264 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 #endregion273 274 #region KspSolver Message Handling275 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 #endregion284 285 #region Helpers286 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 #endregion333 334 #region Event Handlers335 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 #endregion383 }384 }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 //} -
branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization/3.3/TtpOrchestratorNode4.cs
r14586 r14598 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("TtpOrchestratorNode4", "An abstract base class for an orchestrator node for the TTP.")]22 [StorableClass]23 public sealed class TtpOrchestratorNode4 : OrchestratorNode {24 #region Constants25 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 #endregion39 40 #region Thread Results41 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 #endregion45 46 #region Parameters47 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 #endregion75 76 #region Ports77 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 #endregion101 102 #region Results103 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 #endregion115 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 Parameters122 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 #endregion130 131 #region Configure Ports132 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 #endregion143 }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 Handling191 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 Analyze228 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 #endregion253 }254 #endregion255 256 #region TspSolver Message Handling257 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 #endregion266 267 #region KspSolver Message Handling268 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 #endregion277 278 #region Helpers279 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 #endregion326 327 #region Event Handlers328 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 #endregion376 }377 }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("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 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 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 //} -
branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization/3.3/TtpOrchestratorNode5.cs
r14586 r14598 1 1 using System; 2 using System.Collections.Concurrent;3 2 using System.Collections.Generic; 4 3 using System.Linq; … … 33 32 private const string TspSolverName = "TspSolver"; 34 33 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 34 #endregion 35 36 [Storable] 37 private ResultCollection tspResults, kspResults; 38 39 private CancellationTokenSource cts; 45 40 46 41 #region Parameters … … 75 70 76 71 #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; } 72 public IMessagePort MetaSolverOrchestrationPort { 73 get { return (IMessagePort)Ports[MetaSolverName + OrchestrationPortNameSuffix]; } 74 } 75 76 public IMessagePort MetaSolverEvaluationPort { 77 get { return (IMessagePort)Ports[MetaSolverName + EvaluationPortNameSuffix]; } 78 } 79 80 public IMessagePort TspSolverOrchestrationPort { 81 get { return (IMessagePort)Ports[TspSolverName + OrchestrationPortNameSuffix]; } 82 } 83 84 public IMessagePort TspSolverEvaluationPort { 85 get { return (IMessagePort)Ports[TspSolverName + EvaluationPortNameSuffix]; } 86 } 87 88 public IMessagePort KspSolverOrchestrationPort { 89 get { return (IMessagePort)Ports[KspSolverName + OrchestrationPortNameSuffix]; } 90 } 91 92 public IMessagePort KspSolverEvaluationPort { 93 get { return (IMessagePort)Ports[KspSolverName + EvaluationPortNameSuffix]; } 113 94 } 114 95 #endregion … … 116 97 [StorableConstructor] 117 98 private TtpOrchestratorNode5(bool deserializing) : base(deserializing) { } 118 private TtpOrchestratorNode5(TtpOrchestratorNode5 original, Cloner cloner) : base(original, cloner) { } 99 private TtpOrchestratorNode5(TtpOrchestratorNode5 original, Cloner cloner) : base(original, cloner) { 100 RegisterEvents(); 101 } 119 102 public TtpOrchestratorNode5() : this("TtpOrchestratorNode5") { } 120 103 public TtpOrchestratorNode5(string name) : base(name) { … … 137 120 AddEvaluationPort<BinaryVector>(KspSolverName, "KnapsackSolution", "Quality"); 138 121 122 RegisterEvents(); 123 #endregion 124 } 125 126 public override IDeepCloneable Clone(Cloner cloner) { 127 return new TtpOrchestratorNode5(this, cloner); 128 } 129 130 [StorableHook(HookType.AfterDeserialization)] 131 private void AfterDeserialization() { 132 RegisterEvents(); 133 } 134 135 private void RegisterEvents() { 139 136 MetaSolverOrchestrationPort.ConnectedPortChanged += MetaSolverOrchestrationPort_ConnectedPortChanged; 140 137 TspSolverOrchestrationPort.ConnectedPortChanged += TspSolverOrchestrationPort_ConnectedPortChanged; 141 138 KspSolverOrchestrationPort.ConnectedPortChanged += KspSolverOrchestrationPort_ConnectedPortChanged; 142 #endregion143 }144 145 public override IDeepCloneable Clone(Cloner cloner) {146 return new TtpOrchestratorNode5(this, cloner);147 139 } 148 140 149 141 public override void Prepare() { 150 tspThreadResults.Clear();151 kspThreadResults.Clear();152 142 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 143 157 144 var metaMsg = MetaSolverOrchestrationPort.PrepareMessage(); … … 165 152 166 153 public override void Start() { 167 var metaMsg = MetaSolverOrchestrationPort.PrepareMessage(); 168 metaMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Start); 169 MetaSolverOrchestrationPort.SendMessage(metaMsg); 154 cts = new CancellationTokenSource(); 155 156 try { 157 var metaMsg = MetaSolverOrchestrationPort.PrepareMessage(); 158 metaMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Start); 159 MetaSolverOrchestrationPort.SendMessage(metaMsg); 160 } catch (Exception e) { } 170 161 } 171 162 172 163 public override void Pause() { 164 cts.Cancel(); 165 173 166 var metaMsg = MetaSolverOrchestrationPort.PrepareMessage(); 174 167 metaMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Pause); 175 168 MetaSolverOrchestrationPort.SendMessage(metaMsg); 169 170 var tspMsg = TspSolverOrchestrationPort.PrepareMessage(); 171 tspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Stop); 172 TspSolverOrchestrationPort.SendMessage(tspMsg); 173 174 var kspMsg = KspSolverOrchestrationPort.PrepareMessage(); 175 kspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Stop); 176 KspSolverOrchestrationPort.SendMessage(kspMsg); 176 177 } 177 178 178 179 public override void Stop() { 180 cts.Cancel(); 181 179 182 var metaMsg = MetaSolverOrchestrationPort.PrepareMessage(); 180 183 metaMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Stop); 181 184 MetaSolverOrchestrationPort.SendMessage(metaMsg); 185 186 var tspMsg = TspSolverOrchestrationPort.PrepareMessage(); 187 tspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Stop); 188 TspSolverOrchestrationPort.SendMessage(tspMsg); 189 190 var kspMsg = KspSolverOrchestrationPort.PrepareMessage(); 191 kspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Stop); 192 KspSolverOrchestrationPort.SendMessage(kspMsg); 182 193 } 183 194 … … 210 221 kspMsg["Problem"] = ksp; 211 222 KspSolverOrchestrationPort.SendMessage(kspMsg); 212 213 var kspResults = kspThreadResults[Thread.CurrentThread.ManagedThreadId]; 223 cts.Token.ThrowIfCancellationRequested(); 224 214 225 var bestKspSolution = (BinaryVector)kspResults["Best Solution"].Value; 215 226 var kspCapacity = (IntValue)KspParameter.Value.KnapsackCapacity.Clone(); … … 235 246 tspMsg["Problem"] = tpp; 236 247 TspSolverOrchestrationPort.SendMessage(tspMsg); 237 238 var tspResults = tspThreadResults[Thread.CurrentThread.ManagedThreadId]; 248 cts.Token.ThrowIfCancellationRequested(); 249 239 250 var bestTspSolution = (Permutation)tspResults["Best TSP Solution"].Value; 240 251 var coordinates = (DoubleMatrix)TspParameter.Value.Coordinates.Clone(); … … 246 257 ((DoubleValue)message["Quality"]).Value = objectiveValue; 247 258 248 //var ttpResults = new ResultCollection(); 249 //ttpResults.Add(new Result("Quality", new DoubleValue(objectiveValue))); 250 //ttpResults.Add(new Result("Tour", tour)); 251 //ttpResults.Add(new Result("Loot", loot)); 252 253 lock (locker) { 254 //TtpResults.Add(ttpResults); 255 //TspResults.Add(tspResults); 256 //KspResults.Add(kspResults); 257 258 IResult bestQuality; 259 if (!Results.TryGetValue("Best TTP Quality", out bestQuality)) { 260 Results.Add(new Result("Best TTP Quality", new DoubleValue(objectiveValue))); 261 Results.Add(new Result("Best Tour", tour)); 262 Results.Add(new Result("Best Loot", loot)); 263 } else if (((DoubleValue)bestQuality.Value).Value < objectiveValue) { 264 ((DoubleValue)bestQuality.Value).Value = objectiveValue; 265 Results["Best Tour"].Value = tour; 266 Results["Best Loot"].Value = loot; 267 } 259 IResult bestQuality; 260 if (!Results.TryGetValue("Best TTP Quality", out bestQuality)) { 261 Results.Add(new Result("Best TTP Quality", new DoubleValue(objectiveValue))); 262 Results.Add(new Result("Best Tour", tour)); 263 Results.Add(new Result("Best Loot", loot)); 264 } else if (((DoubleValue)bestQuality.Value).Value < objectiveValue) { 265 ((DoubleValue)bestQuality.Value).Value = objectiveValue; 266 Results["Best Tour"].Value = tour; 267 Results["Best Loot"].Value = loot; 268 268 } 269 269 #endregion … … 275 275 var results = (ResultCollection)message["Results"]; 276 276 if (results.ContainsKey("Best TSP Solution")) { 277 tsp ThreadResults[Thread.CurrentThread.ManagedThreadId]= results;277 tspResults = results; 278 278 } 279 279 } … … 286 286 var results = (ResultCollection)message["Results"]; 287 287 if (results.ContainsKey("Best Solution")) { 288 ksp ThreadResults[Thread.CurrentThread.ManagedThreadId]= results;288 kspResults = results; 289 289 } 290 290 }
Note: See TracChangeset
for help on using the changeset viewer.