Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Problems.VehicleRouting/3.4/VehicleRoutingProblem.cs @ 12099

Last change on this file since 12099 was 12009, checked in by ascheibe, 10 years ago

#2212 updated copyright year

File size: 16.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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 HeuristicLab.Analysis;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Data;
30using HeuristicLab.Optimization;
31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33using HeuristicLab.PluginInfrastructure;
34using HeuristicLab.Problems.Instances;
35using HeuristicLab.Problems.VehicleRouting.Encodings.Alba;
36using HeuristicLab.Problems.VehicleRouting.Interfaces;
37using HeuristicLab.Problems.VehicleRouting.Interpreters;
38using HeuristicLab.Problems.VehicleRouting.ProblemInstances;
39using HeuristicLab.Problems.VehicleRouting.Variants;
40
41namespace HeuristicLab.Problems.VehicleRouting {
42  [Item("Vehicle Routing Problem", "Represents a Vehicle Routing Problem.")]
43  [Creatable("Problems")]
44  [StorableClass]
45  public sealed class VehicleRoutingProblem : Problem, ISingleObjectiveHeuristicOptimizationProblem, IStorableContent, IProblemInstanceConsumer<IVRPData> {
46    public string Filename { get; set; }
47
48    public static new Image StaticItemImage {
49      get { return HeuristicLab.Common.Resources.VSImageLibrary.Type; }
50    }
51
52    #region Parameter Properties
53    public ValueParameter<BoolValue> MaximizationParameter {
54      get { return (ValueParameter<BoolValue>)Parameters["Maximization"]; }
55    }
56    IParameter ISingleObjectiveHeuristicOptimizationProblem.MaximizationParameter {
57      get { return MaximizationParameter; }
58    }
59    public ValueParameter<IVRPProblemInstance> ProblemInstanceParameter {
60      get { return (ValueParameter<IVRPProblemInstance>)Parameters["ProblemInstance"]; }
61    }
62    public OptionalValueParameter<DoubleValue> BestKnownQualityParameter {
63      get { return (OptionalValueParameter<DoubleValue>)Parameters["BestKnownQuality"]; }
64    }
65    IParameter ISingleObjectiveHeuristicOptimizationProblem.BestKnownQualityParameter {
66      get { return BestKnownQualityParameter; }
67    }
68    public OptionalValueParameter<VRPSolution> BestKnownSolutionParameter {
69      get { return (OptionalValueParameter<VRPSolution>)Parameters["BestKnownSolution"]; }
70    }
71    public IConstrainedValueParameter<IVRPCreator> SolutionCreatorParameter {
72      get { return (IConstrainedValueParameter<IVRPCreator>)Parameters["SolutionCreator"]; }
73    }
74    IParameter IHeuristicOptimizationProblem.SolutionCreatorParameter {
75      get { return SolutionCreatorParameter; }
76    }
77    public IValueParameter<IVRPEvaluator> EvaluatorParameter {
78      get { return (IValueParameter<IVRPEvaluator>)Parameters["Evaluator"]; }
79    }
80    IParameter IHeuristicOptimizationProblem.EvaluatorParameter {
81      get { return EvaluatorParameter; }
82    }
83    #endregion
84
85    #region Properties
86    public IVRPProblemInstance ProblemInstance {
87      get { return ProblemInstanceParameter.Value; }
88      set { ProblemInstanceParameter.Value = value; }
89    }
90
91    public VRPSolution BestKnownSolution {
92      get { return BestKnownSolutionParameter.Value; }
93      set { BestKnownSolutionParameter.Value = value; }
94    }
95
96    public DoubleValue BestKnownQuality {
97      get { return BestKnownQualityParameter.Value; }
98      set { BestKnownQualityParameter.Value = value; }
99    }
100
101    public ISingleObjectiveEvaluator Evaluator {
102      get { return EvaluatorParameter.Value; }
103    }
104
105    IEvaluator IHeuristicOptimizationProblem.Evaluator {
106      get { return this.Evaluator; }
107    }
108
109    ISolutionCreator IHeuristicOptimizationProblem.SolutionCreator {
110      get { return SolutionCreatorParameter.Value; }
111    }
112    public IVRPCreator SolutionCreator {
113      get { return SolutionCreatorParameter.Value; }
114      set { SolutionCreatorParameter.Value = value; }
115    }
116    private SingleObjectivePopulationDiversityAnalyzer SingleObjectivePopulationDiversityAnalyzer {
117      get { return Operators.OfType<SingleObjectivePopulationDiversityAnalyzer>().FirstOrDefault(); }
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) {
199        //call evaluator
200        BestKnownQuality = new DoubleValue(ProblemInstance.Evaluate(BestKnownSolution.Solution).Quality);
201        BestKnownSolution.Quality = BestKnownQuality;
202      } else {
203        BestKnownQuality = null;
204      }
205    }
206
207    void BestKnownSolutionParameter_ValueChanged(object sender, EventArgs e) {
208      EvalBestKnownSolution();
209    }
210
211    void ProblemInstance_EvaluationChanged(object sender, EventArgs e) {
212      EvalBestKnownSolution();
213    }
214
215    void ProblemInstanceParameter_ValueChanged(object sender, EventArgs e) {
216      InitializeOperators();
217      AttachProblemInstanceEventHandlers();
218
219      EvaluatorParameter.Value = ProblemInstance.SolutionEvaluator;
220
221      OnSolutionCreatorChanged();
222      OnEvaluatorChanged();
223      OnOperatorsChanged();
224    }
225
226    public void SetProblemInstance(IVRPProblemInstance instance) {
227      ProblemInstanceParameter.ValueChanged -= new EventHandler(ProblemInstanceParameter_ValueChanged);
228
229      ProblemInstance = instance;
230      AttachProblemInstanceEventHandlers();
231
232      OnSolutionCreatorChanged();
233      OnEvaluatorChanged();
234
235      ProblemInstanceParameter.ValueChanged += new EventHandler(ProblemInstanceParameter_ValueChanged);
236    }
237
238    private void SolutionCreatorParameter_ValueChanged(object sender, EventArgs e) {
239      OnSolutionCreatorChanged();
240    }
241    private void EvaluatorParameter_ValueChanged(object sender, EventArgs e) {
242      if (ProblemInstance != null)
243        ProblemInstance.SolutionEvaluator = EvaluatorParameter.Value;
244      OnEvaluatorChanged();
245    }
246
247    private void InitializeOperators() {
248      var solutionCreatorParameter = SolutionCreatorParameter as ConstrainedValueParameter<IVRPCreator>;
249      solutionCreatorParameter.ValidValues.Clear();
250
251      Operators.Clear();
252
253      if (ProblemInstance != null) {
254        Operators.AddRange(
255        ProblemInstance.Operators.Concat(
256          ApplicationManager.Manager.GetInstances<IGeneralVRPOperator>().Cast<IOperator>()).OrderBy(op => op.Name));
257        Operators.Add(new VRPSimilarityCalculator());
258        Operators.Add(new SingleObjectivePopulationDiversityAnalyzer());
259
260        IVRPCreator defaultCreator = null;
261        foreach (IVRPCreator creator in Operators.Where(o => o is IVRPCreator)) {
262          solutionCreatorParameter.ValidValues.Add(creator);
263          if (creator is Encodings.Alba.RandomCreator)
264            defaultCreator = creator;
265        }
266        Operators.Add(new AlbaLambdaInterchangeLocalImprovementOperator());
267        if (defaultCreator != null)
268          solutionCreatorParameter.Value = defaultCreator;
269      }
270
271      ParameterizeOperators();
272    }
273
274    private void ParameterizeOperators() {
275      foreach (IOperator op in Operators.OfType<IOperator>()) {
276        if (op is IMultiVRPOperator) {
277          (op as IMultiVRPOperator).SetOperators(Operators.OfType<IOperator>());
278        }
279      }
280      if (ProblemInstance != null) {
281        foreach (ISingleObjectiveImprovementOperator op in Operators.OfType<ISingleObjectiveImprovementOperator>()) {
282          op.SolutionParameter.ActualName = SolutionCreator.VRPToursParameter.ActualName;
283          op.SolutionParameter.Hidden = true;
284        }
285        foreach (ISingleObjectivePathRelinker op in Operators.OfType<ISingleObjectivePathRelinker>()) {
286          op.ParentsParameter.ActualName = SolutionCreator.VRPToursParameter.ActualName;
287          op.ParentsParameter.Hidden = true;
288        }
289        foreach (VRPSimilarityCalculator op in Operators.OfType<VRPSimilarityCalculator>()) {
290          op.SolutionVariableName = SolutionCreator.VRPToursParameter.ActualName;
291          op.QualityVariableName = ProblemInstance.SolutionEvaluator.QualityParameter.ActualName;
292          op.ProblemInstance = ProblemInstance;
293        }
294        if (SingleObjectivePopulationDiversityAnalyzer != null) {
295          SingleObjectivePopulationDiversityAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
296          SingleObjectivePopulationDiversityAnalyzer.QualityParameter.ActualName = ProblemInstance.SolutionEvaluator.QualityParameter.ActualName;
297          SingleObjectivePopulationDiversityAnalyzer.ResultsParameter.ActualName = "Results";
298          SingleObjectivePopulationDiversityAnalyzer.SimilarityCalculator = Operators.OfType<VRPSimilarityCalculator>().SingleOrDefault();
299        }
300      }
301    }
302
303    #endregion
304
305    private void InitializeRandomVRPInstance() {
306      System.Random rand = new System.Random();
307
308      CVRPTWProblemInstance problem = new CVRPTWProblemInstance();
309      int cities = 100;
310
311      problem.Coordinates = new DoubleMatrix(cities + 1, 2);
312      problem.Demand = new DoubleArray(cities + 1);
313      problem.DueTime = new DoubleArray(cities + 1);
314      problem.ReadyTime = new DoubleArray(cities + 1);
315      problem.ServiceTime = new DoubleArray(cities + 1);
316
317      problem.Vehicles.Value = 100;
318      problem.Capacity.Value = 200;
319
320      for (int i = 0; i <= cities; i++) {
321        problem.Coordinates[i, 0] = rand.Next(0, 100);
322        problem.Coordinates[i, 1] = rand.Next(0, 100);
323
324        if (i == 0) {
325          problem.Demand[i] = 0;
326          problem.DueTime[i] = Int16.MaxValue;
327          problem.ReadyTime[i] = 0;
328          problem.ServiceTime[i] = 0;
329        } else {
330          problem.Demand[i] = rand.Next(10, 50);
331          problem.DueTime[i] = rand.Next((int)Math.Ceiling(problem.GetDistance(0, i, null)), 1200);
332          problem.ReadyTime[i] = problem.DueTime[i] - rand.Next(0, 100);
333          problem.ServiceTime[i] = 90;
334        }
335      }
336
337      this.ProblemInstance = problem;
338    }
339
340    public void ImportSolution(string solutionFileName) {
341      SolutionParser parser = new SolutionParser(solutionFileName);
342      parser.Parse();
343
344      HeuristicLab.Problems.VehicleRouting.Encodings.Potvin.PotvinEncoding encoding = new Encodings.Potvin.PotvinEncoding(ProblemInstance);
345
346      int cities = 0;
347      foreach (List<int> route in parser.Routes) {
348        Tour tour = new Tour();
349        tour.Stops.AddRange(route);
350        cities += tour.Stops.Count;
351
352        encoding.Tours.Add(tour);
353      }
354
355      if (cities != ProblemInstance.Coordinates.Rows - 1)
356        ErrorHandling.ShowErrorDialog(new Exception("The optimal solution does not seem to correspond with the problem data"));
357      else {
358        VRPSolution solution = new VRPSolution(ProblemInstance, encoding, new DoubleValue(0));
359        BestKnownSolutionParameter.Value = solution;
360      }
361    }
362
363    #region Instance Consuming
364    public void Load(IVRPData data, IVRPDataInterpreter interpreter) {
365      VRPInstanceDescription instance = interpreter.Interpret(data);
366
367      Name = instance.Name;
368      Description = instance.Description;
369
370      BestKnownQuality = null;
371      BestKnownSolution = null;
372
373      if (ProblemInstance != null && instance.ProblemInstance != null &&
374        instance.ProblemInstance.GetType() == ProblemInstance.GetType())
375        SetProblemInstance(instance.ProblemInstance);
376      else
377        ProblemInstance = instance.ProblemInstance;
378
379      OnReset();
380
381      if (instance.BestKnownQuality != null) {
382        BestKnownQuality = new DoubleValue((double)instance.BestKnownQuality);
383      }
384
385      if (instance.BestKnownSolution != null) {
386        VRPSolution solution = new VRPSolution(ProblemInstance, instance.BestKnownSolution, new DoubleValue(0));
387        BestKnownSolution = solution;
388      }
389    }
390    #endregion
391
392    #region IProblemInstanceConsumer<VRPData> Members
393
394    public void Load(IVRPData data) {
395      var interpreterDataType = data.GetType();
396      var interpreterType = typeof(IVRPDataInterpreter<>).MakeGenericType(interpreterDataType);
397
398      var interpreters = ApplicationManager.Manager.GetTypes(interpreterType);
399
400      var concreteInterpreter = interpreters.Single(t => GetInterpreterDataType(t) == interpreterDataType);
401
402      Load(data, (IVRPDataInterpreter)Activator.CreateInstance(concreteInterpreter));
403    }
404
405    private Type GetInterpreterDataType(Type type) {
406      var parentInterfaces = type.BaseType.GetInterfaces();
407      var interfaces = type.GetInterfaces().Except(parentInterfaces);
408
409      var interpreterInterface = interfaces.Single(i => typeof(IVRPDataInterpreter).IsAssignableFrom(i));
410      return interpreterInterface.GetGenericArguments()[0];
411    }
412
413    #endregion
414  }
415}
Note: See TracBrowser for help on using the repository browser.