Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.Orienteering/HeuristicLab.Problems.Orienteering/3.3/OrienteeringProblem.cs @ 11325

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

#2208

  • Fixed OrienteeringSolution visualization when start or endpoint are out of range
  • Changed some parameters in OP to FixedValueParameter
  • Added start/terminal index check in OP
File size: 19.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2014 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.IO;
24using System.Linq;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Encodings.IntegerVectorEncoding;
29using HeuristicLab.Optimization;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.Problems.Instances;
33using HeuristicLab.Problems.Instances.Types;
34
35namespace HeuristicLab.Problems.Orienteering {
36
37  [Item("Orienteering Problem", "Represents a single objective Orienteering Problem.")]
38  [Creatable("Problems")]
39  [StorableClass]
40  public sealed class OrienteeringProblem
41    : SingleObjectiveHeuristicOptimizationProblem<IOrienteeringEvaluator, IOrienteeringSolutionCreator>,
42    IStorableContent, IProblemInstanceConsumer<OPData>, IProblemInstanceConsumer<TSPData>, IProblemInstanceConsumer<CVRPData> {
43
44    public string Filename { get; set; }
45
46    #region Parameter Properties
47    public OptionalValueParameter<DoubleMatrix> CoordinatesParameter {
48      get { return (OptionalValueParameter<DoubleMatrix>)Parameters["Coordinates"]; }
49    }
50    public IValueParameter<DistanceMatrix> DistanceMatrixParameter {
51      get { return (IValueParameter<DistanceMatrix>)Parameters["DistanceMatrix"]; }
52    }
53
54    public IFixedValueParameter<IntValue> StartingPointParameter {
55      get { return (IFixedValueParameter<IntValue>)Parameters["StartingPoint"]; }
56    }
57    public IFixedValueParameter<IntValue> TerminalPointParameter {
58      get { return (IFixedValueParameter<IntValue>)Parameters["TerminalPoint"]; }
59    }
60    public IFixedValueParameter<DoubleValue> MaximumDistanceParameter {
61      get { return (IFixedValueParameter<DoubleValue>)Parameters["MaximumDistance"]; }
62    }
63    public IValueParameter<DoubleArray> ScoresParameter {
64      get { return (IValueParameter<DoubleArray>)Parameters["Scores"]; }
65    }
66    public IFixedValueParameter<DoubleValue> PointVisitingCostsParameter {
67      get { return (IFixedValueParameter<DoubleValue>)Parameters["PointVisitingCosts"]; }
68    }
69
70    public OptionalValueParameter<IntegerVector> BestKnownSolutionParameter {
71      get { return (OptionalValueParameter<IntegerVector>)Parameters["BestKnownSolution"]; }
72    }
73    #endregion
74
75    #region Properties
76    public DoubleMatrix Coordinates {
77      get { return CoordinatesParameter.Value; }
78      set { CoordinatesParameter.Value = value; }
79    }
80    public DistanceMatrix DistanceMatrix {
81      get { return DistanceMatrixParameter.Value; }
82      set { DistanceMatrixParameter.Value = value; }
83    }
84    public int StartingPoint {
85      get { return StartingPointParameter.Value.Value; }
86      set { StartingPointParameter.Value.Value = value; }
87    }
88    public int TerminalPoint {
89      get { return TerminalPointParameter.Value.Value; }
90      set { TerminalPointParameter.Value.Value = value; }
91    }
92    public double MaximumDistance {
93      get { return MaximumDistanceParameter.Value.Value; }
94      set { MaximumDistanceParameter.Value.Value = value; }
95    }
96    public DoubleArray Scores {
97      get { return ScoresParameter.Value; }
98      set { ScoresParameter.Value = value; }
99    }
100    public double PointVisitingCosts {
101      get { return PointVisitingCostsParameter.Value.Value; }
102      set { PointVisitingCostsParameter.Value.Value = value; }
103    }
104    public IntegerVector BestKnownSolution {
105      get { return BestKnownSolutionParameter.Value; }
106      set { BestKnownSolutionParameter.Value = value; }
107    }
108    private BestOrienteeringSolutionAnalyser BestOrienteeringSolutionAnalyser {
109      get { return Operators.OfType<BestOrienteeringSolutionAnalyser>().SingleOrDefault(); }
110    }
111    #endregion
112
113    [StorableConstructor]
114    private OrienteeringProblem(bool deserializing)
115      : base(deserializing) {
116    }
117    private OrienteeringProblem(OrienteeringProblem original, Cloner cloner)
118      : base(original, cloner) {
119      RegisterEventHandlers();
120    }
121    public override IDeepCloneable Clone(Cloner cloner) {
122      return new OrienteeringProblem(this, cloner);
123    }
124    public OrienteeringProblem()
125      : base(new OrienteeringEvaluator(), new GreedyOrienteeringTourCreator()) {
126      Parameters.Add(new OptionalValueParameter<DoubleMatrix>("Coordinates", "The x- and y-Coordinates of the points."));
127      Parameters.Add(new ValueParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the points."));
128      Parameters.Add(new FixedValueParameter<IntValue>("StartingPoint", "Index of the starting point.", new IntValue(0)));
129      Parameters.Add(new FixedValueParameter<IntValue>("TerminalPoint", "Index of the ending point.", new IntValue(0)));
130      Parameters.Add(new FixedValueParameter<DoubleValue>("MaximumDistance", "The maximum distance constraint for a Orienteering solution."));
131      Parameters.Add(new ValueParameter<DoubleArray>("Scores", "The scores of the points."));
132      Parameters.Add(new FixedValueParameter<DoubleValue>("PointVisitingCosts", "The costs for visiting a point."));
133      Parameters.Add(new OptionalValueParameter<IntegerVector>("BestKnownSolution", "The best known solution of this Orienteering instance."));
134
135      Maximization.Value = true;
136      MaximizationParameter.Hidden = true;
137
138      SolutionCreator.IntegerVectorParameter.ActualName = "OrienteeringSolution";
139
140      InitializeInitialOrienteeringInstance();
141
142      ParameterizeSolutionCreator();
143      ParameterizeEvaluator();
144
145      InitializeOperators();
146      RegisterEventHandlers();
147    }
148
149    #region Events
150    protected override void OnSolutionCreatorChanged() {
151      base.OnSolutionCreatorChanged();
152      SolutionCreator.IntegerVectorParameter.ActualNameChanged += SolutionCreator_IntegerVectorParameter_ActualNameChanged;
153      ParameterizeSolutionCreator();
154      ParameterizeEvaluator();
155      ParameterizeAnalyzer();
156      ParameterizeOperators();
157    }
158    protected override void OnEvaluatorChanged() {
159      base.OnEvaluatorChanged();
160      ParameterizeEvaluator();
161      ParameterizeAnalyzer();
162    }
163    private void SolutionCreator_IntegerVectorParameter_ActualNameChanged(object sender, EventArgs e) {
164      ParameterizeEvaluator();
165      ParameterizeAnalyzer();
166      ParameterizeOperators();
167    }
168    private void CoordinatesParameter_ValueChanged(object sender, EventArgs e) {
169      if (Coordinates != null) {
170        Coordinates.ItemChanged += new EventHandler<EventArgs<int, int>>(CoordinatesValue_ItemChanged);
171        Coordinates.Reset += new EventHandler(CoordinatesValue_Reset);
172      }
173      ParameterizeSolutionCreator();
174      UpdateDistanceMatrix();
175      CheckStartingIndex();
176      CheckTerminalIndex();
177    }
178    private void CoordinatesValue_ItemChanged(object sender, EventArgs<int, int> e) {
179      UpdateDistanceMatrix();
180      CheckStartingIndex();
181      CheckTerminalIndex();
182    }
183    private void CoordinatesValue_Reset(object sender, EventArgs e) {
184      ParameterizeSolutionCreator();
185      UpdateDistanceMatrix();
186      CheckStartingIndex();
187      CheckTerminalIndex();
188    }
189    private void StartingPointParameterValue_ValueChanged(object sender, EventArgs e) {
190      CheckStartingIndex();
191    }
192
193    private void TerminalPointParameterValue_ValueChanged(object sender, EventArgs e) {
194      CheckTerminalIndex();
195    }
196    private void MaximumDistanceParameterValue_ValueChanged(object sender, EventArgs e) { }
197    private void ScoresParameter_ValueChanged(object sender, EventArgs e) {
198      ParameterizeEvaluator();
199      ParameterizeAnalyzer();
200      ParameterizeSolutionCreator();
201
202      ScoresParameter.Value.Reset += new EventHandler(ScoresValue_Reset);
203    }
204    private void ScoresValue_Reset(object sender, EventArgs e) {
205      ParameterizeSolutionCreator();
206    }
207    private void PointVisitingCostsParameterValue_ValueChanged(object sender, EventArgs e) { }
208    #endregion
209
210    #region Helpers
211    [StorableHook(HookType.AfterDeserialization)]
212    private void AfterDeserialization() {
213      RegisterEventHandlers();
214    }
215
216    private void RegisterEventHandlers() {
217      SolutionCreator.IntegerVectorParameter.ActualNameChanged += SolutionCreator_IntegerVectorParameter_ActualNameChanged;
218
219      CoordinatesParameter.ValueChanged += CoordinatesParameter_ValueChanged;
220      if (CoordinatesParameter.Value != null) {
221        CoordinatesParameter.Value.ItemChanged += CoordinatesValue_ItemChanged;
222        CoordinatesParameter.Value.Reset += CoordinatesValue_Reset;
223      }
224
225      StartingPointParameter.Value.ValueChanged += StartingPointParameterValue_ValueChanged;
226      TerminalPointParameter.Value.ValueChanged += TerminalPointParameterValue_ValueChanged;
227      MaximumDistanceParameter.Value.ValueChanged += MaximumDistanceParameterValue_ValueChanged;
228      PointVisitingCostsParameter.Value.ValueChanged += PointVisitingCostsParameterValue_ValueChanged;
229
230      ScoresParameter.ValueChanged += ScoresParameter_ValueChanged;
231      ScoresParameter.Value.Reset += ScoresValue_Reset;
232    }
233
234    private void ParameterizeSolutionCreator() {
235      SolutionCreator.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
236      SolutionCreator.ScoresParameter.ActualName = ScoresParameter.Name;
237      SolutionCreator.MaximumDistanceParameter.ActualName = MaximumDistanceParameter.Name;
238      SolutionCreator.StartingPointParameter.ActualName = StartingPointParameter.Name;
239      SolutionCreator.TerminalPointParameter.ActualName = TerminalPointParameter.Name;
240      SolutionCreator.PointVisitingCostsParameter.ActualName = PointVisitingCostsParameter.Name;
241    }
242    private void ParameterizeEvaluator() {
243      Evaluator.IntegerVectorParameter.ActualName = SolutionCreator.IntegerVectorParameter.ActualName;
244      Evaluator.ScoresParameter.ActualName = ScoresParameter.Name;
245      Evaluator.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
246      Evaluator.MaximumDistanceParameter.ActualName = MaximumDistanceParameter.Name;
247      Evaluator.PointVisitingCostsParameter.ActualName = PointVisitingCostsParameter.Name;
248    }
249    private void ParameterizeAnalyzer() {
250      if (BestOrienteeringSolutionAnalyser != null) {
251        BestOrienteeringSolutionAnalyser.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
252
253        BestOrienteeringSolutionAnalyser.IntegerVector.ActualName = SolutionCreator.IntegerVectorParameter.ActualName;
254        BestOrienteeringSolutionAnalyser.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
255        BestOrienteeringSolutionAnalyser.ScoresParameter.ActualName = ScoresParameter.Name;
256
257        BestOrienteeringSolutionAnalyser.ResultsParameter.ActualName = "Results";
258        BestOrienteeringSolutionAnalyser.BestKnownQualityParameter.ActualName = BestKnownQualityParameter.Name;
259        BestOrienteeringSolutionAnalyser.BestKnownSolutionParameter.ActualName = BestKnownSolutionParameter.Name;
260      }
261    }
262    private void InitializeOperators() {
263      Operators.Add(new BestOrienteeringSolutionAnalyser());
264      ParameterizeAnalyzer();
265
266      Operators.Add(new OrienteeringLocalImprovementOperator());
267      Operators.Add(new OrienteeringShakingOperator());
268      ParameterizeOperators();
269    }
270    private void ParameterizeOperators() {
271      foreach (var op in Operators.OfType<OrienteeringLocalImprovementOperator>()) {
272        op.IntegerVectorParameter.ActualName = SolutionCreator.IntegerVectorParameter.ActualName;
273        op.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
274        op.ScoresParameter.ActualName = ScoresParameter.Name;
275        op.MaximumDistanceParameter.ActualName = MaximumDistanceParameter.Name;
276        op.StartingPointParameter.ActualName = StartingPointParameter.Name;
277        op.TerminalPointParameter.ActualName = TerminalPointParameter.Name;
278        op.PointVisitingCostsParameter.ActualName = PointVisitingCostsParameter.Name;
279      }
280      foreach (var op in Operators.OfType<OrienteeringShakingOperator>()) {
281        op.IntegerVectorParameter.ActualName = SolutionCreator.IntegerVectorParameter.ActualName;
282        op.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
283        op.ScoresParameter.ActualName = ScoresParameter.Name;
284        op.MaximumDistanceParameter.ActualName = MaximumDistanceParameter.Name;
285        op.StartingPointParameter.ActualName = StartingPointParameter.Name;
286        op.TerminalPointParameter.ActualName = TerminalPointParameter.Name;
287        op.PointVisitingCostsParameter.ActualName = PointVisitingCostsParameter.Name;
288      }
289    }
290    #endregion
291
292    private DistanceMatrix CalculateDistanceMatrix(double[,] coordinates) {
293      var distances = DistanceHelper.GetDistanceMatrix(DistanceMeasure.Euclidean, coordinates, null, coordinates.GetLength(0));
294
295      return new DistanceMatrix(distances);
296    }
297    private void UpdateDistanceMatrix() {
298      if (Coordinates == null) {
299        DistanceMatrix = new DistanceMatrix(0, 0);
300        return;
301      }
302
303      var coordinates = Coordinates;
304      int dimension = coordinates.Rows;
305      var distances = new double[dimension, dimension];
306      for (int i = 0; i < dimension - 1; i++) {
307        for (int j = i + 1; j < dimension; j++) {
308          double x1 = coordinates[i, 0];
309          double y1 = coordinates[i, 1];
310          double x2 = coordinates[j, 0];
311          double y2 = coordinates[j, 1];
312          distances[i, j] = Math.Sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
313          distances[j, i] = distances[i, j];
314        }
315      }
316      DistanceMatrix = new DistanceMatrix(distances);
317    }
318    private void CheckStartingIndex() {
319      if (StartingPoint < 0) StartingPoint = 0;
320      if (StartingPoint >= DistanceMatrix.Rows) StartingPoint = DistanceMatrix.Rows - 1;
321    }
322    private void CheckTerminalIndex() {
323      if (TerminalPoint < 0) TerminalPoint = 0;
324      if (TerminalPoint >= DistanceMatrix.Rows) TerminalPoint = DistanceMatrix.Rows - 1;
325    }
326
327    private void InitializeInitialOrienteeringInstance() {
328      var coordinates = new double[21, 2] {
329        {  4.60,  7.10 }, {  5.70, 11.40 }, {  4.40, 12.30 }, {  2.80, 14.30 }, {  3.20, 10.30 },
330        {  3.50,  9.80 }, {  4.40,  8.40 }, {  7.80, 11.00 }, {  8.80,  9.80 }, {  7.70,  8.20 },
331        {  6.30,  7.90 }, {  5.40,  8.20 }, {  5.80,  6.80 }, {  6.70,  5.80 }, { 13.80, 13.10 },
332        { 14.10, 14.20 }, { 11.20, 13.60 }, {  9.70, 16.40 }, {  9.50, 18.80 }, {  4.70, 16.80 },
333        {  5.00,  5.60 }
334      };
335      Coordinates = new DoubleMatrix(coordinates);
336      DistanceMatrix = CalculateDistanceMatrix(coordinates);
337
338      StartingPoint = 0;
339      TerminalPoint = 20;
340      MaximumDistance = 30;
341
342      Scores = new DoubleArray(new double[21] { 0, 20, 20, 30, 15, 15, 10, 20, 20, 20, 15, 10, 10, 25, 40, 40, 30, 30, 50, 30, 0 });
343    }
344
345    #region Instance consuming
346    public void Load(OPData data) {
347      if (data.Coordinates == null && data.Distances == null)
348        throw new InvalidDataException("The given instance specifies no coordinates or distance matrix!");
349      if (data.Coordinates != null && data.Coordinates.GetLength(1) != 2)
350        throw new InvalidDataException("The coordinates of the given instance are not in the right format, there need to be one row for each customer and two columns for the x and y coordinates.");
351
352      // Clear old solutions
353      BestKnownQuality = null;
354      BestKnownSolution = null;
355
356      Name = data.Name;
357      Description = data.Description;
358
359      Coordinates = data.Coordinates != null ? new DoubleMatrix(data.Coordinates) : null;
360      if (data.Distances != null)
361        DistanceMatrix = new DistanceMatrix(data.Distances);
362      else
363        DistanceMatrix = new DistanceMatrix(data.GetDistanceMatrix());
364
365      StartingPoint = data.StartingPoint;
366      TerminalPoint = data.TerminalPoint;
367
368      PointVisitingCosts = data.PointVisitingCosts;
369      MaximumDistance = data.MaximumDistance;
370      Scores = new DoubleArray(data.Scores);
371    }
372
373    public void Load(TSPData data) {
374      if (data.Coordinates == null && data.Distances == null)
375        throw new InvalidDataException("The given instance specifies no coordinates or distance matrix!");
376      if (data.Coordinates != null && data.Coordinates.GetLength(1) != 2)
377        throw new InvalidDataException("The coordinates of the given instance are not in the right format, there need to be one row for each customer and two columns for the x and y coordinates.");
378
379      // Clear old solutions
380      BestKnownQuality = null;
381      BestKnownSolution = null;
382
383      Name = data.Name;
384      Description = data.Description;
385
386      Coordinates = data.Coordinates != null ? new DoubleMatrix(data.Coordinates) : null;
387      if (data.Distances != null)
388        DistanceMatrix = new DistanceMatrix(data.Distances);
389      else
390        DistanceMatrix = new DistanceMatrix(data.GetDistanceMatrix());
391
392      StartingPoint = 0; // First city is interpreted as start point
393      TerminalPoint = data.Dimension - 1; // Last city is interpreted als end point
394
395      PointVisitingCosts = 0;
396      MaximumDistance = DistanceMatrix.Average() * 5.0; // distance from start to end first to last city is interpreted as maximum distance
397      Scores = new DoubleArray(Enumerable.Repeat(1.0, data.Dimension).ToArray()); // all scores are 1
398    }
399
400    public void Load(CVRPData data) {
401      if (data.Coordinates == null && data.Distances == null)
402        throw new InvalidDataException("The given instance specifies no coordinates or distance matrix!");
403      if (data.Coordinates != null && data.Coordinates.GetLength(1) != 2)
404        throw new InvalidDataException("The coordinates of the given instance are not in the right format, there need to be one row for each customer and two columns for the x and y coordinates.");
405
406      // Clear old solutions
407      BestKnownQuality = null;
408      BestKnownSolution = null;
409
410      Name = data.Name;
411      Description = data.Description;
412
413      Coordinates = data.Coordinates != null ? new DoubleMatrix(data.Coordinates) : null;
414      DistanceMatrix = data.Distances != null
415        ? new DistanceMatrix(data.Distances)
416        : CalculateDistanceMatrix(data.Coordinates);
417
418      StartingPoint = 0; // Depot is interpreted as start point
419      TerminalPoint = 0; // Depot is interpreted als end point
420
421      PointVisitingCosts = 0;
422      MaximumDistance = data.Capacity * 2; // capacity is interpreted as max distance
423      Scores = new DoubleArray(data.Demands); // demands are interpreted as scores
424    }
425    #endregion
426  }
427}
Note: See TracBrowser for help on using the repository browser.