Free cookie consent management tool by TermsFeed Policy Generator

source: branches/WebJobManager/HeuristicLab.Problems.VehicleRouting/3.4/VehicleRoutingProblem.cs @ 13820

Last change on this file since 13820 was 13656, checked in by ascheibe, 9 years ago

#2582 created branch for Hive Web Job Manager

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