Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
01/23/17 14:49:07 (7 years ago)
Author:
jkarder
Message:

#2205: worked on optimization networks

  • switched from IConfigurationPorts to IMessagePorts
  • removed option to clone algorithms in OrchestratedAlgorithmNodes
  • made properties of TourProfitProblem storable
  • fixed event handler registration
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  
    2323
    2424    #region Ports
    25     public IConfigurationPort OrchestrationPort {
    26       get { return (IConfigurationPort)Ports[OrchestrationPortName]; }
     25    public IMessagePort OrchestrationPort {
     26      get { return (IMessagePort)Ports[OrchestrationPortName]; }
    2727    }
    28     public IConfigurationPort EvaluationPort {
    29       get { return (IConfigurationPort)Ports[EvaluationPortName]; }
     28    public IMessagePort EvaluationPort {
     29      get { return (IMessagePort)Ports[EvaluationPortName]; }
    3030    }
    3131    #endregion
     
    4242    }
    4343
    44     [Storable]
    45     public bool CloneAlgorithm { get; set; }
    46 
    4744    [StorableConstructor]
    4845    protected OrchestratedAlgorithmNode(bool deserializing) : base(deserializing) { }
    4946    protected OrchestratedAlgorithmNode(OrchestratedAlgorithmNode original, Cloner cloner) : base(original, cloner) {
    50       CloneAlgorithm = original.CloneAlgorithm;
    5147      EvalHook = cloner.Clone(original.EvalHook);
    52 
    53       OrchestrationPort.MessageReceived += OrchestrationPort_MessageReceived;
     48      RegisterEvents();
    5449    }
    5550    public OrchestratedAlgorithmNode() : this("OrchestratedAlgorithmNode") { }
    5651    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);
    6153      Ports.Add(orchestrationPort);
    62       #endregion
    6354
    64       #region EvaluationPort
    65       var evaluationPort = new ConfigurationPort(EvaluationPortName);
     55      var evaluationPort = new MessagePort(EvaluationPortName);
    6656      Ports.Add(evaluationPort);
    67       #endregion
    68       #endregion
     57
     58      RegisterEvents();
    6959    }
    7060
     
    7565    [StorableHook(HookType.AfterDeserialization)]
    7666    private void AfterDeserialization() {
     67      RegisterEvents();
     68    }
     69
     70    private void RegisterEvents() {
    7771      OrchestrationPort.MessageReceived += OrchestrationPort_MessageReceived;
    7872    }
     
    8175    private void OrchestrationPort_MessageReceived(object sender, EventArgs<IMessage, CancellationToken> e) {
    8276      var message = ((EnumValue<OrchestrationMessage>)e.Value["OrchestrationMessage"]).Value;
    83       IAlgorithm alg = null;
    8477
     78      #region Prepare
    8579      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();
    9187
    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              }
    9692
    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              }
    106101
    107           alg.Problem = prob;
     102              Algorithm.Problem = prob;
    108103
    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();
    114118            }
    115           }
    116 
    117           alg.Prepare();
     119            break;
    118120        }
    119121      }
     122      #endregion
    120123
     124      #region Start
    121125      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;
    124131
    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        }
    130158      }
     159      #endregion
    131160
     161      #region Pause
    132162      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        }
    136171      }
     172      #endregion
    137173
     174      #region Stop
    138175      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        }
    141189      }
    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
    153191    }
    154192    #endregion
  • branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization/3.3/OrchestratorNode.cs

    r14586 r14598  
    3939    }
    4040
    41     #region Parameters
    42     //public IValueParameter<EnumValue<OrchestrationMessage>> OrchestrationMessageParameter {
    43     //  get { return (IValueParameter<EnumValue<OrchestrationMessage>>)Parameters[OrchestrationMessageParameterName]; }
    44     //}
    45     #endregion
    46 
    4741    [StorableConstructor]
    4842    protected OrchestratorNode(bool deserializing) : base(deserializing) { }
     
    5145      parameters = cloner.Clone(original.parameters);
    5246      readOnlyParameters = null;
     47      RegisterEvents();
    5348    }
     49
    5450    protected OrchestratorNode() : base("OrchestratorNode") {
    5551      results = new ResultCollection();
     
    7167    }
    7268
     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
    7378    protected void AddOrchestrationPort<T>(string solverName)
    7479        where T : class, IProblem {
    75       var orchestrationPort = new ConfigurationPort(solverName + OrchestrationPortNameSuffix);
     80      var orchestrationPort = new MessagePort(solverName + OrchestrationPortNameSuffix);
    7681      orchestrationPort.Parameters.Add(new PortParameter<EnumValue<OrchestrationMessage>>("OrchestrationMessage") {
    7782        Type = PortParameterType.Output
     
    8792
    8893    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);
    9095      evaluationPort.Parameters.Add(new PortParameter<T>(solutionName) {
    9196        Type = PortParameterType.Input
  • branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization/3.3/Plugin.cs.frame

    r14586 r14598  
    2828  [Plugin("HeuristicLab.Networks.IntegratedOptimization", "3.3.14.$WCREV$")]
    2929  [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")]
    3058  public class HeuristicLabNetworksIntegratedOptimizationPlugin : PluginBase {
    3159  }
  • branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization/3.3/Problems/TourProfitProblem.cs

    r14586 r14598  
    1818    }
    1919
     20    [Storable]
    2021    public TravelingSalesmanProblem Tsp { get; set; }
     22    [Storable]
    2123    public BinaryKnapsackProblem Ksp { get; set; }
     24    [Storable]
    2225    public BinaryVector FixedKspSolution { get; set; }
     26    [Storable]
    2327    public int[] Availability { get; set; }
     28    [Storable]
    2429    public double RentingRatio { get; set; }
     30    [Storable]
    2531    public double MinSpeed { get; set; }
     32    [Storable]
    2633    public double MaxSpeed { get; set; }
    2734
     
    5259
    5360    public override IEnumerable<Individual> GetNeighbors(Individual individual, IRandom random) {
    54       foreach (var move in ExhaustiveInversionMoveGenerator.Generate(individual.Permutation())) {
     61      while (true) {
    5562        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        }
    5772        yield return neighbor;
    5873      }
  • 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;
    99
    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);
     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);
    3030
    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);
    3838
    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);
    4646
    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);
    5454
    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);
     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);
    6363
    64       var tsp = orchestratorNode.TspParameter.Value;
    65       tsp.Coordinates = tspCoordinates;
     64//      var tsp = orchestratorNode.TspParameter.Value;
     65//      tsp.Coordinates = tspCoordinates;
    6666
    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;
    7272
    73       orchestratorNode.AvailabilityParameter.Value = ttpAvailability;
    74       orchestratorNode.MinSpeedParameter.Value = ttpMinSpeed;
    75       orchestratorNode.MaxSpeedParameter.Value = ttpMaxSpeed;
    76       orchestratorNode.RentingRatioParameter.Value = ttpRentingRatio;
    77       #endregion
    78     }
     73//      orchestratorNode.AvailabilityParameter.Value = ttpAvailability;
     74//      orchestratorNode.MinSpeedParameter.Value = ttpMinSpeed;
     75//      orchestratorNode.MaxSpeedParameter.Value = ttpMaxSpeed;
     76//      orchestratorNode.RentingRatioParameter.Value = ttpRentingRatio;
     77//      #endregion
     78//    }
    7979
    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;
    99
    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);
     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);
    3030
    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);
    3838
    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);
    4646
    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);
    5454
    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);
     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);
    6363
    64       var tsp = orchestratorNode.TspParameter.Value;
    65       tsp.Coordinates = tspCoordinates;
     64//      var tsp = orchestratorNode.TspParameter.Value;
     65//      tsp.Coordinates = tspCoordinates;
    6666
    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;
    7272
    73       orchestratorNode.AvailabilityParameter.Value = ttpAvailability;
    74       orchestratorNode.MinSpeedParameter.Value = ttpMinSpeed;
    75       orchestratorNode.MaxSpeedParameter.Value = ttpMaxSpeed;
    76       orchestratorNode.RentingRatioParameter.Value = ttpRentingRatio;
    77       #endregion
    78     }
     73//      orchestratorNode.AvailabilityParameter.Value = ttpAvailability;
     74//      orchestratorNode.MinSpeedParameter.Value = ttpMinSpeed;
     75//      orchestratorNode.MaxSpeedParameter.Value = ttpMaxSpeed;
     76//      orchestratorNode.RentingRatioParameter.Value = ttpRentingRatio;
     77//      #endregion
     78//    }
    7979
    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;
    99
    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);
     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);
    3030
    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);
    3838
    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);
    4646
    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);
    5454
    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);
     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);
    6363
    64       var tsp = orchestratorNode.TspParameter.Value;
    65       tsp.Coordinates = tspCoordinates;
     64//      var tsp = orchestratorNode.TspParameter.Value;
     65//      tsp.Coordinates = tspCoordinates;
    6666
    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;
    7272
    73       orchestratorNode.AvailabilityParameter.Value = ttpAvailability;
    74       orchestratorNode.MinSpeedParameter.Value = ttpMinSpeed;
    75       orchestratorNode.MaxSpeedParameter.Value = ttpMaxSpeed;
    76       orchestratorNode.RentingRatioParameter.Value = ttpRentingRatio;
    77       #endregion
    78     }
     73//      orchestratorNode.AvailabilityParameter.Value = ttpAvailability;
     74//      orchestratorNode.MinSpeedParameter.Value = ttpMinSpeed;
     75//      orchestratorNode.MaxSpeedParameter.Value = ttpMaxSpeed;
     76//      orchestratorNode.RentingRatioParameter.Value = ttpRentingRatio;
     77//      #endregion
     78//    }
    7979
    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  
    11using System;
    22using System.Collections.Generic;
    3 using System.Linq;
    43using HeuristicLab.Algorithms.CMAEvolutionStrategy;
    5 using HeuristicLab.Algorithms.OffspringSelectionGeneticAlgorithm;
     4using HeuristicLab.Algorithms.LocalSearch;
    65using HeuristicLab.Algorithms.ParameterlessPopulationPyramid;
    76using HeuristicLab.Common;
     
    98using HeuristicLab.Core.Networks;
    109using HeuristicLab.Data;
    11 using HeuristicLab.Encodings.PermutationEncoding;
    1210using HeuristicLab.Optimization;
    1311using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    14 using HeuristicLab.Selection;
    1512
    1613namespace HeuristicLab.Networks.IntegratedOptimization {
     
    4845    [StorableConstructor]
    4946    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
    5161    public TtpNetwork5() : base("TtpNetwork5") {
    5262      var orchestratorNode = new TtpOrchestratorNode5("Orchestrator");
     
    5565      var metaSolverNode = new OrchestratedAlgorithmNode("MetaSolver");
    5666      var cmaes = new CMAEvolutionStrategy();
     67      cmaes.Problem = new VariegationProblem();
    5768      cmaes.MaximumGenerations = 80;
    58       cmaes.Engine = new ParallelEngine.ParallelEngine();
    5969      metaSolverNode.Algorithm = cmaes;
    6070      orchestratorNode.MetaSolverOrchestrationPort.ConnectedPort = metaSolverNode.OrchestrationPort;
    6171      Nodes.Add(metaSolverNode);
    6272
    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;
    7796      orchestratorNode.TspSolverOrchestrationPort.ConnectedPort = tspSolverNode.OrchestrationPort;
    7897      Nodes.Add(tspSolverNode);
    7998
    80       var kspSolverNode = new OrchestratedAlgorithmNode("KspSolver") { CloneAlgorithm = true };
     99      var kspSolverNode = new OrchestratedAlgorithmNode("KspSolver");
    81100      var p3 = new ParameterlessPopulationPyramid();
    82101      p3.Problem = orchestratorNode.KspParameter.Value;
     
    109128      orchestratorNode.RentingRatioParameter.Value = ttpRentingRatio;
    110129      #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    }
    120133
    121134    public override IDeepCloneable Clone(Cloner cloner) {
     
    123136    }
    124137
     138    [StorableHook(HookType.AfterDeserialization)]
     139    private void AfterDeserialization() {
     140      RegisterEvents();
     141    }
     142
    125143    #region IOptimizer Members
    126144    public RunCollection Runs { get { return MetaSolver.Algorithm.Runs; } }
    127 
    128145    public IEnumerable<IOptimizer> NestedOptimizers { get { yield break; } }
    129 
    130146    public ExecutionState ExecutionState { get { return MetaSolver.Algorithm.ExecutionState; } }
    131 
    132147    public TimeSpan ExecutionTime { get { return MetaSolver.Algorithm.ExecutionTime; } }
    133148
    134     public void Prepare(bool clearRuns) { MetaSolver.Algorithm.Prepare(clearRuns); }
    135 
     149    public void Prepare(bool clearRuns) { Prepare(); }
    136150    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(); }
    142157    public void Stop() { Orchestrator.Stop(); }
    143158    #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    }
    144209  }
    145210}
  • branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization/3.3/TtpOrchestratorNode1.cs

    r14586 r14598  
    7070
    7171//    #region Ports
    72 //    public IConfigurationPort TspSolverOrchestrationPort {
    73 //      get { return (IConfigurationPort)Ports[TspSolverName + OrchestrationPortNameSuffix]; }
    74 //    }
    75 
    76 //    public IConfigurationPort TspSolverEvaluationPort {
    77 //      get { return (IConfigurationPort)Ports[TspSolverName + EvaluationPortNameSuffix]; }
    78 //    }
    79 
    80 //    public IConfigurationPort KspSolverOrchestrationPort {
    81 //      get { return (IConfigurationPort)Ports[KspSolverName + OrchestrationPortNameSuffix]; }
    82 //    }
    83 
    84 //    public IConfigurationPort KspSolverEvaluationPort {
    85 //      get { return (IConfigurationPort)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]; }
    8686//    }
    8787//    #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 Constants
    25     private const string TspParameterName = "TSP";
    26     private const string KspParameterName = "KSP";
    27     private const string AvailabilityParameterName = "Availability";
    28     private const string MinSpeedParameterName = "MinSpeed";
    29     private const string MaxSpeedParameterName = "MaxSpeed";
    30     private const string RentingRatioParameterName = "RentingRatio";
    31     private const string IterationsParameterName = "Iterations";
    32     private const string MetaSolverName = "MetaSolver";
    33     private const string TspSolverName = "TspSolver";
    34     private const string KspSolverName = "KspSolver";
    35     private const string TspResultsResultName = "TspResults";
    36     private const string KspResultsResultName = "KspResults";
    37     private const string TtpResultsResultName = "TtpResults";
    38     #endregion
    39 
    40     #region Thread Results
    41     private object locker = new object();
    42     private ConcurrentDictionary<int, ResultCollection> tspThreadResults = new ConcurrentDictionary<int, ResultCollection>();
    43     private ConcurrentDictionary<int, ResultCollection> kspThreadResults = new ConcurrentDictionary<int, ResultCollection>();
    44     #endregion
    45 
    46     #region Parameters
    47     public IValueParameter<IntValue> IterationsParameter {
    48       get { return (IValueParameter<IntValue>)Parameters[IterationsParameterName]; }
    49     }
    50 
    51     public IValueParameter<TravelingSalesmanProblem> TspParameter {
    52       get { return (IValueParameter<TravelingSalesmanProblem>)Parameters[TspParameterName]; }
    53     }
    54 
    55     public IValueParameter<BinaryKnapsackProblem> KspParameter {
    56       get { return (IValueParameter<BinaryKnapsackProblem>)Parameters[KspParameterName]; }
    57     }
    58 
    59     public IValueParameter<IntArray> AvailabilityParameter {
    60       get { return (IValueParameter<IntArray>)Parameters[AvailabilityParameterName]; }
    61     }
    62 
    63     public IValueParameter<DoubleValue> MinSpeedParameter {
    64       get { return (IValueParameter<DoubleValue>)Parameters[MinSpeedParameterName]; }
    65     }
    66 
    67     public IValueParameter<DoubleValue> MaxSpeedParameter {
    68       get { return (IValueParameter<DoubleValue>)Parameters[MaxSpeedParameterName]; }
    69     }
    70 
    71     public IValueParameter<DoubleValue> RentingRatioParameter {
    72       get { return (IValueParameter<DoubleValue>)Parameters[RentingRatioParameterName]; }
    73     }
    74     #endregion
    75 
    76     #region Ports
    77     public IConfigurationPort MetaSolverOrchestrationPort {
    78       get { return (IConfigurationPort)Ports[MetaSolverName + OrchestrationPortNameSuffix]; }
    79     }
    80 
    81     public IConfigurationPort MetaSolverEvaluationPort {
    82       get { return (IConfigurationPort)Ports[MetaSolverName + EvaluationPortNameSuffix]; }
    83     }
    84 
    85     public IConfigurationPort TspSolverOrchestrationPort {
    86       get { return (IConfigurationPort)Ports[TspSolverName + OrchestrationPortNameSuffix]; }
    87     }
    88 
    89     public IConfigurationPort TspSolverEvaluationPort {
    90       get { return (IConfigurationPort)Ports[TspSolverName + EvaluationPortNameSuffix]; }
    91     }
    92 
    93     public IConfigurationPort KspSolverOrchestrationPort {
    94       get { return (IConfigurationPort)Ports[KspSolverName + OrchestrationPortNameSuffix]; }
    95     }
    96 
    97     public IConfigurationPort KspSolverEvaluationPort {
    98       get { return (IConfigurationPort)Ports[KspSolverName + EvaluationPortNameSuffix]; }
    99     }
    100     #endregion
    101 
    102     #region Results
    103     public ItemList<ResultCollection> TspResults {
    104       get { return (ItemList<ResultCollection>)Results[TspResultsResultName].Value; }
    105     }
    106 
    107     public ItemList<ResultCollection> KspResults {
    108       get { return (ItemList<ResultCollection>)Results[KspResultsResultName].Value; }
    109     }
    110 
    111     public ItemList<ResultCollection> TtpResults {
    112       get { return (ItemList<ResultCollection>)Results[TtpResultsResultName].Value; }
    113     }
    114     #endregion
    115 
    116     [StorableConstructor]
    117     private 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 }
     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 Constants
    25     private const string TspParameterName = "TSP";
    26     private const string KspParameterName = "KSP";
    27     private const string AvailabilityParameterName = "Availability";
    28     private const string MinSpeedParameterName = "MinSpeed";
    29     private const string MaxSpeedParameterName = "MaxSpeed";
    30     private const string RentingRatioParameterName = "RentingRatio";
    31     private const string IterationsParameterName = "Iterations";
    32     private const string MetaSolverName = "MetaSolver";
    33     private const string TspSolverName = "TspSolver";
    34     private const string KspSolverName = "KspSolver";
    35     private const string TspResultsResultName = "TspResults";
    36     private const string KspResultsResultName = "KspResults";
    37     private const string TtpResultsResultName = "TtpResults";
    38     #endregion
    39 
    40     #region Thread Results
    41     private object locker = new object();
    42     private ConcurrentDictionary<int, ResultCollection> tspThreadResults = new ConcurrentDictionary<int, ResultCollection>();
    43     private ConcurrentDictionary<int, ResultCollection> kspThreadResults = new ConcurrentDictionary<int, ResultCollection>();
    44     #endregion
    45 
    46     #region Parameters
    47     public IValueParameter<IntValue> IterationsParameter {
    48       get { return (IValueParameter<IntValue>)Parameters[IterationsParameterName]; }
    49     }
    50 
    51     public IValueParameter<TravelingSalesmanProblem> TspParameter {
    52       get { return (IValueParameter<TravelingSalesmanProblem>)Parameters[TspParameterName]; }
    53     }
    54 
    55     public IValueParameter<BinaryKnapsackProblem> KspParameter {
    56       get { return (IValueParameter<BinaryKnapsackProblem>)Parameters[KspParameterName]; }
    57     }
    58 
    59     public IValueParameter<IntArray> AvailabilityParameter {
    60       get { return (IValueParameter<IntArray>)Parameters[AvailabilityParameterName]; }
    61     }
    62 
    63     public IValueParameter<DoubleValue> MinSpeedParameter {
    64       get { return (IValueParameter<DoubleValue>)Parameters[MinSpeedParameterName]; }
    65     }
    66 
    67     public IValueParameter<DoubleValue> MaxSpeedParameter {
    68       get { return (IValueParameter<DoubleValue>)Parameters[MaxSpeedParameterName]; }
    69     }
    70 
    71     public IValueParameter<DoubleValue> RentingRatioParameter {
    72       get { return (IValueParameter<DoubleValue>)Parameters[RentingRatioParameterName]; }
    73     }
    74     #endregion
    75 
    76     #region Ports
    77     public IConfigurationPort MetaSolverOrchestrationPort {
    78       get { return (IConfigurationPort)Ports[MetaSolverName + OrchestrationPortNameSuffix]; }
    79     }
    80 
    81     public IConfigurationPort MetaSolverEvaluationPort {
    82       get { return (IConfigurationPort)Ports[MetaSolverName + EvaluationPortNameSuffix]; }
    83     }
    84 
    85     public IConfigurationPort TspSolverOrchestrationPort {
    86       get { return (IConfigurationPort)Ports[TspSolverName + OrchestrationPortNameSuffix]; }
    87     }
    88 
    89     public IConfigurationPort TspSolverEvaluationPort {
    90       get { return (IConfigurationPort)Ports[TspSolverName + EvaluationPortNameSuffix]; }
    91     }
    92 
    93     public IConfigurationPort KspSolverOrchestrationPort {
    94       get { return (IConfigurationPort)Ports[KspSolverName + OrchestrationPortNameSuffix]; }
    95     }
    96 
    97     public IConfigurationPort KspSolverEvaluationPort {
    98       get { return (IConfigurationPort)Ports[KspSolverName + EvaluationPortNameSuffix]; }
    99     }
    100     #endregion
    101 
    102     #region Results
    103     public ItemList<ResultCollection> TspResults {
    104       get { return (ItemList<ResultCollection>)Results[TspResultsResultName].Value; }
    105     }
    106 
    107     public ItemList<ResultCollection> KspResults {
    108       get { return (ItemList<ResultCollection>)Results[KspResultsResultName].Value; }
    109     }
    110 
    111     public ItemList<ResultCollection> TtpResults {
    112       get { return (ItemList<ResultCollection>)Results[TtpResultsResultName].Value; }
    113     }
    114     #endregion
    115 
    116     [StorableConstructor]
    117     private TtpOrchestratorNode3(bool deserializing) : base(deserializing) { }
    118     private TtpOrchestratorNode3(TtpOrchestratorNode3 original, Cloner cloner) : base(original, cloner) { }
    119     public TtpOrchestratorNode3() : this("TtpOrchestratorNode3") { }
    120     public TtpOrchestratorNode3(string name) : base(name) {
    121       #region Configure Parameters
    122       Parameters.Add(new ValueParameter<IntValue>(IterationsParameterName, new IntValue(20)));
    123       Parameters.Add(new ValueParameter<TravelingSalesmanProblem>(TspParameterName, new TravelingSalesmanProblem()));
    124       Parameters.Add(new ValueParameter<BinaryKnapsackProblem>(KspParameterName, new BinaryKnapsackProblem()));
    125       Parameters.Add(new ValueParameter<IntArray>(AvailabilityParameterName));
    126       Parameters.Add(new ValueParameter<DoubleValue>(MinSpeedParameterName, new DoubleValue(0.1)));
    127       Parameters.Add(new ValueParameter<DoubleValue>(MaxSpeedParameterName, new DoubleValue(1.0)));
    128       Parameters.Add(new ValueParameter<DoubleValue>(RentingRatioParameterName, new DoubleValue(0.5)));
    129       #endregion
    130 
    131       #region Configure Ports
    132       AddOrchestrationPort<VariegationProblem>(MetaSolverName);
    133       AddEvaluationPort<RealVector>(MetaSolverName, "RealVector", "Quality");
    134       AddOrchestrationPort<TravelingSalesmanProblem>(TspSolverName);
    135       AddEvaluationPort<Permutation>(TspSolverName, "TSPTour", "TSPTourLength");
    136       AddOrchestrationPort<BinaryKnapsackProblem>(KspSolverName);
    137       AddEvaluationPort<BinaryVector>(KspSolverName, "KnapsackSolution", "Quality");
    138 
    139       MetaSolverOrchestrationPort.ConnectedPortChanged += MetaSolverOrchestrationPort_ConnectedPortChanged;
    140       TspSolverOrchestrationPort.ConnectedPortChanged += TspSolverOrchestrationPort_ConnectedPortChanged;
    141       KspSolverOrchestrationPort.ConnectedPortChanged += KspSolverOrchestrationPort_ConnectedPortChanged;
    142       #endregion
    143     }
    144 
    145     public override IDeepCloneable Clone(Cloner cloner) {
    146       return new TtpOrchestratorNode3(this, cloner);
    147     }
    148 
    149     public override void Prepare() {
    150       tspThreadResults.Clear();
    151       kspThreadResults.Clear();
    152       Results.Clear();
    153       Results.Add(new Result(TspResultsResultName, new ItemList<ResultCollection>()));
    154       Results.Add(new Result(KspResultsResultName, new ItemList<ResultCollection>()));
    155       Results.Add(new Result(TtpResultsResultName, new ItemList<ResultCollection>()));
    156     }
    157 
    158     public override void Start() {
    159       var metaMsg = MetaSolverOrchestrationPort.PrepareMessage();
    160       metaMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.QualityAdaption);
    161       var problem = new VariegationProblem();
    162       problem.Encoding.Length = KspParameter.Value.Length + TspParameter.Value.Coordinates.Rows * 2;
    163       problem.Encoding.Bounds = new DoubleMatrix(new[,] { { -1.0, 1.0 } });
    164       metaMsg["Problem"] = problem;
    165       MetaSolverOrchestrationPort.SendMessage(metaMsg);
    166     }
    167 
    168     public override void Pause() {
    169       throw new NotImplementedException();
    170     }
    171 
    172     public override void Stop() {
    173       throw new NotImplementedException();
    174     }
    175 
    176     protected override void ProcessMessage(IMessage message, IMessagePort port, CancellationToken token) {
    177       var messageActions = new Dictionary<IMessagePort, Action<IMessage>>();
    178       messageActions.Add(MetaSolverOrchestrationPort, MetaSolverOrchestrationPortMessage);
    179       messageActions.Add(MetaSolverEvaluationPort, MetaSolverEvaluationPortMessage);
    180       messageActions.Add(TspSolverOrchestrationPort, TspSolverOrchestrationPortMessage);
    181       messageActions.Add(TspSolverEvaluationPort, TspSolverEvaluationPortMessage);
    182       messageActions.Add(KspSolverOrchestrationPort, KspSolverOrchestrationPortMessage);
    183       messageActions.Add(KspSolverEvaluationPort, KspSolverEvaluationPortMessage);
    184 
    185       messageActions[port](message);
    186 
    187       base.ProcessMessage(message, port, token);
    188     }
    189 
    190     #region MetaSolver Message Handling
    191     private void MetaSolverOrchestrationPortMessage(IMessage message) { }
    192 
    193     private void MetaSolverEvaluationPortMessage(IMessage message) {
    194       var factors = (RealVector)message["RealVector"];
    195       int fi = 0;
    196 
    197       var ksp = (BinaryKnapsackProblem)KspParameter.Value.Clone();
    198       while (fi < ksp.Values.Length) {
    199         ksp.Values[fi] = (int)Math.Ceiling(ksp.Values[fi] * factors[fi]);
    200         ++fi;
    201       }
    202 
    203       var kspMsg = KspSolverOrchestrationPort.PrepareMessage();
    204       kspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Start);
    205       kspMsg["Problem"] = ksp;
    206       KspSolverOrchestrationPort.SendMessage(kspMsg);
    207 
    208       var kspResults = kspThreadResults[Thread.CurrentThread.ManagedThreadId];
    209       var bestKspSolution = (BinaryVector)kspResults["Best Solution"].Value;
    210       var kspCapacity = (IntValue)KspParameter.Value.KnapsackCapacity.Clone();
    211       var kspPenalty = new DoubleValue(0.0);
    212       var kspWeights = (IntArray)KspParameter.Value.Weights.Clone();
    213       var kspValues = (IntArray)KspParameter.Value.Values.Clone();
    214       var bestKspQuality = KnapsackEvaluator.Apply(bestKspSolution, kspCapacity, kspPenalty, kspWeights, kspValues).Quality;
    215       var loot = new KnapsackSolution(bestKspSolution, bestKspQuality, kspCapacity, kspWeights, kspValues);
    216       kspResults.Add(new Result("Best KSP Solution", loot));
    217 
    218       var tsp = (TravelingSalesmanProblem)TspParameter.Value.Clone();
    219       for (int j = 0; j < tsp.Coordinates.Rows; j++) {
    220         tsp.Coordinates[j, 0] = (int)Math.Ceiling(tsp.Coordinates[j, 0] * factors[fi + j * 2]);
    221         tsp.Coordinates[j, 1] = (int)Math.Ceiling(tsp.Coordinates[j, 1] * factors[fi + j * 2 + 1]);
    222       }
    223 
    224       var tspMsg = TspSolverOrchestrationPort.PrepareMessage();
    225       tspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Start);
    226       tspMsg["Problem"] = tsp;
    227       TspSolverOrchestrationPort.SendMessage(tspMsg);
    228 
    229       var tspResults = tspThreadResults[Thread.CurrentThread.ManagedThreadId];
    230       var tour = (PathTSPTour)tspResults["Best TSP Solution"].Value;
    231       tour.Coordinates = (DoubleMatrix)TspParameter.Value.Coordinates.Clone();
    232       tour.Quality.Value = TSPCoordinatesPathEvaluator.Apply(new TSPEuclideanPathEvaluator(), tour.Coordinates, tour.Permutation);
    233 
    234       #region Analyze
    235       double objectiveValue = EvaluateTtp(TspParameter.Value, tour.Permutation.ToArray(), KspParameter.Value, loot.BinaryVector.ToArray());
    236       ((DoubleValue)message["Quality"]).Value = objectiveValue;
    237 
    238       var ttpResults = new ResultCollection();
    239       ttpResults.Add(new Result("Quality", new DoubleValue(objectiveValue)));
    240       ttpResults.Add(new Result("Tour", tour));
    241       ttpResults.Add(new Result("Loot", loot));
    242 
    243       lock (locker) {
    244         TtpResults.Add(ttpResults);
    245         TspResults.Add(tspResults);
    246         KspResults.Add(kspResults);
    247 
    248         IResult bestQuality;
    249         if (!Results.TryGetValue("Best TTP Quality", out bestQuality)) {
    250           Results.Add(new Result("Best TTP Quality", new DoubleValue(objectiveValue)));
    251           Results.Add(new Result("Best Tour", tour));
    252           Results.Add(new Result("Best Loot", loot));
    253         } else if (((DoubleValue)bestQuality.Value).Value < objectiveValue) {
    254           ((DoubleValue)bestQuality.Value).Value = objectiveValue;
    255           Results["Best Tour"].Value = tour;
    256           Results["Best Loot"].Value = loot;
    257         }
    258       }
    259       #endregion
    260     }
    261     #endregion
    262 
    263     #region TspSolver Message Handling
    264     private void TspSolverOrchestrationPortMessage(IMessage message) {
    265       var results = (ResultCollection)message["Results"];
    266       if (results.ContainsKey("Best TSP Solution")) {
    267         tspThreadResults[Thread.CurrentThread.ManagedThreadId] = results;
    268       }
    269     }
    270 
    271     private void TspSolverEvaluationPortMessage(IMessage message) { }
    272     #endregion
    273 
    274     #region KspSolver Message Handling
    275     private void KspSolverOrchestrationPortMessage(IMessage message) {
    276       var results = (ResultCollection)message["Results"];
    277       if (results.ContainsKey("Best Solution")) {
    278         kspThreadResults[Thread.CurrentThread.ManagedThreadId] = results;
    279       }
    280     }
    281 
    282     private void KspSolverEvaluationPortMessage(IMessage message) { }
    283     #endregion
    284 
    285     #region Helpers
    286     private double EvaluateTtp(TravelingSalesmanProblem tsp, int[] tour, BinaryKnapsackProblem ksp, bool[] loot) {
    287       bool feasible;
    288       return EvaluateTtp(tsp, tour, ksp, loot, out feasible);
    289     }
    290 
    291     private double EvaluateTtp(TravelingSalesmanProblem tsp, int[] tour, BinaryKnapsackProblem ksp, bool[] loot, out bool feasible) {
    292       double collectedWeight = 0.0;
    293       double objectiveValue = 0.0;
    294       double infeasibleBaseLine = -1000000.0;
    295       double speedCoefficient = (MaxSpeedParameter.Value.Value - MinSpeedParameter.Value.Value) / ksp.KnapsackCapacity.Value;
    296 
    297       int hideoutIdx = 0;
    298       while (tour[hideoutIdx] != 0) hideoutIdx++;
    299       int cityIdx = (hideoutIdx + 1) % tour.Length;
    300       int lastCityIdx = hideoutIdx;
    301 
    302       while (cityIdx != hideoutIdx) {
    303         double oldCollectedWeight = collectedWeight;
    304         var availableItems = AvailabilityParameter.Value.Select((c, i) => new { CityIdx = c, ItemIdx = i }).Where(x => x.CityIdx == tour[cityIdx]);
    305 
    306         foreach (var item in availableItems) {
    307           if (!loot[item.ItemIdx]) continue;
    308           collectedWeight += ksp.Weights[item.ItemIdx];
    309           objectiveValue += ksp.Values[item.ItemIdx];
    310         }
    311 
    312         objectiveValue -= Distance(tsp.Coordinates.CloneAsMatrix(), tour[lastCityIdx], tour[cityIdx]) * RentingRatioParameter.Value.Value /
    313                           (MaxSpeedParameter.Value.Value - speedCoefficient * oldCollectedWeight);
    314         lastCityIdx = cityIdx;
    315         cityIdx = (cityIdx + 1) % tour.Length;
    316       }
    317 
    318       objectiveValue -= Distance(tsp.Coordinates.CloneAsMatrix(), tour[lastCityIdx], tour[hideoutIdx]) * RentingRatioParameter.Value.Value /
    319                         (MaxSpeedParameter.Value.Value - speedCoefficient * collectedWeight);
    320 
    321       feasible = collectedWeight <= ksp.KnapsackCapacity.Value;
    322       if (!feasible) objectiveValue = infeasibleBaseLine - collectedWeight;
    323 
    324       return objectiveValue;
    325     }
    326 
    327     private double Distance(double[,] coords, int fromIdx, int toIdx) {
    328       double fromX = coords[fromIdx, 0], fromY = coords[fromIdx, 1],
    329              toX = coords[toIdx, 0], toY = coords[toIdx, 1];
    330       return (int)Math.Ceiling(Math.Sqrt((toX - fromX) * (toX - fromX) + (toY - fromY) * (toY - fromY)));
    331     }
    332     #endregion
    333 
    334     #region Event Handlers
    335     private void MetaSolverOrchestrationPort_ConnectedPortChanged(object sender, EventArgs e) {
    336       if (MetaSolverOrchestrationPort.ConnectedPort == null) return;
    337 
    338       var node = MetaSolverOrchestrationPort.ConnectedPort.Parent as OrchestratedAlgorithmNode;
    339       if (node == null) return;
    340 
    341       var hook = new HookOperator { Name = "Meta Eval Hook" };
    342       hook.Parameters.Add(new LookupParameter<RealVector>("RealVector") { Hidden = true });
    343       hook.Parameters.Add(new LookupParameter<DoubleValue>("Quality") { Hidden = true });
    344       node.EvalHook = hook;
    345 
    346       node.OrchestrationPort.CloneParametersFromPort(MetaSolverOrchestrationPort);
    347       node.EvaluationPort.CloneParametersFromPort(MetaSolverEvaluationPort);
    348       node.EvaluationPort.ConnectedPort = MetaSolverEvaluationPort;
    349     }
    350 
    351     private void TspSolverOrchestrationPort_ConnectedPortChanged(object sender, EventArgs e) {
    352       if (TspSolverOrchestrationPort.ConnectedPort == null) return;
    353 
    354       var node = TspSolverOrchestrationPort.ConnectedPort.Parent as OrchestratedAlgorithmNode;
    355       if (node == null) return;
    356 
    357       var hook = new HookOperator { Name = "TSP Eval Hook" };
    358       hook.Parameters.Add(new LookupParameter<Permutation>("TSPTour") { Hidden = true });
    359       hook.Parameters.Add(new LookupParameter<DoubleValue>("TSPTourLength") { Hidden = true });
    360       node.EvalHook = hook;
    361 
    362       node.OrchestrationPort.CloneParametersFromPort(TspSolverOrchestrationPort);
    363       node.EvaluationPort.CloneParametersFromPort(TspSolverEvaluationPort);
    364       node.EvaluationPort.ConnectedPort = TspSolverEvaluationPort;
    365     }
    366 
    367     private void KspSolverOrchestrationPort_ConnectedPortChanged(object sender, EventArgs e) {
    368       if (KspSolverOrchestrationPort.ConnectedPort == null) return;
    369 
    370       var node = KspSolverOrchestrationPort.ConnectedPort.Parent as OrchestratedAlgorithmNode;
    371       if (node == null) return;
    372 
    373       var hook = new HookOperator { Name = "KSP Eval Hook" };
    374       hook.Parameters.Add(new LookupParameter<BinaryVector>("KnapsackSolution") { Hidden = true });
    375       hook.Parameters.Add(new LookupParameter<DoubleValue>("Quality") { Hidden = true });
    376       node.EvalHook = hook;
    377 
    378       node.OrchestrationPort.CloneParametersFromPort(KspSolverOrchestrationPort);
    379       node.EvaluationPort.CloneParametersFromPort(KspSolverEvaluationPort);
    380       node.EvaluationPort.ConnectedPort = KspSolverEvaluationPort;
    381     }
    382     #endregion
    383   }
    384 }
     1//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 Constants
    25     private const string TspParameterName = "TSP";
    26     private const string KspParameterName = "KSP";
    27     private const string AvailabilityParameterName = "Availability";
    28     private const string MinSpeedParameterName = "MinSpeed";
    29     private const string MaxSpeedParameterName = "MaxSpeed";
    30     private const string RentingRatioParameterName = "RentingRatio";
    31     private const string IterationsParameterName = "Iterations";
    32     private const string MetaSolverName = "MetaSolver";
    33     private const string TspSolverName = "TspSolver";
    34     private const string KspSolverName = "KspSolver";
    35     private const string TspResultsResultName = "TspResults";
    36     private const string KspResultsResultName = "KspResults";
    37     private const string TtpResultsResultName = "TtpResults";
    38     #endregion
    39 
    40     #region Thread Results
    41     private object locker = new object();
    42     private ConcurrentDictionary<int, ResultCollection> tspThreadResults = new ConcurrentDictionary<int, ResultCollection>();
    43     private ConcurrentDictionary<int, ResultCollection> kspThreadResults = new ConcurrentDictionary<int, ResultCollection>();
    44     #endregion
    45 
    46     #region Parameters
    47     public IValueParameter<IntValue> IterationsParameter {
    48       get { return (IValueParameter<IntValue>)Parameters[IterationsParameterName]; }
    49     }
    50 
    51     public IValueParameter<TravelingSalesmanProblem> TspParameter {
    52       get { return (IValueParameter<TravelingSalesmanProblem>)Parameters[TspParameterName]; }
    53     }
    54 
    55     public IValueParameter<BinaryKnapsackProblem> KspParameter {
    56       get { return (IValueParameter<BinaryKnapsackProblem>)Parameters[KspParameterName]; }
    57     }
    58 
    59     public IValueParameter<IntArray> AvailabilityParameter {
    60       get { return (IValueParameter<IntArray>)Parameters[AvailabilityParameterName]; }
    61     }
    62 
    63     public IValueParameter<DoubleValue> MinSpeedParameter {
    64       get { return (IValueParameter<DoubleValue>)Parameters[MinSpeedParameterName]; }
    65     }
    66 
    67     public IValueParameter<DoubleValue> MaxSpeedParameter {
    68       get { return (IValueParameter<DoubleValue>)Parameters[MaxSpeedParameterName]; }
    69     }
    70 
    71     public IValueParameter<DoubleValue> RentingRatioParameter {
    72       get { return (IValueParameter<DoubleValue>)Parameters[RentingRatioParameterName]; }
    73     }
    74     #endregion
    75 
    76     #region Ports
    77     public IConfigurationPort MetaSolverOrchestrationPort {
    78       get { return (IConfigurationPort)Ports[MetaSolverName + OrchestrationPortNameSuffix]; }
    79     }
    80 
    81     public IConfigurationPort MetaSolverEvaluationPort {
    82       get { return (IConfigurationPort)Ports[MetaSolverName + EvaluationPortNameSuffix]; }
    83     }
    84 
    85     public IConfigurationPort TspSolverOrchestrationPort {
    86       get { return (IConfigurationPort)Ports[TspSolverName + OrchestrationPortNameSuffix]; }
    87     }
    88 
    89     public IConfigurationPort TspSolverEvaluationPort {
    90       get { return (IConfigurationPort)Ports[TspSolverName + EvaluationPortNameSuffix]; }
    91     }
    92 
    93     public IConfigurationPort KspSolverOrchestrationPort {
    94       get { return (IConfigurationPort)Ports[KspSolverName + OrchestrationPortNameSuffix]; }
    95     }
    96 
    97     public IConfigurationPort KspSolverEvaluationPort {
    98       get { return (IConfigurationPort)Ports[KspSolverName + EvaluationPortNameSuffix]; }
    99     }
    100     #endregion
    101 
    102     #region Results
    103     public ItemList<ResultCollection> TspResults {
    104       get { return (ItemList<ResultCollection>)Results[TspResultsResultName].Value; }
    105     }
    106 
    107     public ItemList<ResultCollection> KspResults {
    108       get { return (ItemList<ResultCollection>)Results[KspResultsResultName].Value; }
    109     }
    110 
    111     public ItemList<ResultCollection> TtpResults {
    112       get { return (ItemList<ResultCollection>)Results[TtpResultsResultName].Value; }
    113     }
    114     #endregion
    115 
    116     [StorableConstructor]
    117     private TtpOrchestratorNode4(bool deserializing) : base(deserializing) { }
    118     private TtpOrchestratorNode4(TtpOrchestratorNode4 original, Cloner cloner) : base(original, cloner) { }
    119     public TtpOrchestratorNode4() : this("TtpOrchestratorNode4") { }
    120     public TtpOrchestratorNode4(string name) : base(name) {
    121       #region Configure Parameters
    122       Parameters.Add(new ValueParameter<IntValue>(IterationsParameterName, new IntValue(20)));
    123       Parameters.Add(new ValueParameter<TravelingSalesmanProblem>(TspParameterName, new TravelingSalesmanProblem()));
    124       Parameters.Add(new ValueParameter<BinaryKnapsackProblem>(KspParameterName, new BinaryKnapsackProblem()));
    125       Parameters.Add(new ValueParameter<IntArray>(AvailabilityParameterName));
    126       Parameters.Add(new ValueParameter<DoubleValue>(MinSpeedParameterName, new DoubleValue(0.1)));
    127       Parameters.Add(new ValueParameter<DoubleValue>(MaxSpeedParameterName, new DoubleValue(1.0)));
    128       Parameters.Add(new ValueParameter<DoubleValue>(RentingRatioParameterName, new DoubleValue(0.5)));
    129       #endregion
    130 
    131       #region Configure Ports
    132       AddOrchestrationPort<VariegationProblem>(MetaSolverName);
    133       AddEvaluationPort<RealVector>(MetaSolverName, "RealVector", "Quality");
    134       AddOrchestrationPort<TravelingSalesmanProblem>(TspSolverName);
    135       AddEvaluationPort<Permutation>(TspSolverName, "TSPTour", "TSPTourLength");
    136       AddOrchestrationPort<BinaryKnapsackProblem>(KspSolverName);
    137       AddEvaluationPort<BinaryVector>(KspSolverName, "KnapsackSolution", "Quality");
    138 
    139       MetaSolverOrchestrationPort.ConnectedPortChanged += MetaSolverOrchestrationPort_ConnectedPortChanged;
    140       TspSolverOrchestrationPort.ConnectedPortChanged += TspSolverOrchestrationPort_ConnectedPortChanged;
    141       KspSolverOrchestrationPort.ConnectedPortChanged += KspSolverOrchestrationPort_ConnectedPortChanged;
    142       #endregion
    143     }
    144 
    145     public override IDeepCloneable Clone(Cloner cloner) {
    146       return new TtpOrchestratorNode4(this, cloner);
    147     }
    148 
    149     public override void Prepare() {
    150       tspThreadResults.Clear();
    151       kspThreadResults.Clear();
    152       Results.Clear();
    153       Results.Add(new Result(TspResultsResultName, new ItemList<ResultCollection>()));
    154       Results.Add(new Result(KspResultsResultName, new ItemList<ResultCollection>()));
    155       Results.Add(new Result(TtpResultsResultName, new ItemList<ResultCollection>()));
    156     }
    157 
    158     public override void Start() {
    159       var metaMsg = MetaSolverOrchestrationPort.PrepareMessage();
    160       metaMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.QualityAdaption);
    161       var problem = new VariegationProblem();
    162       problem.Encoding.Length = TspParameter.Value.Coordinates.Rows * 2;
    163       problem.Encoding.Bounds = new DoubleMatrix(new[,] { { -1.0, 1.0 } });
    164       metaMsg["Problem"] = problem;
    165       MetaSolverOrchestrationPort.SendMessage(metaMsg);
    166     }
    167 
    168     public override void Pause() {
    169       throw new NotImplementedException();
    170     }
    171 
    172     public override void Stop() {
    173       throw new NotImplementedException();
    174     }
    175 
    176     protected override void ProcessMessage(IMessage message, IMessagePort port, CancellationToken token) {
    177       var messageActions = new Dictionary<IMessagePort, Action<IMessage>>();
    178       messageActions.Add(MetaSolverOrchestrationPort, MetaSolverOrchestrationPortMessage);
    179       messageActions.Add(MetaSolverEvaluationPort, MetaSolverEvaluationPortMessage);
    180       messageActions.Add(TspSolverOrchestrationPort, TspSolverOrchestrationPortMessage);
    181       messageActions.Add(TspSolverEvaluationPort, TspSolverEvaluationPortMessage);
    182       messageActions.Add(KspSolverOrchestrationPort, KspSolverOrchestrationPortMessage);
    183       messageActions.Add(KspSolverEvaluationPort, KspSolverEvaluationPortMessage);
    184 
    185       messageActions[port](message);
    186 
    187       base.ProcessMessage(message, port, token);
    188     }
    189 
    190     #region MetaSolver Message Handling
    191     private void MetaSolverOrchestrationPortMessage(IMessage message) { }
    192 
    193     private void MetaSolverEvaluationPortMessage(IMessage message) {
    194       var factors = (RealVector)message["RealVector"];
    195 
    196       var tsp = (TravelingSalesmanProblem)TspParameter.Value.Clone();
    197       for (int j = 0; j < tsp.Coordinates.Rows; j++) {
    198         tsp.Coordinates[j, 0] = (int)Math.Ceiling(tsp.Coordinates[j, 0] * factors[j * 2]);
    199         tsp.Coordinates[j, 1] = (int)Math.Ceiling(tsp.Coordinates[j, 1] * factors[j * 2 + 1]);
    200       }
    201 
    202       var tspMsg = TspSolverOrchestrationPort.PrepareMessage();
    203       tspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Start);
    204       tspMsg["Problem"] = tsp;
    205       TspSolverOrchestrationPort.SendMessage(tspMsg);
    206 
    207       var tspResults = tspThreadResults[Thread.CurrentThread.ManagedThreadId];
    208       var tour = (PathTSPTour)tspResults["Best TSP Solution"].Value;
    209       tour.Coordinates = (DoubleMatrix)TspParameter.Value.Coordinates.Clone();
    210       tour.Quality.Value = TSPCoordinatesPathEvaluator.Apply(new TSPEuclideanPathEvaluator(), tour.Coordinates, tour.Permutation);
    211 
    212       var kspMsg = KspSolverOrchestrationPort.PrepareMessage();
    213       kspMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Start);
    214       kspMsg["Problem"] = (BinaryKnapsackProblem)KspParameter.Value.Clone();
    215       KspSolverOrchestrationPort.SendMessage(kspMsg);
    216 
    217       var kspResults = kspThreadResults[Thread.CurrentThread.ManagedThreadId];
    218       var bestKspSolution = (BinaryVector)kspResults["Best Solution"].Value;
    219       var kspCapacity = (IntValue)KspParameter.Value.KnapsackCapacity.Clone();
    220       var kspPenalty = new DoubleValue(0.0);
    221       var kspWeights = (IntArray)KspParameter.Value.Weights.Clone();
    222       var kspValues = (IntArray)KspParameter.Value.Values.Clone();
    223       var bestKspQuality = KnapsackEvaluator.Apply(bestKspSolution, kspCapacity, kspPenalty, kspWeights, kspValues).Quality;
    224       var loot = new KnapsackSolution(bestKspSolution, bestKspQuality, kspCapacity, kspWeights, kspValues);
    225       kspResults.Add(new Result("Best KSP Solution", loot));
    226 
    227       #region Analyze
    228       double objectiveValue = EvaluateTtp(TspParameter.Value, tour.Permutation.ToArray(), KspParameter.Value, loot.BinaryVector.ToArray());
    229       ((DoubleValue)message["Quality"]).Value = objectiveValue;
    230 
    231       var ttpResults = new ResultCollection();
    232       ttpResults.Add(new Result("Quality", new DoubleValue(objectiveValue)));
    233       ttpResults.Add(new Result("Tour", tour));
    234       ttpResults.Add(new Result("Loot", loot));
    235 
    236       lock (locker) {
    237         TtpResults.Add(ttpResults);
    238         TspResults.Add(tspResults);
    239         KspResults.Add(kspResults);
    240 
    241         IResult bestQuality;
    242         if (!Results.TryGetValue("Best TTP Quality", out bestQuality)) {
    243           Results.Add(new Result("Best TTP Quality", new DoubleValue(objectiveValue)));
    244           Results.Add(new Result("Best Tour", tour));
    245           Results.Add(new Result("Best Loot", loot));
    246         } else if (((DoubleValue)bestQuality.Value).Value < objectiveValue) {
    247           ((DoubleValue)bestQuality.Value).Value = objectiveValue;
    248           Results["Best Tour"].Value = tour;
    249           Results["Best Loot"].Value = loot;
    250         }
    251       }
    252       #endregion
    253     }
    254     #endregion
    255 
    256     #region TspSolver Message Handling
    257     private void TspSolverOrchestrationPortMessage(IMessage message) {
    258       var results = (ResultCollection)message["Results"];
    259       if (results.ContainsKey("Best TSP Solution")) {
    260         tspThreadResults[Thread.CurrentThread.ManagedThreadId] = results;
    261       }
    262     }
    263 
    264     private void TspSolverEvaluationPortMessage(IMessage message) { }
    265     #endregion
    266 
    267     #region KspSolver Message Handling
    268     private void KspSolverOrchestrationPortMessage(IMessage message) {
    269       var results = (ResultCollection)message["Results"];
    270       if (results.ContainsKey("Best Solution")) {
    271         kspThreadResults[Thread.CurrentThread.ManagedThreadId] = results;
    272       }
    273     }
    274 
    275     private void KspSolverEvaluationPortMessage(IMessage message) { }
    276     #endregion
    277 
    278     #region Helpers
    279     private double EvaluateTtp(TravelingSalesmanProblem tsp, int[] tour, BinaryKnapsackProblem ksp, bool[] loot) {
    280       bool feasible;
    281       return EvaluateTtp(tsp, tour, ksp, loot, out feasible);
    282     }
    283 
    284     private double EvaluateTtp(TravelingSalesmanProblem tsp, int[] tour, BinaryKnapsackProblem ksp, bool[] loot, out bool feasible) {
    285       double collectedWeight = 0.0;
    286       double objectiveValue = 0.0;
    287       double infeasibleBaseLine = -1000000.0;
    288       double speedCoefficient = (MaxSpeedParameter.Value.Value - MinSpeedParameter.Value.Value) / ksp.KnapsackCapacity.Value;
    289 
    290       int hideoutIdx = 0;
    291       while (tour[hideoutIdx] != 0) hideoutIdx++;
    292       int cityIdx = (hideoutIdx + 1) % tour.Length;
    293       int lastCityIdx = hideoutIdx;
    294 
    295       while (cityIdx != hideoutIdx) {
    296         double oldCollectedWeight = collectedWeight;
    297         var availableItems = AvailabilityParameter.Value.Select((c, i) => new { CityIdx = c, ItemIdx = i }).Where(x => x.CityIdx == tour[cityIdx]);
    298 
    299         foreach (var item in availableItems) {
    300           if (!loot[item.ItemIdx]) continue;
    301           collectedWeight += ksp.Weights[item.ItemIdx];
    302           objectiveValue += ksp.Values[item.ItemIdx];
    303         }
    304 
    305         objectiveValue -= Distance(tsp.Coordinates.CloneAsMatrix(), tour[lastCityIdx], tour[cityIdx]) * RentingRatioParameter.Value.Value /
    306                           (MaxSpeedParameter.Value.Value - speedCoefficient * oldCollectedWeight);
    307         lastCityIdx = cityIdx;
    308         cityIdx = (cityIdx + 1) % tour.Length;
    309       }
    310 
    311       objectiveValue -= Distance(tsp.Coordinates.CloneAsMatrix(), tour[lastCityIdx], tour[hideoutIdx]) * RentingRatioParameter.Value.Value /
    312                         (MaxSpeedParameter.Value.Value - speedCoefficient * collectedWeight);
    313 
    314       feasible = collectedWeight <= ksp.KnapsackCapacity.Value;
    315       if (!feasible) objectiveValue = infeasibleBaseLine - collectedWeight;
    316 
    317       return objectiveValue;
    318     }
    319 
    320     private double Distance(double[,] coords, int fromIdx, int toIdx) {
    321       double fromX = coords[fromIdx, 0], fromY = coords[fromIdx, 1],
    322              toX = coords[toIdx, 0], toY = coords[toIdx, 1];
    323       return (int)Math.Ceiling(Math.Sqrt((toX - fromX) * (toX - fromX) + (toY - fromY) * (toY - fromY)));
    324     }
    325     #endregion
    326 
    327     #region Event Handlers
    328     private void MetaSolverOrchestrationPort_ConnectedPortChanged(object sender, EventArgs e) {
    329       if (MetaSolverOrchestrationPort.ConnectedPort == null) return;
    330 
    331       var node = MetaSolverOrchestrationPort.ConnectedPort.Parent as OrchestratedAlgorithmNode;
    332       if (node == null) return;
    333 
    334       var hook = new HookOperator { Name = "Meta Eval Hook" };
    335       hook.Parameters.Add(new LookupParameter<RealVector>("RealVector") { Hidden = true });
    336       hook.Parameters.Add(new LookupParameter<DoubleValue>("Quality") { Hidden = true });
    337       node.EvalHook = hook;
    338 
    339       node.OrchestrationPort.CloneParametersFromPort(MetaSolverOrchestrationPort);
    340       node.EvaluationPort.CloneParametersFromPort(MetaSolverEvaluationPort);
    341       node.EvaluationPort.ConnectedPort = MetaSolverEvaluationPort;
    342     }
    343 
    344     private void TspSolverOrchestrationPort_ConnectedPortChanged(object sender, EventArgs e) {
    345       if (TspSolverOrchestrationPort.ConnectedPort == null) return;
    346 
    347       var node = TspSolverOrchestrationPort.ConnectedPort.Parent as OrchestratedAlgorithmNode;
    348       if (node == null) return;
    349 
    350       var hook = new HookOperator { Name = "TSP Eval Hook" };
    351       hook.Parameters.Add(new LookupParameter<Permutation>("TSPTour") { Hidden = true });
    352       hook.Parameters.Add(new LookupParameter<DoubleValue>("TSPTourLength") { Hidden = true });
    353       node.EvalHook = hook;
    354 
    355       node.OrchestrationPort.CloneParametersFromPort(TspSolverOrchestrationPort);
    356       node.EvaluationPort.CloneParametersFromPort(TspSolverEvaluationPort);
    357       node.EvaluationPort.ConnectedPort = TspSolverEvaluationPort;
    358     }
    359 
    360     private void KspSolverOrchestrationPort_ConnectedPortChanged(object sender, EventArgs e) {
    361       if (KspSolverOrchestrationPort.ConnectedPort == null) return;
    362 
    363       var node = KspSolverOrchestrationPort.ConnectedPort.Parent as OrchestratedAlgorithmNode;
    364       if (node == null) return;
    365 
    366       var hook = new HookOperator { Name = "KSP Eval Hook" };
    367       hook.Parameters.Add(new LookupParameter<BinaryVector>("KnapsackSolution") { Hidden = true });
    368       hook.Parameters.Add(new LookupParameter<DoubleValue>("Quality") { Hidden = true });
    369       node.EvalHook = hook;
    370 
    371       node.OrchestrationPort.CloneParametersFromPort(KspSolverOrchestrationPort);
    372       node.EvaluationPort.CloneParametersFromPort(KspSolverEvaluationPort);
    373       node.EvaluationPort.ConnectedPort = KspSolverEvaluationPort;
    374     }
    375     #endregion
    376   }
    377 }
     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  
    11using System;
    2 using System.Collections.Concurrent;
    32using System.Collections.Generic;
    43using System.Linq;
     
    3332    private const string TspSolverName = "TspSolver";
    3433    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;
    4540
    4641    #region Parameters
     
    7570
    7671    #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]; }
    11394    }
    11495    #endregion
     
    11697    [StorableConstructor]
    11798    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    }
    119102    public TtpOrchestratorNode5() : this("TtpOrchestratorNode5") { }
    120103    public TtpOrchestratorNode5(string name) : base(name) {
     
    137120      AddEvaluationPort<BinaryVector>(KspSolverName, "KnapsackSolution", "Quality");
    138121
     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() {
    139136      MetaSolverOrchestrationPort.ConnectedPortChanged += MetaSolverOrchestrationPort_ConnectedPortChanged;
    140137      TspSolverOrchestrationPort.ConnectedPortChanged += TspSolverOrchestrationPort_ConnectedPortChanged;
    141138      KspSolverOrchestrationPort.ConnectedPortChanged += KspSolverOrchestrationPort_ConnectedPortChanged;
    142       #endregion
    143     }
    144 
    145     public override IDeepCloneable Clone(Cloner cloner) {
    146       return new TtpOrchestratorNode5(this, cloner);
    147139    }
    148140
    149141    public override void Prepare() {
    150       tspThreadResults.Clear();
    151       kspThreadResults.Clear();
    152142      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>()));
    156143
    157144      var metaMsg = MetaSolverOrchestrationPort.PrepareMessage();
     
    165152
    166153    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) { }
    170161    }
    171162
    172163    public override void Pause() {
     164      cts.Cancel();
     165
    173166      var metaMsg = MetaSolverOrchestrationPort.PrepareMessage();
    174167      metaMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Pause);
    175168      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);
    176177    }
    177178
    178179    public override void Stop() {
     180      cts.Cancel();
     181
    179182      var metaMsg = MetaSolverOrchestrationPort.PrepareMessage();
    180183      metaMsg["OrchestrationMessage"] = new EnumValue<OrchestrationMessage>(OrchestrationMessage.Stop);
    181184      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);
    182193    }
    183194
     
    210221      kspMsg["Problem"] = ksp;
    211222      KspSolverOrchestrationPort.SendMessage(kspMsg);
    212 
    213       var kspResults = kspThreadResults[Thread.CurrentThread.ManagedThreadId];
     223      cts.Token.ThrowIfCancellationRequested();
     224
    214225      var bestKspSolution = (BinaryVector)kspResults["Best Solution"].Value;
    215226      var kspCapacity = (IntValue)KspParameter.Value.KnapsackCapacity.Clone();
     
    235246      tspMsg["Problem"] = tpp;
    236247      TspSolverOrchestrationPort.SendMessage(tspMsg);
    237 
    238       var tspResults = tspThreadResults[Thread.CurrentThread.ManagedThreadId];
     248      cts.Token.ThrowIfCancellationRequested();
     249
    239250      var bestTspSolution = (Permutation)tspResults["Best TSP Solution"].Value;
    240251      var coordinates = (DoubleMatrix)TspParameter.Value.Coordinates.Clone();
     
    246257      ((DoubleValue)message["Quality"]).Value = objectiveValue;
    247258
    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;
    268268      }
    269269      #endregion
     
    275275      var results = (ResultCollection)message["Results"];
    276276      if (results.ContainsKey("Best TSP Solution")) {
    277         tspThreadResults[Thread.CurrentThread.ManagedThreadId] = results;
     277        tspResults = results;
    278278      }
    279279    }
     
    286286      var results = (ResultCollection)message["Results"];
    287287      if (results.ContainsKey("Best Solution")) {
    288         kspThreadResults[Thread.CurrentThread.ManagedThreadId] = results;
     288        kspResults = results;
    289289      }
    290290    }
Note: See TracChangeset for help on using the changeset viewer.