Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 10381 was 10363, checked in by pfleck, 11 years ago

#2141 - corrected evaluator assignment for construction, cloning and deserialization

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