Free cookie consent management tool by TermsFeed Policy Generator

source: branches/VRP/HeuristicLab.Problems.VehicleRouting/3.4/VehicleRoutingProblem.cs @ 7871

Last change on this file since 7871 was 7871, checked in by svonolfe, 12 years ago

Added support for included TSPLib CVRP instances (#1177)

File size: 18.1 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 System.Drawing;
25using System.Linq;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Encodings.PermutationEncoding;
30using HeuristicLab.Optimization;
31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33using HeuristicLab.PluginInfrastructure;
34using HeuristicLab.Problems.VehicleRouting.Interfaces;
35using HeuristicLab.Problems.VehicleRouting.Parsers;
36using HeuristicLab.Problems.VehicleRouting.ProblemInstances;
37using HeuristicLab.Problems.VehicleRouting.Variants;
38using HeuristicLab.Problems.Instances;
39using System.Reflection;
40using HeuristicLab.Problems.VehicleRouting.Interpreters;
41
42namespace HeuristicLab.Problems.VehicleRouting {
43  [Item("Vehicle Routing Problem", "Represents a Vehicle Routing Problem.")]
44  [Creatable("Problems")]
45  [StorableClass]
46  public sealed class VehicleRoutingProblem : ParameterizedNamedItem, ISingleObjectiveHeuristicOptimizationProblem, IStorableContent, IProblemInstanceConsumer<IVRPData> {
47    public string Filename { get; set; }
48
49    public static new Image StaticItemImage {
50      get { return HeuristicLab.Common.Resources.VSImageLibrary.Type; }
51    }
52
53    #region Parameter Properties
54    public ValueParameter<BoolValue> MaximizationParameter {
55      get { return (ValueParameter<BoolValue>)Parameters["Maximization"]; }
56    }
57    IParameter ISingleObjectiveHeuristicOptimizationProblem.MaximizationParameter {
58      get { return MaximizationParameter; }
59    }
60    public ValueParameter<IVRPProblemInstance> ProblemInstanceParameter {
61      get { return (ValueParameter<IVRPProblemInstance>)Parameters["ProblemInstance"]; }
62    }
63    public OptionalValueParameter<DoubleValue> BestKnownQualityParameter {
64      get { return (OptionalValueParameter<DoubleValue>)Parameters["BestKnownQuality"]; }
65    }
66    IParameter ISingleObjectiveHeuristicOptimizationProblem.BestKnownQualityParameter {
67      get { return BestKnownQualityParameter; }
68    }
69    public OptionalValueParameter<VRPSolution> BestKnownSolutionParameter {
70      get { return (OptionalValueParameter<VRPSolution>)Parameters["BestKnownSolution"]; }
71    }
72    public IValueParameter<IVRPCreator> SolutionCreatorParameter {
73      get { return (IValueParameter<IVRPCreator>)Parameters["SolutionCreator"]; }
74    }
75    IParameter IHeuristicOptimizationProblem.SolutionCreatorParameter {
76      get { return SolutionCreatorParameter; }
77    }
78    public IValueParameter<IVRPEvaluator> EvaluatorParameter {
79      get { return (IValueParameter<IVRPEvaluator>)Parameters["Evaluator"]; }
80    }
81    IParameter IHeuristicOptimizationProblem.EvaluatorParameter {
82      get { return EvaluatorParameter; }
83    }
84    #endregion
85
86    #region Properties
87    public IVRPProblemInstance ProblemInstance {
88      get { return ProblemInstanceParameter.Value; }
89      set { ProblemInstanceParameter.Value = value; }
90    }
91
92    public VRPSolution BestKnownSolution {
93      get { return BestKnownSolutionParameter.Value; }
94      set { BestKnownSolutionParameter.Value = value; }
95    }
96
97    public DoubleValue BestKnownQuality {
98      get { return BestKnownQualityParameter.Value; }
99      set { BestKnownQualityParameter.Value = value; }
100    }
101
102    public ISingleObjectiveEvaluator Evaluator {
103      get { return EvaluatorParameter.Value; }
104    }
105
106    IEvaluator IHeuristicOptimizationProblem.Evaluator {
107      get { return this.Evaluator; }
108    }
109
110    public ISolutionCreator SolutionCreator {
111      get { return SolutionCreatorParameter.Value; }
112    }
113
114    [Storable]
115    private List<IOperator> operators;
116
117    public IEnumerable<IOperator> Operators {
118      get { return operators; }
119    }
120    #endregion
121
122    [StorableConstructor]
123    private VehicleRoutingProblem(bool deserializing) : base(deserializing) { }
124    public VehicleRoutingProblem()
125      : base() {
126      Parameters.Add(new ValueParameter<BoolValue>("Maximization", "Set to false as the Vehicle Routing Problem is a minimization problem.", new BoolValue(false)));
127      Parameters.Add(new ValueParameter<IVRPProblemInstance>("ProblemInstance", "The VRP problem instance"));
128      Parameters.Add(new OptionalValueParameter<DoubleValue>("BestKnownQuality", "The quality of the best known solution of this VRP instance."));
129      Parameters.Add(new OptionalValueParameter<VRPSolution>("BestKnownSolution", "The best known solution of this VRP instance."));
130
131      Parameters.Add(new ConstrainedValueParameter<IVRPCreator>("SolutionCreator", "The operator which should be used to create new VRP solutions."));
132      Parameters.Add(new ValueParameter<IVRPEvaluator>("Evaluator", "The operator which should be used to evaluate VRP solutions."));
133
134      EvaluatorParameter.Hidden = true;
135
136      operators = new List<IOperator>();
137
138      InitializeRandomVRPInstance();
139      InitializeOperators();
140
141      AttachEventHandlers();
142      AttachProblemInstanceEventHandlers();
143    }
144
145    public override IDeepCloneable Clone(Cloner cloner) {
146      return new VehicleRoutingProblem(this, cloner);
147    }
148
149    private VehicleRoutingProblem(VehicleRoutingProblem original, Cloner cloner)
150      : base(original, cloner) {
151      this.operators = original.operators.Select(x => (IOperator)cloner.Clone(x)).ToList();
152      this.AttachEventHandlers();
153    }
154
155    #region Events
156    public event EventHandler SolutionCreatorChanged;
157    private void OnSolutionCreatorChanged() {
158      EventHandler handler = SolutionCreatorChanged;
159      if (handler != null) handler(this, EventArgs.Empty);
160    }
161    public event EventHandler EvaluatorChanged;
162    private void OnEvaluatorChanged() {
163      EventHandler handler = EvaluatorChanged;
164      if (handler != null) handler(this, EventArgs.Empty);
165    }
166    public event EventHandler OperatorsChanged;
167    private void OnOperatorsChanged() {
168      EventHandler handler = OperatorsChanged;
169      if (handler != null) handler(this, EventArgs.Empty);
170    }
171    public event EventHandler Reset;
172    private void OnReset() {
173      EventHandler handler = Reset;
174      if (handler != null) handler(this, EventArgs.Empty);
175    } 
176    #endregion
177
178    #region Helpers
179    [StorableHook(HookType.AfterDeserialization)]
180    private void AfterDeserializationHook() {
181      AttachEventHandlers();
182      AttachProblemInstanceEventHandlers();
183    }
184
185    private void AttachEventHandlers() {
186      ProblemInstanceParameter.ValueChanged += new EventHandler(ProblemInstanceParameter_ValueChanged);
187      BestKnownSolutionParameter.ValueChanged += new EventHandler(BestKnownSolutionParameter_ValueChanged);
188    }
189
190    private void AttachProblemInstanceEventHandlers() {
191      var solutionCreatorParameter = SolutionCreatorParameter as ConstrainedValueParameter<IVRPCreator>;
192      solutionCreatorParameter.ValidValues.Clear();
193
194      if (ProblemInstance != null) {
195        EvaluatorParameter.Value = ProblemInstance.SolutionEvaluator;
196        foreach (IVRPCreator creator in operators.Where(o => o is IVRPCreator)) {
197          solutionCreatorParameter.ValidValues.Add(creator);
198        }
199        ProblemInstance.EvaluationChanged += new EventHandler(ProblemInstance_EvaluationChanged);
200      }     
201    }
202
203    private void EvalBestKnownSolution() {
204      if (BestKnownSolution != null) {
205        //call evaluator
206        BestKnownQuality = new DoubleValue(ProblemInstance.Evaluate(BestKnownSolution.Solution).Quality);
207        BestKnownSolution.Quality = BestKnownQuality;
208      } else {
209        BestKnownQuality = null;
210      }
211    }
212
213    void BestKnownSolutionParameter_ValueChanged(object sender, EventArgs e) {
214      EvalBestKnownSolution();
215    }
216
217    void ProblemInstance_EvaluationChanged(object sender, EventArgs e) {
218      EvalBestKnownSolution();
219    }
220
221    void ProblemInstanceParameter_ValueChanged(object sender, EventArgs e) {
222      InitializeOperators();
223      AttachProblemInstanceEventHandlers();
224
225      OnSolutionCreatorChanged();
226      OnEvaluatorChanged();
227      OnOperatorsChanged();
228    }
229
230    public void SetProblemInstance(IVRPProblemInstance instance) {
231      ProblemInstanceParameter.ValueChanged -= new EventHandler(ProblemInstanceParameter_ValueChanged);
232
233      ProblemInstance = instance;
234      AttachProblemInstanceEventHandlers();
235
236      OnSolutionCreatorChanged();
237      OnEvaluatorChanged();
238
239      ProblemInstanceParameter.ValueChanged += new EventHandler(ProblemInstanceParameter_ValueChanged);
240    }
241
242    private void SolutionCreatorParameter_ValueChanged(object sender, EventArgs e) {
243      ParameterizeSolutionCreator();
244     
245      OnSolutionCreatorChanged();
246    }
247    private void EvaluatorParameter_ValueChanged(object sender, EventArgs e) {
248      OnEvaluatorChanged();
249    }
250
251    private void InitializeOperators() {
252      operators = new List<IOperator>();
253
254      if (ProblemInstance != null) {
255        operators.AddRange(
256        ProblemInstance.Operators.Concat(
257          ApplicationManager.Manager.GetInstances<IGeneralVRPOperator>().Cast<IOperator>()).OrderBy(op => op.Name));
258      }
259
260      ParameterizeOperators();
261    }
262
263    private void ParameterizeSolutionCreator() {
264      if (SolutionCreator is IMultiVRPOperator) {
265        (SolutionCreator as IMultiVRPOperator).SetOperators(Operators);
266      }
267    }
268
269    private void ParameterizeOperators() {
270      foreach (IOperator op in Operators) {
271        if (op is IMultiVRPOperator) {
272          (op as IMultiVRPOperator).SetOperators(Operators);
273        }
274      }
275    }
276    #endregion
277
278    public void ImportFromCordeau(string cordeauFileName) {
279      CordeauParser parser = new CordeauParser(cordeauFileName);
280      parser.Parse();
281
282      this.Name = parser.ProblemName;
283      MDCVRPTWProblemInstance problem = new MDCVRPTWProblemInstance();
284
285      problem.Coordinates = new DoubleMatrix(parser.Coordinates);
286      problem.Vehicles.Value = parser.Vehicles;
287      problem.Capacity = new DoubleArray(parser.Capacity);
288      problem.Demand = new DoubleArray(parser.Demands);
289      problem.Depots.Value = parser.Depots;
290      problem.VehicleDepotAssignment = new IntArray(parser.Vehicles);
291      problem.ReadyTime = new DoubleArray(parser.Readytimes);
292      problem.ServiceTime = new DoubleArray(parser.Servicetimes);
293      problem.DueTime = new DoubleArray(parser.Duetimes);
294
295      int depot = 0;
296      int i = 0;
297      while(i < parser.Vehicles) {
298        problem.VehicleDepotAssignment[i] = depot;
299
300        i++;
301        if (i % (parser.Vehicles / parser.Depots) == 0)
302          depot++;
303      }
304
305      this.ProblemInstance = problem;
306
307      OnReset();
308    }
309
310    public void ImportFromLiLim(string liLimFileName) {
311      LiLimParser parser = new LiLimParser(liLimFileName);
312      parser.Parse();
313
314      this.Name = parser.ProblemName;
315      CVRPPDTWProblemInstance problem = new CVRPPDTWProblemInstance();
316
317      problem.Coordinates = new DoubleMatrix(parser.Coordinates);
318      problem.Vehicles.Value = parser.Vehicles;
319      problem.Capacity.Value = parser.Capacity;
320      problem.Demand = new DoubleArray(parser.Demands);
321      problem.ReadyTime = new DoubleArray(parser.Readytimes);
322      problem.DueTime = new DoubleArray(parser.Duetimes);
323      problem.ServiceTime = new DoubleArray(parser.Servicetimes);
324      problem.PickupDeliveryLocation = new IntArray(parser.PickupDeliveryLocations);
325
326      this.ProblemInstance = problem;
327
328      OnReset();
329    }
330
331    public void ImportFromSolomon(string solomonFileName) {
332      SolomonParser parser = new SolomonParser(solomonFileName);
333      parser.Parse();
334
335      this.Name = parser.ProblemName;
336      CVRPTWProblemInstance problem = new CVRPTWProblemInstance();
337     
338      problem.Coordinates = new DoubleMatrix(parser.Coordinates);
339      problem.Vehicles.Value = parser.Vehicles;
340      problem.Capacity.Value = parser.Capacity;
341      problem.Demand = new DoubleArray(parser.Demands);
342      problem.ReadyTime = new DoubleArray(parser.Readytimes);
343      problem.DueTime = new DoubleArray(parser.Duetimes);
344      problem.ServiceTime = new DoubleArray(parser.Servicetimes);
345
346      this.ProblemInstance = problem;
347
348      OnReset();
349    }
350
351    public void ImportFromTSPLib(string tspFileName) {
352      TSPLIBParser parser = new TSPLIBParser(tspFileName);
353      parser.Parse();
354
355      this.Name = parser.Name;
356      int problemSize = parser.Demands.Length;
357
358      if (parser.Depot != 1) {
359        ErrorHandling.ShowErrorDialog(new Exception("Invalid depot specification"));
360        return;
361      }
362
363      if (parser.WeightType != TSPLIBParser.TSPLIBEdgeWeightType.EUC_2D)  {
364        ErrorHandling.ShowErrorDialog(new Exception("Invalid weight type"));
365        return;
366      }
367
368      CVRPTWProblemInstance problem = new CVRPTWProblemInstance();
369      problem.Coordinates = new DoubleMatrix(parser.Vertices);
370      if (parser.Vehicles != -1)
371        problem.Vehicles.Value = parser.Vehicles;
372      else
373        problem.Vehicles.Value = problemSize - 1;
374      problem.Capacity.Value = parser.Capacity;
375      problem.Demand = new DoubleArray(parser.Demands);
376      problem.ReadyTime = new DoubleArray(problemSize);
377      problem.DueTime = new DoubleArray(problemSize);
378      problem.ServiceTime = new DoubleArray(problemSize);
379
380      for (int i = 0; i < problemSize; i++) {
381        problem.ReadyTime[i] = 0;
382        problem.DueTime[i] = int.MaxValue;
383        problem.ServiceTime[i] = 0;
384      }
385
386      if (parser.Distance != -1) {
387        problem.DueTime[0] = parser.Distance;
388      }
389
390      this.ProblemInstance = problem;
391
392      OnReset();
393    }
394
395    public void ImportFromORLib(string orFileName) {
396      ORLIBParser parser = new ORLIBParser(orFileName);
397      parser.Parse();
398
399      this.Name = parser.Name;
400      int problemSize = parser.Demands.Length;
401
402      CVRPProblemInstance problem = new CVRPProblemInstance();
403
404      problem.Coordinates = new DoubleMatrix(parser.Vertices);
405      problem.Vehicles.Value = problemSize - 1;
406      problem.Capacity.Value = parser.Capacity;
407      problem.Demand = new DoubleArray(parser.Demands);
408
409      this.ProblemInstance = problem;
410
411      OnReset();
412    }
413
414    private void InitializeRandomVRPInstance() {
415      System.Random rand = new System.Random();
416
417      CVRPTWProblemInstance problem = new CVRPTWProblemInstance();
418      int cities = 100;
419
420      problem.Coordinates = new DoubleMatrix(cities + 1, 2);
421      problem.Demand = new DoubleArray(cities + 1);
422      problem.DueTime = new DoubleArray(cities + 1);
423      problem.ReadyTime = new DoubleArray(cities + 1);
424      problem.ServiceTime = new DoubleArray(cities + 1);
425
426      problem.Vehicles.Value = 100;
427      problem.Capacity.Value = 200;
428
429      for (int i = 0; i <= cities; i++) {
430        problem.Coordinates[i, 0] = rand.Next(0, 100);
431        problem.Coordinates[i, 1] = rand.Next(0, 100);
432
433        if (i == 0) {
434          problem.Demand[i] = 0;
435          problem.DueTime[i] = Int16.MaxValue;
436          problem.ReadyTime[i] = 0;
437          problem.ServiceTime[i] = 0;
438        } else {
439          problem.Demand[i] = rand.Next(10, 50);
440          problem.DueTime[i] = rand.Next((int)Math.Ceiling(problem.GetDistance(0, i, null)), 1200);
441          problem.ReadyTime[i] = problem.DueTime[i] - rand.Next(0, 100);
442          problem.ServiceTime[i] = 90;
443        }
444      }
445
446      this.ProblemInstance = problem;
447    }
448
449    public void ImportSolution(string solutionFileName) {
450      SolutionParser parser = new SolutionParser(solutionFileName);
451      parser.Parse();
452
453      HeuristicLab.Problems.VehicleRouting.Encodings.Potvin.PotvinEncoding encoding = new Encodings.Potvin.PotvinEncoding(ProblemInstance);
454
455      int cities = 0;
456      foreach (List<int> route in parser.Routes) {
457        Tour tour = new Tour();
458        tour.Stops.AddRange(route);
459        cities += tour.Stops.Count;
460
461        encoding.Tours.Add(tour);
462      }
463
464      if (cities != ProblemInstance.Coordinates.Rows - 1)
465        ErrorHandling.ShowErrorDialog(new Exception("The optimal solution does not seem to correspond with the problem data"));
466      else {
467        VRPSolution solution = new VRPSolution(ProblemInstance, encoding, new DoubleValue(0));
468        BestKnownSolutionParameter.Value = solution;
469      }
470    }
471
472    public void Load(IVRPData data) {
473      Type interpreterType = typeof(IVRPDataInterpreter<>).MakeGenericType(data.GetType());
474      var interpreters = ApplicationManager.Manager.GetInstances(interpreterType);
475      if (interpreters.Count() > 0) {
476        IVRPDataInterpreter interpreter = interpreters.First() as IVRPDataInterpreter;
477        VRPInstanceDescription instance = interpreter.Interpret(data);
478
479        Name = instance.Name;
480        Description = instance.Description;
481        ProblemInstance = instance.ProblemInstance;
482
483        OnReset();
484
485        if (instance.BestKnownQuality != null) {
486          BestKnownQuality = new DoubleValue((double)instance.BestKnownQuality);
487        }
488
489        if (instance.BestKnownSolution != null) {
490          VRPSolution solution = new VRPSolution(ProblemInstance, instance.BestKnownSolution, new DoubleValue(0));
491          BestKnownSolutionParameter.Value = solution;
492        }
493      } else {
494        throw new Exception("Cannot find an interpreter for " + data.GetType());
495      }   
496    }
497  }
498}
Note: See TracBrowser for help on using the repository browser.