Free cookie consent management tool by TermsFeed Policy Generator

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

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

Fixed issues related to display of VRP solution (#1177)

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