Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OaaS/HeuristicLab.Problems.VehicleRouting/3.4/VehicleRoutingProblem.cs @ 12587

Last change on this file since 12587 was 9363, checked in by spimming, 12 years ago

#1888:

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