Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2521_ProblemRefactoring/HeuristicLab.Problems.VehicleRouting/3.4/VehicleRoutingProblem.cs @ 17714

Last change on this file since 17714 was 17711, checked in by abeham, 4 years ago

#2521: working on VRP

File size: 13.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 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 System.Threading;
27using HEAL.Attic;
28using HeuristicLab.Analysis;
29using HeuristicLab.Common;
30using HeuristicLab.Core;
31using HeuristicLab.Data;
32using HeuristicLab.Optimization;
33using HeuristicLab.Optimization.Operators;
34using HeuristicLab.Parameters;
35using HeuristicLab.PluginInfrastructure;
36using HeuristicLab.Problems.Instances;
37using HeuristicLab.Problems.VehicleRouting.Encodings.Potvin;
38using HeuristicLab.Problems.VehicleRouting.Interfaces;
39using HeuristicLab.Problems.VehicleRouting.Interpreters;
40using HeuristicLab.Problems.VehicleRouting.ProblemInstances;
41
42namespace HeuristicLab.Problems.VehicleRouting {
43  [Item("Vehicle Routing Problem (VRP)", "Represents a Vehicle Routing Problem.")]
44  [Creatable(CreatableAttribute.Categories.CombinatorialProblems, Priority = 110)]
45  [StorableType("95137523-AE3B-4638-958C-E86829D54CE3")]
46  public sealed class VehicleRoutingProblem : SingleObjectiveProblem<IVRPEncoding, IVRPEncodedSolution>, IProblemInstanceConsumer<IVRPData> {
47
48    public static new Image StaticItemImage {
49      get { return HeuristicLab.Common.Resources.VSImageLibrary.Type; }
50    }
51
52    #region Parameter Properties
53    public ValueParameter<IVRPProblemInstance> ProblemInstanceParameter {
54      get { return (ValueParameter<IVRPProblemInstance>)Parameters["ProblemInstance"]; }
55    }
56    public OptionalValueParameter<VRPSolution> BestKnownSolutionParameter {
57      get { return (OptionalValueParameter<VRPSolution>)Parameters["BestKnownSolution"]; }
58    }
59    #endregion
60
61    #region Properties
62    public IVRPProblemInstance ProblemInstance {
63      get { return ProblemInstanceParameter.Value; }
64      set { ProblemInstanceParameter.Value = value; }
65    }
66
67    public VRPSolution BestKnownSolution {
68      get { return BestKnownSolutionParameter.Value; }
69      set { BestKnownSolutionParameter.Value = value; }
70    }
71    #endregion
72
73    [StorableConstructor]
74    private VehicleRoutingProblem(StorableConstructorFlag _) : base(_) { }
75    public VehicleRoutingProblem()
76      : base(new PotvinEncoding()) {
77      EncodingParameter.Hidden = false;
78
79      Parameters.Add(new ValueParameter<IVRPProblemInstance>("ProblemInstance", "The VRP problem instance"));
80      Parameters.Add(new OptionalValueParameter<VRPSolution>("BestKnownSolution", "The best known solution of this VRP instance."));
81
82      InitializeRandomVRPInstance();
83      InitializeOperators();
84
85      AttachEventHandlers();
86      AttachProblemInstanceEventHandlers();
87    }
88
89    public override IDeepCloneable Clone(Cloner cloner) {
90      cloner.Clone(ProblemInstance);
91      return new VehicleRoutingProblem(this, cloner);
92    }
93
94    private VehicleRoutingProblem(VehicleRoutingProblem original, Cloner cloner)
95      : base(original, cloner) {
96      this.AttachEventHandlers();
97      this.AttachProblemInstanceEventHandlers();
98    }
99
100    public override void Evaluate(ISingleObjectiveSolutionContext<IVRPEncodedSolution> solutionContext, IRandom random, CancellationToken cancellationToken) {
101      solutionContext.EvaluationResult = ProblemInstance.Evaluate(solutionContext.EncodedSolution);
102    }
103    public override ISingleObjectiveEvaluationResult Evaluate(IVRPEncodedSolution solution, IRandom random, CancellationToken cancellationToken) {
104      return ProblemInstance.Evaluate(solution);
105    }
106
107    public override void Analyze(ISingleObjectiveSolutionContext<IVRPEncodedSolution>[] solutionContexts, ResultCollection results, IRandom random) {
108      base.Analyze(solutionContexts, results, random);
109      var evaluations = solutionContexts.Select(x => (VRPEvaluation)x.EvaluationResult);
110
111      var bestInPop = evaluations.Select((x, index) => new { index, Eval = x }).OrderBy(x => x.Eval.Quality).First();
112      IResult bestSolutionResult;
113      if (!results.TryGetValue("Best VRP Solution", out bestSolutionResult) || !(bestSolutionResult.Value is VRPSolution)) {
114        var best = new VRPSolution(ProblemInstance, solutionContexts[bestInPop.index].EncodedSolution, (VRPEvaluation)bestInPop.Eval.Clone());
115        if (bestSolutionResult != null)
116          bestSolutionResult.Value = best;
117        else results.Add(bestSolutionResult = new Result("Best VRP Solution", best));
118      }
119
120      var bestSolution = (VRPSolution)bestSolutionResult.Value;
121      if (bestSolution == null || bestInPop.Eval.Quality < bestSolution.Evaluation.Quality) {
122        var best = new VRPSolution(ProblemInstance,
123          (IVRPEncodedSolution)solutionContexts[bestInPop.index].EncodedSolution.Clone(),
124          (VRPEvaluation)bestInPop.Eval.Clone());
125        bestSolutionResult.Value = best;
126      };
127
128      var bestValidInPop = evaluations.Select((x, index) => new { index, Eval = x }).Where(x => x.Eval.IsFeasible).OrderBy(x => x.Eval.Quality).FirstOrDefault();
129      IResult bestValidSolutionResult;
130      if (!results.TryGetValue("Best Valid VRP Solution", out bestValidSolutionResult) || !(bestValidSolutionResult.Value is VRPSolution)) {
131        var bestValid = new VRPSolution(ProblemInstance, solutionContexts[bestValidInPop.index].EncodedSolution, (VRPEvaluation)bestValidInPop.Eval.Clone());
132        if (bestValidSolutionResult != null)
133          bestValidSolutionResult.Value = bestValid;
134        else results.Add(bestValidSolutionResult = new Result("Best Valid VRP Solution", bestValid));
135      }
136
137      if (bestValidInPop != null) {
138        var bestValidSolution = (VRPSolution)bestValidSolutionResult.Value;
139        if (bestValidSolution == null || bestValidInPop.Eval.Quality < bestValidSolution.Evaluation.Quality) {
140          var best = new VRPSolution(ProblemInstance,
141            (IVRPEncodedSolution)solutionContexts[bestValidInPop.index].EncodedSolution.Clone(),
142            (VRPEvaluation)bestValidInPop.Eval.Clone());
143          bestValidSolutionResult.Value = best;
144        };
145      }
146    }
147
148    #region Helpers
149    [StorableHook(HookType.AfterDeserialization)]
150    private void AfterDeserialization() {
151      AttachEventHandlers();
152      AttachProblemInstanceEventHandlers();
153    }
154
155    [Storable(OldName = "operators")]
156    private List<IOperator> StorableOperators {
157      set { Operators.AddRange(value); }
158    }
159
160    private void AttachEventHandlers() {
161      ProblemInstanceParameter.ValueChanged += new EventHandler(ProblemInstanceParameter_ValueChanged);
162      BestKnownSolutionParameter.ValueChanged += new EventHandler(BestKnownSolutionParameter_ValueChanged);
163    }
164
165    private void AttachProblemInstanceEventHandlers() {
166      if (ProblemInstance != null) {
167        ProblemInstance.EvaluationChanged += new EventHandler(ProblemInstance_EvaluationChanged);
168      }
169    }
170
171    private void EvalBestKnownSolution() {
172      if (BestKnownSolution == null) return;
173      try {
174        //call evaluator
175        var evaluation = ProblemInstance.Evaluate(BestKnownSolution.Solution);
176        BestKnownQuality = evaluation.Quality;
177        BestKnownSolution.Evaluation = evaluation;
178      } catch {
179        BestKnownQuality = double.NaN;
180        BestKnownSolution = null;
181      }
182    }
183
184    void BestKnownSolutionParameter_ValueChanged(object sender, EventArgs e) {
185      EvalBestKnownSolution();
186    }
187
188    void ProblemInstance_EvaluationChanged(object sender, EventArgs e) {
189      BestKnownQuality = double.NaN;
190      if (BestKnownSolution != null) {
191        // the tour is not valid if there are more vehicles in it than allowed
192        if (ProblemInstance.Vehicles.Value < BestKnownSolution.Solution.GetTours().Count) {
193          BestKnownSolution = null;
194        } else EvalBestKnownSolution();
195      }
196    }
197
198    void ProblemInstanceParameter_ValueChanged(object sender, EventArgs e) {
199      InitializeOperators();
200      AttachProblemInstanceEventHandlers();
201
202      OnOperatorsChanged();
203    }
204
205    public void SetProblemInstance(IVRPProblemInstance instance) {
206      ProblemInstanceParameter.ValueChanged -= new EventHandler(ProblemInstanceParameter_ValueChanged);
207
208      ProblemInstance = instance;
209      AttachProblemInstanceEventHandlers();
210
211      ProblemInstanceParameter.ValueChanged += new EventHandler(ProblemInstanceParameter_ValueChanged);
212    }
213
214    private void InitializeOperators() {
215      Encoding.FilterOperators(ProblemInstance);
216
217      Operators.Add(new VRPSimilarityCalculator());
218      Operators.Add(new QualitySimilarityCalculator());
219      Operators.Add(new PopulationSimilarityAnalyzer(Operators.OfType<ISolutionSimilarityCalculator>()));
220      //Operators.AddRange(ProblemInstance.Operators.OfType<IAnalyzer>());
221    }
222
223    protected override void ParameterizeOperators() {
224      base.ParameterizeOperators();
225      Parameterize();
226    }
227
228    private void Parameterize() {
229      foreach (ISolutionSimilarityCalculator op in Operators.OfType<ISolutionSimilarityCalculator>()) {
230        op.SolutionVariableName = Encoding.Name;
231        op.QualityVariableName = Evaluator.QualityParameter.ActualName;
232        var calc = op as VRPSimilarityCalculator;
233        if (calc != null) calc.ProblemInstance = ProblemInstance;
234      }
235    }
236
237    #endregion
238
239    private void InitializeRandomVRPInstance() {
240      System.Random rand = new System.Random();
241
242      CVRPTWProblemInstance problem = new CVRPTWProblemInstance();
243      int cities = 100;
244
245      problem.Coordinates = new DoubleMatrix(cities + 1, 2);
246      problem.Demand = new DoubleArray(cities + 1);
247      problem.DueTime = new DoubleArray(cities + 1);
248      problem.ReadyTime = new DoubleArray(cities + 1);
249      problem.ServiceTime = new DoubleArray(cities + 1);
250
251      problem.Vehicles.Value = 100;
252      problem.Capacity.Value = 200;
253
254      for (int i = 0; i <= cities; i++) {
255        problem.Coordinates[i, 0] = rand.Next(0, 100);
256        problem.Coordinates[i, 1] = rand.Next(0, 100);
257
258        if (i == 0) {
259          problem.Demand[i] = 0;
260          problem.DueTime[i] = Int16.MaxValue;
261          problem.ReadyTime[i] = 0;
262          problem.ServiceTime[i] = 0;
263        } else {
264          problem.Demand[i] = rand.Next(10, 50);
265          problem.DueTime[i] = rand.Next((int)Math.Ceiling(problem.GetDistance(0, i, null)), 1200);
266          problem.ReadyTime[i] = problem.DueTime[i] - rand.Next(0, 100);
267          problem.ServiceTime[i] = 90;
268        }
269      }
270
271      this.ProblemInstance = problem;
272    }
273
274    public void ImportSolution(string solutionFileName) {
275      SolutionParser parser = new SolutionParser(solutionFileName);
276      parser.Parse();
277
278      HeuristicLab.Problems.VehicleRouting.Encodings.Potvin.PotvinEncodedSolution encoding = new Encodings.Potvin.PotvinEncodedSolution(ProblemInstance);
279
280      int cities = 0;
281      foreach (List<int> route in parser.Routes) {
282        Tour tour = new Tour();
283        tour.Stops.AddRange(route);
284        cities += tour.Stops.Count;
285
286        encoding.Tours.Add(tour);
287      }
288
289      if (cities != ProblemInstance.Coordinates.Rows - 1)
290        ErrorHandling.ShowErrorDialog(new Exception("The optimal solution does not seem to correspond with the problem data"));
291      else {
292        VRPSolution solution = new VRPSolution(ProblemInstance, encoding, ProblemInstance.Evaluate(encoding));
293        BestKnownSolutionParameter.Value = solution;
294      }
295    }
296
297    #region Instance Consuming
298    public void Load(IVRPData data, IVRPDataInterpreter interpreter) {
299      VRPInstanceDescription instance = interpreter.Interpret(data);
300
301      Name = instance.Name;
302      Description = instance.Description;
303
304      BestKnownQuality = double.NaN;
305      BestKnownSolution = null;
306
307      if (ProblemInstance != null && instance.ProblemInstance != null &&
308        instance.ProblemInstance.GetType() == ProblemInstance.GetType())
309        SetProblemInstance(instance.ProblemInstance);
310      else
311        ProblemInstance = instance.ProblemInstance;
312
313      OnReset();
314
315      if (instance.BestKnownQuality != null) {
316        BestKnownQuality = instance.BestKnownQuality ?? double.NaN;
317      }
318
319      if (instance.BestKnownSolution != null) {
320        VRPSolution solution = new VRPSolution(ProblemInstance, instance.BestKnownSolution, ProblemInstance.Evaluate(instance.BestKnownSolution));
321        BestKnownSolution = solution;
322      }
323    }
324    #endregion
325
326    #region IProblemInstanceConsumer<VRPData> Members
327
328    public void Load(IVRPData data) {
329      var interpreterDataType = data.GetType();
330      var interpreterType = typeof(IVRPDataInterpreter<>).MakeGenericType(interpreterDataType);
331
332      var interpreters = ApplicationManager.Manager.GetTypes(interpreterType);
333
334      var concreteInterpreter = interpreters.Single(t => GetInterpreterDataType(t) == interpreterDataType);
335
336      Load(data, (IVRPDataInterpreter)Activator.CreateInstance(concreteInterpreter));
337    }
338
339    private Type GetInterpreterDataType(Type type) {
340      var parentInterfaces = type.BaseType.GetInterfaces();
341      var interfaces = type.GetInterfaces().Except(parentInterfaces);
342
343      var interpreterInterface = interfaces.Single(i => typeof(IVRPDataInterpreter).IsAssignableFrom(i));
344      return interpreterInterface.GetGenericArguments()[0];
345    }
346    #endregion
347  }
348}
Note: See TracBrowser for help on using the repository browser.