Free cookie consent management tool by TermsFeed Policy Generator

source: branches/VRP/HeuristicLab.Problems.VehicleRouting/3.4/Encodings/Potvin/Creators/PushForwardInsertionCreator.cs @ 6881

Last change on this file since 6881 was 6881, checked in by svonolfe, 13 years ago

Fixed small issue in PFIH (#1177)

File size: 14.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using HeuristicLab.Core;
25using HeuristicLab.Data;
26using HeuristicLab.Encodings.PermutationEncoding;
27using HeuristicLab.Optimization;
28using HeuristicLab.Parameters;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30using HeuristicLab.Common;
31using HeuristicLab.Problems.VehicleRouting.Interfaces;
32using HeuristicLab.Problems.VehicleRouting.ProblemInstances;
33using HeuristicLab.Problems.VehicleRouting.Variants;
34
35namespace HeuristicLab.Problems.VehicleRouting.Encodings.Potvin {
36  [Item("PushForwardInsertionCreator", "Creates a randomly initialized VRP solution.")]
37  [StorableClass]
38  public sealed class PushForwardInsertionCreator : PotvinCreator, IStochasticOperator {
39    #region IStochasticOperator Members
40    public ILookupParameter<IRandom> RandomParameter {
41      get { return (LookupParameter<IRandom>)Parameters["Random"]; }
42    }
43    #endregion
44
45    public IValueParameter<DoubleValue> Alpha {
46      get { return (IValueParameter<DoubleValue>)Parameters["Alpha"]; }
47    }
48    public IValueParameter<DoubleValue> AlphaVariance {
49      get { return (IValueParameter<DoubleValue>)Parameters["AlphaVariance"]; }
50    }
51    public IValueParameter<DoubleValue> Beta {
52      get { return (IValueParameter<DoubleValue>)Parameters["Beta"]; }
53    }
54    public IValueParameter<DoubleValue> BetaVariance {
55      get { return (IValueParameter<DoubleValue>)Parameters["BetaVariance"]; }
56    }
57    public IValueParameter<DoubleValue> Gamma {
58      get { return (IValueParameter<DoubleValue>)Parameters["Gamma"]; }
59    }
60    public IValueParameter<DoubleValue> GammaVariance {
61      get { return (IValueParameter<DoubleValue>)Parameters["GammaVariance"]; }
62    }
63
64    [StorableConstructor]
65    private PushForwardInsertionCreator(bool deserializing) : base(deserializing) { }
66
67    public PushForwardInsertionCreator()
68      : base() {
69      Parameters.Add(new LookupParameter<IRandom>("Random", "The pseudo random number generator."));
70      Parameters.Add(new ValueParameter<DoubleValue>("Alpha", "The alpha value.", new DoubleValue(0.7)));
71      Parameters.Add(new ValueParameter<DoubleValue>("AlphaVariance", "The alpha variance.", new DoubleValue(0.5)));
72      Parameters.Add(new ValueParameter<DoubleValue>("Beta", "The beta value.", new DoubleValue(0.1)));
73      Parameters.Add(new ValueParameter<DoubleValue>("BetaVariance", "The beta variance.", new DoubleValue(0.07)));
74      Parameters.Add(new ValueParameter<DoubleValue>("Gamma", "The gamma value.", new DoubleValue(0.2)));
75      Parameters.Add(new ValueParameter<DoubleValue>("GammaVariance", "The gamma variance.", new DoubleValue(0.14)));
76    }
77
78    public override IDeepCloneable Clone(Cloner cloner) {
79      return new PushForwardInsertionCreator(this, cloner);
80    }
81
82    private PushForwardInsertionCreator(PushForwardInsertionCreator original, Cloner cloner)
83      : base(original, cloner) {
84    }
85
86    // use the Box-Mueller transform in the polar form to generate a N(0,1) random variable out of two uniformly distributed random variables
87    private static double Gauss(IRandom random) {
88      double u = 0.0, v = 0.0, s = 0.0;
89      do {
90        u = (random.NextDouble() * 2) - 1;
91        v = (random.NextDouble() * 2) - 1;
92        s = Math.Sqrt(u * u + v * v);
93      } while (s < Double.Epsilon || s > 1);
94      return u * Math.Sqrt((-2.0 * Math.Log(s)) / s);
95    }
96
97    private static double N(double mu, double sigma, IRandom random) {
98      return mu + (sigma * Gauss(random)); // transform the random variable sampled from N(0,1) to N(mu,sigma)
99    }
100
101    private static double GetDistance(int start, int end, IVRPProblemInstance problemInstance) {
102      double distance = 0.0;
103
104      double startX = problemInstance.Coordinates[start, 0];
105      double startY = problemInstance.Coordinates[start, 1];
106
107      double endX = problemInstance.Coordinates[end, 0];
108      double endY = problemInstance.Coordinates[end, 1];
109
110      distance =
111          Math.Sqrt(
112            Math.Pow(startX - endX, 2) +
113            Math.Pow(startY - endY, 2));
114
115      return distance;
116    }
117
118    private static int GetNearestDepot(IVRPProblemInstance problemInstance, List<int> depots, int customer,
119      double alpha, double beta, double gamma, out double minCost) {
120      int nearest = -1;
121      minCost = double.MaxValue;
122
123      int depotCount = 1;
124      IMultiDepotProblemInstance mdp = problemInstance as IMultiDepotProblemInstance;
125      if (mdp != null) {
126        depotCount = mdp.Depots.Value;
127      }
128
129      foreach (int depot in depots) {
130        double x0 = problemInstance.Coordinates[depot, 0];
131        double y0 = problemInstance.Coordinates[depot, 1];
132
133        double distance = GetDistance(customer + depotCount - 1, depot, problemInstance);
134       
135        double dueTime = 0;
136        if (problemInstance is ITimeWindowedProblemInstance)
137          dueTime = (problemInstance as ITimeWindowedProblemInstance).DueTime[customer + depotCount - 1];
138        if (dueTime == double.MaxValue)
139          dueTime = 0;
140
141        double dist;
142        if (problemInstance.Coordinates[customer + depotCount - 1, 0] < x0)
143          dist = -distance;
144        else
145          dist = distance;
146
147        double cost = alpha * distance + // distance 0 <-> City[i]
148                   -beta * dueTime + // latest arrival time
149                   -gamma * (Math.Asin((problemInstance.Coordinates[customer + depotCount - 1, 1] - y0) / dist) / 360 * dist); // polar angle
150
151        if (cost < minCost) {
152          minCost = cost;
153          nearest = depot;
154        }
155      }
156
157      return nearest;
158    }
159
160    private static List<int> SortCustomers(IVRPProblemInstance problemInstance, List<int> customers, List<int> depots,
161      Dictionary<int, int> depotAssignment,
162      double alpha, double beta, double gamma) {
163      List<int> sortedCustomers = new List<int>();
164      depotAssignment.Clear();
165
166      List<double> costList = new List<double>();
167
168      for (int i = 0; i < customers.Count; i++) {
169        double cost;
170        int depot = GetNearestDepot(problemInstance, depots, customers[i],
171          alpha, beta, gamma,
172          out cost);
173        depotAssignment[customers[i]] = depot;
174
175        int index = 0;
176        while (index < costList.Count && costList[index] < cost) index++;
177        costList.Insert(index, cost);
178        sortedCustomers.Insert(index, customers[i]);
179      }
180
181      return sortedCustomers;
182    }
183
184    private static bool RemoveUnusedDepots(List<int> depots, Dictionary<int, List<int>> vehicles) {
185      List<int> toBeRemoved = new List<int>();
186
187      foreach (int depot in depots) {
188        if (vehicles[depot].Count == 0)
189          toBeRemoved.Add(depot);
190      }
191
192      foreach (int depot in toBeRemoved) {
193        depots.Remove(depot);
194        vehicles.Remove(depot);
195      }
196
197      return toBeRemoved.Count > 0;
198    }
199
200    public static PotvinEncoding CreateSolution(IVRPProblemInstance problemInstance, IRandom random,
201      double alphaValue = 0.7, double betaValue = 0.1, double gammaValue = 0.2,
202      double alphaVariance = 0.5, double betaVariance = 0.07, double gammaVariance = 0.14) {
203      PotvinEncoding result = new PotvinEncoding(problemInstance);
204
205      IPickupAndDeliveryProblemInstance pdp = problemInstance as IPickupAndDeliveryProblemInstance;
206      IMultiDepotProblemInstance mdp = problemInstance as IMultiDepotProblemInstance;
207
208      double alpha, beta, gamma;
209      alpha = N(alphaValue, Math.Sqrt(alphaVariance), random);
210      beta = N(betaValue, Math.Sqrt(betaVariance), random);
211      gamma = N(gammaValue, Math.Sqrt(gammaVariance), random);
212
213      List<int> unroutedCustomers = new List<int>();
214      for (int i = 1; i <= problemInstance.Cities.Value; i++) {
215        if (pdp == null || (problemInstance.GetDemand(i) >= 0))
216          unroutedCustomers.Add(i);
217      }
218
219      List<int> depots = new List<int>();
220      if (mdp != null) {
221        for (int i = 0; i < mdp.Depots.Value; i++) {
222          depots.Add(i);
223        }
224      } else {
225        depots.Add(0);
226      }
227
228      Dictionary<int, List<int>> vehicles = new Dictionary<int, List<int>>();
229      foreach (int depot in depots) {
230        vehicles[depot] = new List<int>();
231
232        int vehicleCount = problemInstance.Vehicles.Value;
233        if (mdp != null) {
234          for (int vehicle = 0; vehicle < mdp.VehicleDepotAssignment.Length; vehicle++) {
235            if (mdp.VehicleDepotAssignment[vehicle] == depot) {
236              vehicles[depot].Add(vehicle);
237            }
238          }
239        } else {
240          for (int vehicle = 0; vehicle < vehicleCount; vehicle++) {
241            vehicles[depot].Add(vehicle);
242          }
243        }
244      }
245
246      RemoveUnusedDepots(depots, vehicles);
247      Dictionary<int, int> depotAssignment = new Dictionary<int, int>();
248
249      unroutedCustomers = SortCustomers(
250        problemInstance, unroutedCustomers, depots, depotAssignment,
251        alpha, beta, gamma);
252
253      /////////
254      Tour tour = new Tour();
255      result.Tours.Add(tour);
256      int currentCustomer = unroutedCustomers[0];
257      unroutedCustomers.RemoveAt(0);
258
259      int currentDepot = depotAssignment[currentCustomer];
260      int currentVehicle = vehicles[currentDepot][0];
261      vehicles[currentDepot].RemoveAt(0);
262      if (RemoveUnusedDepots(depots, vehicles)) {
263        unroutedCustomers = SortCustomers(
264        problemInstance, unroutedCustomers, depots, depotAssignment,
265        alpha, beta, gamma);
266      }
267
268      result.VehicleAssignment[result.Tours.Count - 1] = currentVehicle;
269
270      tour.Stops.Add(currentCustomer);
271      if (pdp != null) {
272        tour.Stops.Add(pdp.GetPickupDeliveryLocation(currentCustomer));
273      }
274      ////////
275
276      while (unroutedCustomers.Count > 0) {
277        double minimumCost = double.MaxValue;
278        int customer = -1;
279        int indexOfMinimumCost = -1;
280        int indexOfMinimumCost2 = -1;
281
282        foreach (int unrouted in unroutedCustomers) {
283          VRPEvaluation eval = problemInstance.EvaluateTour(tour, result);
284          double originalCosts = eval.Quality;
285
286          for (int i = 0; i <= tour.Stops.Count; i++) {
287            tour.Stops.Insert(i, unrouted);
288            eval = problemInstance.EvaluateTour(tour, result);
289            double tourCost = eval.Quality - originalCosts;
290
291            if (pdp != null) {
292              for (int j = i + 1; j <= tour.Stops.Count; j++) {
293                bool feasible;
294                double cost = tourCost +
295                  problemInstance.GetInsertionCosts(eval, result, pdp.GetPickupDeliveryLocation(unrouted), 0, j, out feasible);
296                if (cost < minimumCost && feasible) {
297                  customer = unrouted;
298                  minimumCost = cost;
299                  indexOfMinimumCost = i;
300                  indexOfMinimumCost2 = j;
301                }
302              }
303            } else {
304              double cost = tourCost;
305              bool feasible = problemInstance.Feasible(eval);
306              if (cost < minimumCost && feasible) {
307                customer = unrouted;
308                minimumCost = cost;
309                indexOfMinimumCost = i;
310              }
311            }
312
313            tour.Stops.RemoveAt(i);
314          }
315        }
316
317        if (indexOfMinimumCost == -1 && vehicles.Count == 0) {
318          indexOfMinimumCost = tour.Stops.Count;
319          indexOfMinimumCost2 = tour.Stops.Count + 1;
320          customer = unroutedCustomers[0];
321        }
322
323        // insert customer if found
324        if (indexOfMinimumCost != -1) {
325          tour.Stops.Insert(indexOfMinimumCost, customer);
326          if (pdp != null) {
327            tour.Stops.Insert(indexOfMinimumCost2, pdp.GetPickupDeliveryLocation(customer));
328          }
329
330          unroutedCustomers.Remove(customer);
331        } else { // no feasible customer found
332          tour = new Tour();
333          result.Tours.Add(tour);
334          currentCustomer = unroutedCustomers[0];
335          unroutedCustomers.RemoveAt(0);
336
337          currentDepot = depotAssignment[currentCustomer];
338          currentVehicle = vehicles[currentDepot][0];
339          vehicles[currentDepot].RemoveAt(0);
340          if (RemoveUnusedDepots(depots, vehicles)) {
341            unroutedCustomers = SortCustomers(
342            problemInstance, unroutedCustomers, depots, depotAssignment,
343            alpha, beta, gamma);
344          }
345
346          result.VehicleAssignment[result.Tours.Count - 1] = currentVehicle;
347
348          tour.Stops.Add(currentCustomer);
349          if (pdp != null) {
350            tour.Stops.Add(pdp.GetPickupDeliveryLocation(currentCustomer));
351          }
352        }
353      }
354
355      if (mdp != null) {
356        List<int> availableVehicles = new List<int>();
357        for (int i = 0; i < mdp.Vehicles.Value; i++)
358          availableVehicles.Add(i);
359
360        for (int i = 0; i < result.VehicleAssignment.Length; i++) {
361          if (result.VehicleAssignment[i] != -1)
362            availableVehicles.Remove(result.VehicleAssignment[i]);
363        }
364
365        for (int i = 0; i < result.VehicleAssignment.Length; i++) {
366          if (result.VehicleAssignment[i] == -1) {
367            result.VehicleAssignment[i] = availableVehicles[0];
368            availableVehicles.RemoveAt(0);
369          }
370        }
371      }
372
373      return result;
374    }
375
376    public override IOperation Apply() {
377      VRPToursParameter.ActualValue = CreateSolution(ProblemInstance, RandomParameter.ActualValue,
378        Alpha.Value.Value, Beta.Value.Value, Gamma.Value.Value,
379        AlphaVariance.Value.Value, BetaVariance.Value.Value, GammaVariance.Value.Value);
380
381      return base.Apply();
382    }
383  }
384}
Note: See TracBrowser for help on using the repository browser.