Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ProblemRefactoring/HeuristicLab.Problems.Knapsack/3.3/KnapsackProblem.cs @ 14778

Last change on this file since 14778 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
RevLine 
[3070]1#region License Information
2/* HeuristicLab
[12012]3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[3070]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;
[8720]25using HeuristicLab.Analysis;
[3070]26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Encodings.BinaryVectorEncoding;
30using HeuristicLab.Optimization;
[12102]31using HeuristicLab.Optimization.Operators;
[3070]32using HeuristicLab.Parameters;
33using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
34
35namespace HeuristicLab.Problems.Knapsack {
[13173]36  [Item("Knapsack Problem (KSP)", "Represents a Knapsack problem.")]
[12504]37  [Creatable(CreatableAttribute.Categories.CombinatorialProblems, Priority = 200)]
[3070]38  [StorableClass]
[13404]39  public sealed class KnapsackProblem : SingleObjectiveProblem<BinaryVectorEncoding, BinaryVector> {
40    public override bool Maximization { get { return true; } }
[4419]41
[3070]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    }
[3787]52    public OptionalValueParameter<BinaryVector> BestKnownSolutionParameter {
53      get { return (OptionalValueParameter<BinaryVector>)Parameters["BestKnownSolution"]; }
54    }
[3070]55    #endregion
56
57    #region Properties
[13404]58    public int KnapsackCapacity {
59      get { return KnapsackCapacityParameter.Value.Value; }
60      set { KnapsackCapacityParameter.Value.Value = value; }
[3109]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    }
[3787]70    public BinaryVector BestKnownSolution {
71      get { return BestKnownSolutionParameter.Value; }
72      set { BestKnownSolutionParameter.Value = value; }
73    }
[3667]74    private BestKnapsackSolutionAnalyzer BestKnapsackSolutionAnalyzer {
[6938]75      get { return Operators.OfType<BestKnapsackSolutionAnalyzer>().FirstOrDefault(); }
[3641]76    }
[3070]77    #endregion
78
[4098]79    [StorableConstructor]
[4118]80    private KnapsackProblem(bool deserializing) : base(deserializing) { }
[4722]81    private KnapsackProblem(KnapsackProblem original, Cloner cloner)
82      : base(original, cloner) {
[7351]83      RegisterEventHandlers();
[4722]84    }
[3166]85    public KnapsackProblem()
[13404]86      : base(new BinaryVectorEncoding("Selection")) {
87      Parameters.Add(new ValueParameter<IntValue>("KnapsackCapacity", "Capacity of the Knapsack.", new IntValue(1)));
[3070]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)));
[3787]90      Parameters.Add(new OptionalValueParameter<BinaryVector>("BestKnownSolution", "The best known solution of this Knapsack instance."));
[3070]91
[13404]92      InitializeRandomKnapsackInstance();
[14429]93      Encoding.Length = Weights.Length;
[3125]94
[13404]95      InitializeOperators();
96      RegisterEventHandlers();
97    }
[6938]98
[13404]99    public override double Evaluate(BinaryVector solution, IRandom random) {
[14429]100      var weights = Weights;
101      var values = Values;
[13404]102      var totalWeight = 0.0;
103      var totalValue = 0.0;
104      for (var i = 0; i < solution.Length; i++) {
105        if (!solution[i]) continue;
[14429]106        totalWeight += weights[i];
107        totalValue += values[i];
[13404]108      }
109      return totalWeight > KnapsackCapacity ? KnapsackCapacity - totalWeight : totalValue;
110    }
[5287]111
[13404]112    public override IDeepCloneable Clone(Cloner cloner) {
113      return new KnapsackProblem(this, cloner);
114    }
[3070]115
[13404]116    [StorableHook(HookType.AfterDeserialization)]
117    private void AfterDeserialization() {
[7351]118      RegisterEventHandlers();
[3070]119    }
120
[13404]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
[3070]132    #region Events
[13404]133    protected override void OnEncodingChanged() {
134      base.OnEncodingChanged();
135      Parameterize();
136    }
[13469]137    //TODO check with abeham if this is really necessary
138    //protected override void OnSolutionCreatorChanged() {
139    //  base.OnSolutionCreatorChanged();
140    //  Parameterize();
141    //}
[6938]142    protected override void OnEvaluatorChanged() {
143      base.OnEvaluatorChanged();
[13404]144      Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged;
145      Parameterize();
[3070]146    }
[13404]147    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
148      Parameterize();
[3070]149    }
[6938]150    private void KnapsackCapacityParameter_ValueChanged(object sender, EventArgs e) {
[13404]151      Parameterize();
[3070]152    }
[6938]153    private void WeightsParameter_ValueChanged(object sender, EventArgs e) {
[13404]154      Parameterize();
155      WeightsParameter.Value.Reset += WeightsValue_Reset;
[3070]156    }
[6938]157    private void WeightsValue_Reset(object sender, EventArgs e) {
[13404]158      if (WeightsParameter.Value != null && ValuesParameter.Value != null) {
159        ((IStringConvertibleArray)ValuesParameter.Value).Length = Weights.Length;
160        Encoding.Length = Weights.Length;
161      }
162      Parameterize();
[3111]163    }
[6938]164    private void ValuesParameter_ValueChanged(object sender, EventArgs e) {
[13404]165      Parameterize();
166      ValuesParameter.Value.Reset += ValuesValue_Reset;
[3109]167    }
[6938]168    private void ValuesValue_Reset(object sender, EventArgs e) {
[13404]169      if (WeightsParameter.Value != null && ValuesParameter.Value != null) {
170        ((IStringConvertibleArray)WeightsParameter.Value).Length = Values.Length;
171        Encoding.Length = Values.Length;
172      }
173      Parameterize();
[3111]174    }
[13404]175    private void Encoding_LengthParameter_ValueChanged(object sender, EventArgs e) {
176      if (Weights.Length != Encoding.Length) {
177        ((IStringConvertibleArray)WeightsParameter.Value).Length = Encoding.Length;
[3124]178      }
[13404]179      if (Values.Length != Encoding.Length) {
180        ((IStringConvertibleArray)ValuesParameter.Value).Length = Encoding.Length;
181      }
182      Parameterize();
[3124]183    }
[3070]184    #endregion
185
186    #region Helpers
[13404]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();
[4118]199    }
[13404]200    private void Parameterize() {
201      var operators = new List<IItem>();
[4118]202
[8720]203      if (BestKnapsackSolutionAnalyzer != null) {
[13404]204        operators.Add(BestKnapsackSolutionAnalyzer);
[8720]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      }
[13404]218      foreach (var op in Operators.OfType<IKnapsackMoveEvaluator>()) {
219        operators.Add(op);
[3124]220        op.KnapsackCapacityParameter.ActualName = KnapsackCapacityParameter.Name;
[6053]221        op.KnapsackCapacityParameter.Hidden = true;
[3124]222        op.WeightsParameter.ActualName = WeightsParameter.Name;
[6053]223        op.WeightsParameter.Hidden = true;
[3124]224        op.ValuesParameter.ActualName = ValuesParameter.Name;
[6053]225        op.ValuesParameter.Hidden = true;
[13404]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        }
[3124]234      }
[13404]235      foreach (var op in Operators.OfType<ISingleObjectiveImprovementOperator>()) {
236        operators.Add(op);
237        op.SolutionParameter.ActualName = Encoding.Name;
[8334]238        op.SolutionParameter.Hidden = true;
239      }
[13404]240      foreach (var op in Operators.OfType<ISingleObjectivePathRelinker>()) {
241        operators.Add(op);
242        op.ParentsParameter.ActualName = Encoding.Name;
[8334]243        op.ParentsParameter.Hidden = true;
244      }
[13404]245      foreach (var op in Operators.OfType<ISolutionSimilarityCalculator>()) {
246        operators.Add(op);
247        op.SolutionVariableName = Encoding.Name;
[8334]248        op.QualityVariableName = Evaluator.QualityParameter.ActualName;
249      }
[13404]250
251      if (operators.Count > 0) Encoding.ConfigureOperators(Operators);
[3070]252    }
253    #endregion
[4098]254
255    private void InitializeRandomKnapsackInstance() {
[13404]256      var sysrand = new System.Random();
[4098]257
[14429]258      var power = sysrand.Next(5, 11);
259      var itemCount = (int)Math.Pow(2, power);
[4098]260      Weights = new IntArray(itemCount);
261      Values = new IntArray(itemCount);
262
263      double totalWeight = 0;
264
265      for (int i = 0; i < itemCount; i++) {
[14429]266        var value = sysrand.Next(1, 30);
267        var weight = sysrand.Next(1, 30);
[4098]268
269        Values[i] = value;
270        Weights[i] = weight;
271        totalWeight += weight;
272      }
273
[14429]274      KnapsackCapacity = (int)Math.Round(0.5 * totalWeight);
[4098]275    }
[3070]276  }
277}
Note: See TracBrowser for help on using the repository browser.