#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.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using HeuristicLab.Common; using HeuristicLab.Core; using HeuristicLab.Core.Networks; using HeuristicLab.Data; using HeuristicLab.Encodings.IntegerVectorEncoding; using HeuristicLab.Encodings.RealVectorEncoding; using HeuristicLab.Optimization; using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; using HeuristicLab.Problems.FacilityLocation; using HeuristicLab.Problems.VehicleRouting; using HeuristicLab.Problems.VehicleRouting.Encodings.General; using HeuristicLab.Problems.VehicleRouting.ProblemInstances; namespace HeuristicLab.Networks.IntegratedOptimization.LocationRouting { [Item("LrpOrchestratorNode3", "Orchestrator for LRP optimization network version 3.")] [StorableClass] public sealed class LrpOrchestratorNode3 : LrpOrchestratorNode { [StorableConstructor] private LrpOrchestratorNode3(bool deserializing) : base(deserializing) { } private LrpOrchestratorNode3(LrpOrchestratorNode3 original, Cloner cloner) : base(original, cloner) { } public LrpOrchestratorNode3() : this("LrpOrchestratorNode3") { } public LrpOrchestratorNode3(string name) : base(name) { MetaSolverOrchestrationPort = CreateOrchestrationPort>(MetaSolverName + OrchestrationPortNameSuffix); MetaSolverEvaluationPort = CreateEvaluationPort(MetaSolverName + EvaluationPortNameSuffix, "RealVector", "Quality"); FlpSolverOrchestrationPort = CreateOrchestrationPort(FlpSolverName + OrchestrationPortNameSuffix); VrpSolverOrchestrationPort = CreateOrchestrationPort(VrpSolverName + OrchestrationPortNameSuffix); VrpParameter.Value.ProblemInstance = new MDCVRPProblemInstance(); } public override IDeepCloneable Clone(Cloner cloner) { return new LrpOrchestratorNode3(this, cloner); } protected override void InstanceParameter_Value_ToStringChanged(object sender, EventArgs e) { string filePath = InstanceParameter.Value.Value; LrpUtils.Import(filePath, out nrOfDepots, out nrOfCustomers, out depotCoordinates, out customerCoordinates, out distanceType, out depotCapacities, out customerDemands, out depotCosts, out vehicleCapacity, out vehicleCost); var flp = FlpParameter.Value; flp.CustomerDemandsParameter.Value = new DoubleArray(customerDemands); flp.DeliveryCostsParameter.Value = new DoubleMatrix(LrpUtils.GetFlpDeliveryCosts(depotCoordinates, customerCoordinates, distanceType)); flp.DepotCapacitiesParameter.Value = new DoubleArray(depotCapacities); flp.Encoding.Length = nrOfCustomers; flp.OpeningCostsParameter.Value = new DoubleArray(depotCosts); var vrpInstance = (MDCVRPProblemInstance)VrpParameter.Value.ProblemInstance; vrpInstance.Demand = new DoubleArray(customerDemands); vrpInstance.FleetUsageFactor.Value = vehicleCost; vrpInstance.OverloadPenalty.Value = vehicleCost * 1000.0; var crossover = VrpParameter.Value.OperatorsParameter.Value.OfType().Single(x => x.Name == "MultiVRPSolutionCrossover"); foreach (var c in crossover.Operators) crossover.Operators.SetItemCheckedState(c, c.Name.StartsWith("Potvin")); var mutator = VrpParameter.Value.OperatorsParameter.Value.OfType().Single(x => x.Name == "MultiVRPSolutionManipulator"); foreach (var m in mutator.Operators) mutator.Operators.SetItemCheckedState(m, Regex.IsMatch(m.Name, @"Potvin(One|Two).*")); Prepare(); } 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; problem.Encoding.Bounds = new DoubleMatrix(new[,] { { -1.0, 1.0 } }); metaMsg["Problem"] = problem; MetaSolverOrchestrationPort.SendMessage(metaMsg); } #region MetaSolver Message Handling protected override void MetaSolverEvaluationPortMessage(IMessage message) { var factors = (RealVector)message["RealVector"]; var flp = (FacilityLocationProblem)FlpParameter.Value.Clone(); var dc = (double[])depotCosts.Clone(); for (int i = 0; i < nrOfDepots; i++) dc[i] = dc[i] * factors[i]; flp.OpeningCostsParameter.Value = new DoubleArray(dc); 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 = FlpParameter.Value.GetSolution(bestFlpSolution); var depots = new HashSet(bestFlpSolution).OrderBy(x => x).ToArray(); var customers = Enumerable.Range(0, bestFlpSolution.Length).ToArray(); var vrp = (VehicleRoutingProblem)VrpParameter.Value.Clone(); var vrpInstance = (MDCVRPProblemInstance)vrp.ProblemInstance; var coordinates = LrpUtils.GetVrpCoordinates(depotCoordinates, customerCoordinates, depots, customers); var distances = LrpUtils.GetVrpDistances(coordinates, distanceType); var capacities = new Dictionary(); for (int i = 0; i < depots.Length; i++) { double depotCapacity = depotCapacities[depots[i]]; double nrOfVehicles = depotCapacity / vehicleCapacity; int nrOfTotalVehicles = (int)Math.Ceiling(nrOfVehicles); int nrOfFullVehicles = (int)Math.Floor(nrOfVehicles); double[] vehicleCapacities = Enumerable.Repeat(vehicleCapacity, nrOfTotalVehicles).ToArray(); if (nrOfFullVehicles < nrOfTotalVehicles) vehicleCapacities[nrOfTotalVehicles - 1] = depotCapacity - nrOfFullVehicles * vehicleCapacity; capacities.Add(i, vehicleCapacities); } vrpInstance.Capacity = new DoubleArray(capacities.OrderBy(x => x.Key).SelectMany(x => x.Value).ToArray()); vrpInstance.Coordinates = new DoubleMatrix(coordinates); vrpInstance.Depots.Value = depots.Length; vrpInstance.DistanceMatrix = new DoubleMatrix(distances); vrpInstance.VehicleDepotAssignment = new IntArray(capacities.OrderBy(x => x.Key).SelectMany((x, i) => Enumerable.Repeat(i, x.Value.Length)).ToArray()); vrpInstance.Vehicles.Value = vrpInstance.VehicleDepotAssignment.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 vrpSolution = (VRPSolution)bestVrpSolutionResult.Value.Clone(); #region Analyze double objectiveValue = LrpUtils.Evaluate(flpSolution, new[] { vrpSolution }); bool[] usedDepots = new bool[depots.Length]; foreach (var tour in vrpSolution.Solution.GetTours()) { int tourIdx = vrpSolution.Solution.GetTourIndex(tour); int vehicleIdx = vrpSolution.Solution.GetVehicleAssignment(tourIdx); int depotIdx = vrpInstance.VehicleDepotAssignment[vehicleIdx]; usedDepots[depotIdx] = true; } for (int i = 0; i < usedDepots.Length; i++) if (!usedDepots[i]) objectiveValue -= flpSolution.OpeningCosts[depots[i]]; ((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 Solution", vrpSolution)); } else if (objectiveValue < ((DoubleValue)bestQuality.Value).Value) { ((DoubleValue)bestQuality.Value).Value = objectiveValue; Results["Best FLP Solution"].Value = flpSolution; Results["Best VRP Solution"].Value = vrpSolution; } #endregion } #endregion } }