source: branches/2521_ProblemRefactoring/HeuristicLab.Problems.Knapsack/3.3/KnapsackProblem.cs @ 17544

Last change on this file since 17544 was 17544, checked in by abeham, 8 weeks ago

#2521: worked on refactoring, worked a lot on binary encoding / problems

File size: 11.2 KB
Line 
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
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using System.Threading;
26using HEAL.Attic;
27using HeuristicLab.Analysis;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Data;
31using HeuristicLab.Encodings.BinaryVectorEncoding;
32using HeuristicLab.Optimization;
33using HeuristicLab.Optimization.Operators;
34using HeuristicLab.Parameters;
35
36namespace HeuristicLab.Problems.Knapsack {
37  [Item("Knapsack Problem (KSP)", "Represents a Knapsack problem.")]
38  [Creatable(CreatableAttribute.Categories.CombinatorialProblems, Priority = 200)]
39  [StorableType("8CEDAFA2-6E0A-4D4B-B6C6-F85CC58B824E")]
40  public sealed class KnapsackProblem : BinaryVectorProblem {
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(StorableConstructorFlag _) : base(_) { }
81    private KnapsackProblem(KnapsackProblem original, Cloner cloner)
82      : base(original, cloner) {
83      RegisterEventHandlers();
84    }
85    public KnapsackProblem()
86      : base(new BinaryVectorEncoding("Selection")) {
87      Maximization = true;
88      Parameters.Add(new ValueParameter<IntValue>("KnapsackCapacity", "Capacity of the Knapsack.", new IntValue(1)));
89      Parameters.Add(new ValueParameter<IntArray>("Weights", "The weights of the items.", new IntArray(5)));
90      Parameters.Add(new ValueParameter<IntArray>("Values", "The values of the items.", new IntArray(5)));
91      Parameters.Add(new OptionalValueParameter<BinaryVector>("BestKnownSolution", "The best known solution of this Knapsack instance."));
92
93      Dimension = Weights.Length;
94      InitializeRandomKnapsackInstance();
95
96      InitializeOperators();
97      RegisterEventHandlers();
98    }
99
100    public override ISingleObjectiveEvaluationResult Evaluate(BinaryVector solution, IRandom random, CancellationToken cancellationToken) {
101      var totalWeight = 0.0;
102      var totalValue = 0.0;
103      for (var i = 0; i < solution.Length; i++) {
104        if (!solution[i]) continue;
105        totalWeight += Weights[i];
106        totalValue += Values[i];
107      }
108      var quality = totalWeight > KnapsackCapacity ? KnapsackCapacity - totalWeight : totalValue;
109      return new SingleObjectiveEvaluationResult(quality);
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    }
129
130    #region Events
131    protected override void OnEncodingChanged() {
132      base.OnEncodingChanged();
133      Parameterize();
134    }
135    //TODO check with abeham if this is really necessary
136    //protected override void OnSolutionCreatorChanged() {
137    //  base.OnSolutionCreatorChanged();
138    //  Parameterize();
139    //}
140    protected override void OnEvaluatorChanged() {
141      base.OnEvaluatorChanged();
142      Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged;
143      Parameterize();
144    }
145    protected override void DimensionOnChanged() {
146      base.DimensionOnChanged();
147      if (Weights.Length != Dimension) {
148        ((IStringConvertibleArray)WeightsParameter.Value).Length = Dimension;
149      }
150      if (Values.Length != Dimension) {
151        ((IStringConvertibleArray)ValuesParameter.Value).Length = Dimension;
152      }
153      Parameterize();
154    }
155    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
156      Parameterize();
157    }
158    private void KnapsackCapacityParameter_ValueChanged(object sender, EventArgs e) {
159      Parameterize();
160    }
161    private void WeightsParameter_ValueChanged(object sender, EventArgs e) {
162      Parameterize();
163      WeightsParameter.Value.Reset += WeightsValue_Reset;
164    }
165    private void WeightsValue_Reset(object sender, EventArgs e) {
166      if (WeightsParameter.Value != null && ValuesParameter.Value != null) {
167        ((IStringConvertibleArray)ValuesParameter.Value).Length = Weights.Length;
168        Dimension = Weights.Length;
169      }
170      Parameterize();
171    }
172    private void ValuesParameter_ValueChanged(object sender, EventArgs e) {
173      Parameterize();
174      ValuesParameter.Value.Reset += ValuesValue_Reset;
175    }
176    private void ValuesValue_Reset(object sender, EventArgs e) {
177      if (WeightsParameter.Value != null && ValuesParameter.Value != null) {
178        ((IStringConvertibleArray)WeightsParameter.Value).Length = Values.Length;
179        Dimension = Values.Length;
180      }
181      Parameterize();
182    }
183    #endregion
184
185    #region Helpers
186    private void InitializeOperators() {
187      Operators.Add(new KnapsackImprovementOperator());
188      Operators.Add(new KnapsackPathRelinker());
189      Operators.Add(new KnapsackSimultaneousPathRelinker());
190      Operators.Add(new QualitySimilarityCalculator());
191      Operators.Add(new NoSimilarityCalculator());
192
193      Operators.Add(new BestKnapsackSolutionAnalyzer());
194      Operators.Add(new PopulationSimilarityAnalyzer(Operators.OfType<ISolutionSimilarityCalculator>()));
195
196      Operators.Add(new KnapsackOneBitflipMoveEvaluator());
197      Parameterize();
198    }
199    private void Parameterize() {
200      var operators = new List<IItem>();
201
202      if (BestKnapsackSolutionAnalyzer != null) {
203        operators.Add(BestKnapsackSolutionAnalyzer);
204        BestKnapsackSolutionAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
205        BestKnapsackSolutionAnalyzer.MaximizationParameter.Hidden = true;
206        BestKnapsackSolutionAnalyzer.BestKnownQualityParameter.ActualName = BestKnownQualityParameter.Name;
207        BestKnapsackSolutionAnalyzer.BestKnownQualityParameter.Hidden = true;
208        BestKnapsackSolutionAnalyzer.BestKnownSolutionParameter.ActualName = BestKnownSolutionParameter.Name;
209        BestKnapsackSolutionAnalyzer.BestKnownSolutionParameter.Hidden = true;
210        BestKnapsackSolutionAnalyzer.KnapsackCapacityParameter.ActualName = KnapsackCapacityParameter.Name;
211        BestKnapsackSolutionAnalyzer.KnapsackCapacityParameter.Hidden = true;
212        BestKnapsackSolutionAnalyzer.WeightsParameter.ActualName = WeightsParameter.Name;
213        BestKnapsackSolutionAnalyzer.WeightsParameter.Hidden = true;
214        BestKnapsackSolutionAnalyzer.ValuesParameter.ActualName = ValuesParameter.Name;
215        BestKnapsackSolutionAnalyzer.ValuesParameter.Hidden = true;
216      }
217      foreach (var op in Operators.OfType<IKnapsackMoveEvaluator>()) {
218        operators.Add(op);
219        op.KnapsackCapacityParameter.ActualName = KnapsackCapacityParameter.Name;
220        op.KnapsackCapacityParameter.Hidden = true;
221        op.WeightsParameter.ActualName = WeightsParameter.Name;
222        op.WeightsParameter.Hidden = true;
223        op.ValuesParameter.ActualName = ValuesParameter.Name;
224        op.ValuesParameter.Hidden = true;
225
226        var bitflipMoveEval = op as IKnapsackOneBitflipMoveEvaluator;
227        if (bitflipMoveEval != null) {
228          foreach (var moveOp in Encoding.Operators.OfType<IOneBitflipMoveQualityOperator>()) {
229            moveOp.MoveQualityParameter.ActualName = bitflipMoveEval.MoveQualityParameter.ActualName;
230            moveOp.MoveQualityParameter.Hidden = true;
231          }
232        }
233      }
234      foreach (var op in Operators.OfType<ISingleObjectiveImprovementOperator>()) {
235        operators.Add(op);
236        op.SolutionParameter.ActualName = Encoding.Name;
237        op.SolutionParameter.Hidden = true;
238      }
239      foreach (var op in Operators.OfType<ISingleObjectivePathRelinker>()) {
240        operators.Add(op);
241        op.ParentsParameter.ActualName = Encoding.Name;
242        op.ParentsParameter.Hidden = true;
243      }
244      foreach (var op in Operators.OfType<ISolutionSimilarityCalculator>()) {
245        operators.Add(op);
246        op.SolutionVariableName = Encoding.Name;
247        op.QualityVariableName = Evaluator.QualityParameter.ActualName;
248      }
249
250      if (operators.Count > 0) Encoding.ConfigureOperators(Operators);
251    }
252    #endregion
253
254    private void InitializeRandomKnapsackInstance() {
255      var sysrand = new System.Random();
256
257      var itemCount = sysrand.Next(10, 100);
258      Weights = new IntArray(itemCount);
259      Values = new IntArray(itemCount);
260
261      double totalWeight = 0;
262
263      for (int i = 0; i < itemCount; i++) {
264        var value = sysrand.Next(1, 10);
265        var weight = sysrand.Next(1, 10);
266
267        Values[i] = value;
268        Weights[i] = weight;
269        totalWeight += weight;
270      }
271
272      KnapsackCapacity = (int)Math.Round(0.7 * totalWeight);
273      Dimension = Weights.Length;
274    }
275  }
276}
Note: See TracBrowser for help on using the repository browser.