Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GP-MoveOperators/HeuristicLab.Problems.VehicleRouting/3.4/VehicleRoutingProblem.cs @ 8660

Last change on this file since 8660 was 8660, checked in by gkronber, 12 years ago

#1847 merged r8205:8635 from trunk into branch

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