/// <summary> /// Gets the directedId in the route for the given id. /// </summary> public static int GetDirectedId(this Tour tour, int id) { var directed = DirectedHelper.BuildDirectedId(id, 0); if (tour.Contains(directed)) { return(directed); } directed = DirectedHelper.BuildDirectedId(id, 1); if (tour.Contains(directed)) { return(directed); } directed = DirectedHelper.BuildDirectedId(id, 2); if (tour.Contains(directed)) { return(directed); } directed = DirectedHelper.BuildDirectedId(id, 3); if (tour.Contains(directed)) { return(directed); } return(Constants.NOT_SET); }
/// <summary> /// Solves the given problem. /// </summary> /// <returns></returns> public override Tour Solve(SequenceDirectedProblem problem, SequenceDirectedObjective objective, out float fitness) { var directedTour = new int[problem.Sequence.Count]; var i = 0; foreach (var c in problem.Sequence) { directedTour[i] = DirectedHelper.BuildDirectedId(c, RandomGeneratorExtensions.GetRandom().Generate(4)); i++; } Tour tour = null; if (problem.Sequence.First == problem.Sequence.Last) { tour = new Tour(directedTour, directedTour[0]); } else { tour = new Tour(directedTour, directedTour[directedTour.Length - 1]); } fitness = objective.Calculate(problem, tour); return(tour); }
/// <summary> /// Creates an initial empty tour, add fixed first and/or last customer. /// </summary> /// <returns></returns> public Tour CreateEmptyTour() { var firstDirectedId = DirectedHelper.BuildDirectedId(this.First, 0); if (!this.Last.HasValue) { return(new Tours.Tour(new int[] { firstDirectedId }, null)); } else { if (this.Last == this.First) { return(new Tours.Tour(new int[] { firstDirectedId }, firstDirectedId)); } var lastDirectedId = DirectedHelper.BuildDirectedId(this.Last.Value, 0); return(new Tour(new int[] { firstDirectedId, lastDirectedId }, lastDirectedId)); } }
/// <summary> /// Applies this operator. /// </summary> public bool Apply(SequenceDirectedProblem problem, SequenceDirectedObjective objective, Tour solution, out float delta) { var weights = problem.Weights; delta = objective.Zero; var fitnessBefore = objective.Calculate(problem, solution); var enumerator = solution.GetEnumerator(); while (enumerator.MoveNext()) { var previous = enumerator.Current; var previousDepartureId = DirectedHelper.ExtractDepartureId(previous); var current = solution.GetNeigbour(previous); if (current == Constants.NOT_SET) { // last of open. continue; } var next = solution.GetNeigbour(current); var nextArrivalId = Constants.NOT_SET; if (next != Constants.NOT_SET) { nextArrivalId = DirectedHelper.ExtractArrivalId(next); } int currentTurn, currentId, currentArrivalId, currentDepartureId; DirectedHelper.ExtractAll(current, out currentArrivalId, out currentDepartureId, out currentId, out currentTurn); var weightBefore = weights[previousDepartureId][currentArrivalId]; var weightAfter = float.MaxValue; var newDirectedId = Constants.NOT_SET; if (next == Constants.NOT_SET) { // there is no next, only one option here: // 0 or 1: arrival id offset = 0 OR // 2 or 3: arrival id offset = 1 if (currentArrivalId % 2 == 0) { // check turn = 2. weightAfter = weights[previousDepartureId][currentArrivalId + 1]; if (weightAfter < weightBefore) { // do the switch. newDirectedId = DirectedHelper.BuildDirectedId(currentId, 2); } } else { // check turn = 0 weightAfter = weights[previousDepartureId][currentArrivalId - 1]; if (weightAfter < weightBefore) { // do the switch. newDirectedId = DirectedHelper.BuildDirectedId(currentId, 0); } } } else { // three options left, excluding the current one of 4. weightBefore += weights[currentDepartureId][nextArrivalId]; weightBefore += problem.TurnPenalties[currentTurn]; currentArrivalId = currentArrivalId - (currentArrivalId % 2); currentDepartureId = currentDepartureId - (currentDepartureId % 2); for (var i = 0; i < 4; i++) { if (i == currentTurn) { continue; } int arrivalOffset, departureOffset; DirectedHelper.ExtractOffset(i, out arrivalOffset, out departureOffset); var newWeightAfter = weights[previousDepartureId][currentArrivalId + arrivalOffset] + weights[currentDepartureId + departureOffset][nextArrivalId] + problem.TurnPenalties[i]; if (newWeightAfter < weightAfter && newWeightAfter < weightBefore) { newDirectedId = DirectedHelper.BuildDirectedId(currentId, i); weightAfter = newWeightAfter; } } } // switch if a new directed if was found. if (newDirectedId != Constants.NOT_SET) { solution.Replace(current, newDirectedId); } } var fitnessAfter = objective.Calculate(problem, solution); delta = objective.Subtract(problem, fitnessBefore, fitnessAfter); return(objective.CompareTo(problem, delta, objective.Zero) > 0); }
/// <summary> /// Returns true if there was an improvement, false otherwise. /// </summary> /// <returns></returns> public bool Apply(TSPTWProblem problem, TSPTWObjective objective, Tour tour, out float delta) { delta = 0; var fitness = objective.Calculate(problem, tour); var customers = new List <int>(problem.Times.Length + 1); customers.AddRange(tour); if (tour.Last == tour.First) { // add last customer at the end if it's the same as the first one. customers.Add(tour.Last.Value); } // select two edges with at least one edge between them at both sides of the tour. var weightBefore = 0f; if (problem.Windows[DirectedHelper.ExtractId(customers[0])].Min > weightBefore) { // wait here! weightBefore = problem.Windows[DirectedHelper.ExtractId(customers[0])].Min; } for (var edge1 = 0; edge1 < customers.Count - 3; edge1++) { // iterate over all from-edges. var edge11 = customers[edge1 + 0]; var edge12 = customers[edge1 + 1]; // extract directional information. int edge11arrivalId, edge11departureId, edge11id, edge11turn; DirectedHelper.ExtractAll(edge11, out edge11arrivalId, out edge11departureId, out edge11id, out edge11turn); int edge12arrivalId, edge12departureId, edge12id, edge12turn; DirectedHelper.ExtractAll(edge12, out edge12arrivalId, out edge12departureId, out edge12id, out edge12turn); for (var edge2 = edge1 + 2; edge2 < customers.Count - 1; edge2++) { // iterate over all possible to-edges given the from-edge. var edge21 = customers[edge2 + 0]; var edge22 = customers[edge2 + 1]; // at this point we have two edges 11->12->...->21->22->... // attempt to reverse the part in between. // 1: calculate the reverse part and check if feasible. // 2: if not feasible then stop. // 3: if feasible then calculate the forward part. // 4: if better then accept the result. // calculate het best possible reverse sequence by switching turns and departure and arrivel id's. // First start by creating a sequence with all turns and arrival and departure id's equal to zero. var part = new List <int>(); part.Add(DirectedHelper.UpdateDepartureOffset(edge11, 0)); for (var b = edge2; b > edge1; b--) { part.Add(DirectedHelper.BuildDirectedId(DirectedHelper.ExtractId(customers[b]), 0)); } part.Add(DirectedHelper.UpdateArrivalOffset(edge22, 0)); var localDelta = this.OptimizePart(problem, part); while (localDelta > 0.1) { localDelta = this.OptimizePart(problem, part); } int violated; float violatedTime, waitTime; var partTime = objective.CalculateTimeForPart(problem, part, weightBefore, out violated, out violatedTime, out waitTime); if (violated == 0) { // new part is feasible, this should be fine. var existingPart = new List <int>(); existingPart.Add(edge11); for (var c = edge1 + 1; c < edge2; c++) { existingPart.Add(customers[c]); } existingPart.Add(edge22); var existingPartTime = objective.CalculateTimeForPart(problem, existingPart, weightBefore, out violated, out violatedTime, out waitTime); if (existingPartTime > partTime) { // an improvment, add the new part. tour.Replace(edge11, part[0]); tour.Replace(edge22, part[part.Count - 1]); for (var c = 1; c < part.Count; c++) { tour.ReplaceEdgeFrom(part[c - 1], part[c]); } var newFitness = objective.Calculate(problem, tour); delta = fitness - newFitness; return(true); } } } // update weight before. weightBefore += problem.Times[edge11arrivalId][edge12arrivalId]; weightBefore += problem.TurnPenalties[edge11turn]; if (problem.Windows[DirectedHelper.ExtractId(customers[edge1])].Min > weightBefore) { // wait here! weightBefore = problem.Windows[DirectedHelper.ExtractId(customers[edge1])].Min; } } return(false); }
/// <summary> /// Optimizes the given part of the tour by choosing the best improvements in either the departureOffset or arrivalOffset of the first/last customers or the turns at any of the intermediate ones. /// </summary> private float OptimizePart(TSPTWProblem problem, List <int> part) { int turn1, arrivalId1, departureId1, id1; int turn2, arrivalId2, departureId2, id2; int turn3, arrivalId3, departureId3, id3; var delta = 0f; // the positive difference. var arrivalIdChange = -1; var departureIdChange = -1; var customerIdx = -1; var customerTurn = -1; // try changing the departureId. DirectedHelper.ExtractAll(part[0], out arrivalId1, out departureId1, out id1, out turn1); DirectedHelper.ExtractAll(part[1], out arrivalId2, out departureId2, out id2, out turn2); var weight = problem.TurnPenalties[turn1]; weight += problem.Times[departureId1][arrivalId2]; var new0 = DirectedHelper.SwitchDepartureOffset(part[0]); DirectedHelper.ExtractAll(new0, out arrivalId3, out departureId3, out id3, out turn3); var newWeight = problem.TurnPenalties[turn3]; newWeight += problem.Times[departureId3][arrivalId2]; if (newWeight < weight) { // there was an improvement found in changing the departure id. departureIdChange = DirectedHelper.ExtractDepartureId(new0); delta = newWeight - weight; } // try changing the arrivalId. DirectedHelper.ExtractAll(part[part.Count - 2], out arrivalId1, out departureId1, out id1, out turn1); DirectedHelper.ExtractAll(part[part.Count - 1], out arrivalId2, out departureId2, out id2, out turn2); weight = problem.TurnPenalties[turn2]; weight += problem.Times[departureId1][arrivalId2]; var newLast = DirectedHelper.SwitchArrivalOffset(part[part.Count - 1]); DirectedHelper.ExtractAll(newLast, out arrivalId3, out departureId3, out id3, out turn3); newWeight = problem.TurnPenalties[turn3]; newWeight += problem.Times[departureId1][arrivalId3]; if (newWeight < weight && delta < (newWeight - weight)) { // there was an improvement found in changing the arrival id. arrivalIdChange = DirectedHelper.ExtractDepartureId(newLast); departureIdChange = -1; delta = newWeight - weight; } for (var c = 1; c < part.Count - 1; c++) { var perviousDepartureId = DirectedHelper.ExtractDepartureId(part[c - 1]); DirectedHelper.ExtractAll(part[c], out arrivalId1, out departureId1, out id1, out turn1); var nextArrivalid = DirectedHelper.ExtractArrivalId(part[c + 1]); weight = problem.Times[perviousDepartureId][arrivalId1]; weight += problem.TurnPenalties[turn1]; weight += problem.Times[departureId1][nextArrivalid]; for (var t = 0; t < 3; t++) { if (t == turn1) { continue; } var newDirectedId = DirectedHelper.BuildDirectedId(id1, t); DirectedHelper.ExtractAll(newDirectedId, out arrivalId2, out departureId2, out id2, out turn2); newWeight = problem.Times[perviousDepartureId][arrivalId2]; newWeight += problem.TurnPenalties[turn2]; newWeight += problem.Times[departureId2][nextArrivalid]; if (newWeight < weight && delta < (newWeight - weight)) { // there was an improvement found in changing the turn. arrivalIdChange = -1; departureIdChange = -1; customerIdx = c; customerTurn = t; delta = newWeight - weight; } } } if (delta > 0) { if (departureIdChange != -1) { part[0] = DirectedHelper.SwitchDepartureOffset(part[0]); } else if (arrivalIdChange != -1) { part[part.Count - 1] = DirectedHelper.SwitchArrivalOffset(part[part.Count - 1]); } else if (customerIdx != -1) { part[customerIdx] = DirectedHelper.BuildDirectedId( DirectedHelper.ExtractId(part[customerIdx]), customerTurn); } } return(delta); }
/// <summary> /// Inserts the given customer at the best location if possible. /// </summary> /// <param name="tour">The tour to insert into.</param> /// <param name="weights">The directed weights.</param> /// <param name="turnPenalties">The turn pentalties.</param> /// <param name="customer">The customer to insert.</param> /// <param name="metric">The metric to use, time, distance or custom.</param> /// <param name="max">The maximum allowed cost of the insertion.</param> public static Weight InsertCheapestDirected(this Tour tour, Weight[][] weights, Weight[] turnPenalties, ProfileMetric metric, int customer, Weight max) { if (tour.Count == 1) { // there is only one customer, the first one in the route. if (tour.First == tour.Last) { // there is one customer but it's both the start and the end. var firstId = DirectedHelper.ExtractId(tour.First); var bestCost = new Weight() { Distance = float.MaxValue, Time = float.MaxValue, Value = float.MaxValue }; var bestDirected1Id = int.MaxValue; var bestDirected2Id = int.MaxValue; for (var turn1 = 0; turn1 < 4; turn1++) { var firstDirectedId = DirectedHelper.BuildDirectedId(firstId, turn1); var firstArrivalId = DirectedHelper.ExtractArrivalId(firstDirectedId); var firstDepartureId = DirectedHelper.ExtractDepartureId(firstDirectedId); for (var turn2 = 0; turn2 < 4; turn2++) { var customerDirectedId = DirectedHelper.BuildDirectedId(customer, turn2); var customerArrivalId = DirectedHelper.ExtractArrivalId(customerDirectedId); var customerDepartureId = DirectedHelper.ExtractDepartureId(customerDirectedId); var weight = turnPenalties[turn1]; weight += turnPenalties[turn2]; weight += weights[firstDepartureId][customerArrivalId]; weight += weights[customerDepartureId][firstArrivalId]; if (bestCost.GetForMetric(metric) > weight.GetForMetric(metric)) { bestDirected1Id = firstDirectedId; bestDirected2Id = customerDirectedId; bestCost = weight; } } } if (bestCost.GetForMetric(metric) <= max.GetForMetric(metric)) { tour.Replace(tour.First, bestDirected1Id); tour.InsertAfter(tour.First, bestDirected2Id); return bestCost; } } else { // there is one customer, the last one is not set. var firstId = DirectedHelper.ExtractId(tour.First); int departureOffset1, arrivalOffset2; var cost = DirectedHelper.CheapestInsert(weights, turnPenalties, firstId, customer, metric, out departureOffset1, out arrivalOffset2); if (cost.GetForMetric(metric) <= max.GetForMetric(metric)) { var newFirst = DirectedHelper.UpdateDepartureOffset( DirectedHelper.BuildDirectedId(firstId, 0), departureOffset1); var customerDirectedId = DirectedHelper.UpdateArrivalOffset( DirectedHelper.BuildDirectedId(customer, 0), arrivalOffset2); tour.Replace(tour.First, newFirst); tour.InsertAfter(tour.First, customerDirectedId); return cost; } } } else { // at least 2 customers already exist, insert a new one in between. var cost = Weight.MaxValue; var departureOffsetFrom = Constants.NOT_SET; var arrivalOffsetTo = Constants.NOT_SET; var turn = Constants.NOT_SET; var location = new Pair(int.MaxValue, int.MaxValue); foreach (var pair in tour.Pairs()) { int departureOffset1, arrivalOffset3, turn2; var fromIsFirst = tour.IsFirst(pair.From); var toIsLast = tour.IsLast(pair.To); var localCost = CheapestInsertionDirectedHelper.CalculateCheapestInsert(weights, turnPenalties, metric, pair.From, customer, pair.To, !fromIsFirst, !toIsLast, out departureOffset1, out arrivalOffset3, out turn2); if (localCost.GetForMetric(metric) < cost.GetForMetric(metric)) { cost = localCost; location = pair; departureOffsetFrom = departureOffset1; arrivalOffsetTo = arrivalOffset3; turn = turn2; } } if (cost.GetForMetric(metric) <= max.GetForMetric(metric)) { var directedId = DirectedHelper.BuildDirectedId(customer, turn); tour.InsertAfter(location.From, directedId); // update departure offset at from. var newFromId = DirectedHelper.UpdateDepartureOffset(location.From, departureOffsetFrom); if (location.From != newFromId) { tour.Replace(location.From, newFromId); } var newToId = DirectedHelper.UpdateArrivalOffset(location.To, arrivalOffsetTo); if (location.To != newToId) { tour.Replace(location.To, newToId); } return cost; } } return Weight.Zero; // insert failed, probably costs are too high (above given max parameter). }
/// <summary> /// Applies this operator. /// </summary> public bool Apply(TSProblem problem, TSPObjective objective, Tour solution, out float delta) { if (problem.Weights.Length <= 2) { delta = 0; return(false); } var weights = problem.Weights; delta = 0; // test switching directions in random order. if (_pool == null || solution.Count != _pool.Size) { // create a new pool. _pool = new RandomPool(solution.Count); } else { // just reset the existing one. _pool.Reset(); } while (_pool.MoveNext()) { var previous = solution.GetDirectedId(_pool.Current); var previousDepartureId = DirectedHelper.ExtractDepartureId(previous); var current = solution.GetNeigbour(previous); if (current == Constants.NOT_SET) { // last of open. continue; } var next = solution.GetNeigbour(current); var nextArrivalId = Constants.NOT_SET; if (next != Constants.NOT_SET) { nextArrivalId = DirectedHelper.ExtractArrivalId(next); } int currentTurn, currentId, currentArrivalId, currentDepartureId; DirectedHelper.ExtractAll(current, out currentArrivalId, out currentDepartureId, out currentId, out currentTurn); var weightBefore = weights[previousDepartureId][currentArrivalId]; var weightAfter = float.MaxValue; var newDirectedId = Constants.NOT_SET; if (next == Constants.NOT_SET) { // there is no next, only one option here: // 0 or 1: arrival id offset = 0 OR // 2 or 3: arrival id offset = 1 if (currentArrivalId % 2 == 0) { // check turn = 2. weightAfter = weights[previousDepartureId][currentArrivalId + 1]; if (weightAfter < weightBefore) { // do the switch. newDirectedId = DirectedHelper.BuildDirectedId(currentId, 2); } } else { // check turn = 0 weightAfter = weights[previousDepartureId][currentArrivalId - 1]; if (weightAfter < weightBefore) { // do the switch. newDirectedId = DirectedHelper.BuildDirectedId(currentId, 0); } } } else { // three options left, excluding the current one of 4. weightBefore += weights[currentDepartureId][nextArrivalId]; weightBefore += problem.TurnPenalties[currentTurn]; currentArrivalId = currentArrivalId - (currentArrivalId % 2); currentDepartureId = currentDepartureId - (currentDepartureId % 2); for (var i = 0; i < 4; i++) { if (i == currentTurn) { continue; } int arrivalOffset, departureOffset; DirectedHelper.ExtractOffset(i, out arrivalOffset, out departureOffset); var newWeightAfter = weights[previousDepartureId][currentArrivalId + arrivalOffset] + weights[currentDepartureId + departureOffset][nextArrivalId] + problem.TurnPenalties[i]; if (newWeightAfter < weightAfter && newWeightAfter < weightBefore) { newDirectedId = DirectedHelper.BuildDirectedId(currentId, i); weightAfter = newWeightAfter; } } } // switch if a new directed if was found. if (newDirectedId != Constants.NOT_SET) { delta = weightAfter - weightBefore; // negative when improvement. solution.Replace(current, newDirectedId); } } return(delta < 0); }