Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2522_RefactorPluginInfrastructure/HeuristicLab.Problems.VehicleRouting/3.4/VehicleRoutingProblem.cs @ 17514

Last change on this file since 17514 was 15973, checked in by gkronber, 6 years ago

#2522: merged trunk changes from r13402:15972 to branch resolving conflicts where necessary

File size: 16.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 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.IO;
26using System.Linq;
27using System.Reflection;
28using HeuristicLab.Analysis;
29using HeuristicLab.Common;
30using HeuristicLab.Core;
31using HeuristicLab.Data;
32using HeuristicLab.Optimization;
33using HeuristicLab.Optimization.Operators;
34using HeuristicLab.Parameters;
35using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
36using HeuristicLab.PluginInfrastructure;
37using HeuristicLab.Problems.Instances;
38using HeuristicLab.Problems.VehicleRouting.Encodings.Alba;
39using HeuristicLab.Problems.VehicleRouting.Interfaces;
40using HeuristicLab.Problems.VehicleRouting.Interpreters;
41using HeuristicLab.Problems.VehicleRouting.ProblemInstances;
42using HeuristicLab.Problems.VehicleRouting.Variants;
43
44namespace HeuristicLab.Problems.VehicleRouting {
45  [Item("Vehicle Routing Problem (VRP)", "Represents a Vehicle Routing Problem.")]
46  [Creatable(CreatableAttribute.Categories.CombinatorialProblems, Priority = 110)]
47  [StorableClass]
48  public sealed class VehicleRoutingProblem : Problem, ISingleObjectiveHeuristicOptimizationProblem, IStorableContent, IProblemInstanceConsumer<IVRPData> {
49    public string Filename { get; set; }
50
51    public static new Image StaticItemImage {
52      get { return HeuristicLab.Common.Resources.VSImageLibrary.Type; }
53    }
54
55    #region Parameter Properties
56    public ValueParameter<BoolValue> MaximizationParameter {
57      get { return (ValueParameter<BoolValue>)Parameters["Maximization"]; }
58    }
59    IParameter ISingleObjectiveHeuristicOptimizationProblem.MaximizationParameter {
60      get { return MaximizationParameter; }
61    }
62    public ValueParameter<IVRPProblemInstance> ProblemInstanceParameter {
63      get { return (ValueParameter<IVRPProblemInstance>)Parameters["ProblemInstance"]; }
64    }
65    public OptionalValueParameter<DoubleValue> BestKnownQualityParameter {
66      get { return (OptionalValueParameter<DoubleValue>)Parameters["BestKnownQuality"]; }
67    }
68    IParameter ISingleObjectiveHeuristicOptimizationProblem.BestKnownQualityParameter {
69      get { return BestKnownQualityParameter; }
70    }
71    public OptionalValueParameter<VRPSolution> BestKnownSolutionParameter {
72      get { return (OptionalValueParameter<VRPSolution>)Parameters["BestKnownSolution"]; }
73    }
74    public IConstrainedValueParameter<IVRPCreator> SolutionCreatorParameter {
75      get { return (IConstrainedValueParameter<IVRPCreator>)Parameters["SolutionCreator"]; }
76    }
77    IParameter IHeuristicOptimizationProblem.SolutionCreatorParameter {
78      get { return SolutionCreatorParameter; }
79    }
80    public IValueParameter<IVRPEvaluator> EvaluatorParameter {
81      get { return (IValueParameter<IVRPEvaluator>)Parameters["Evaluator"]; }
82    }
83    IParameter IHeuristicOptimizationProblem.EvaluatorParameter {
84      get { return EvaluatorParameter; }
85    }
86    #endregion
87
88    #region Properties
89    public IVRPProblemInstance ProblemInstance {
90      get { return ProblemInstanceParameter.Value; }
91      set { ProblemInstanceParameter.Value = value; }
92    }
93
94    public VRPSolution BestKnownSolution {
95      get { return BestKnownSolutionParameter.Value; }
96      set { BestKnownSolutionParameter.Value = value; }
97    }
98
99    public DoubleValue BestKnownQuality {
100      get { return BestKnownQualityParameter.Value; }
101      set { BestKnownQualityParameter.Value = value; }
102    }
103
104    public ISingleObjectiveEvaluator Evaluator {
105      get { return EvaluatorParameter.Value; }
106    }
107
108    IEvaluator IHeuristicOptimizationProblem.Evaluator {
109      get { return this.Evaluator; }
110    }
111
112    ISolutionCreator IHeuristicOptimizationProblem.SolutionCreator {
113      get { return SolutionCreatorParameter.Value; }
114    }
115    public IVRPCreator SolutionCreator {
116      get { return SolutionCreatorParameter.Value; }
117      set { SolutionCreatorParameter.Value = value; }
118    }
119    #endregion
120
121    [StorableConstructor]
122    private VehicleRoutingProblem(bool deserializing) : base(deserializing) { }
123    public VehicleRoutingProblem()
124      : base() {
125      Parameters.Add(new ValueParameter<BoolValue>("Maximization", "Set to false as the Vehicle Routing Problem is a minimization problem.", new BoolValue(false)));
126      Parameters.Add(new ValueParameter<IVRPProblemInstance>("ProblemInstance", "The VRP problem instance"));
127      Parameters.Add(new OptionalValueParameter<DoubleValue>("BestKnownQuality", "The quality of the best known solution of this VRP instance."));
128      Parameters.Add(new OptionalValueParameter<VRPSolution>("BestKnownSolution", "The best known solution of this VRP instance."));
129
130      Parameters.Add(new ConstrainedValueParameter<IVRPCreator>("SolutionCreator", "The operator which should be used to create new VRP solutions."));
131      Parameters.Add(new ValueParameter<IVRPEvaluator>("Evaluator", "The operator which should be used to evaluate VRP solutions."));
132
133      EvaluatorParameter.Hidden = true;
134
135      InitializeRandomVRPInstance();
136      InitializeOperators();
137
138      AttachEventHandlers();
139      AttachProblemInstanceEventHandlers();
140
141      EvaluatorParameter.Value = ProblemInstance.SolutionEvaluator;
142    }
143
144    public override IDeepCloneable Clone(Cloner cloner) {
145      cloner.Clone(ProblemInstance);
146      return new VehicleRoutingProblem(this, cloner);
147    }
148
149    private VehicleRoutingProblem(VehicleRoutingProblem original, Cloner cloner)
150      : base(original, cloner) {
151      this.AttachEventHandlers();
152      this.AttachProblemInstanceEventHandlers();
153
154      ProblemInstance.SolutionEvaluator = EvaluatorParameter.Value;
155    }
156
157    #region Events
158    public event EventHandler SolutionCreatorChanged;
159    private void OnSolutionCreatorChanged() {
160      EventHandler handler = SolutionCreatorChanged;
161      if (handler != null) handler(this, EventArgs.Empty);
162    }
163    public event EventHandler EvaluatorChanged;
164    private void OnEvaluatorChanged() {
165      EventHandler handler = EvaluatorChanged;
166      if (handler != null) handler(this, EventArgs.Empty);
167    }
168    #endregion
169
170    #region Helpers
171    [StorableHook(HookType.AfterDeserialization)]
172    private void AfterDeserialization() {
173      AttachEventHandlers();
174      AttachProblemInstanceEventHandlers();
175
176      ProblemInstance.SolutionEvaluator = EvaluatorParameter.Value;
177    }
178
179    [Storable(Name = "operators", AllowOneWay = true)]
180    private List<IOperator> StorableOperators {
181      set { Operators.AddRange(value); }
182    }
183
184    private void AttachEventHandlers() {
185      ProblemInstanceParameter.ValueChanged += new EventHandler(ProblemInstanceParameter_ValueChanged);
186      BestKnownSolutionParameter.ValueChanged += new EventHandler(BestKnownSolutionParameter_ValueChanged);
187      EvaluatorParameter.ValueChanged += new EventHandler(EvaluatorParameter_ValueChanged);
188      SolutionCreatorParameter.ValueChanged += new EventHandler(SolutionCreatorParameter_ValueChanged);
189    }
190
191    private void AttachProblemInstanceEventHandlers() {
192      if (ProblemInstance != null) {
193        ProblemInstance.EvaluationChanged += new EventHandler(ProblemInstance_EvaluationChanged);
194      }
195    }
196
197    private void EvalBestKnownSolution() {
198      if (BestKnownSolution == null) return;
199      try {
200        //call evaluator
201        BestKnownQuality = new DoubleValue(ProblemInstance.Evaluate(BestKnownSolution.Solution).Quality);
202        BestKnownSolution.Quality = BestKnownQuality;
203      } catch {
204        BestKnownQuality = null;
205        BestKnownSolution = null;
206      }
207    }
208
209    void BestKnownSolutionParameter_ValueChanged(object sender, EventArgs e) {
210      EvalBestKnownSolution();
211    }
212
213    void ProblemInstance_EvaluationChanged(object sender, EventArgs e) {
214      BestKnownQuality = null;
215      if (BestKnownSolution != null) {
216        // the tour is not valid if there are more vehicles in it than allowed
217        if (ProblemInstance.Vehicles.Value < BestKnownSolution.Solution.GetTours().Count) {
218          BestKnownSolution = null;
219        } else EvalBestKnownSolution();
220      }
221    }
222
223    void ProblemInstanceParameter_ValueChanged(object sender, EventArgs e) {
224      InitializeOperators();
225      AttachProblemInstanceEventHandlers();
226
227      EvaluatorParameter.Value = ProblemInstance.SolutionEvaluator;
228
229      OnSolutionCreatorChanged();
230      OnEvaluatorChanged();
231      OnOperatorsChanged();
232    }
233
234    public void SetProblemInstance(IVRPProblemInstance instance) {
235      ProblemInstanceParameter.ValueChanged -= new EventHandler(ProblemInstanceParameter_ValueChanged);
236
237      ProblemInstance = instance;
238      AttachProblemInstanceEventHandlers();
239
240      OnSolutionCreatorChanged();
241      OnEvaluatorChanged();
242
243      ProblemInstanceParameter.ValueChanged += new EventHandler(ProblemInstanceParameter_ValueChanged);
244    }
245
246    private void SolutionCreatorParameter_ValueChanged(object sender, EventArgs e) {
247      OnSolutionCreatorChanged();
248    }
249    private void EvaluatorParameter_ValueChanged(object sender, EventArgs e) {
250      if (ProblemInstance != null)
251        ProblemInstance.SolutionEvaluator = EvaluatorParameter.Value;
252      OnEvaluatorChanged();
253    }
254
255    private void InitializeOperators() {
256      var solutionCreatorParameter = SolutionCreatorParameter as ConstrainedValueParameter<IVRPCreator>;
257      solutionCreatorParameter.ValidValues.Clear();
258
259      Operators.Clear();
260
261      if (ProblemInstance != null) {
262        Operators.AddRange(
263        ProblemInstance.Operators.Concat(
264          ApplicationManager.Manager.GetInstances<IGeneralVRPOperator>().Cast<IOperator>()).OrderBy(op => op.Name));
265        Operators.Add(new VRPSimilarityCalculator());
266        Operators.Add(new QualitySimilarityCalculator());
267        Operators.Add(new PopulationSimilarityAnalyzer(Operators.OfType<ISolutionSimilarityCalculator>()));
268
269        IVRPCreator defaultCreator = null;
270        foreach (IVRPCreator creator in Operators.Where(o => o is IVRPCreator)) {
271          solutionCreatorParameter.ValidValues.Add(creator);
272          if (creator is Encodings.Alba.RandomCreator)
273            defaultCreator = creator;
274        }
275        Operators.Add(new AlbaLambdaInterchangeLocalImprovementOperator());
276        if (defaultCreator != null)
277          solutionCreatorParameter.Value = defaultCreator;
278      }
279
280      ParameterizeOperators();
281    }
282
283    private void ParameterizeOperators() {
284      foreach (IOperator op in Operators.OfType<IOperator>()) {
285        if (op is IMultiVRPOperator) {
286          (op as IMultiVRPOperator).SetOperators(Operators.OfType<IOperator>());
287        }
288      }
289      if (ProblemInstance != null) {
290        foreach (ISingleObjectiveImprovementOperator op in Operators.OfType<ISingleObjectiveImprovementOperator>()) {
291          op.SolutionParameter.ActualName = SolutionCreator.VRPToursParameter.ActualName;
292          op.SolutionParameter.Hidden = true;
293        }
294        foreach (ISingleObjectivePathRelinker op in Operators.OfType<ISingleObjectivePathRelinker>()) {
295          op.ParentsParameter.ActualName = SolutionCreator.VRPToursParameter.ActualName;
296          op.ParentsParameter.Hidden = true;
297        }
298        foreach (ISolutionSimilarityCalculator op in Operators.OfType<ISolutionSimilarityCalculator>()) {
299          op.SolutionVariableName = SolutionCreator.VRPToursParameter.ActualName;
300          op.QualityVariableName = ProblemInstance.SolutionEvaluator.QualityParameter.ActualName;
301          var calc = op as VRPSimilarityCalculator;
302          if (calc != null) calc.ProblemInstance = ProblemInstance;
303        }
304      }
305    }
306
307    #endregion
308
309    private void InitializeRandomVRPInstance() {
310      System.Random rand = new System.Random();
311
312      CVRPTWProblemInstance problem = new CVRPTWProblemInstance();
313      int cities = 100;
314
315      problem.Coordinates = new DoubleMatrix(cities + 1, 2);
316      problem.Demand = new DoubleArray(cities + 1);
317      problem.DueTime = new DoubleArray(cities + 1);
318      problem.ReadyTime = new DoubleArray(cities + 1);
319      problem.ServiceTime = new DoubleArray(cities + 1);
320
321      problem.Vehicles.Value = 100;
322      problem.Capacity.Value = 200;
323
324      for (int i = 0; i <= cities; i++) {
325        problem.Coordinates[i, 0] = rand.Next(0, 100);
326        problem.Coordinates[i, 1] = rand.Next(0, 100);
327
328        if (i == 0) {
329          problem.Demand[i] = 0;
330          problem.DueTime[i] = Int16.MaxValue;
331          problem.ReadyTime[i] = 0;
332          problem.ServiceTime[i] = 0;
333        } else {
334          problem.Demand[i] = rand.Next(10, 50);
335          problem.DueTime[i] = rand.Next((int)Math.Ceiling(problem.GetDistance(0, i, null)), 1200);
336          problem.ReadyTime[i] = problem.DueTime[i] - rand.Next(0, 100);
337          problem.ServiceTime[i] = 90;
338        }
339      }
340
341      this.ProblemInstance = problem;
342    }
343
344    public void ImportSolution(string solutionFileName) {
345      SolutionParser parser = new SolutionParser(solutionFileName);
346      parser.Parse();
347
348      HeuristicLab.Problems.VehicleRouting.Encodings.Potvin.PotvinEncoding encoding = new Encodings.Potvin.PotvinEncoding(ProblemInstance);
349
350      int cities = 0;
351      foreach (List<int> route in parser.Routes) {
352        Tour tour = new Tour();
353        tour.Stops.AddRange(route);
354        cities += tour.Stops.Count;
355
356        encoding.Tours.Add(tour);
357      }
358
359      if (cities != ProblemInstance.Coordinates.Rows - 1)
360        throw new IOException("Cannot read file. The optimal solution does not seem to correspond with the problem data");
361      else {
362        VRPSolution solution = new VRPSolution(ProblemInstance, encoding, new DoubleValue(0));
363        BestKnownSolutionParameter.Value = solution;
364      }
365    }
366
367    #region Instance Consuming
368    public void Load(IVRPData data, IVRPDataInterpreter interpreter) {
369      VRPInstanceDescription instance = interpreter.Interpret(data);
370
371      Name = instance.Name;
372      Description = instance.Description;
373
374      BestKnownQuality = null;
375      BestKnownSolution = null;
376
377      if (ProblemInstance != null && instance.ProblemInstance != null &&
378        instance.ProblemInstance.GetType() == ProblemInstance.GetType())
379        SetProblemInstance(instance.ProblemInstance);
380      else
381        ProblemInstance = instance.ProblemInstance;
382
383      OnReset();
384
385      if (instance.BestKnownQuality != null) {
386        BestKnownQuality = new DoubleValue((double)instance.BestKnownQuality);
387      }
388
389      if (instance.BestKnownSolution != null) {
390        VRPSolution solution = new VRPSolution(ProblemInstance, instance.BestKnownSolution, new DoubleValue(0));
391        BestKnownSolution = solution;
392      }
393    }
394    #endregion
395
396    #region IProblemInstanceConsumer<VRPData> Members
397
398    public void Load(IVRPData data) {
399      var interpreterDataType = data.GetType();
400      var interpreterType = typeof(IVRPDataInterpreter<>).MakeGenericType(interpreterDataType);
401
402      var interpreters = ApplicationManager.Manager.GetTypes(interpreterType);
403
404      var concreteInterpreter = interpreters.Single(t => GetInterpreterDataType(t) == interpreterDataType);
405
406      Load(data, (IVRPDataInterpreter)Activator.CreateInstance(concreteInterpreter));
407    }
408
409    private Type GetInterpreterDataType(Type type) {
410      var parentInterfaces = type.BaseType.GetInterfaces();
411      var interfaces = type.GetInterfaces().Except(parentInterfaces);
412
413      var interpreterInterface = interfaces.Single(i => typeof(IVRPDataInterpreter).IsAssignableFrom(i));
414      return interpreterInterface.GetGenericArguments()[0];
415    }
416
417    #endregion
418  }
419}
Note: See TracBrowser for help on using the repository browser.