Free cookie consent management tool by TermsFeed Policy Generator

source: branches/VRP/HeuristicLab.Problems.VehicleRouting/3.4/VehicleRoutingProblem.cs @ 8003

Last change on this file since 8003 was 8003, checked in by ascheibe, 12 years ago

#1177 adapted VRP branch to changes of r7999

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