Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2521: completed port of VRP (needs testing though)

File size: 14.1 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    private void AttachEventHandlers() {
156      ProblemInstanceParameter.ValueChanged += new EventHandler(ProblemInstanceParameter_ValueChanged);
157      BestKnownSolutionParameter.ValueChanged += new EventHandler(BestKnownSolutionParameter_ValueChanged);
158    }
159
160    private void AttachProblemInstanceEventHandlers() {
161      if (ProblemInstance != null) {
162        ProblemInstance.EvaluationChanged += new EventHandler(ProblemInstance_EvaluationChanged);
163      }
164    }
165
166    void BestKnownSolutionParameter_ValueChanged(object sender, EventArgs e) {
167      EvalBestKnownSolution();
168    }
169
170    void ProblemInstance_EvaluationChanged(object sender, EventArgs e) {
171      BestKnownQuality = double.NaN;
172      if (BestKnownSolution != null) {
173        // the tour is not valid if there are more vehicles in it than allowed
174        if (ProblemInstance.Vehicles.Value < BestKnownSolution.Solution.GetTours().Count) {
175          BestKnownSolution = null;
176        } else EvalBestKnownSolution();
177      }
178    }
179
180    private void EvalBestKnownSolution() {
181      if (BestKnownSolution == null) return;
182      try {
183        //call evaluator
184        var evaluation = ProblemInstance.Evaluate(BestKnownSolution.Solution);
185        BestKnownQuality = evaluation.Quality;
186        BestKnownSolution.Evaluation = evaluation;
187      } catch {
188        BestKnownQuality = double.NaN;
189        BestKnownSolution = null;
190      }
191    }
192
193    void ProblemInstanceParameter_ValueChanged(object sender, EventArgs e) {
194      InitializeOperators();
195      AttachProblemInstanceEventHandlers();
196    }
197
198    protected override void OnEncodingChanged() {
199      base.OnEncodingChanged();
200      InitializeOperators();
201    }
202
203    private void InitializeOperators() {
204      Encoding.FilterOperators(ProblemInstance);
205
206      var newOps = ProblemInstance.FilterOperators(Operators.OfType<IOperator>())
207        .Union(Operators.Where(x => !(x is IOperator) || x.GetType().Namespace.StartsWith("HeuristicLab.Optimization")))
208        .ToList();
209      var operatorTypes = new HashSet<Type>(newOps.Select(x => x.GetType()));
210      if (operatorTypes.Add(typeof(VRPSimilarityCalculator)))
211        newOps.Add(new VRPSimilarityCalculator());
212      if (operatorTypes.Add(typeof(QualitySimilarityCalculator)))
213        newOps.Add(new QualitySimilarityCalculator());
214      if (operatorTypes.Add(typeof(PopulationSimilarityAnalyzer)))
215        newOps.Add(new PopulationSimilarityAnalyzer(Operators.OfType<ISolutionSimilarityCalculator>()));
216
217      var assembly = typeof(VehicleRoutingProblem).Assembly;
218      var analyzers = ApplicationManager.Manager.GetTypes(new[] { typeof(IAnalyzer) }, assembly, true, false, false)
219        .Where(x => operatorTypes.Add(x)).Select(t => (IOperator)Activator.CreateInstance(t)).ToList();
220      newOps.AddRange(ProblemInstance.FilterOperators(analyzers));
221     
222      Operators.Replace(newOps);
223    }
224
225    protected override void ParameterizeOperators() {
226      base.ParameterizeOperators();
227      Parameterize();
228    }
229
230    private void Parameterize() {
231      foreach (ISolutionSimilarityCalculator op in Operators.OfType<ISolutionSimilarityCalculator>()) {
232        op.SolutionVariableName = Encoding.Name;
233        op.QualityVariableName = Evaluator.QualityParameter.ActualName;
234        var calc = op as VRPSimilarityCalculator;
235        if (calc != null) calc.ProblemInstance = ProblemInstance;
236      }
237    }
238
239    #endregion
240
241    private void InitializeRandomVRPInstance() {
242      System.Random rand = new System.Random();
243
244      CVRPTWProblemInstance problem = new CVRPTWProblemInstance();
245      int cities = 100;
246
247      problem.Coordinates = new DoubleMatrix(cities + 1, 2);
248      problem.Demand = new DoubleArray(cities + 1);
249      problem.DueTime = new DoubleArray(cities + 1);
250      problem.ReadyTime = new DoubleArray(cities + 1);
251      problem.ServiceTime = new DoubleArray(cities + 1);
252
253      problem.Vehicles.Value = 100;
254      problem.Capacity.Value = 200;
255
256      for (int i = 0; i <= cities; i++) {
257        problem.Coordinates[i, 0] = rand.Next(0, 100);
258        problem.Coordinates[i, 1] = rand.Next(0, 100);
259
260        if (i == 0) {
261          problem.Demand[i] = 0;
262          problem.DueTime[i] = Int16.MaxValue;
263          problem.ReadyTime[i] = 0;
264          problem.ServiceTime[i] = 0;
265        } else {
266          problem.Demand[i] = rand.Next(10, 50);
267          problem.DueTime[i] = rand.Next((int)Math.Ceiling(problem.GetDistance(0, i, null)), 1200);
268          problem.ReadyTime[i] = problem.DueTime[i] - rand.Next(0, 100);
269          problem.ServiceTime[i] = 90;
270        }
271      }
272
273      this.ProblemInstance = problem;
274    }
275
276    public void ImportSolution(string solutionFileName) {
277      SolutionParser parser = new SolutionParser(solutionFileName);
278      parser.Parse();
279
280      HeuristicLab.Problems.VehicleRouting.Encodings.Potvin.PotvinEncodedSolution encoding = new Encodings.Potvin.PotvinEncodedSolution(ProblemInstance);
281
282      int cities = 0;
283      foreach (List<int> route in parser.Routes) {
284        Tour tour = new Tour();
285        tour.Stops.AddRange(route);
286        cities += tour.Stops.Count;
287
288        encoding.Tours.Add(tour);
289      }
290
291      if (cities != ProblemInstance.Coordinates.Rows - 1)
292        ErrorHandling.ShowErrorDialog(new Exception("The optimal solution does not seem to correspond with the problem data"));
293      else {
294        VRPSolution solution = new VRPSolution(ProblemInstance, encoding, ProblemInstance.Evaluate(encoding));
295        BestKnownSolutionParameter.Value = solution;
296      }
297    }
298
299    #region Instance Consuming
300    public void Load(IVRPData data, IVRPDataInterpreter interpreter) {
301      VRPInstanceDescription instance = interpreter.Interpret(data);
302
303      Name = instance.Name;
304      Description = instance.Description;
305
306      BestKnownQuality = double.NaN;
307      BestKnownSolution = null;
308
309      ProblemInstance = instance.ProblemInstance;
310
311      OnReset();
312
313      if (instance.BestKnownQuality != null) {
314        BestKnownQuality = instance.BestKnownQuality ?? double.NaN;
315      }
316
317      if (instance.BestKnownSolution != null) {
318        VRPSolution solution = new VRPSolution(ProblemInstance, instance.BestKnownSolution, ProblemInstance.Evaluate(instance.BestKnownSolution));
319        BestKnownSolution = solution;
320      }
321    }
322    #endregion
323
324    #region IProblemInstanceConsumer<VRPData> Members
325
326    public void Load(IVRPData data) {
327      var interpreterDataType = data.GetType();
328      var interpreterType = typeof(IVRPDataInterpreter<>).MakeGenericType(interpreterDataType);
329
330      var interpreters = ApplicationManager.Manager.GetTypes(interpreterType);
331
332      var concreteInterpreter = interpreters.Single(t => GetInterpreterDataType(t) == interpreterDataType);
333
334      Load(data, (IVRPDataInterpreter)Activator.CreateInstance(concreteInterpreter));
335    }
336
337    private Type GetInterpreterDataType(Type type) {
338      var parentInterfaces = type.BaseType.GetInterfaces();
339      var interfaces = type.GetInterfaces().Except(parentInterfaces);
340
341      var interpreterInterface = interfaces.Single(i => typeof(IVRPDataInterpreter).IsAssignableFrom(i));
342      return interpreterInterface.GetGenericArguments()[0];
343    }
344    #endregion
345  }
346}
Note: See TracBrowser for help on using the repository browser.