Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.VehicleRouting/3.4/VehicleRoutingProblem.cs @ 8878

Last change on this file since 8878 was 8720, checked in by jkarder, 12 years ago

#1899: applied the changes suggested by ascheibe in comment:6:ticket:1899

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