Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2521: working on VRP

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