private static int GetNearestDepot(IVRPProblemInstance problemInstance, List <int> depots, int customer,
                                           double alpha, double beta, double gamma, out double minCost)
        {
            int nearest = -1;

            minCost = double.MaxValue;

            int depotCount = 1;
            IMultiDepotProblemInstance mdp = problemInstance as IMultiDepotProblemInstance;

            if (mdp != null)
            {
                depotCount = mdp.Depots.Value;
            }

            foreach (int depot in depots)
            {
                double x0 = problemInstance.Coordinates[depot, 0];
                double y0 = problemInstance.Coordinates[depot, 1];

                double distance = GetDistance(customer + depotCount - 1, depot, problemInstance);

                double dueTime = 0;
                if (problemInstance is ITimeWindowedProblemInstance)
                {
                    dueTime = (problemInstance as ITimeWindowedProblemInstance).DueTime[customer + depotCount - 1];
                }
                if (dueTime == double.MaxValue)
                {
                    dueTime = 0;
                }

                double x = problemInstance.Coordinates[customer + depotCount - 1, 0];
                double y = problemInstance.Coordinates[customer + depotCount - 1, 1];

                double cost = alpha * distance +                                                              // distance 0 <-> City[i]
                              -beta * dueTime +                                                               // latest arrival time
                              -gamma * ((Math.Atan2(y - y0, x - x0) + Math.PI) / (2.0 * Math.PI) * distance); // polar angle

                if (cost < minCost)
                {
                    minCost = cost;
                    nearest = depot;
                }
            }

            return(nearest);
        }
        protected override void EvaluateTour(VRPEvaluation eval, IVRPProblemInstance instance, Tour tour, IVRPEncoding solution)
        {
            TourInsertionInfo tourInfo = new TourInsertionInfo(solution.GetVehicleAssignment(solution.GetTourIndex(tour)));

            eval.InsertionInfo.AddTourInsertionInfo(tourInfo);
            double originalQuality = eval.Quality;

            IHeterogenousCapacitatedProblemInstance cvrpInstance = instance as IHeterogenousCapacitatedProblemInstance;
            DoubleArray demand = instance.Demand;

            ITimeWindowedProblemInstance vrptw = instance as ITimeWindowedProblemInstance;
            DoubleArray dueTime      = vrptw.DueTime;
            DoubleArray readyTime    = vrptw.ReadyTime;
            DoubleArray serviceTimes = vrptw.ServiceTime;

            IPickupAndDeliveryProblemInstance pdp = instance as IPickupAndDeliveryProblemInstance;
            IntArray pickupDeliveryLocation       = pdp.PickupDeliveryLocation;

            IMultiDepotProblemInstance mdp = instance as IMultiDepotProblemInstance;
            IntArray vehicleAssignment     = mdp.VehicleDepotAssignment;
            int      depots = mdp.Depots.Value;

            double time        = 0.0;
            double waitingTime = 0.0;
            double serviceTime = 0.0;
            double tardiness   = 0.0;
            double overweight  = 0.0;
            double distance    = 0.0;

            int tourIndex = solution.GetTourIndex(tour);
            int vehicle   = solution.GetVehicleAssignment(tourIndex);
            int depot     = vehicleAssignment[vehicle];

            double capacity = cvrpInstance.Capacity[vehicle];

            double currentLoad           = 0.0;
            Dictionary <int, bool> stops = new Dictionary <int, bool>();
            int pickupViolations         = 0;

            double tourStartTime = readyTime[0];

            time = tourStartTime;

            //simulate a tour, start and end at depot
            for (int i = 0; i <= tour.Stops.Count; i++)
            {
                int start = 0;
                if (i > 0)
                {
                    start = tour.Stops[i - 1];
                }
                int end = 0;
                if (i < tour.Stops.Count)
                {
                    end = tour.Stops[i];
                }

                //drive there
                double currentDistace = vrptw.GetDistance(start, end, solution);
                time     += currentDistace;
                distance += currentDistace;

                double arrivalTime = time;

                int endIndex;
                if (end == 0)
                {
                    endIndex = depot;
                }
                else
                {
                    endIndex = end + depots - 1;
                }

                //check if it was serviced on time
                if (time > dueTime[endIndex])
                {
                    tardiness += time - dueTime[endIndex];
                }

                //wait
                double currentWaitingTime = 0.0;
                if (time < readyTime[endIndex])
                {
                    currentWaitingTime = readyTime[endIndex] - time;
                }

                double waitTime = readyTime[endIndex] - time;

                waitingTime += currentWaitingTime;
                time        += currentWaitingTime;

                double spareTime            = dueTime[endIndex] - time;
                double arrivalSpareCapacity = capacity - currentLoad;

                if (end > 0)
                {
                    //service
                    double currentServiceTime = serviceTimes[end - 1];
                    serviceTime += currentServiceTime;
                    time        += currentServiceTime;

                    //Pickup / deliver
                    bool validPickupDelivery =
                        validPickupDelivery =
                            ((demand[end - 1] >= 0) ||
                             (stops.ContainsKey(pickupDeliveryLocation[end - 1])));

                    if (validPickupDelivery)
                    {
                        currentLoad += demand[end - 1];
                    }
                    else
                    {
                        pickupViolations++;
                    }

                    if (currentLoad > capacity)
                    {
                        overweight += currentLoad - capacity;
                    }
                }

                double spareCapacity           = capacity - currentLoad;
                CVRPPDTWInsertionInfo stopInfo = new CVRPPDTWInsertionInfo(start, end, spareCapacity, tourStartTime,
                                                                           arrivalTime, time, spareTime, waitTime, new List <int>(stops.Keys), arrivalSpareCapacity);
                tourInfo.AddStopInsertionInfo(stopInfo);

                stops.Add(end, true);
            }

            eval.Quality            += instance.FleetUsageFactor.Value;
            eval.Quality            += instance.DistanceFactor.Value * distance;
            eval.Distance           += distance;
            eval.VehicleUtilization += 1;

            (eval as CVRPEvaluation).Overload += overweight;
            double tourPenalty = 0;
            double penalty     = overweight * cvrpInstance.OverloadPenalty.Value;

            eval.Penalty += penalty;
            eval.Quality += penalty;
            tourPenalty  += penalty;

            (eval as CVRPTWEvaluation).Tardiness  += tardiness;
            (eval as CVRPTWEvaluation).TravelTime += time;

            penalty       = tardiness * vrptw.TardinessPenalty.Value;
            eval.Penalty += penalty;
            eval.Quality += penalty;
            tourPenalty  += penalty;

            (eval as CVRPPDTWEvaluation).PickupViolations += pickupViolations;
            penalty       = pickupViolations * pdp.PickupViolationPenalty.Value;
            eval.Penalty += penalty;
            tourPenalty  += penalty;

            eval.Quality    += penalty;
            eval.Quality    += time * vrptw.TimeFactor.Value;
            tourInfo.Penalty = tourPenalty;
            tourInfo.Quality = eval.Quality - originalQuality;
        }
        protected override double GetTourInsertionCosts(IVRPProblemInstance instance, IVRPEncoding solution, TourInsertionInfo tourInsertionInfo, int index, int customer,
                                                        out bool feasible)
        {
            CVRPPDTWInsertionInfo insertionInfo = tourInsertionInfo.GetStopInsertionInfo(index) as CVRPPDTWInsertionInfo;

            double costs = 0;

            feasible = tourInsertionInfo.Penalty < double.Epsilon;
            bool tourFeasible = true;

            ICapacitatedProblemInstance cvrp = instance as ICapacitatedProblemInstance;
            double overloadPenalty           = cvrp.OverloadPenalty.Value;

            ITimeWindowedProblemInstance vrptw = instance as ITimeWindowedProblemInstance;
            DoubleArray dueTime          = vrptw.DueTime;
            DoubleArray readyTime        = vrptw.ReadyTime;
            DoubleArray serviceTimes     = vrptw.ServiceTime;
            double      tardinessPenalty = vrptw.TardinessPenalty.Value;

            IMultiDepotProblemInstance mdp = instance as IMultiDepotProblemInstance;
            int depots = mdp.Depots.Value;

            IPickupAndDeliveryProblemInstance pdp = instance as IPickupAndDeliveryProblemInstance;
            IntArray pickupDeliveryLocation       = pdp.PickupDeliveryLocation;
            double   pickupPenalty = pdp.PickupViolationPenalty.Value;

            double startDistance, endDistance;

            costs += instance.GetInsertionDistance(insertionInfo.Start, customer, insertionInfo.End, solution, out startDistance, out endDistance);

            double demand = instance.GetDemand(customer);

            if (demand > insertionInfo.ArrivalSpareCapacity)
            {
                tourFeasible = feasible = false;
                if (insertionInfo.ArrivalSpareCapacity >= 0)
                {
                    costs += (demand - insertionInfo.ArrivalSpareCapacity) * overloadPenalty;
                }
                else
                {
                    costs += demand * overloadPenalty;
                }
            }
            int destination = pickupDeliveryLocation[customer - 1];

            bool validPickup = true;

            if (demand < 0 && !insertionInfo.Visited.Contains(destination))
            {
                tourFeasible = feasible = false;
                validPickup  = false;
                costs       += pickupPenalty;
            }

            double time      = 0;
            double tardiness = 0;

            if (index > 0)
            {
                time = (tourInsertionInfo.GetStopInsertionInfo(index - 1) as CVRPTWInsertionInfo).LeaveTime;
            }
            else
            {
                time = insertionInfo.TourStartTime;
            }

            time += startDistance;

            int customerIndex = customer + depots - 1;

            if (time > dueTime[customerIndex])
            {
                tardiness += time - dueTime[customerIndex];
            }
            if (time < readyTime[customerIndex])
            {
                time += readyTime[customerIndex] - time;
            }
            time += serviceTimes[customer - 1];
            time += endDistance;

            double additionalTime = time - (tourInsertionInfo.GetStopInsertionInfo(index) as CVRPTWInsertionInfo).ArrivalTime;

            for (int i = index; i < tourInsertionInfo.GetStopCount(); i++)
            {
                CVRPTWInsertionInfo nextStop = tourInsertionInfo.GetStopInsertionInfo(i) as CVRPTWInsertionInfo;

                if (demand >= 0)
                {
                    if (nextStop.End == destination)
                    {
                        demand = 0;
                        costs -= pickupPenalty;
                        if (tourInsertionInfo.Penalty == pickupPenalty && tourFeasible)
                        {
                            feasible = true;
                        }
                    }
                    else if (nextStop.SpareCapacity < 0)
                    {
                        costs += demand * overloadPenalty;
                    }
                    else if (nextStop.SpareCapacity < demand)
                    {
                        tourFeasible = feasible = false;
                        costs       += (demand - nextStop.SpareCapacity) * overloadPenalty;
                    }
                }
                else if (validPickup)
                {
                    if (nextStop.SpareCapacity < 0)
                    {
                        costs += Math.Max(demand, nextStop.SpareCapacity) * overloadPenalty;
                    }
                }

                if (additionalTime < 0)
                {
                    //arrive earlier than before
                    //wait probably
                    if (nextStop.WaitingTime < 0)
                    {
                        double wait = nextStop.WaitingTime - additionalTime;
                        if (wait > 0)
                        {
                            additionalTime += wait;
                        }
                    }
                    else
                    {
                        additionalTime = 0;
                    }

                    //check due date, decrease tardiness
                    if (nextStop.SpareTime < 0)
                    {
                        costs += Math.Max(nextStop.SpareTime, additionalTime) * tardinessPenalty;
                    }
                }
                else
                {
                    //arrive later than before, probably don't have to wait
                    if (nextStop.WaitingTime > 0)
                    {
                        additionalTime -= Math.Min(additionalTime, nextStop.WaitingTime);
                    }

                    //check due date
                    if (nextStop.SpareTime > 0)
                    {
                        double spare = nextStop.SpareTime - additionalTime;
                        if (spare < 0)
                        {
                            tardiness += -spare;
                        }
                    }
                    else
                    {
                        tardiness += additionalTime;
                    }
                }
            }

            costs += additionalTime * vrptw.TimeFactor.Value;

            if (tardiness > 0)
            {
                tourFeasible = feasible = false;
            }

            costs += tardiness * tardinessPenalty;

            return(costs);
        }
        protected override void EvaluateTour(VRPEvaluation eval, IVRPProblemInstance instance, Tour tour, IVRPEncoding solution)
        {
            TourInsertionInfo tourInfo = new TourInsertionInfo(solution.GetVehicleAssignment(solution.GetTourIndex(tour)));

            eval.InsertionInfo.AddTourInsertionInfo(tourInfo);
            double originalQuality = eval.Quality;

            IHeterogenousCapacitatedProblemInstance cvrpInstance = instance as IHeterogenousCapacitatedProblemInstance;
            DoubleArray demand = instance.Demand;

            ITimeWindowedProblemInstance vrptw = instance as ITimeWindowedProblemInstance;
            DoubleArray dueTime      = vrptw.DueTime;
            DoubleArray readyTime    = vrptw.ReadyTime;
            DoubleArray serviceTimes = vrptw.ServiceTime;

            IMultiDepotProblemInstance mdp = instance as IMultiDepotProblemInstance;
            IntArray vehicleAssignment     = mdp.VehicleDepotAssignment;
            int      depots = mdp.Depots.Value;

            double time        = 0.0;
            double waitingTime = 0.0;
            double serviceTime = 0.0;
            double tardiness   = 0.0;
            double delivered   = 0.0;
            double overweight  = 0.0;
            double distance    = 0.0;

            int tourIndex = solution.GetTourIndex(tour);
            int vehicle   = solution.GetVehicleAssignment(tourIndex);
            int depot     = vehicleAssignment[vehicle];

            double capacity = cvrpInstance.Capacity[vehicle];

            for (int i = 0; i < tour.Stops.Count; i++)
            {
                delivered += instance.GetDemand(tour.Stops[i]);
            }

            double spareCapacity = capacity - delivered;

            double tourStartTime = vrptw.ReadyTime[depot];

            time = tourStartTime;

            //simulate a tour, start and end at depot
            for (int i = 0; i <= tour.Stops.Count; i++)
            {
                int start = 0;
                if (i > 0)
                {
                    start = tour.Stops[i - 1];
                }
                int end = 0;
                if (i < tour.Stops.Count)
                {
                    end = tour.Stops[i];
                }

                //drive there
                double currentDistace = vrptw.GetDistance(start, end, solution);
                time     += currentDistace;
                distance += currentDistace;

                double arrivalTime = time;

                int endIndex;
                if (end == 0)
                {
                    endIndex = depot;
                }
                else
                {
                    endIndex = end + depots - 1;
                }

                //check if it was serviced on time
                if (time > dueTime[endIndex])
                {
                    tardiness += time - dueTime[endIndex];
                }

                //wait
                double currentWaitingTime = 0.0;
                if (time < readyTime[endIndex])
                {
                    currentWaitingTime = readyTime[endIndex] - time;
                }

                double waitTime = readyTime[endIndex] - time;

                waitingTime += currentWaitingTime;
                time        += currentWaitingTime;

                double spareTime = dueTime[endIndex] - time;

                //service
                double currentServiceTime = 0;
                if (end > 0)
                {
                    currentServiceTime = serviceTimes[end - 1];
                }
                serviceTime += currentServiceTime;
                time        += currentServiceTime;

                CVRPTWInsertionInfo stopInfo = new CVRPTWInsertionInfo(start, end, spareCapacity, tourStartTime, arrivalTime, time, spareTime, waitTime);
                tourInfo.AddStopInsertionInfo(stopInfo);
            }

            eval.Quality            += instance.FleetUsageFactor.Value;
            eval.Quality            += instance.DistanceFactor.Value * distance;
            eval.Distance           += distance;
            eval.VehicleUtilization += 1;

            if (delivered > capacity)
            {
                overweight = delivered - capacity;
            }

            (eval as CVRPEvaluation).Overload += overweight;
            double tourPenalty = 0;
            double penalty     = overweight * cvrpInstance.OverloadPenalty.Value;

            eval.Penalty += penalty;
            eval.Quality += penalty;
            tourPenalty  += penalty;

            (eval as CVRPTWEvaluation).Tardiness  += tardiness;
            (eval as CVRPTWEvaluation).TravelTime += time;

            penalty          = tardiness * vrptw.TardinessPenalty.Value;
            eval.Penalty    += penalty;
            eval.Quality    += penalty;
            tourPenalty     += penalty;
            eval.Quality    += time * vrptw.TimeFactor.Value;
            tourInfo.Penalty = tourPenalty;
            tourInfo.Quality = eval.Quality - originalQuality;
        }
        public static PotvinEncoding CreateSolution(IVRPProblemInstance problemInstance, IRandom random,
                                                    double alphaValue    = 0.7, double betaValue    = 0.1, double gammaValue     = 0.2,
                                                    double alphaVariance = 0.5, double betaVariance = 0.07, double gammaVariance = 0.14)
        {
            PotvinEncoding result = new PotvinEncoding(problemInstance);

            IPickupAndDeliveryProblemInstance pdp = problemInstance as IPickupAndDeliveryProblemInstance;
            IMultiDepotProblemInstance        mdp = problemInstance as IMultiDepotProblemInstance;

            double alpha, beta, gamma;

            alpha = N(alphaValue, Math.Sqrt(alphaVariance), random);
            beta  = N(betaValue, Math.Sqrt(betaVariance), random);
            gamma = N(gammaValue, Math.Sqrt(gammaVariance), random);

            List <int> unroutedCustomers = new List <int>();

            for (int i = 1; i <= problemInstance.Cities.Value; i++)
            {
                if (pdp == null || (problemInstance.GetDemand(i) >= 0))
                {
                    unroutedCustomers.Add(i);
                }
            }

            List <int> depots = new List <int>();

            if (mdp != null)
            {
                for (int i = 0; i < mdp.Depots.Value; i++)
                {
                    depots.Add(i);
                }
            }
            else
            {
                depots.Add(0);
            }

            Dictionary <int, List <int> > vehicles = new Dictionary <int, List <int> >();

            foreach (int depot in depots)
            {
                vehicles[depot] = new List <int>();

                int vehicleCount = problemInstance.Vehicles.Value;
                if (mdp != null)
                {
                    for (int vehicle = 0; vehicle < mdp.VehicleDepotAssignment.Length; vehicle++)
                    {
                        if (mdp.VehicleDepotAssignment[vehicle] == depot)
                        {
                            vehicles[depot].Add(vehicle);
                        }
                    }
                }
                else
                {
                    for (int vehicle = 0; vehicle < vehicleCount; vehicle++)
                    {
                        vehicles[depot].Add(vehicle);
                    }
                }
            }

            RemoveUnusedDepots(depots, vehicles);
            Dictionary <int, int> depotAssignment = new Dictionary <int, int>();

            unroutedCustomers = SortCustomers(
                problemInstance, unroutedCustomers, depots, depotAssignment,
                alpha, beta, gamma);

            /////////
            Tour tour = new Tour();

            result.Tours.Add(tour);
            int currentCustomer = unroutedCustomers[0];

            unroutedCustomers.RemoveAt(0);

            int currentDepot   = depotAssignment[currentCustomer];
            int currentVehicle = vehicles[currentDepot][0];

            vehicles[currentDepot].RemoveAt(0);
            if (RemoveUnusedDepots(depots, vehicles))
            {
                unroutedCustomers = SortCustomers(
                    problemInstance, unroutedCustomers, depots, depotAssignment,
                    alpha, beta, gamma);
            }

            result.VehicleAssignment[result.Tours.Count - 1] = currentVehicle;

            tour.Stops.Add(currentCustomer);
            if (pdp != null)
            {
                tour.Stops.Add(pdp.GetPickupDeliveryLocation(currentCustomer));
            }
            ////////

            while (unroutedCustomers.Count > 0)
            {
                double minimumCost         = double.MaxValue;
                int    customer            = -1;
                int    indexOfMinimumCost  = -1;
                int    indexOfMinimumCost2 = -1;

                foreach (int unrouted in unroutedCustomers)
                {
                    VRPEvaluation eval          = problemInstance.EvaluateTour(tour, result);
                    double        originalCosts = eval.Quality;

                    for (int i = 0; i <= tour.Stops.Count; i++)
                    {
                        tour.Stops.Insert(i, unrouted);
                        eval = problemInstance.EvaluateTour(tour, result);
                        double tourCost = eval.Quality - originalCosts;

                        if (pdp != null)
                        {
                            for (int j = i + 1; j <= tour.Stops.Count; j++)
                            {
                                bool   feasible;
                                double cost = tourCost +
                                              problemInstance.GetInsertionCosts(eval, result, pdp.GetPickupDeliveryLocation(unrouted), 0, j, out feasible);
                                if (cost < minimumCost && feasible)
                                {
                                    customer            = unrouted;
                                    minimumCost         = cost;
                                    indexOfMinimumCost  = i;
                                    indexOfMinimumCost2 = j;
                                }
                            }
                        }
                        else
                        {
                            double cost     = tourCost;
                            bool   feasible = problemInstance.Feasible(eval);
                            if (cost < minimumCost && feasible)
                            {
                                customer           = unrouted;
                                minimumCost        = cost;
                                indexOfMinimumCost = i;
                            }
                        }

                        tour.Stops.RemoveAt(i);
                    }
                }

                if (indexOfMinimumCost == -1 && vehicles.Count == 0)
                {
                    indexOfMinimumCost  = tour.Stops.Count;
                    indexOfMinimumCost2 = tour.Stops.Count + 1;
                    customer            = unroutedCustomers[0];
                }

                // insert customer if found
                if (indexOfMinimumCost != -1)
                {
                    tour.Stops.Insert(indexOfMinimumCost, customer);
                    if (pdp != null)
                    {
                        tour.Stops.Insert(indexOfMinimumCost2, pdp.GetPickupDeliveryLocation(customer));
                    }

                    unroutedCustomers.Remove(customer);
                }
                else // no feasible customer found
                {
                    tour = new Tour();
                    result.Tours.Add(tour);
                    currentCustomer = unroutedCustomers[0];
                    unroutedCustomers.RemoveAt(0);

                    currentDepot   = depotAssignment[currentCustomer];
                    currentVehicle = vehicles[currentDepot][0];
                    vehicles[currentDepot].RemoveAt(0);
                    if (RemoveUnusedDepots(depots, vehicles))
                    {
                        unroutedCustomers = SortCustomers(
                            problemInstance, unroutedCustomers, depots, depotAssignment,
                            alpha, beta, gamma);
                    }

                    result.VehicleAssignment[result.Tours.Count - 1] = currentVehicle;

                    tour.Stops.Add(currentCustomer);
                    if (pdp != null)
                    {
                        tour.Stops.Add(pdp.GetPickupDeliveryLocation(currentCustomer));
                    }
                }
            }

            if (mdp != null)
            {
                List <int> availableVehicles = new List <int>();
                for (int i = 0; i < mdp.Vehicles.Value; i++)
                {
                    availableVehicles.Add(i);
                }

                for (int i = 0; i < result.VehicleAssignment.Length; i++)
                {
                    if (result.VehicleAssignment[i] != -1)
                    {
                        availableVehicles.Remove(result.VehicleAssignment[i]);
                    }
                }

                for (int i = 0; i < result.VehicleAssignment.Length; i++)
                {
                    if (result.VehicleAssignment[i] == -1)
                    {
                        result.VehicleAssignment[i] = availableVehicles[0];
                        availableVehicles.RemoveAt(0);
                    }
                }
            }

            return(result);
        }