Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1797 added an interface IConstrainedValueParameter, added a test case to check the name, visibility and type of the parameter-property for constrainedValueParameters, corrected all properties in IParameterizedItems

File size: 13.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      var solutionCreatorParameter = SolutionCreatorParameter as ConstrainedValueParameter<IVRPCreator>;
181      solutionCreatorParameter.ValidValues.Clear();
182
183      if (ProblemInstance != null) {
184        EvaluatorParameter.Value = ProblemInstance.SolutionEvaluator;
185        IVRPCreator defaultCreator = null;
186        foreach (IVRPCreator creator in Operators.Where(o => o is IVRPCreator)) {
187          solutionCreatorParameter.ValidValues.Add(creator);
188          if (creator is Encodings.Alba.RandomCreator)
189            defaultCreator = creator;
190        }
191        if (defaultCreator != null)
192          solutionCreatorParameter.Value = defaultCreator;
193
194        ProblemInstance.EvaluationChanged += new EventHandler(ProblemInstance_EvaluationChanged);
195      }
196    }
197
198    private void EvalBestKnownSolution() {
199      if (BestKnownSolution != null) {
200        //call evaluator
201        BestKnownQuality = new DoubleValue(ProblemInstance.Evaluate(BestKnownSolution.Solution).Quality);
202        BestKnownSolution.Quality = BestKnownQuality;
203      } else {
204        BestKnownQuality = null;
205      }
206    }
207
208    void BestKnownSolutionParameter_ValueChanged(object sender, EventArgs e) {
209      EvalBestKnownSolution();
210    }
211
212    void ProblemInstance_EvaluationChanged(object sender, EventArgs e) {
213      EvaluatorParameter.Value = ProblemInstance.SolutionEvaluator;
214      EvalBestKnownSolution();
215    }
216
217    void ProblemInstanceParameter_ValueChanged(object sender, EventArgs e) {
218      InitializeOperators();
219      AttachProblemInstanceEventHandlers();
220
221      OnSolutionCreatorChanged();
222      OnEvaluatorChanged();
223      OnOperatorsChanged();
224    }
225
226    public void SetProblemInstance(IVRPProblemInstance instance) {
227      ProblemInstanceParameter.ValueChanged -= new EventHandler(ProblemInstanceParameter_ValueChanged);
228
229      ProblemInstance = instance;
230      AttachProblemInstanceEventHandlers();
231
232      OnSolutionCreatorChanged();
233      OnEvaluatorChanged();
234
235      ProblemInstanceParameter.ValueChanged += new EventHandler(ProblemInstanceParameter_ValueChanged);
236    }
237
238    private void SolutionCreatorParameter_ValueChanged(object sender, EventArgs e) {
239      OnSolutionCreatorChanged();
240    }
241    private void EvaluatorParameter_ValueChanged(object sender, EventArgs e) {
242      if (ProblemInstance != null)
243        ProblemInstance.SolutionEvaluator = EvaluatorParameter.Value;
244      OnEvaluatorChanged();
245    }
246
247    private void InitializeOperators() {
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      }
255
256      ParameterizeOperators();
257    }
258
259    private void ParameterizeOperators() {
260      foreach (IOperator op in Operators.OfType<IOperator>()) {
261        if (op is IMultiVRPOperator) {
262          (op as IMultiVRPOperator).SetOperators(Operators.OfType<IOperator>());
263        }
264      }
265    }
266    #endregion
267
268    private void InitializeRandomVRPInstance() {
269      System.Random rand = new System.Random();
270
271      CVRPTWProblemInstance problem = new CVRPTWProblemInstance();
272      int cities = 100;
273
274      problem.Coordinates = new DoubleMatrix(cities + 1, 2);
275      problem.Demand = new DoubleArray(cities + 1);
276      problem.DueTime = new DoubleArray(cities + 1);
277      problem.ReadyTime = new DoubleArray(cities + 1);
278      problem.ServiceTime = new DoubleArray(cities + 1);
279
280      problem.Vehicles.Value = 100;
281      problem.Capacity.Value = 200;
282
283      for (int i = 0; i <= cities; i++) {
284        problem.Coordinates[i, 0] = rand.Next(0, 100);
285        problem.Coordinates[i, 1] = rand.Next(0, 100);
286
287        if (i == 0) {
288          problem.Demand[i] = 0;
289          problem.DueTime[i] = Int16.MaxValue;
290          problem.ReadyTime[i] = 0;
291          problem.ServiceTime[i] = 0;
292        } else {
293          problem.Demand[i] = rand.Next(10, 50);
294          problem.DueTime[i] = rand.Next((int)Math.Ceiling(problem.GetDistance(0, i, null)), 1200);
295          problem.ReadyTime[i] = problem.DueTime[i] - rand.Next(0, 100);
296          problem.ServiceTime[i] = 90;
297        }
298      }
299
300      this.ProblemInstance = problem;
301    }
302
303    public void ImportSolution(string solutionFileName) {
304      SolutionParser parser = new SolutionParser(solutionFileName);
305      parser.Parse();
306
307      HeuristicLab.Problems.VehicleRouting.Encodings.Potvin.PotvinEncoding encoding = new Encodings.Potvin.PotvinEncoding(ProblemInstance);
308
309      int cities = 0;
310      foreach (List<int> route in parser.Routes) {
311        Tour tour = new Tour();
312        tour.Stops.AddRange(route);
313        cities += tour.Stops.Count;
314
315        encoding.Tours.Add(tour);
316      }
317
318      if (cities != ProblemInstance.Coordinates.Rows - 1)
319        ErrorHandling.ShowErrorDialog(new Exception("The optimal solution does not seem to correspond with the problem data"));
320      else {
321        VRPSolution solution = new VRPSolution(ProblemInstance, encoding, new DoubleValue(0));
322        BestKnownSolutionParameter.Value = solution;
323      }
324    }
325
326    public void Load(IVRPData data) {
327      Type interpreterType = typeof(IVRPDataInterpreter<>).MakeGenericType(data.GetType());
328      var interpreters = ApplicationManager.Manager.GetInstances(interpreterType);
329      if (interpreters.Count() > 0) {
330        IVRPDataInterpreter interpreter = interpreters.First() as IVRPDataInterpreter;
331        VRPInstanceDescription instance = interpreter.Interpret(data);
332
333        Name = instance.Name;
334        Description = instance.Description;
335        if (ProblemInstance != null && instance.ProblemInstance != null &&
336          instance.ProblemInstance.GetType() == ProblemInstance.GetType())
337          SetProblemInstance(instance.ProblemInstance);
338        else
339          ProblemInstance = instance.ProblemInstance;
340
341        OnReset();
342        BestKnownQuality = null;
343        BestKnownSolution = null;
344
345        if (instance.BestKnownQuality != null) {
346          BestKnownQuality = new DoubleValue((double)instance.BestKnownQuality);
347        }
348
349        if (instance.BestKnownSolution != null) {
350          VRPSolution solution = new VRPSolution(ProblemInstance, instance.BestKnownSolution, new DoubleValue(0));
351          BestKnownSolution = solution;
352        }
353      } else {
354        throw new Exception("Cannot find an interpreter for " + data.GetType());
355      }
356    }
357  }
358}
Note: See TracBrowser for help on using the repository browser.