Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 10362 was 10362, checked in by pfleck, 10 years ago

#2141 - corrected assignment of the evaluator after deserialization

File size: 15.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 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      this.AttachProblemInstanceEventHandlers();
156    }
157
158    #region Events
159    public event EventHandler SolutionCreatorChanged;
160    private void OnSolutionCreatorChanged() {
161      EventHandler handler = SolutionCreatorChanged;
162      if (handler != null) handler(this, EventArgs.Empty);
163    }
164    public event EventHandler EvaluatorChanged;
165    private void OnEvaluatorChanged() {
166      EventHandler handler = EvaluatorChanged;
167      if (handler != null) handler(this, EventArgs.Empty);
168    }
169    #endregion
170
171    #region Helpers
172    [StorableHook(HookType.AfterDeserialization)]
173    private void AfterDeserialization() {
174      AttachEventHandlers();
175      AttachProblemInstanceEventHandlers();
176    }
177
178    [Storable(Name = "operators", AllowOneWay = true)]
179    private List<IOperator> StorableOperators {
180      set { Operators.AddRange(value); }
181    }
182
183    private void AttachEventHandlers() {
184      ProblemInstanceParameter.ValueChanged += new EventHandler(ProblemInstanceParameter_ValueChanged);
185      BestKnownSolutionParameter.ValueChanged += new EventHandler(BestKnownSolutionParameter_ValueChanged);
186      EvaluatorParameter.ValueChanged += new EventHandler(EvaluatorParameter_ValueChanged);
187      SolutionCreatorParameter.ValueChanged += new EventHandler(SolutionCreatorParameter_ValueChanged);
188    }
189
190    private void AttachProblemInstanceEventHandlers() {
191      if (ProblemInstance != null) {
192        ProblemInstance.SolutionEvaluator = EvaluatorParameter.Value;
193        ProblemInstance.EvaluationChanged += new EventHandler(ProblemInstance_EvaluationChanged);
194      }
195    }
196
197    private void EvalBestKnownSolution() {
198      if (BestKnownSolution != null) {
199        //call evaluator
200        BestKnownQuality = new DoubleValue(ProblemInstance.Evaluate(BestKnownSolution.Solution).Quality);
201        BestKnownSolution.Quality = BestKnownQuality;
202      } else {
203        BestKnownQuality = null;
204      }
205    }
206
207    void BestKnownSolutionParameter_ValueChanged(object sender, EventArgs e) {
208      EvalBestKnownSolution();
209    }
210
211    void ProblemInstance_EvaluationChanged(object sender, EventArgs e) {
212      EvaluatorParameter.Value = ProblemInstance.SolutionEvaluator;
213      EvalBestKnownSolution();
214    }
215
216    void ProblemInstanceParameter_ValueChanged(object sender, EventArgs e) {
217      InitializeOperators();
218      AttachProblemInstanceEventHandlers();
219
220      OnSolutionCreatorChanged();
221      OnEvaluatorChanged();
222      OnOperatorsChanged();
223    }
224
225    public void SetProblemInstance(IVRPProblemInstance instance) {
226      ProblemInstanceParameter.ValueChanged -= new EventHandler(ProblemInstanceParameter_ValueChanged);
227
228      ProblemInstance = instance;
229      AttachProblemInstanceEventHandlers();
230
231      OnSolutionCreatorChanged();
232      OnEvaluatorChanged();
233
234      ProblemInstanceParameter.ValueChanged += new EventHandler(ProblemInstanceParameter_ValueChanged);
235    }
236
237    private void SolutionCreatorParameter_ValueChanged(object sender, EventArgs e) {
238      OnSolutionCreatorChanged();
239    }
240    private void EvaluatorParameter_ValueChanged(object sender, EventArgs e) {
241      if (ProblemInstance != null)
242        ProblemInstance.SolutionEvaluator = EvaluatorParameter.Value;
243      OnEvaluatorChanged();
244    }
245
246    private void InitializeOperators() {
247      var solutionCreatorParameter = SolutionCreatorParameter as ConstrainedValueParameter<IVRPCreator>;
248      solutionCreatorParameter.ValidValues.Clear();
249
250      Operators.Clear();
251
252      if (ProblemInstance != null) {
253        Operators.AddRange(
254        ProblemInstance.Operators.Concat(
255          ApplicationManager.Manager.GetInstances<IGeneralVRPOperator>().Cast<IOperator>()).OrderBy(op => op.Name));
256        Operators.Add(new VRPSimilarityCalculator());
257        Operators.Add(new SingleObjectivePopulationDiversityAnalyzer());
258
259        IVRPCreator defaultCreator = null;
260        foreach (IVRPCreator creator in Operators.Where(o => o is IVRPCreator)) {
261          solutionCreatorParameter.ValidValues.Add(creator);
262          if (creator is Encodings.Alba.RandomCreator)
263            defaultCreator = creator;
264        }
265        if (defaultCreator != null)
266          solutionCreatorParameter.Value = defaultCreator;
267      }
268
269      ParameterizeOperators();
270    }
271
272    private void ParameterizeOperators() {
273      foreach (IOperator op in Operators.OfType<IOperator>()) {
274        if (op is IMultiVRPOperator) {
275          (op as IMultiVRPOperator).SetOperators(Operators.OfType<IOperator>());
276        }
277      }
278      if (ProblemInstance != null) {
279        foreach (ISingleObjectiveImprovementOperator op in Operators.OfType<ISingleObjectiveImprovementOperator>()) {
280          op.SolutionParameter.ActualName = SolutionCreator.VRPToursParameter.ActualName;
281          op.SolutionParameter.Hidden = true;
282        }
283        foreach (ISingleObjectivePathRelinker op in Operators.OfType<ISingleObjectivePathRelinker>()) {
284          op.ParentsParameter.ActualName = SolutionCreator.VRPToursParameter.ActualName;
285          op.ParentsParameter.Hidden = true;
286        }
287        foreach (VRPSimilarityCalculator op in Operators.OfType<VRPSimilarityCalculator>()) {
288          op.SolutionVariableName = SolutionCreator.VRPToursParameter.ActualName;
289          op.QualityVariableName = ProblemInstance.SolutionEvaluator.QualityParameter.ActualName;
290          op.ProblemInstance = ProblemInstance;
291        }
292        if (SingleObjectivePopulationDiversityAnalyzer != null) {
293          SingleObjectivePopulationDiversityAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
294          SingleObjectivePopulationDiversityAnalyzer.QualityParameter.ActualName = ProblemInstance.SolutionEvaluator.QualityParameter.ActualName;
295          SingleObjectivePopulationDiversityAnalyzer.ResultsParameter.ActualName = "Results";
296          SingleObjectivePopulationDiversityAnalyzer.SimilarityCalculator = Operators.OfType<VRPSimilarityCalculator>().SingleOrDefault();
297        }
298      }
299    }
300
301    #endregion
302
303    private void InitializeRandomVRPInstance() {
304      System.Random rand = new System.Random();
305
306      CVRPTWProblemInstance problem = new CVRPTWProblemInstance();
307      int cities = 100;
308
309      problem.Coordinates = new DoubleMatrix(cities + 1, 2);
310      problem.Demand = new DoubleArray(cities + 1);
311      problem.DueTime = new DoubleArray(cities + 1);
312      problem.ReadyTime = new DoubleArray(cities + 1);
313      problem.ServiceTime = new DoubleArray(cities + 1);
314
315      problem.Vehicles.Value = 100;
316      problem.Capacity.Value = 200;
317
318      for (int i = 0; i <= cities; i++) {
319        problem.Coordinates[i, 0] = rand.Next(0, 100);
320        problem.Coordinates[i, 1] = rand.Next(0, 100);
321
322        if (i == 0) {
323          problem.Demand[i] = 0;
324          problem.DueTime[i] = Int16.MaxValue;
325          problem.ReadyTime[i] = 0;
326          problem.ServiceTime[i] = 0;
327        } else {
328          problem.Demand[i] = rand.Next(10, 50);
329          problem.DueTime[i] = rand.Next((int)Math.Ceiling(problem.GetDistance(0, i, null)), 1200);
330          problem.ReadyTime[i] = problem.DueTime[i] - rand.Next(0, 100);
331          problem.ServiceTime[i] = 90;
332        }
333      }
334
335      this.ProblemInstance = problem;
336    }
337
338    public void ImportSolution(string solutionFileName) {
339      SolutionParser parser = new SolutionParser(solutionFileName);
340      parser.Parse();
341
342      HeuristicLab.Problems.VehicleRouting.Encodings.Potvin.PotvinEncoding encoding = new Encodings.Potvin.PotvinEncoding(ProblemInstance);
343
344      int cities = 0;
345      foreach (List<int> route in parser.Routes) {
346        Tour tour = new Tour();
347        tour.Stops.AddRange(route);
348        cities += tour.Stops.Count;
349
350        encoding.Tours.Add(tour);
351      }
352
353      if (cities != ProblemInstance.Coordinates.Rows - 1)
354        ErrorHandling.ShowErrorDialog(new Exception("The optimal solution does not seem to correspond with the problem data"));
355      else {
356        VRPSolution solution = new VRPSolution(ProblemInstance, encoding, new DoubleValue(0));
357        BestKnownSolutionParameter.Value = solution;
358      }
359    }
360
361    #region Instance Consuming
362    public void Load(IVRPData data, IVRPDataInterpreter interpreter) {
363      VRPInstanceDescription instance = interpreter.Interpret(data);
364
365      Name = instance.Name;
366      Description = instance.Description;
367      if (ProblemInstance != null && instance.ProblemInstance != null &&
368        instance.ProblemInstance.GetType() == ProblemInstance.GetType())
369        SetProblemInstance(instance.ProblemInstance);
370      else
371        ProblemInstance = instance.ProblemInstance;
372
373      OnReset();
374      BestKnownQuality = null;
375      BestKnownSolution = null;
376
377      if (instance.BestKnownQuality != null) {
378        BestKnownQuality = new DoubleValue((double)instance.BestKnownQuality);
379      }
380
381      if (instance.BestKnownSolution != null) {
382        VRPSolution solution = new VRPSolution(ProblemInstance, instance.BestKnownSolution, new DoubleValue(0));
383        BestKnownSolution = solution;
384      }
385    }
386
387    public void Load(CVRPData data) {
388      Load(data, new CVRPInterpreter());
389    }
390
391    public void Load(CVRPTWData data) {
392      Load(data, new CVRPTWInterpreter());
393    }
394
395    public void Load(MDCVRPData data) {
396      Load(data, new MDCVRPInterpreter());
397    }
398
399    public void Load(MDCVRPTWData data) {
400      Load(data, new MDCVRPTWInterpreter());
401    }
402
403    public void Load(PDPTWData data) {
404      Load(data, new PDPTWInterpreter());
405    }
406
407    #endregion
408  }
409}
Note: See TracBrowser for help on using the repository browser.