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

Last change on this file since 7853 was 7853, checked in by svonolfe, 7 years ago

Added missing creators (#1177)

File size: 16.6 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    }
185
186    private void AttachProblemInstanceEventHandlers() {
187      var solutionCreatorParameter = SolutionCreatorParameter as ConstrainedValueParameter<IVRPCreator>;
188      solutionCreatorParameter.ValidValues.Clear();
189
190      if (ProblemInstance != null) {
191        EvaluatorParameter.Value = ProblemInstance.SolutionEvaluator;
192        foreach (IVRPCreator creator in operators.Where(o => o is IVRPCreator)) {
193          solutionCreatorParameter.ValidValues.Add(creator);
194        }
195        ProblemInstance.EvaluationChanged += new EventHandler(ProblemInstance_EvaluationChanged);
196      }     
197    }
198
199    void ProblemInstance_EvaluationChanged(object sender, EventArgs e) {
200      if (BestKnownSolution != null) {
201        //call evaluator
202        BestKnownQuality = new DoubleValue(ProblemInstance.Evaluate(BestKnownSolution.Solution).Quality);
203        BestKnownSolution.Quality = BestKnownQuality;
204      } else {
205        BestKnownQuality = null;
206      }
207    }
208
209    void ProblemInstanceParameter_ValueChanged(object sender, EventArgs e) {
210      InitializeOperators();
211      AttachProblemInstanceEventHandlers();
212
213      OnSolutionCreatorChanged();
214      OnEvaluatorChanged();
215      OnOperatorsChanged();
216    }
217
218    public void SetProblemInstance(IVRPProblemInstance instance) {
219      ProblemInstanceParameter.ValueChanged -= new EventHandler(ProblemInstanceParameter_ValueChanged);
220
221      ProblemInstance = instance;
222      AttachProblemInstanceEventHandlers();
223
224      OnSolutionCreatorChanged();
225      OnEvaluatorChanged();
226
227      ProblemInstanceParameter.ValueChanged += new EventHandler(ProblemInstanceParameter_ValueChanged);
228    }
229
230    private void SolutionCreatorParameter_ValueChanged(object sender, EventArgs e) {
231      ParameterizeSolutionCreator();
232     
233      OnSolutionCreatorChanged();
234    }
235    private void EvaluatorParameter_ValueChanged(object sender, EventArgs e) {
236      OnEvaluatorChanged();
237    }
238
239    private void InitializeOperators() {
240      operators = new List<IOperator>();
241
242      if (ProblemInstance != null) {
243        operators.AddRange(
244        ProblemInstance.Operators.Concat(
245          ApplicationManager.Manager.GetInstances<IGeneralVRPOperator>().Cast<IOperator>()).OrderBy(op => op.Name));
246      }
247
248      ParameterizeOperators();
249    }
250
251    private void ParameterizeSolutionCreator() {
252      if (SolutionCreator is IMultiVRPOperator) {
253        (SolutionCreator as IMultiVRPOperator).SetOperators(Operators);
254      }
255    }
256
257    private void ParameterizeOperators() {
258      foreach (IOperator op in Operators) {
259        if (op is IMultiVRPOperator) {
260          (op as IMultiVRPOperator).SetOperators(Operators);
261        }
262      }
263    }
264    #endregion
265
266    public void ImportFromCordeau(string cordeauFileName) {
267      CordeauParser parser = new CordeauParser(cordeauFileName);
268      parser.Parse();
269
270      this.Name = parser.ProblemName;
271      MDCVRPTWProblemInstance problem = new MDCVRPTWProblemInstance();
272
273      problem.Coordinates = new DoubleMatrix(parser.Coordinates);
274      problem.Vehicles.Value = parser.Vehicles;
275      problem.Capacity = new DoubleArray(parser.Capacity);
276      problem.Demand = new DoubleArray(parser.Demands);
277      problem.Depots.Value = parser.Depots;
278      problem.VehicleDepotAssignment = new IntArray(parser.Vehicles);
279      problem.ReadyTime = new DoubleArray(parser.Readytimes);
280      problem.ServiceTime = new DoubleArray(parser.Servicetimes);
281      problem.DueTime = new DoubleArray(parser.Duetimes);
282
283      int depot = 0;
284      int i = 0;
285      while(i < parser.Vehicles) {
286        problem.VehicleDepotAssignment[i] = depot;
287
288        i++;
289        if (i % (parser.Vehicles / parser.Depots) == 0)
290          depot++;
291      }
292
293      this.ProblemInstance = problem;
294
295      OnReset();
296    }
297
298    public void ImportFromLiLim(string liLimFileName) {
299      LiLimParser parser = new LiLimParser(liLimFileName);
300      parser.Parse();
301
302      this.Name = parser.ProblemName;
303      CVRPPDTWProblemInstance problem = new CVRPPDTWProblemInstance();
304
305      problem.Coordinates = new DoubleMatrix(parser.Coordinates);
306      problem.Vehicles.Value = parser.Vehicles;
307      problem.Capacity.Value = parser.Capacity;
308      problem.Demand = new DoubleArray(parser.Demands);
309      problem.ReadyTime = new DoubleArray(parser.Readytimes);
310      problem.DueTime = new DoubleArray(parser.Duetimes);
311      problem.ServiceTime = new DoubleArray(parser.Servicetimes);
312      problem.PickupDeliveryLocation = new IntArray(parser.PickupDeliveryLocations);
313
314      this.ProblemInstance = problem;
315
316      OnReset();
317    }
318
319    public void ImportFromSolomon(string solomonFileName) {
320      SolomonParser parser = new SolomonParser(solomonFileName);
321      parser.Parse();
322
323      this.Name = parser.ProblemName;
324      CVRPTWProblemInstance problem = new CVRPTWProblemInstance();
325     
326      problem.Coordinates = new DoubleMatrix(parser.Coordinates);
327      problem.Vehicles.Value = parser.Vehicles;
328      problem.Capacity.Value = parser.Capacity;
329      problem.Demand = new DoubleArray(parser.Demands);
330      problem.ReadyTime = new DoubleArray(parser.Readytimes);
331      problem.DueTime = new DoubleArray(parser.Duetimes);
332      problem.ServiceTime = new DoubleArray(parser.Servicetimes);
333
334      this.ProblemInstance = problem;
335
336      OnReset();
337    }
338
339    public void ImportFromTSPLib(string tspFileName) {
340      TSPLIBParser parser = new TSPLIBParser(tspFileName);
341      parser.Parse();
342
343      this.Name = parser.Name;
344      int problemSize = parser.Demands.Length;
345
346      if (parser.Depot != 1) {
347        ErrorHandling.ShowErrorDialog(new Exception("Invalid depot specification"));
348        return;
349      }
350
351      if (parser.WeightType != TSPLIBParser.TSPLIBEdgeWeightType.EUC_2D)  {
352        ErrorHandling.ShowErrorDialog(new Exception("Invalid weight type"));
353        return;
354      }
355
356      CVRPTWProblemInstance problem = new CVRPTWProblemInstance();
357      problem.Coordinates = new DoubleMatrix(parser.Vertices);
358      if (parser.Vehicles != -1)
359        problem.Vehicles.Value = parser.Vehicles;
360      else
361        problem.Vehicles.Value = problemSize - 1;
362      problem.Capacity.Value = parser.Capacity;
363      problem.Demand = new DoubleArray(parser.Demands);
364      problem.ReadyTime = new DoubleArray(problemSize);
365      problem.DueTime = new DoubleArray(problemSize);
366      problem.ServiceTime = new DoubleArray(problemSize);
367
368      for (int i = 0; i < problemSize; i++) {
369        problem.ReadyTime[i] = 0;
370        problem.DueTime[i] = int.MaxValue;
371        problem.ServiceTime[i] = 0;
372      }
373
374      if (parser.Distance != -1) {
375        problem.DueTime[0] = parser.Distance;
376      }
377
378      this.ProblemInstance = problem;
379
380      OnReset();
381    }
382
383    public void ImportFromORLib(string orFileName) {
384      ORLIBParser parser = new ORLIBParser(orFileName);
385      parser.Parse();
386
387      this.Name = parser.Name;
388      int problemSize = parser.Demands.Length;
389
390      CVRPProblemInstance problem = new CVRPProblemInstance();
391
392      problem.Coordinates = new DoubleMatrix(parser.Vertices);
393      problem.Vehicles.Value = problemSize - 1;
394      problem.Capacity.Value = parser.Capacity;
395      problem.Demand = new DoubleArray(parser.Demands);
396
397      this.ProblemInstance = problem;
398
399      OnReset();
400    }
401
402    private void InitializeRandomVRPInstance() {
403      System.Random rand = new System.Random();
404
405      CVRPTWProblemInstance problem = new CVRPTWProblemInstance();
406      int cities = 100;
407
408      problem.Coordinates = new DoubleMatrix(cities + 1, 2);
409      problem.Demand = new DoubleArray(cities + 1);
410      problem.DueTime = new DoubleArray(cities + 1);
411      problem.ReadyTime = new DoubleArray(cities + 1);
412      problem.ServiceTime = new DoubleArray(cities + 1);
413
414      problem.Vehicles.Value = 100;
415      problem.Capacity.Value = 200;
416
417      for (int i = 0; i <= cities; i++) {
418        problem.Coordinates[i, 0] = rand.Next(0, 100);
419        problem.Coordinates[i, 1] = rand.Next(0, 100);
420
421        if (i == 0) {
422          problem.Demand[i] = 0;
423          problem.DueTime[i] = Int16.MaxValue;
424          problem.ReadyTime[i] = 0;
425          problem.ServiceTime[i] = 0;
426        } else {
427          problem.Demand[i] = rand.Next(10, 50);
428          problem.DueTime[i] = rand.Next((int)Math.Ceiling(problem.GetDistance(0, i, null)), 1200);
429          problem.ReadyTime[i] = problem.DueTime[i] - rand.Next(0, 100);
430          problem.ServiceTime[i] = 90;
431        }
432      }
433
434      this.ProblemInstance = problem;
435    }
436
437    public void ImportSolution(string solutionFileName) {
438      SolutionParser parser = new SolutionParser(solutionFileName);
439      parser.Parse();
440
441      HeuristicLab.Problems.VehicleRouting.Encodings.Potvin.PotvinEncoding encoding = new Encodings.Potvin.PotvinEncoding(ProblemInstance);
442
443      int cities = 0;
444      foreach (List<int> route in parser.Routes) {
445        Tour tour = new Tour();
446        tour.Stops.AddRange(route);
447        cities += tour.Stops.Count;
448
449        encoding.Tours.Add(tour);
450      }
451
452      if (cities != ProblemInstance.Coordinates.Rows - 1)
453        ErrorHandling.ShowErrorDialog(new Exception("The optimal solution does not seem to correspond with the problem data"));
454      else {
455        VRPSolution solution = new VRPSolution(ProblemInstance, encoding, new DoubleValue(0));
456        BestKnownSolutionParameter.Value = solution;
457      }
458    }
459  }
460}
Note: See TracBrowser for help on using the repository browser.