Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OptimizationNetworks/HeuristicLab.Networks.IntegratedOptimization.TravelingThief/3.3/Problems/TravelingThiefProblem.cs @ 14671

Last change on this file since 14671 was 14671, checked in by jkarder, 7 years ago

#2205: worked on optimization networks

  • added ttp as basic problem for baseline comparison
File size: 6.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2017 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.Linq;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Encodings.BinaryVectorEncoding;
29using HeuristicLab.Encodings.PermutationEncoding;
30using HeuristicLab.Optimization;
31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33using HeuristicLab.Problems.Knapsack;
34using HeuristicLab.Problems.TravelingSalesman;
35
36namespace HeuristicLab.Networks.IntegratedOptimization.TravelingThief {
37  [Item("Traveling Thief Problem (TTP)", "")]
38  [Creatable(CreatableAttribute.Categories.Problems, Priority = 999)]
39  [StorableClass]
40  public sealed class TravelingThiefProblem : SingleObjectiveBasicProblem<MultiEncoding> {
41    private const string InstanceParameterName = "Instance";
42
43    [Storable]
44    private Dictionary<int, int[]> availability;
45    [Storable]
46    private double minSpeed, maxSpeed, rentingRatio;
47    [Storable]
48    private TravelingSalesmanProblem tsp;
49    [Storable]
50    private BinaryKnapsackProblem ksp;
51
52    public override bool Maximization {
53      get { return true; }
54    }
55
56    public IFixedValueParameter<TextFileValue> InstanceParameter {
57      get { return (IFixedValueParameter<TextFileValue>)Parameters[InstanceParameterName]; }
58    }
59
60    [StorableConstructor]
61    private TravelingThiefProblem(bool deserializing) : base(deserializing) { }
62    private TravelingThiefProblem(TravelingThiefProblem original, Cloner cloner) : base(original, cloner) {
63      if (original.availability != null) availability = original.availability.ToDictionary(k => k.Key, v => (int[])v.Value.Clone());
64      minSpeed = original.minSpeed;
65      maxSpeed = original.maxSpeed;
66      rentingRatio = original.rentingRatio;
67      tsp = cloner.Clone(original.tsp);
68      ksp = cloner.Clone(original.ksp);
69
70      InstanceParameter.Value.ToStringChanged += InstanceParameter_Value_ToStringChanged;
71    }
72    public TravelingThiefProblem() {
73      Parameters.Add(new FixedValueParameter<TextFileValue>(InstanceParameterName));
74
75      InstanceParameter.Value.ToStringChanged += InstanceParameter_Value_ToStringChanged;
76
77      Encoding.Add(new BinaryVectorEncoding("loot"))
78              .Add(new PermutationEncoding("tour"));
79    }
80
81
82    [StorableHook(HookType.AfterDeserialization)]
83    private void AfterDeserialization() {
84      InstanceParameter.Value.ToStringChanged += InstanceParameter_Value_ToStringChanged;
85    }
86
87    private void InstanceParameter_Value_ToStringChanged(object sender, EventArgs e) {
88      string filePath = InstanceParameter.Value.Value;
89
90      TtpUtils.DistanceType distanceType;
91      double[,] tspCoordinates;
92      int kspCapacity;
93      int[] kspItemValues, kspItemWeights;
94      int[] ttpAvailability;
95
96      TtpUtils.Import(filePath, out tspCoordinates, out distanceType,
97                                out kspCapacity, out kspItemValues, out kspItemWeights,
98                                out ttpAvailability, out minSpeed, out maxSpeed, out rentingRatio);
99
100      this.availability = TtpUtils.GetAvailability(ttpAvailability);
101
102      tsp = new TravelingSalesmanProblem();
103      tsp.Coordinates = new DoubleMatrix(tspCoordinates);
104      tsp.DistanceMatrix = new DistanceMatrix(TtpUtils.GetDistances(tsp.Coordinates, distanceType));
105
106      ksp = new BinaryKnapsackProblem();
107      ksp.KnapsackCapacity.Value = kspCapacity;
108      ksp.Encoding.Length = kspItemValues.Length;
109      ksp.Values = new IntArray(kspItemValues);
110      ksp.Weights = new IntArray(kspItemWeights);
111
112      Encoding.Encodings.OfType<BinaryVectorEncoding>().Single().Length = ksp.Encoding.Length;
113      Encoding.Encodings.OfType<PermutationEncoding>().Single().Length = tsp.Coordinates.Rows;
114    }
115
116    public override IDeepCloneable Clone(Cloner cloner) {
117      return new TravelingThiefProblem(this, cloner);
118    }
119
120    public override double Evaluate(Individual individual, IRandom random) {
121      var binaryVector = individual.BinaryVector();
122      var permutation = individual.Permutation();
123      return TtpUtils.Evaluate(tsp, permutation.ToArray(), ksp, binaryVector.ToArray(), availability, rentingRatio, minSpeed, maxSpeed);
124    }
125
126    public override void Analyze(Individual[] individuals, double[] qualities, ResultCollection results, IRandom random) {
127      base.Analyze(individuals, qualities, results, random);
128      var orderedIndividuals = individuals.Zip(qualities, (i, q) => new { Individual = i, Quality = q }).OrderBy(z => z.Quality);
129      var best = Maximization ? orderedIndividuals.Last() : orderedIndividuals.First();
130      var bestIndividual = best.Individual;
131      var bestQuality = best.Quality;
132
133      if (!results.ContainsKey("Best TTP Quality")) {
134        results.Add(new Result("Best TTP Quality", typeof(DoubleValue)));
135        results.Add(new Result("Best Tour", typeof(PathTSPTour)));
136        results.Add(new Result("Best Loot", typeof(KnapsackSolution)));
137      }
138      results["Best TTP Quality"].Value = new DoubleValue(bestQuality);
139      results["Best Tour"].Value = new PathTSPTour(
140        (DoubleMatrix)tsp.Coordinates.Clone(),
141        (Permutation)bestIndividual.Permutation().Clone(),
142        new DoubleValue(double.NaN)
143      );
144      results["Best Loot"].Value = new KnapsackSolution(
145        (BinaryVector)bestIndividual.BinaryVector().Clone(),
146        new DoubleValue(double.NaN),
147        (IntValue)ksp.KnapsackCapacity.Clone(),
148        (IntArray)ksp.Weights.Clone(),
149        (IntArray)ksp.Values.Clone()
150      );
151    }
152  }
153}
Note: See TracBrowser for help on using the repository browser.