1 | #region License Information
|
---|
2 | /* HeuristicLab
|
---|
3 | * Copyright (C) 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 |
|
---|
22 | using System;
|
---|
23 | using System.Linq;
|
---|
24 | using System.Threading;
|
---|
25 | using HEAL.Attic;
|
---|
26 | using HeuristicLab.Analysis;
|
---|
27 | using HeuristicLab.Common;
|
---|
28 | using HeuristicLab.Core;
|
---|
29 | using HeuristicLab.Data;
|
---|
30 | using HeuristicLab.Encodings.BinaryVectorEncoding;
|
---|
31 | using HeuristicLab.Optimization;
|
---|
32 | using HeuristicLab.Optimization.Operators;
|
---|
33 | using HeuristicLab.Parameters;
|
---|
34 |
|
---|
35 | namespace HeuristicLab.Problems.Knapsack {
|
---|
36 | [Item("Knapsack Problem (KSP)", "Represents a Knapsack problem.")]
|
---|
37 | [Creatable(CreatableAttribute.Categories.CombinatorialProblems, Priority = 200)]
|
---|
38 | [StorableType("8CEDAFA2-6E0A-4D4B-B6C6-F85CC58B824E")]
|
---|
39 | public sealed class KnapsackProblem : BinaryVectorProblem {
|
---|
40 |
|
---|
41 | #region Parameter Properties
|
---|
42 | [Storable] public ValueParameter<IntValue> KnapsackCapacityParameter { get; private set; }
|
---|
43 | [Storable] public ValueParameter<IntArray> WeightsParameter { get; private set; }
|
---|
44 | [Storable] public ValueParameter<IntArray> ValuesParameter { get; private set; }
|
---|
45 | [Storable] public OptionalValueParameter<BinaryVector> BestKnownSolutionParameter { get; private set; }
|
---|
46 | #endregion
|
---|
47 |
|
---|
48 | #region Properties
|
---|
49 | public int KnapsackCapacity {
|
---|
50 | get { return KnapsackCapacityParameter.Value.Value; }
|
---|
51 | set { KnapsackCapacityParameter.Value.Value = value; }
|
---|
52 | }
|
---|
53 | public IntArray Weights {
|
---|
54 | get { return WeightsParameter.Value; }
|
---|
55 | set { WeightsParameter.Value = value; }
|
---|
56 | }
|
---|
57 | public IntArray Values {
|
---|
58 | get { return ValuesParameter.Value; }
|
---|
59 | set { ValuesParameter.Value = value; }
|
---|
60 | }
|
---|
61 | public BinaryVector BestKnownSolution {
|
---|
62 | get { return BestKnownSolutionParameter.Value; }
|
---|
63 | set { BestKnownSolutionParameter.Value = value; }
|
---|
64 | }
|
---|
65 | #endregion
|
---|
66 |
|
---|
67 | [StorableConstructor]
|
---|
68 | private KnapsackProblem(StorableConstructorFlag _) : base(_) { }
|
---|
69 | private KnapsackProblem(KnapsackProblem original, Cloner cloner)
|
---|
70 | : base(original, cloner) {
|
---|
71 | KnapsackCapacityParameter = cloner.Clone(original.KnapsackCapacityParameter);
|
---|
72 | WeightsParameter = cloner.Clone(original.WeightsParameter);
|
---|
73 | ValuesParameter = cloner.Clone(original.ValuesParameter);
|
---|
74 | BestKnownSolutionParameter = cloner.Clone(original.BestKnownSolutionParameter);
|
---|
75 | RegisterEventHandlers();
|
---|
76 | }
|
---|
77 | public KnapsackProblem()
|
---|
78 | : base(new BinaryVectorEncoding("Selection")) {
|
---|
79 | DimensionRefParameter.ReadOnly = true;
|
---|
80 | Maximization = true;
|
---|
81 | Parameters.Add(KnapsackCapacityParameter = new ValueParameter<IntValue>("KnapsackCapacity", "Capacity of the Knapsack.", new IntValue(1)));
|
---|
82 | Parameters.Add(WeightsParameter = new ValueParameter<IntArray>("Weights", "The weights of the items.", new IntArray(5)));
|
---|
83 | Parameters.Add(ValuesParameter = new ValueParameter<IntArray>("Values", "The values of the items.", new IntArray(5)));
|
---|
84 | Parameters.Add(BestKnownSolutionParameter = new OptionalValueParameter<BinaryVector>("BestKnownSolution", "The best known solution of this Knapsack instance."));
|
---|
85 | Dimension = Weights.Length;
|
---|
86 |
|
---|
87 | InitializeRandomKnapsackInstance();
|
---|
88 |
|
---|
89 | InitializeOperators();
|
---|
90 | RegisterEventHandlers();
|
---|
91 | }
|
---|
92 |
|
---|
93 | public override ISingleObjectiveEvaluationResult Evaluate(BinaryVector solution, IRandom random, CancellationToken cancellationToken) {
|
---|
94 | var totalWeight = 0.0;
|
---|
95 | var totalValue = 0.0;
|
---|
96 | for (var i = 0; i < solution.Length; i++) {
|
---|
97 | if (!solution[i]) continue;
|
---|
98 | totalWeight += Weights[i];
|
---|
99 | totalValue += Values[i];
|
---|
100 | }
|
---|
101 | var quality = totalWeight > KnapsackCapacity ? KnapsackCapacity - totalWeight : totalValue;
|
---|
102 | return new SingleObjectiveEvaluationResult(quality);
|
---|
103 | }
|
---|
104 |
|
---|
105 | public override void Analyze(BinaryVector[] solutions, double[] qualities, ResultCollection results, IRandom random) {
|
---|
106 | base.Analyze(solutions, qualities, results, random);
|
---|
107 |
|
---|
108 | var best = GetBestSolution(solutions, qualities);
|
---|
109 |
|
---|
110 | if (double.IsNaN(BestKnownQuality) || IsBetter(best.Item2, BestKnownQuality)) {
|
---|
111 | BestKnownQuality = best.Item2;
|
---|
112 | BestKnownSolution = (BinaryVector)best.Item1.Clone();
|
---|
113 | }
|
---|
114 |
|
---|
115 | IResult result;
|
---|
116 | if (!results.TryGetValue("Best Knapsack Solution", out result)) {
|
---|
117 | results.Add(result = new Result("Best Knapsack Solution", typeof(KnapsackSolution)));
|
---|
118 | }
|
---|
119 | var solution = (KnapsackSolution)result.Value;
|
---|
120 | if (solution == null) {
|
---|
121 | solution = new KnapsackSolution((BinaryVector)best.Item1.Clone(), new DoubleValue(best.Item2),
|
---|
122 | KnapsackCapacityParameter.Value, WeightsParameter.Value, ValuesParameter.Value);
|
---|
123 | result.Value = solution;
|
---|
124 | } else {
|
---|
125 | if (IsBetter(best.Item2, solution.Quality.Value)) {
|
---|
126 | solution.BinaryVector = (BinaryVector)best.Item1.Clone();
|
---|
127 | solution.Quality = new DoubleValue(best.Item2);
|
---|
128 | solution.Capacity = KnapsackCapacityParameter.Value;
|
---|
129 | solution.Weights = WeightsParameter.Value;
|
---|
130 | solution.Values = ValuesParameter.Value;
|
---|
131 | }
|
---|
132 | }
|
---|
133 | }
|
---|
134 |
|
---|
135 | public override IDeepCloneable Clone(Cloner cloner) {
|
---|
136 | return new KnapsackProblem(this, cloner);
|
---|
137 | }
|
---|
138 |
|
---|
139 | [StorableHook(HookType.AfterDeserialization)]
|
---|
140 | private void AfterDeserialization() {
|
---|
141 | RegisterEventHandlers();
|
---|
142 | }
|
---|
143 |
|
---|
144 | private void RegisterEventHandlers() {
|
---|
145 | WeightsParameter.ValueChanged += WeightsParameter_ValueChanged;
|
---|
146 | WeightsParameter.Value.Reset += (_, __) => SyncValuesToWeights();
|
---|
147 | ValuesParameter.ValueChanged += ValuesParameter_ValueChanged;
|
---|
148 | ValuesParameter.Value.Reset += (_, __) => SyncWeightsToValues();
|
---|
149 | }
|
---|
150 |
|
---|
151 | #region Events
|
---|
152 | protected override void DimensionOnChanged() {
|
---|
153 | base.DimensionOnChanged();
|
---|
154 | if (Weights.Length != Dimension) {
|
---|
155 | ((IStringConvertibleArray)WeightsParameter.Value).Length = Dimension;
|
---|
156 | }
|
---|
157 | if (Values.Length != Dimension) {
|
---|
158 | ((IStringConvertibleArray)ValuesParameter.Value).Length = Dimension;
|
---|
159 | }
|
---|
160 | }
|
---|
161 | private void WeightsParameter_ValueChanged(object sender, EventArgs e) {
|
---|
162 | WeightsParameter.Value.Reset += (_, __) => SyncValuesToWeights();
|
---|
163 | SyncValuesToWeights();
|
---|
164 | }
|
---|
165 | private void ValuesParameter_ValueChanged(object sender, EventArgs e) {
|
---|
166 | ValuesParameter.Value.Reset += (_, __) => SyncWeightsToValues();
|
---|
167 | SyncWeightsToValues();
|
---|
168 | }
|
---|
169 | private void SyncWeightsToValues() {
|
---|
170 | if (WeightsParameter.Value != null && ValuesParameter.Value != null) {
|
---|
171 | ((IStringConvertibleArray)WeightsParameter.Value).Length = Values.Length;
|
---|
172 | Dimension = Values.Length;
|
---|
173 | }
|
---|
174 | }
|
---|
175 | private void SyncValuesToWeights() {
|
---|
176 | if (WeightsParameter.Value != null && ValuesParameter.Value != null) {
|
---|
177 | ((IStringConvertibleArray)ValuesParameter.Value).Length = Weights.Length;
|
---|
178 | Dimension = Weights.Length;
|
---|
179 | }
|
---|
180 | }
|
---|
181 | #endregion
|
---|
182 |
|
---|
183 | #region Helpers
|
---|
184 | private void InitializeOperators() {
|
---|
185 | Operators.AddRange(new IItem[] { new KnapsackImprovementOperator(),
|
---|
186 | new KnapsackPathRelinker(), new KnapsackSimultaneousPathRelinker(),
|
---|
187 | new QualitySimilarityCalculator(), new NoSimilarityCalculator(),
|
---|
188 | new KnapsackOneBitflipMoveEvaluator()});
|
---|
189 | Operators.Add(new PopulationSimilarityAnalyzer(Operators.OfType<ISolutionSimilarityCalculator>()));
|
---|
190 |
|
---|
191 | ParameterizeOperators();
|
---|
192 | }
|
---|
193 |
|
---|
194 | protected override void ParameterizeOperators() {
|
---|
195 | base.ParameterizeOperators();
|
---|
196 | Parameterize();
|
---|
197 | }
|
---|
198 |
|
---|
199 | private void Parameterize() {
|
---|
200 | foreach (var op in Operators.OfType<IKnapsackMoveEvaluator>()) {
|
---|
201 | op.KnapsackCapacityParameter.ActualName = KnapsackCapacityParameter.Name;
|
---|
202 | op.KnapsackCapacityParameter.Hidden = true;
|
---|
203 | op.WeightsParameter.ActualName = WeightsParameter.Name;
|
---|
204 | op.WeightsParameter.Hidden = true;
|
---|
205 | op.ValuesParameter.ActualName = ValuesParameter.Name;
|
---|
206 | op.ValuesParameter.Hidden = true;
|
---|
207 | }
|
---|
208 | }
|
---|
209 | #endregion
|
---|
210 |
|
---|
211 | private void InitializeRandomKnapsackInstance() {
|
---|
212 | var sysrand = new System.Random();
|
---|
213 |
|
---|
214 | var itemCount = sysrand.Next(10, 100);
|
---|
215 | Weights = new IntArray(itemCount);
|
---|
216 | Values = new IntArray(itemCount);
|
---|
217 |
|
---|
218 | double totalWeight = 0;
|
---|
219 |
|
---|
220 | for (int i = 0; i < itemCount; i++) {
|
---|
221 | var value = sysrand.Next(1, 10);
|
---|
222 | var weight = sysrand.Next(1, 10);
|
---|
223 |
|
---|
224 | Values[i] = value;
|
---|
225 | Weights[i] = weight;
|
---|
226 | totalWeight += weight;
|
---|
227 | }
|
---|
228 |
|
---|
229 | KnapsackCapacity = (int)Math.Round(0.7 * totalWeight);
|
---|
230 | Dimension = Weights.Length;
|
---|
231 | }
|
---|
232 | }
|
---|
233 | }
|
---|