Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 12087 was 12087, checked in by jkarder, 9 years ago

#2332: removed unused similarity analyzer properties

File size: 15.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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.Encodings.Alba;
36using HeuristicLab.Problems.VehicleRouting.Interfaces;
37using HeuristicLab.Problems.VehicleRouting.Interpreters;
38using HeuristicLab.Problems.VehicleRouting.ProblemInstances;
39using HeuristicLab.Problems.VehicleRouting.Variants;
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 : Problem, 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 IConstrainedValueParameter<IVRPCreator> SolutionCreatorParameter {
72      get { return (IConstrainedValueParameter<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    ISolutionCreator IHeuristicOptimizationProblem.SolutionCreator {
110      get { return SolutionCreatorParameter.Value; }
111    }
112    public IVRPCreator SolutionCreator {
113      get { return SolutionCreatorParameter.Value; }
114      set { SolutionCreatorParameter.Value = value; }
115    }
116    #endregion
117
118    [StorableConstructor]
119    private VehicleRoutingProblem(bool deserializing) : base(deserializing) { }
120    public VehicleRoutingProblem()
121      : base() {
122      Parameters.Add(new ValueParameter<BoolValue>("Maximization", "Set to false as the Vehicle Routing Problem is a minimization problem.", new BoolValue(false)));
123      Parameters.Add(new ValueParameter<IVRPProblemInstance>("ProblemInstance", "The VRP problem instance"));
124      Parameters.Add(new OptionalValueParameter<DoubleValue>("BestKnownQuality", "The quality of the best known solution of this VRP instance."));
125      Parameters.Add(new OptionalValueParameter<VRPSolution>("BestKnownSolution", "The best known solution of this VRP instance."));
126
127      Parameters.Add(new ConstrainedValueParameter<IVRPCreator>("SolutionCreator", "The operator which should be used to create new VRP solutions."));
128      Parameters.Add(new ValueParameter<IVRPEvaluator>("Evaluator", "The operator which should be used to evaluate VRP solutions."));
129
130      EvaluatorParameter.Hidden = true;
131
132      InitializeRandomVRPInstance();
133      InitializeOperators();
134
135      AttachEventHandlers();
136      AttachProblemInstanceEventHandlers();
137
138      EvaluatorParameter.Value = ProblemInstance.SolutionEvaluator;
139    }
140
141    public override IDeepCloneable Clone(Cloner cloner) {
142      cloner.Clone(ProblemInstance);
143      return new VehicleRoutingProblem(this, cloner);
144    }
145
146    private VehicleRoutingProblem(VehicleRoutingProblem original, Cloner cloner)
147      : base(original, cloner) {
148      this.AttachEventHandlers();
149      this.AttachProblemInstanceEventHandlers();
150
151      ProblemInstance.SolutionEvaluator = EvaluatorParameter.Value;
152    }
153
154    #region Events
155    public event EventHandler SolutionCreatorChanged;
156    private void OnSolutionCreatorChanged() {
157      EventHandler handler = SolutionCreatorChanged;
158      if (handler != null) handler(this, EventArgs.Empty);
159    }
160    public event EventHandler EvaluatorChanged;
161    private void OnEvaluatorChanged() {
162      EventHandler handler = EvaluatorChanged;
163      if (handler != null) handler(this, EventArgs.Empty);
164    }
165    #endregion
166
167    #region Helpers
168    [StorableHook(HookType.AfterDeserialization)]
169    private void AfterDeserialization() {
170      AttachEventHandlers();
171      AttachProblemInstanceEventHandlers();
172
173      ProblemInstance.SolutionEvaluator = EvaluatorParameter.Value;
174    }
175
176    [Storable(Name = "operators", AllowOneWay = true)]
177    private List<IOperator> StorableOperators {
178      set { Operators.AddRange(value); }
179    }
180
181    private void AttachEventHandlers() {
182      ProblemInstanceParameter.ValueChanged += new EventHandler(ProblemInstanceParameter_ValueChanged);
183      BestKnownSolutionParameter.ValueChanged += new EventHandler(BestKnownSolutionParameter_ValueChanged);
184      EvaluatorParameter.ValueChanged += new EventHandler(EvaluatorParameter_ValueChanged);
185      SolutionCreatorParameter.ValueChanged += new EventHandler(SolutionCreatorParameter_ValueChanged);
186    }
187
188    private void AttachProblemInstanceEventHandlers() {
189      if (ProblemInstance != null) {
190        ProblemInstance.EvaluationChanged += new EventHandler(ProblemInstance_EvaluationChanged);
191      }
192    }
193
194    private void EvalBestKnownSolution() {
195      if (BestKnownSolution != null) {
196        //call evaluator
197        BestKnownQuality = new DoubleValue(ProblemInstance.Evaluate(BestKnownSolution.Solution).Quality);
198        BestKnownSolution.Quality = BestKnownQuality;
199      } else {
200        BestKnownQuality = null;
201      }
202    }
203
204    void BestKnownSolutionParameter_ValueChanged(object sender, EventArgs e) {
205      EvalBestKnownSolution();
206    }
207
208    void ProblemInstance_EvaluationChanged(object sender, EventArgs e) {
209      EvalBestKnownSolution();
210    }
211
212    void ProblemInstanceParameter_ValueChanged(object sender, EventArgs e) {
213      InitializeOperators();
214      AttachProblemInstanceEventHandlers();
215
216      EvaluatorParameter.Value = ProblemInstance.SolutionEvaluator;
217
218      OnSolutionCreatorChanged();
219      OnEvaluatorChanged();
220      OnOperatorsChanged();
221    }
222
223    public void SetProblemInstance(IVRPProblemInstance instance) {
224      ProblemInstanceParameter.ValueChanged -= new EventHandler(ProblemInstanceParameter_ValueChanged);
225
226      ProblemInstance = instance;
227      AttachProblemInstanceEventHandlers();
228
229      OnSolutionCreatorChanged();
230      OnEvaluatorChanged();
231
232      ProblemInstanceParameter.ValueChanged += new EventHandler(ProblemInstanceParameter_ValueChanged);
233    }
234
235    private void SolutionCreatorParameter_ValueChanged(object sender, EventArgs e) {
236      OnSolutionCreatorChanged();
237    }
238    private void EvaluatorParameter_ValueChanged(object sender, EventArgs e) {
239      if (ProblemInstance != null)
240        ProblemInstance.SolutionEvaluator = EvaluatorParameter.Value;
241      OnEvaluatorChanged();
242    }
243
244    private void InitializeOperators() {
245      var solutionCreatorParameter = SolutionCreatorParameter as ConstrainedValueParameter<IVRPCreator>;
246      solutionCreatorParameter.ValidValues.Clear();
247
248      Operators.Clear();
249
250      if (ProblemInstance != null) {
251        Operators.AddRange(
252        ProblemInstance.Operators.Concat(
253          ApplicationManager.Manager.GetInstances<IGeneralVRPOperator>().Cast<IOperator>()).OrderBy(op => op.Name));
254        Operators.Add(new VRPSimilarityCalculator());
255        Operators.Add(new PopulationSimilarityAnalyzer(Operators.OfType<ISolutionSimilarityCalculator>()));
256
257        IVRPCreator defaultCreator = null;
258        foreach (IVRPCreator creator in Operators.Where(o => o is IVRPCreator)) {
259          solutionCreatorParameter.ValidValues.Add(creator);
260          if (creator is Encodings.Alba.RandomCreator)
261            defaultCreator = creator;
262        }
263        Operators.Add(new AlbaLambdaInterchangeLocalImprovementOperator());
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      }
292    }
293
294    #endregion
295
296    private void InitializeRandomVRPInstance() {
297      System.Random rand = new System.Random();
298
299      CVRPTWProblemInstance problem = new CVRPTWProblemInstance();
300      int cities = 100;
301
302      problem.Coordinates = new DoubleMatrix(cities + 1, 2);
303      problem.Demand = new DoubleArray(cities + 1);
304      problem.DueTime = new DoubleArray(cities + 1);
305      problem.ReadyTime = new DoubleArray(cities + 1);
306      problem.ServiceTime = new DoubleArray(cities + 1);
307
308      problem.Vehicles.Value = 100;
309      problem.Capacity.Value = 200;
310
311      for (int i = 0; i <= cities; i++) {
312        problem.Coordinates[i, 0] = rand.Next(0, 100);
313        problem.Coordinates[i, 1] = rand.Next(0, 100);
314
315        if (i == 0) {
316          problem.Demand[i] = 0;
317          problem.DueTime[i] = Int16.MaxValue;
318          problem.ReadyTime[i] = 0;
319          problem.ServiceTime[i] = 0;
320        } else {
321          problem.Demand[i] = rand.Next(10, 50);
322          problem.DueTime[i] = rand.Next((int)Math.Ceiling(problem.GetDistance(0, i, null)), 1200);
323          problem.ReadyTime[i] = problem.DueTime[i] - rand.Next(0, 100);
324          problem.ServiceTime[i] = 90;
325        }
326      }
327
328      this.ProblemInstance = problem;
329    }
330
331    public void ImportSolution(string solutionFileName) {
332      SolutionParser parser = new SolutionParser(solutionFileName);
333      parser.Parse();
334
335      HeuristicLab.Problems.VehicleRouting.Encodings.Potvin.PotvinEncoding encoding = new Encodings.Potvin.PotvinEncoding(ProblemInstance);
336
337      int cities = 0;
338      foreach (List<int> route in parser.Routes) {
339        Tour tour = new Tour();
340        tour.Stops.AddRange(route);
341        cities += tour.Stops.Count;
342
343        encoding.Tours.Add(tour);
344      }
345
346      if (cities != ProblemInstance.Coordinates.Rows - 1)
347        ErrorHandling.ShowErrorDialog(new Exception("The optimal solution does not seem to correspond with the problem data"));
348      else {
349        VRPSolution solution = new VRPSolution(ProblemInstance, encoding, new DoubleValue(0));
350        BestKnownSolutionParameter.Value = solution;
351      }
352    }
353
354    #region Instance Consuming
355    public void Load(IVRPData data, IVRPDataInterpreter interpreter) {
356      VRPInstanceDescription instance = interpreter.Interpret(data);
357
358      Name = instance.Name;
359      Description = instance.Description;
360
361      BestKnownQuality = null;
362      BestKnownSolution = null;
363
364      if (ProblemInstance != null && instance.ProblemInstance != null &&
365        instance.ProblemInstance.GetType() == ProblemInstance.GetType())
366        SetProblemInstance(instance.ProblemInstance);
367      else
368        ProblemInstance = instance.ProblemInstance;
369
370      OnReset();
371
372      if (instance.BestKnownQuality != null) {
373        BestKnownQuality = new DoubleValue((double)instance.BestKnownQuality);
374      }
375
376      if (instance.BestKnownSolution != null) {
377        VRPSolution solution = new VRPSolution(ProblemInstance, instance.BestKnownSolution, new DoubleValue(0));
378        BestKnownSolution = solution;
379      }
380    }
381    #endregion
382
383    #region IProblemInstanceConsumer<VRPData> Members
384
385    public void Load(IVRPData data) {
386      var interpreterDataType = data.GetType();
387      var interpreterType = typeof(IVRPDataInterpreter<>).MakeGenericType(interpreterDataType);
388
389      var interpreters = ApplicationManager.Manager.GetTypes(interpreterType);
390
391      var concreteInterpreter = interpreters.Single(t => GetInterpreterDataType(t) == interpreterDataType);
392
393      Load(data, (IVRPDataInterpreter)Activator.CreateInstance(concreteInterpreter));
394    }
395
396    private Type GetInterpreterDataType(Type type) {
397      var parentInterfaces = type.BaseType.GetInterfaces();
398      var interfaces = type.GetInterfaces().Except(parentInterfaces);
399
400      var interpreterInterface = interfaces.Single(i => typeof(IVRPDataInterpreter).IsAssignableFrom(i));
401      return interpreterInterface.GetGenericArguments()[0];
402    }
403
404    #endregion
405  }
406}
Note: See TracBrowser for help on using the repository browser.