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
RevLine 
[4360]1#region License Information
2/* HeuristicLab
[17226]3 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[4360]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;
[17698]26using System.Threading;
[17513]27using HEAL.Attic;
[8720]28using HeuristicLab.Analysis;
[4360]29using HeuristicLab.Common;
30using HeuristicLab.Core;
31using HeuristicLab.Data;
32using HeuristicLab.Optimization;
[12102]33using HeuristicLab.Optimization.Operators;
[4360]34using HeuristicLab.Parameters;
35using HeuristicLab.PluginInfrastructure;
[7934]36using HeuristicLab.Problems.Instances;
[17706]37using HeuristicLab.Problems.VehicleRouting.Encodings.Potvin;
[4362]38using HeuristicLab.Problems.VehicleRouting.Interfaces;
[7934]39using HeuristicLab.Problems.VehicleRouting.Interpreters;
[4362]40using HeuristicLab.Problems.VehicleRouting.ProblemInstances;
[4360]41
42namespace HeuristicLab.Problems.VehicleRouting {
[13173]43  [Item("Vehicle Routing Problem (VRP)", "Represents a Vehicle Routing Problem.")]
[12504]44  [Creatable(CreatableAttribute.Categories.CombinatorialProblems, Priority = 110)]
[16723]45  [StorableType("95137523-AE3B-4638-958C-E86829D54CE3")]
[17699]46  public sealed class VehicleRoutingProblem : SingleObjectiveProblem<IVRPEncoding, IVRPEncodedSolution>, IProblemInstanceConsumer<IVRPData> {
[7203]47
48    public static new Image StaticItemImage {
[5867]49      get { return HeuristicLab.Common.Resources.VSImageLibrary.Type; }
[4360]50    }
51
[4362]52    #region Parameter Properties
53    public ValueParameter<IVRPProblemInstance> ProblemInstanceParameter {
54      get { return (ValueParameter<IVRPProblemInstance>)Parameters["ProblemInstance"]; }
55    }
[4860]56    public OptionalValueParameter<VRPSolution> BestKnownSolutionParameter {
57      get { return (OptionalValueParameter<VRPSolution>)Parameters["BestKnownSolution"]; }
58    }
[4362]59    #endregion
[4360]60
[4362]61    #region Properties
62    public IVRPProblemInstance ProblemInstance {
63      get { return ProblemInstanceParameter.Value; }
64      set { ProblemInstanceParameter.Value = value; }
[4360]65    }
66
[4860]67    public VRPSolution BestKnownSolution {
68      get { return BestKnownSolutionParameter.Value; }
69      set { BestKnownSolutionParameter.Value = value; }
70    }
[4360]71    #endregion
72
73    [StorableConstructor]
[16723]74    private VehicleRoutingProblem(StorableConstructorFlag _) : base(_) { }
[4360]75    public VehicleRoutingProblem()
[17706]76      : base(new PotvinEncoding()) {
[4362]77      Parameters.Add(new ValueParameter<IVRPProblemInstance>("ProblemInstance", "The VRP problem instance"));
[4860]78      Parameters.Add(new OptionalValueParameter<VRPSolution>("BestKnownSolution", "The best known solution of this VRP instance."));
[4365]79
[4360]80      InitializeRandomVRPInstance();
[4365]81      InitializeOperators();
[4360]82
83      AttachEventHandlers();
[4362]84      AttachProblemInstanceEventHandlers();
[4360]85    }
86
87    public override IDeepCloneable Clone(Cloner cloner) {
[7906]88      cloner.Clone(ProblemInstance);
[4752]89      return new VehicleRoutingProblem(this, cloner);
[4360]90    }
91
[4752]92    private VehicleRoutingProblem(VehicleRoutingProblem original, Cloner cloner)
93      : base(original, cloner) {
94      this.AttachEventHandlers();
[10360]95      this.AttachProblemInstanceEventHandlers();
[4752]96    }
97
[17710]98    public override void Evaluate(ISingleObjectiveSolutionContext<IVRPEncodedSolution> solutionContext, IRandom random, CancellationToken cancellationToken) {
99      solutionContext.EvaluationResult = ProblemInstance.Evaluate(solutionContext.EncodedSolution);
100    }
[17699]101    public override ISingleObjectiveEvaluationResult Evaluate(IVRPEncodedSolution solution, IRandom random, CancellationToken cancellationToken) {
[17709]102      return ProblemInstance.Evaluate(solution);
[4360]103    }
104
[17710]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
[4360]146    #region Helpers
147    [StorableHook(HookType.AfterDeserialization)]
[7934]148    private void AfterDeserialization() {
[4360]149      AttachEventHandlers();
[4362]150      AttachProblemInstanceEventHandlers();
[4360]151    }
152
[16801]153    [Storable(OldName = "operators")]
[8006]154    private List<IOperator> StorableOperators {
155      set { Operators.AddRange(value); }
156    }
157
[4360]158    private void AttachEventHandlers() {
[4362]159      ProblemInstanceParameter.ValueChanged += new EventHandler(ProblemInstanceParameter_ValueChanged);
[7861]160      BestKnownSolutionParameter.ValueChanged += new EventHandler(BestKnownSolutionParameter_ValueChanged);
[4360]161    }
[4362]162
163    private void AttachProblemInstanceEventHandlers() {
164      if (ProblemInstance != null) {
[7852]165        ProblemInstance.EvaluationChanged += new EventHandler(ProblemInstance_EvaluationChanged);
[7934]166      }
[7852]167    }
[4860]168
[7861]169    private void EvalBestKnownSolution() {
[16692]170      if (BestKnownSolution == null) return;
171      try {
[7852]172        //call evaluator
[17710]173        var evaluation = ProblemInstance.Evaluate(BestKnownSolution.Solution);
174        BestKnownQuality = evaluation.Quality;
175        BestKnownSolution.Evaluation = evaluation;
[16692]176      } catch {
[17698]177        BestKnownQuality = double.NaN;
[16692]178        BestKnownSolution = null;
[4362]179      }
[4360]180    }
[4362]181
[7861]182    void BestKnownSolutionParameter_ValueChanged(object sender, EventArgs e) {
183      EvalBestKnownSolution();
184    }
185
186    void ProblemInstance_EvaluationChanged(object sender, EventArgs e) {
[17698]187      BestKnownQuality = double.NaN;
[16692]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      }
[7861]194    }
195
[4362]196    void ProblemInstanceParameter_ValueChanged(object sender, EventArgs e) {
[17709]197      InitializeOperators();
[4362]198      AttachProblemInstanceEventHandlers();
[4365]199
[17709]200      OnOperatorsChanged();
[4360]201    }
[6907]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
[4365]212    private void InitializeOperators() {
[17704]213      Operators.Add(new VRPSimilarityCalculator());
214      Operators.Add(new QualitySimilarityCalculator());
215      Operators.Add(new PopulationSimilarityAnalyzer(Operators.OfType<ISolutionSimilarityCalculator>()));
[17710]216      //Operators.AddRange(ProblemInstance.Operators.OfType<IAnalyzer>());
[4365]217    }
218
[17698]219    protected override void ParameterizeOperators() {
220      base.ParameterizeOperators();
221      Parameterize();
222    }
223
224    private void Parameterize() {
[17704]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;
[4365]230      }
231    }
[8346]232
[4360]233    #endregion
234
235    private void InitializeRandomVRPInstance() {
236      System.Random rand = new System.Random();
237
[4362]238      CVRPTWProblemInstance problem = new CVRPTWProblemInstance();
[4360]239      int cities = 100;
[4362]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);
[6851]261          problem.DueTime[i] = rand.Next((int)Math.Ceiling(problem.GetDistance(0, i, null)), 1200);
[4362]262          problem.ReadyTime[i] = problem.DueTime[i] - rand.Next(0, 100);
263          problem.ServiceTime[i] = 90;
264        }
265      }
266
267      this.ProblemInstance = problem;
[4360]268    }
[4860]269
270    public void ImportSolution(string solutionFileName) {
271      SolutionParser parser = new SolutionParser(solutionFileName);
272      parser.Parse();
273
[17698]274      HeuristicLab.Problems.VehicleRouting.Encodings.Potvin.PotvinEncodedSolution encoding = new Encodings.Potvin.PotvinEncodedSolution(ProblemInstance);
[4860]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 {
[17710]288        VRPSolution solution = new VRPSolution(ProblemInstance, encoding, ProblemInstance.Evaluate(encoding));
[7852]289        BestKnownSolutionParameter.Value = solution;
[4860]290      }
291    }
[7871]292
[8905]293    #region Instance Consuming
294    public void Load(IVRPData data, IVRPDataInterpreter interpreter) {
295      VRPInstanceDescription instance = interpreter.Interpret(data);
[7871]296
[8905]297      Name = instance.Name;
298      Description = instance.Description;
[10860]299
[17698]300      BestKnownQuality = double.NaN;
[10860]301      BestKnownSolution = null;
302
[8905]303      if (ProblemInstance != null && instance.ProblemInstance != null &&
304        instance.ProblemInstance.GetType() == ProblemInstance.GetType())
305        SetProblemInstance(instance.ProblemInstance);
306      else
307        ProblemInstance = instance.ProblemInstance;
[7871]308
[8905]309      OnReset();
[7871]310
[8905]311      if (instance.BestKnownQuality != null) {
[17698]312        BestKnownQuality = instance.BestKnownQuality ?? double.NaN;
[8905]313      }
[7871]314
[8905]315      if (instance.BestKnownSolution != null) {
[17710]316        VRPSolution solution = new VRPSolution(ProblemInstance, instance.BestKnownSolution, ProblemInstance.Evaluate(instance.BestKnownSolution));
[8905]317        BestKnownSolution = solution;
[7934]318      }
[7871]319    }
[10435]320    #endregion
[8905]321
[10435]322    #region IProblemInstanceConsumer<VRPData> Members
[8905]323
[11285]324    public void Load(IVRPData data) {
[10651]325      var interpreterDataType = data.GetType();
326      var interpreterType = typeof(IVRPDataInterpreter<>).MakeGenericType(interpreterDataType);
[8905]327
[10651]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));
[8905]333    }
334
[10651]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    }
[8905]342    #endregion
[4360]343  }
344}
Note: See TracBrowser for help on using the repository browser.