Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 7907 was 7906, checked in by svonolfe, 12 years ago

Fixed issues that prevented the unit tests to pass (#1177)

File size: 14.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Encodings.PermutationEncoding;
30using HeuristicLab.Optimization;
31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33using HeuristicLab.PluginInfrastructure;
34using HeuristicLab.Problems.VehicleRouting.Interfaces;
35using HeuristicLab.Problems.VehicleRouting.ProblemInstances;
36using HeuristicLab.Problems.VehicleRouting.Variants;
37using HeuristicLab.Problems.Instances;
38using System.Reflection;
39using HeuristicLab.Problems.VehicleRouting.Interpreters;
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 : ParameterizedNamedItem, 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 IValueParameter<IVRPCreator> SolutionCreatorParameter {
72      get { return (IValueParameter<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    public ISolutionCreator SolutionCreator {
110      get { return SolutionCreatorParameter.Value; }
111    }
112
113    [Storable]
114    private List<IOperator> operators;
115
116    public IEnumerable<IOperator> Operators {
117      get { return operators; }
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      operators = new List<IOperator>();
136
137      InitializeRandomVRPInstance();
138      InitializeOperators();
139
140      AttachEventHandlers();
141      AttachProblemInstanceEventHandlers();
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.operators = original.operators.Select(x => (IOperator)cloner.Clone(x)).ToList();
152      this.AttachEventHandlers();
153    }
154
155    #region Events
156    public event EventHandler SolutionCreatorChanged;
157    private void OnSolutionCreatorChanged() {
158      EventHandler handler = SolutionCreatorChanged;
159      if (handler != null) handler(this, EventArgs.Empty);
160    }
161    public event EventHandler EvaluatorChanged;
162    private void OnEvaluatorChanged() {
163      EventHandler handler = EvaluatorChanged;
164      if (handler != null) handler(this, EventArgs.Empty);
165    }
166    public event EventHandler OperatorsChanged;
167    private void OnOperatorsChanged() {
168      EventHandler handler = OperatorsChanged;
169      if (handler != null) handler(this, EventArgs.Empty);
170    }
171    public event EventHandler Reset;
172    private void OnReset() {
173      EventHandler handler = Reset;
174      if (handler != null) handler(this, EventArgs.Empty);
175    } 
176    #endregion
177
178    #region Helpers
179    [StorableHook(HookType.AfterDeserialization)]
180    private void AfterDeserializationHook() {
181      AttachEventHandlers();
182      AttachProblemInstanceEventHandlers();
183    }
184
185    private void AttachEventHandlers() {
186      ProblemInstanceParameter.ValueChanged += new EventHandler(ProblemInstanceParameter_ValueChanged);
187      BestKnownSolutionParameter.ValueChanged += new EventHandler(BestKnownSolutionParameter_ValueChanged);
188    }
189
190    private void AttachProblemInstanceEventHandlers() {
191      var solutionCreatorParameter = SolutionCreatorParameter as ConstrainedValueParameter<IVRPCreator>;
192      solutionCreatorParameter.ValidValues.Clear();
193
194      if (ProblemInstance != null) {
195        EvaluatorParameter.Value = ProblemInstance.SolutionEvaluator;
196        IVRPCreator defaultCreator = null;
197        foreach (IVRPCreator creator in operators.Where(o => o is IVRPCreator)) {
198          solutionCreatorParameter.ValidValues.Add(creator);
199          if (creator is Encodings.Alba.RandomCreator)
200            defaultCreator = creator;
201        }
202        if (defaultCreator != null)
203          solutionCreatorParameter.Value = defaultCreator;
204
205        ProblemInstance.EvaluationChanged += new EventHandler(ProblemInstance_EvaluationChanged);
206      }     
207    }
208
209    private void EvalBestKnownSolution() {
210      if (BestKnownSolution != null) {
211        //call evaluator
212        BestKnownQuality = new DoubleValue(ProblemInstance.Evaluate(BestKnownSolution.Solution).Quality);
213        BestKnownSolution.Quality = BestKnownQuality;
214      } else {
215        BestKnownQuality = null;
216      }
217    }
218
219    void BestKnownSolutionParameter_ValueChanged(object sender, EventArgs e) {
220      EvalBestKnownSolution();
221    }
222
223    void ProblemInstance_EvaluationChanged(object sender, EventArgs e) {
224      EvalBestKnownSolution();
225    }
226
227    void ProblemInstanceParameter_ValueChanged(object sender, EventArgs e) {
228      InitializeOperators();
229      AttachProblemInstanceEventHandlers();
230
231      OnSolutionCreatorChanged();
232      OnEvaluatorChanged();
233      OnOperatorsChanged();
234    }
235
236    public void SetProblemInstance(IVRPProblemInstance instance) {
237      ProblemInstanceParameter.ValueChanged -= new EventHandler(ProblemInstanceParameter_ValueChanged);
238
239      ProblemInstance = instance;
240      AttachProblemInstanceEventHandlers();
241
242      OnSolutionCreatorChanged();
243      OnEvaluatorChanged();
244
245      ProblemInstanceParameter.ValueChanged += new EventHandler(ProblemInstanceParameter_ValueChanged);
246    }
247
248    private void SolutionCreatorParameter_ValueChanged(object sender, EventArgs e) {
249      ParameterizeSolutionCreator();
250     
251      OnSolutionCreatorChanged();
252    }
253    private void EvaluatorParameter_ValueChanged(object sender, EventArgs e) {
254      OnEvaluatorChanged();
255    }
256
257    private void InitializeOperators() {
258      operators = new List<IOperator>();
259
260      if (ProblemInstance != null) {
261        operators.AddRange(
262        ProblemInstance.Operators.Concat(
263          ApplicationManager.Manager.GetInstances<IGeneralVRPOperator>().Cast<IOperator>()).OrderBy(op => op.Name));
264      }
265
266      ParameterizeOperators();
267    }
268
269    private void ParameterizeSolutionCreator() {
270      if (SolutionCreator is IMultiVRPOperator) {
271        (SolutionCreator as IMultiVRPOperator).SetOperators(Operators);
272      }
273    }
274
275    private void ParameterizeOperators() {
276      foreach (IOperator op in Operators) {
277        if (op is IMultiVRPOperator) {
278          (op as IMultiVRPOperator).SetOperators(Operators);
279        }
280      }
281    }
282    #endregion
283
284    private void InitializeRandomVRPInstance() {
285      System.Random rand = new System.Random();
286
287      CVRPTWProblemInstance problem = new CVRPTWProblemInstance();
288      int cities = 100;
289
290      problem.Coordinates = new DoubleMatrix(cities + 1, 2);
291      problem.Demand = new DoubleArray(cities + 1);
292      problem.DueTime = new DoubleArray(cities + 1);
293      problem.ReadyTime = new DoubleArray(cities + 1);
294      problem.ServiceTime = new DoubleArray(cities + 1);
295
296      problem.Vehicles.Value = 100;
297      problem.Capacity.Value = 200;
298
299      for (int i = 0; i <= cities; i++) {
300        problem.Coordinates[i, 0] = rand.Next(0, 100);
301        problem.Coordinates[i, 1] = rand.Next(0, 100);
302
303        if (i == 0) {
304          problem.Demand[i] = 0;
305          problem.DueTime[i] = Int16.MaxValue;
306          problem.ReadyTime[i] = 0;
307          problem.ServiceTime[i] = 0;
308        } else {
309          problem.Demand[i] = rand.Next(10, 50);
310          problem.DueTime[i] = rand.Next((int)Math.Ceiling(problem.GetDistance(0, i, null)), 1200);
311          problem.ReadyTime[i] = problem.DueTime[i] - rand.Next(0, 100);
312          problem.ServiceTime[i] = 90;
313        }
314      }
315
316      this.ProblemInstance = problem;
317    }
318
319    public void ImportSolution(string solutionFileName) {
320      SolutionParser parser = new SolutionParser(solutionFileName);
321      parser.Parse();
322
323      HeuristicLab.Problems.VehicleRouting.Encodings.Potvin.PotvinEncoding encoding = new Encodings.Potvin.PotvinEncoding(ProblemInstance);
324
325      int cities = 0;
326      foreach (List<int> route in parser.Routes) {
327        Tour tour = new Tour();
328        tour.Stops.AddRange(route);
329        cities += tour.Stops.Count;
330
331        encoding.Tours.Add(tour);
332      }
333
334      if (cities != ProblemInstance.Coordinates.Rows - 1)
335        ErrorHandling.ShowErrorDialog(new Exception("The optimal solution does not seem to correspond with the problem data"));
336      else {
337        VRPSolution solution = new VRPSolution(ProblemInstance, encoding, new DoubleValue(0));
338        BestKnownSolutionParameter.Value = solution;
339      }
340    }
341
342    public void Load(IVRPData data) {
343      Type interpreterType = typeof(IVRPDataInterpreter<>).MakeGenericType(data.GetType());
344      var interpreters = ApplicationManager.Manager.GetInstances(interpreterType);
345      if (interpreters.Count() > 0) {
346        IVRPDataInterpreter interpreter = interpreters.First() as IVRPDataInterpreter;
347        VRPInstanceDescription instance = interpreter.Interpret(data);
348
349        Name = instance.Name;
350        Description = instance.Description;
351        if (ProblemInstance != null && instance.ProblemInstance != null &&
352          instance.ProblemInstance.GetType() == ProblemInstance.GetType())
353          SetProblemInstance(instance.ProblemInstance);
354        else
355          ProblemInstance = instance.ProblemInstance;
356
357        OnReset();
358        BestKnownQuality = null;
359        BestKnownSolution = null;
360
361        if (instance.BestKnownQuality != null) {
362          BestKnownQuality = new DoubleValue((double)instance.BestKnownQuality);
363        }
364
365        if (instance.BestKnownSolution != null) {
366          VRPSolution solution = new VRPSolution(ProblemInstance, instance.BestKnownSolution, new DoubleValue(0));
367          BestKnownSolution = solution;
368        }
369      } else {
370        throw new Exception("Cannot find an interpreter for " + data.GetType());
371      }   
372    }
373  }
374}
Note: See TracBrowser for help on using the repository browser.