#region License Information
/* HeuristicLab
* Copyright (C) 2002-2017 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
*
* This file is part of HeuristicLab.
*
* HeuristicLab is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HeuristicLab is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HeuristicLab. If not, see .
*/
#endregion
using System;
using System.Linq;
using HeuristicLab.Common;
using HeuristicLab.Core;
using HeuristicLab.Core.Networks;
using HeuristicLab.Data;
using HeuristicLab.Encodings.BinaryVectorEncoding;
using HeuristicLab.Encodings.IntegerVectorEncoding;
using HeuristicLab.Operators;
using HeuristicLab.Optimization;
using HeuristicLab.Parameters;
using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
using HeuristicLab.Problems.FacilityLocation;
using HeuristicLab.Problems.VehicleRouting;
using HeuristicLab.Problems.VehicleRouting.ProblemInstances;
namespace HeuristicLab.Networks.IntegratedOptimization.LocationRouting {
[Item("LrpOrchestratorNode5", "Orchestrator for LRP optimization network version 5.")]
[StorableClass]
public sealed class LrpOrchestratorNode5 : LrpOrchestratorNode {
[StorableConstructor]
private LrpOrchestratorNode5(bool deserializing) : base(deserializing) { }
private LrpOrchestratorNode5(LrpOrchestratorNode5 original, Cloner cloner) : base(original, cloner) { }
public LrpOrchestratorNode5() : this("LrpOrchestratorNode5") { }
public LrpOrchestratorNode5(string name) : base(name) {
MetaSolverOrchestrationPort = CreateOrchestrationPort>(MetaSolverName + OrchestrationPortNameSuffix);
MetaSolverEvaluationPort = CreateEvaluationPort(MetaSolverName + EvaluationPortNameSuffix, "BinaryVector", "Quality");
FlpSolverOrchestrationPort = CreateOrchestrationPort(FlpSolverName + OrchestrationPortNameSuffix);
VrpSolverOrchestrationPort = CreateOrchestrationPort(VrpSolverName + OrchestrationPortNameSuffix);
}
public override IDeepCloneable Clone(Cloner cloner) {
return new LrpOrchestratorNode5(this, cloner);
}
protected override void MetaSolverOrchestrationPort_ConnectedPortChanged(object sender, EventArgs e) {
if (MetaSolverOrchestrationPort.ConnectedPort == null) return;
var node = MetaSolverOrchestrationPort.ConnectedPort.Parent as OrchestratedAlgorithmNode;
if (node == null) return;
var hook = new HookOperator { Name = "Meta Eval Hook" };
hook.Parameters.Add(new LookupParameter("BinaryVector") { Hidden = true });
hook.Parameters.Add(new LookupParameter("Quality") { Hidden = true });
node.EvalHook = hook;
node.OrchestrationPort.CloneParametersFromPort(MetaSolverOrchestrationPort);
node.EvaluationPort.CloneParametersFromPort(MetaSolverEvaluationPort);
node.EvaluationPort.ConnectedPort = MetaSolverEvaluationPort;
}
public override void Prepare(bool clearRuns = false) {
base.Prepare(clearRuns);
var metaMsg = MetaSolverOrchestrationPort.PrepareMessage();
var msgFlags = OrchestrationMessage.Prepare | OrchestrationMessage.SetEvalHook;
if (clearRuns) msgFlags |= OrchestrationMessage.ClearRuns;
metaMsg["OrchestrationMessage"] = new EnumValue(msgFlags);
var problem = new MinimizationVariegationProblem();
problem.Encoding.Length = nrOfDepots;
metaMsg["Problem"] = problem;
MetaSolverOrchestrationPort.SendMessage(metaMsg);
}
#region MetaSolver Message Handling
protected override void MetaSolverEvaluationPortMessage(IMessage message) {
var selection = (BinaryVector)message["BinaryVector"];
var inverse = selection.Select((x, i) => Tuple.Create(x, i)).Where(x => x.Item1).Select(x => x.Item2).ToArray();
if (!inverse.Any()) {
((DoubleValue)message["Quality"]).Value = double.MaxValue;
return;
}
var flp = (FacilityLocationProblem)FlpParameter.Value.Clone();
double[,] newDepotCoordinates = new double[inverse.Length, 2];
double[] newDepotCosts = new double[inverse.Length];
double[] newDepotCapacities = new double[inverse.Length];
int newIdx = 0;
for (int oldIdx = 0; oldIdx < selection.Length; oldIdx++) {
if (!selection[oldIdx]) continue;
newDepotCoordinates[newIdx, 0] = depotCoordinates[oldIdx, 0];
newDepotCoordinates[newIdx, 1] = depotCoordinates[oldIdx, 1];
newDepotCosts[newIdx] = depotCosts[oldIdx];
newDepotCapacities[newIdx] = depotCapacities[oldIdx];
++newIdx;
}
flp.OpeningCostsParameter.Value = new DoubleArray(newDepotCosts);
flp.DepotCapacitiesParameter.Value = new DoubleArray(newDepotCapacities);
flp.DeliveryCostsParameter.Value = new DoubleMatrix(LrpUtils.GetFlpDeliveryCosts(newDepotCoordinates, customerCoordinates, distanceType));
var flpMsg = FlpSolverOrchestrationPort.PrepareMessage();
flpMsg["OrchestrationMessage"] = new EnumValue(OrchestrationMessage.Prepare | OrchestrationMessage.ClearRuns | OrchestrationMessage.Start);
flpMsg["Problem"] = flp;
FlpSolverOrchestrationPort.SendMessage(flpMsg);
cts.Token.ThrowIfCancellationRequested();
var flpResults = (ResultCollection)flpMsg["Results"];
var bestFlpSolution = (IntegerVector)flpResults["Best Solution"].Value;
var flpSolution = flp.GetSolution(bestFlpSolution);
var depots = bestFlpSolution.Select((x, i) => Tuple.Create(inverse[x], i)).GroupBy(x => x.Item1, x => x.Item2);
var vrpSolutions = new ResultCollection(depots.Count());
foreach (var depot in depots.OrderBy(x => x.Key)) {
var depotIdx = depot.Key;
var customers = depot.ToArray();
var vrp = (VehicleRoutingProblem)VrpParameter.Value.Clone();
var vrpInstance = (CVRPProblemInstance)vrp.ProblemInstance;
var coordinates = LrpUtils.GetVrpCoordinates(depotCoordinates, customerCoordinates, new[] { depotIdx }, customers);
var distances = LrpUtils.GetVrpDistances(coordinates, distanceType);
vrpInstance.Coordinates = new DoubleMatrix(coordinates);
vrpInstance.DistanceMatrix = new DoubleMatrix(distances);
vrpInstance.Demand = new DoubleArray(new[] { 0.0 }.Concat(customers.Select(x => customerDemands[x])).ToArray());
vrpInstance.Vehicles.Value = customers.Length;
var vrpMsg = VrpSolverOrchestrationPort.PrepareMessage();
vrpMsg["OrchestrationMessage"] = new EnumValue(OrchestrationMessage.Prepare | OrchestrationMessage.ClearRuns | OrchestrationMessage.Start);
vrpMsg["Problem"] = vrp;
VrpSolverOrchestrationPort.SendMessage(vrpMsg);
cts.Token.ThrowIfCancellationRequested();
var vrpResults = (ResultCollection)vrpMsg["Results"];
IResult bestVrpSolutionResult;
if (!vrpResults.TryGetValue("Best valid VRP Solution", out bestVrpSolutionResult)
&& !vrpResults.TryGetValue("Best VRP Solution", out bestVrpSolutionResult)) {
// no best solution found ... throw?
}
var bestVrpSolution = (VRPSolution)bestVrpSolutionResult.Value.Clone();
vrpSolutions.Add(new Result("Depot " + depot.Key, bestVrpSolution));
}
#region Analyze
double objectiveValue = LrpUtils.Evaluate(flpSolution, vrpSolutions.Select(x => (VRPSolution)x.Value).ToArray());
((DoubleValue)message["Quality"]).Value = objectiveValue;
IResult bestQuality;
if (!Results.TryGetValue("Best LRP Quality", out bestQuality)) {
Results.Add(new Result("Best LRP Quality", new DoubleValue(objectiveValue)));
Results.Add(new Result("Best FLP Solution", flpSolution));
Results.Add(new Result("Best VRP Solutions", vrpSolutions));
} else if (objectiveValue < ((DoubleValue)bestQuality.Value).Value) {
((DoubleValue)bestQuality.Value).Value = objectiveValue;
Results["Best FLP Solution"].Value = flpSolution;
Results["Best VRP Solutions"].Value = vrpSolutions;
}
#endregion
}
#endregion
}
}