Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ScopedAlgorithms/HeuristicLab.Problems.Knapsack/3.3/KnapsackProblem.cs @ 14815

Last change on this file since 14815 was 14429, checked in by abeham, 8 years ago

#2701, #2708: Made a new branch from ProblemRefactoring and removed ScopedBasicAlgorithm branch (which becomes MemPR branch)

File size: 11.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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.Analysis;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Encodings.BinaryVectorEncoding;
30using HeuristicLab.Optimization;
31using HeuristicLab.Optimization.Operators;
32using HeuristicLab.Parameters;
33using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
34
35namespace HeuristicLab.Problems.Knapsack {
36  [Item("Knapsack Problem (KSP)", "Represents a Knapsack problem.")]
37  [Creatable(CreatableAttribute.Categories.CombinatorialProblems, Priority = 200)]
38  [StorableClass]
39  public sealed class KnapsackProblem : SingleObjectiveProblem<BinaryVectorEncoding, BinaryVector> {
40    public override bool Maximization { get { return true; } }
41
42    #region Parameter Properties
43    public ValueParameter<IntValue> KnapsackCapacityParameter {
44      get { return (ValueParameter<IntValue>)Parameters["KnapsackCapacity"]; }
45    }
46    public ValueParameter<IntArray> WeightsParameter {
47      get { return (ValueParameter<IntArray>)Parameters["Weights"]; }
48    }
49    public ValueParameter<IntArray> ValuesParameter {
50      get { return (ValueParameter<IntArray>)Parameters["Values"]; }
51    }
52    public OptionalValueParameter<BinaryVector> BestKnownSolutionParameter {
53      get { return (OptionalValueParameter<BinaryVector>)Parameters["BestKnownSolution"]; }
54    }
55    #endregion
56
57    #region Properties
58    public int KnapsackCapacity {
59      get { return KnapsackCapacityParameter.Value.Value; }
60      set { KnapsackCapacityParameter.Value.Value = value; }
61    }
62    public IntArray Weights {
63      get { return WeightsParameter.Value; }
64      set { WeightsParameter.Value = value; }
65    }
66    public IntArray Values {
67      get { return ValuesParameter.Value; }
68      set { ValuesParameter.Value = value; }
69    }
70    public BinaryVector BestKnownSolution {
71      get { return BestKnownSolutionParameter.Value; }
72      set { BestKnownSolutionParameter.Value = value; }
73    }
74    private BestKnapsackSolutionAnalyzer BestKnapsackSolutionAnalyzer {
75      get { return Operators.OfType<BestKnapsackSolutionAnalyzer>().FirstOrDefault(); }
76    }
77    #endregion
78
79    [StorableConstructor]
80    private KnapsackProblem(bool deserializing) : base(deserializing) { }
81    private KnapsackProblem(KnapsackProblem original, Cloner cloner)
82      : base(original, cloner) {
83      RegisterEventHandlers();
84    }
85    public KnapsackProblem()
86      : base(new BinaryVectorEncoding("Selection")) {
87      Parameters.Add(new ValueParameter<IntValue>("KnapsackCapacity", "Capacity of the Knapsack.", new IntValue(1)));
88      Parameters.Add(new ValueParameter<IntArray>("Weights", "The weights of the items.", new IntArray(5)));
89      Parameters.Add(new ValueParameter<IntArray>("Values", "The values of the items.", new IntArray(5)));
90      Parameters.Add(new OptionalValueParameter<BinaryVector>("BestKnownSolution", "The best known solution of this Knapsack instance."));
91
92      InitializeRandomKnapsackInstance();
93      Encoding.Length = Weights.Length;
94
95      InitializeOperators();
96      RegisterEventHandlers();
97    }
98
99    public override double Evaluate(BinaryVector solution, IRandom random) {
100      var weights = Weights;
101      var values = Values;
102      var totalWeight = 0.0;
103      var totalValue = 0.0;
104      for (var i = 0; i < solution.Length; i++) {
105        if (!solution[i]) continue;
106        totalWeight += weights[i];
107        totalValue += values[i];
108      }
109      return totalWeight > KnapsackCapacity ? KnapsackCapacity - totalWeight : totalValue;
110    }
111
112    public override IDeepCloneable Clone(Cloner cloner) {
113      return new KnapsackProblem(this, cloner);
114    }
115
116    [StorableHook(HookType.AfterDeserialization)]
117    private void AfterDeserialization() {
118      RegisterEventHandlers();
119    }
120
121    private void RegisterEventHandlers() {
122      Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged;
123      KnapsackCapacityParameter.ValueChanged += KnapsackCapacityParameter_ValueChanged;
124      WeightsParameter.ValueChanged += WeightsParameter_ValueChanged;
125      WeightsParameter.Value.Reset += WeightsValue_Reset;
126      ValuesParameter.ValueChanged += ValuesParameter_ValueChanged;
127      ValuesParameter.Value.Reset += ValuesValue_Reset;
128      // TODO: There is no even to detect if the parameter itself was changed
129      Encoding.LengthParameter.ValueChanged += Encoding_LengthParameter_ValueChanged;
130    }
131
132    #region Events
133    protected override void OnEncodingChanged() {
134      base.OnEncodingChanged();
135      Parameterize();
136    }
137    //TODO check with abeham if this is really necessary
138    //protected override void OnSolutionCreatorChanged() {
139    //  base.OnSolutionCreatorChanged();
140    //  Parameterize();
141    //}
142    protected override void OnEvaluatorChanged() {
143      base.OnEvaluatorChanged();
144      Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged;
145      Parameterize();
146    }
147    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
148      Parameterize();
149    }
150    private void KnapsackCapacityParameter_ValueChanged(object sender, EventArgs e) {
151      Parameterize();
152    }
153    private void WeightsParameter_ValueChanged(object sender, EventArgs e) {
154      Parameterize();
155      WeightsParameter.Value.Reset += WeightsValue_Reset;
156    }
157    private void WeightsValue_Reset(object sender, EventArgs e) {
158      if (WeightsParameter.Value != null && ValuesParameter.Value != null) {
159        ((IStringConvertibleArray)ValuesParameter.Value).Length = Weights.Length;
160        Encoding.Length = Weights.Length;
161      }
162      Parameterize();
163    }
164    private void ValuesParameter_ValueChanged(object sender, EventArgs e) {
165      Parameterize();
166      ValuesParameter.Value.Reset += ValuesValue_Reset;
167    }
168    private void ValuesValue_Reset(object sender, EventArgs e) {
169      if (WeightsParameter.Value != null && ValuesParameter.Value != null) {
170        ((IStringConvertibleArray)WeightsParameter.Value).Length = Values.Length;
171        Encoding.Length = Values.Length;
172      }
173      Parameterize();
174    }
175    private void Encoding_LengthParameter_ValueChanged(object sender, EventArgs e) {
176      if (Weights.Length != Encoding.Length) {
177        ((IStringConvertibleArray)WeightsParameter.Value).Length = Encoding.Length;
178      }
179      if (Values.Length != Encoding.Length) {
180        ((IStringConvertibleArray)ValuesParameter.Value).Length = Encoding.Length;
181      }
182      Parameterize();
183    }
184    #endregion
185
186    #region Helpers
187    private void InitializeOperators() {
188      Operators.Add(new KnapsackImprovementOperator());
189      Operators.Add(new KnapsackPathRelinker());
190      Operators.Add(new KnapsackSimultaneousPathRelinker());
191      Operators.Add(new KnapsackSimilarityCalculator());
192      Operators.Add(new QualitySimilarityCalculator());
193      Operators.Add(new NoSimilarityCalculator());
194
195      Operators.Add(new BestKnapsackSolutionAnalyzer());
196      Operators.Add(new PopulationSimilarityAnalyzer(Operators.OfType<ISolutionSimilarityCalculator>()));
197
198      Parameterize();
199    }
200    private void Parameterize() {
201      var operators = new List<IItem>();
202
203      if (BestKnapsackSolutionAnalyzer != null) {
204        operators.Add(BestKnapsackSolutionAnalyzer);
205        BestKnapsackSolutionAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
206        BestKnapsackSolutionAnalyzer.MaximizationParameter.Hidden = true;
207        BestKnapsackSolutionAnalyzer.BestKnownQualityParameter.ActualName = BestKnownQualityParameter.Name;
208        BestKnapsackSolutionAnalyzer.BestKnownQualityParameter.Hidden = true;
209        BestKnapsackSolutionAnalyzer.BestKnownSolutionParameter.ActualName = BestKnownSolutionParameter.Name;
210        BestKnapsackSolutionAnalyzer.BestKnownSolutionParameter.Hidden = true;
211        BestKnapsackSolutionAnalyzer.KnapsackCapacityParameter.ActualName = KnapsackCapacityParameter.Name;
212        BestKnapsackSolutionAnalyzer.KnapsackCapacityParameter.Hidden = true;
213        BestKnapsackSolutionAnalyzer.WeightsParameter.ActualName = WeightsParameter.Name;
214        BestKnapsackSolutionAnalyzer.WeightsParameter.Hidden = true;
215        BestKnapsackSolutionAnalyzer.ValuesParameter.ActualName = ValuesParameter.Name;
216        BestKnapsackSolutionAnalyzer.ValuesParameter.Hidden = true;
217      }
218      foreach (var op in Operators.OfType<IKnapsackMoveEvaluator>()) {
219        operators.Add(op);
220        op.KnapsackCapacityParameter.ActualName = KnapsackCapacityParameter.Name;
221        op.KnapsackCapacityParameter.Hidden = true;
222        op.WeightsParameter.ActualName = WeightsParameter.Name;
223        op.WeightsParameter.Hidden = true;
224        op.ValuesParameter.ActualName = ValuesParameter.Name;
225        op.ValuesParameter.Hidden = true;
226
227        var bitflipMoveEval = op as IKnapsackOneBitflipMoveEvaluator;
228        if (bitflipMoveEval != null) {
229          foreach (var moveOp in Encoding.Operators.OfType<IOneBitflipMoveQualityOperator>()) {
230            moveOp.MoveQualityParameter.ActualName = bitflipMoveEval.MoveQualityParameter.ActualName;
231            moveOp.MoveQualityParameter.Hidden = true;
232          }
233        }
234      }
235      foreach (var op in Operators.OfType<ISingleObjectiveImprovementOperator>()) {
236        operators.Add(op);
237        op.SolutionParameter.ActualName = Encoding.Name;
238        op.SolutionParameter.Hidden = true;
239      }
240      foreach (var op in Operators.OfType<ISingleObjectivePathRelinker>()) {
241        operators.Add(op);
242        op.ParentsParameter.ActualName = Encoding.Name;
243        op.ParentsParameter.Hidden = true;
244      }
245      foreach (var op in Operators.OfType<ISolutionSimilarityCalculator>()) {
246        operators.Add(op);
247        op.SolutionVariableName = Encoding.Name;
248        op.QualityVariableName = Evaluator.QualityParameter.ActualName;
249      }
250
251      if (operators.Count > 0) Encoding.ConfigureOperators(Operators);
252    }
253    #endregion
254
255    private void InitializeRandomKnapsackInstance() {
256      var sysrand = new System.Random();
257
258      var power = sysrand.Next(5, 11);
259      var itemCount = (int)Math.Pow(2, power);
260      Weights = new IntArray(itemCount);
261      Values = new IntArray(itemCount);
262
263      double totalWeight = 0;
264
265      for (int i = 0; i < itemCount; i++) {
266        var value = sysrand.Next(1, 30);
267        var weight = sysrand.Next(1, 30);
268
269        Values[i] = value;
270        Weights[i] = weight;
271        totalWeight += weight;
272      }
273
274      KnapsackCapacity = (int)Math.Round(0.5 * totalWeight);
275    }
276  }
277}
Note: See TracBrowser for help on using the repository browser.