Free cookie consent management tool by TermsFeed Policy Generator

source: branches/gp-crossover/HeuristicLab.Problems.Knapsack/3.3/KnapsackProblem.cs @ 7030

Last change on this file since 7030 was 6939, checked in by abeham, 13 years ago

#1663

  • Added hiding of Maximization parameter
  • Fixed AfterDeserializationHook in KnapsackProblem
  • Ported ArtificialAntProblem to use the SingleObjectiveHeuristicOptimizationProblem base class
File size: 13.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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.Optimization;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.PluginInfrastructure;
33
34namespace HeuristicLab.Problems.Knapsack {
35  [Item("Knapsack Problem", "Represents a Knapsack problem.")]
36  [Creatable("Problems")]
37  [StorableClass]
38  public sealed class KnapsackProblem : SingleObjectiveHeuristicOptimizationProblem<IKnapsackEvaluator, IBinaryVectorCreator>, IStorableContent {
39    public string Filename { get; set; }
40
41    #region Parameter Properties
42    public ValueParameter<IntValue> KnapsackCapacityParameter {
43      get { return (ValueParameter<IntValue>)Parameters["KnapsackCapacity"]; }
44    }
45    public ValueParameter<IntArray> WeightsParameter {
46      get { return (ValueParameter<IntArray>)Parameters["Weights"]; }
47    }
48    public ValueParameter<IntArray> ValuesParameter {
49      get { return (ValueParameter<IntArray>)Parameters["Values"]; }
50    }
51    public ValueParameter<DoubleValue> PenaltyParameter {
52      get { return (ValueParameter<DoubleValue>)Parameters["Penalty"]; }
53    }
54    public OptionalValueParameter<BinaryVector> BestKnownSolutionParameter {
55      get { return (OptionalValueParameter<BinaryVector>)Parameters["BestKnownSolution"]; }
56    }
57    #endregion
58
59    #region Properties
60    public IntValue KnapsackCapacity {
61      get { return KnapsackCapacityParameter.Value; }
62      set { KnapsackCapacityParameter.Value = value; }
63    }
64    public IntArray Weights {
65      get { return WeightsParameter.Value; }
66      set { WeightsParameter.Value = value; }
67    }
68    public IntArray Values {
69      get { return ValuesParameter.Value; }
70      set { ValuesParameter.Value = value; }
71    }
72    public DoubleValue Penalty {
73      get { return PenaltyParameter.Value; }
74      set { PenaltyParameter.Value = value; }
75    }
76    public BinaryVector BestKnownSolution {
77      get { return BestKnownSolutionParameter.Value; }
78      set { BestKnownSolutionParameter.Value = value; }
79    }
80    private BestKnapsackSolutionAnalyzer BestKnapsackSolutionAnalyzer {
81      get { return Operators.OfType<BestKnapsackSolutionAnalyzer>().FirstOrDefault(); }
82    }
83    #endregion
84
85    // BackwardsCompatibility3.3
86    #region Backwards compatible code, remove with 3.4
87    [Obsolete]
88    [Storable(Name = "operators")]
89    private IEnumerable<IOperator> oldOperators {
90      get { return null; }
91      set {
92        if (value != null && value.Any())
93          Operators.AddRange(value);
94      }
95    }
96    #endregion
97
98    [StorableConstructor]
99    private KnapsackProblem(bool deserializing) : base(deserializing) { }
100    private KnapsackProblem(KnapsackProblem original, Cloner cloner)
101      : base(original, cloner) {
102      AttachEventHandlers();
103    }
104    public override IDeepCloneable Clone(Cloner cloner) {
105      return new KnapsackProblem(this, cloner);
106    }
107    public KnapsackProblem()
108      : base(new KnapsackEvaluator(), new RandomBinaryVectorCreator()) {
109      Parameters.Add(new ValueParameter<IntValue>("KnapsackCapacity", "Capacity of the Knapsack.", new IntValue(0)));
110      Parameters.Add(new ValueParameter<IntArray>("Weights", "The weights of the items.", new IntArray(5)));
111      Parameters.Add(new ValueParameter<IntArray>("Values", "The values of the items.", new IntArray(5)));
112      Parameters.Add(new ValueParameter<DoubleValue>("Penalty", "The penalty value for each unit of overweight.", new DoubleValue(1)));
113      Parameters.Add(new OptionalValueParameter<BinaryVector>("BestKnownSolution", "The best known solution of this Knapsack instance."));
114
115      Maximization.Value = true;
116      MaximizationParameter.Hidden = true;
117
118      SolutionCreator.BinaryVectorParameter.ActualName = "KnapsackSolution";
119
120      InitializeRandomKnapsackInstance();
121
122      ParameterizeSolutionCreator();
123      ParameterizeEvaluator();
124
125      InitializeOperators();
126      AttachEventHandlers();
127    }
128
129    #region Events
130    protected override void OnSolutionCreatorChanged() {
131      base.OnSolutionCreatorChanged();
132      SolutionCreator.BinaryVectorParameter.ActualNameChanged += new EventHandler(SolutionCreator_BinaryVectorParameter_ActualNameChanged);
133      ParameterizeSolutionCreator();
134      ParameterizeEvaluator();
135      ParameterizeAnalyzer();
136      ParameterizeOperators();
137    }
138    protected override void OnEvaluatorChanged() {
139      base.OnEvaluatorChanged();
140      ParameterizeEvaluator();
141      ParameterizeAnalyzer();
142    }
143    private void SolutionCreator_BinaryVectorParameter_ActualNameChanged(object sender, EventArgs e) {
144      ParameterizeEvaluator();
145      ParameterizeAnalyzer();
146      ParameterizeOperators();
147    }
148    private void KnapsackCapacityParameter_ValueChanged(object sender, EventArgs e) {
149      ParameterizeEvaluator();
150      ParameterizeAnalyzer();
151    }
152    private void WeightsParameter_ValueChanged(object sender, EventArgs e) {
153      ParameterizeEvaluator();
154      ParameterizeAnalyzer();
155      ParameterizeSolutionCreator();
156
157      WeightsParameter.Value.Reset += new EventHandler(WeightsValue_Reset);
158    }
159    private void WeightsValue_Reset(object sender, EventArgs e) {
160      ParameterizeSolutionCreator();
161
162      if (WeightsParameter.Value != null && ValuesParameter.Value != null)
163        ((IStringConvertibleArray)ValuesParameter.Value).Length = WeightsParameter.Value.Length;
164    }
165    private void ValuesParameter_ValueChanged(object sender, EventArgs e) {
166      ParameterizeEvaluator();
167      ParameterizeAnalyzer();
168      ParameterizeSolutionCreator();
169
170      ValuesParameter.Value.Reset += new EventHandler(ValuesValue_Reset);
171    }
172    private void ValuesValue_Reset(object sender, EventArgs e) {
173      ParameterizeSolutionCreator();
174
175      if (WeightsParameter.Value != null && ValuesParameter.Value != null)
176        ((IStringConvertibleArray)WeightsParameter.Value).Length = ValuesParameter.Value.Length;
177    }
178    private void PenaltyParameter_ValueChanged(object sender, EventArgs e) {
179      ParameterizeEvaluator();
180    }
181    private void OneBitflipMoveParameter_ActualNameChanged(object sender, EventArgs e) {
182      string name = ((ILookupParameter<OneBitflipMove>)sender).ActualName;
183      foreach (IOneBitflipMoveOperator op in Operators.OfType<IOneBitflipMoveOperator>()) {
184        op.OneBitflipMoveParameter.ActualName = name;
185      }
186    }
187    #endregion
188
189    #region Helpers
190    [StorableHook(HookType.AfterDeserialization)]
191    private void AfterDeserialization() {
192      // BackwardsCompatibility3.3
193      #region Backwards compatible code (remove with 3.4)
194      if (Operators.Count == 0) InitializeOperators();
195      #endregion
196      AttachEventHandlers();
197    }
198
199    private void AttachEventHandlers() {
200      SolutionCreator.BinaryVectorParameter.ActualNameChanged += new EventHandler(SolutionCreator_BinaryVectorParameter_ActualNameChanged);
201      KnapsackCapacityParameter.ValueChanged += new EventHandler(KnapsackCapacityParameter_ValueChanged);
202      WeightsParameter.ValueChanged += new EventHandler(WeightsParameter_ValueChanged);
203      WeightsParameter.Value.Reset += new EventHandler(WeightsValue_Reset);
204      ValuesParameter.ValueChanged += new EventHandler(ValuesParameter_ValueChanged);
205      ValuesParameter.Value.Reset += new EventHandler(ValuesValue_Reset);
206      PenaltyParameter.ValueChanged += new EventHandler(PenaltyParameter_ValueChanged);
207    }
208    private void ParameterizeSolutionCreator() {
209      if (SolutionCreator.LengthParameter.Value == null ||
210        SolutionCreator.LengthParameter.Value.Value != WeightsParameter.Value.Length)
211        SolutionCreator.LengthParameter.Value = new IntValue(WeightsParameter.Value.Length);
212    }
213    private void ParameterizeEvaluator() {
214      if (Evaluator is KnapsackEvaluator) {
215        KnapsackEvaluator knapsackEvaluator =
216          (KnapsackEvaluator)Evaluator;
217        knapsackEvaluator.BinaryVectorParameter.ActualName = SolutionCreator.BinaryVectorParameter.ActualName;
218        knapsackEvaluator.BinaryVectorParameter.Hidden = true;
219        knapsackEvaluator.KnapsackCapacityParameter.ActualName = KnapsackCapacityParameter.Name;
220        knapsackEvaluator.KnapsackCapacityParameter.Hidden = true;
221        knapsackEvaluator.WeightsParameter.ActualName = WeightsParameter.Name;
222        knapsackEvaluator.WeightsParameter.Hidden = true;
223        knapsackEvaluator.ValuesParameter.ActualName = ValuesParameter.Name;
224        knapsackEvaluator.ValuesParameter.Hidden = true;
225        knapsackEvaluator.PenaltyParameter.ActualName = PenaltyParameter.Name;
226        knapsackEvaluator.PenaltyParameter.Hidden = true;
227      }
228    }
229    private void ParameterizeAnalyzer() {
230      BestKnapsackSolutionAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
231      BestKnapsackSolutionAnalyzer.MaximizationParameter.Hidden = true;
232      BestKnapsackSolutionAnalyzer.BestKnownQualityParameter.ActualName = BestKnownQualityParameter.Name;
233      BestKnapsackSolutionAnalyzer.BestKnownQualityParameter.Hidden = true;
234      BestKnapsackSolutionAnalyzer.BestKnownSolutionParameter.ActualName = BestKnownSolutionParameter.Name;
235      BestKnapsackSolutionAnalyzer.BestKnownSolutionParameter.Hidden = true;
236      BestKnapsackSolutionAnalyzer.BinaryVectorParameter.ActualName = SolutionCreator.BinaryVectorParameter.ActualName;
237      BestKnapsackSolutionAnalyzer.BinaryVectorParameter.Hidden = true;
238      BestKnapsackSolutionAnalyzer.KnapsackCapacityParameter.ActualName = KnapsackCapacityParameter.Name;
239      BestKnapsackSolutionAnalyzer.KnapsackCapacityParameter.Hidden = true;
240      BestKnapsackSolutionAnalyzer.WeightsParameter.ActualName = WeightsParameter.Name;
241      BestKnapsackSolutionAnalyzer.WeightsParameter.Hidden = true;
242      BestKnapsackSolutionAnalyzer.ValuesParameter.ActualName = ValuesParameter.Name;
243      BestKnapsackSolutionAnalyzer.ValuesParameter.Hidden = true;
244    }
245    private void InitializeOperators() {
246      Operators.Add(new BestKnapsackSolutionAnalyzer());
247      ParameterizeAnalyzer();
248      foreach (IBinaryVectorOperator op in ApplicationManager.Manager.GetInstances<IBinaryVectorOperator>()) {
249        if (!(op is ISingleObjectiveMoveEvaluator) || (op is IKnapsackMoveEvaluator)) {
250          Operators.Add(op);
251        }
252      }
253      ParameterizeOperators();
254      InitializeMoveGenerators();
255    }
256    private void InitializeMoveGenerators() {
257      foreach (IOneBitflipMoveOperator op in Operators.OfType<IOneBitflipMoveOperator>()) {
258        if (op is IMoveGenerator) {
259          op.OneBitflipMoveParameter.ActualNameChanged += new EventHandler(OneBitflipMoveParameter_ActualNameChanged);
260        }
261      }
262    }
263    private void ParameterizeOperators() {
264      foreach (IBinaryVectorCrossover op in Operators.OfType<IBinaryVectorCrossover>()) {
265        op.ParentsParameter.ActualName = SolutionCreator.BinaryVectorParameter.ActualName;
266        op.ParentsParameter.Hidden = true;
267        op.ChildParameter.ActualName = SolutionCreator.BinaryVectorParameter.ActualName;
268        op.ChildParameter.Hidden = true;
269      }
270      foreach (IBinaryVectorManipulator op in Operators.OfType<IBinaryVectorManipulator>()) {
271        op.BinaryVectorParameter.ActualName = SolutionCreator.BinaryVectorParameter.ActualName;
272        op.BinaryVectorParameter.Hidden = true;
273      }
274      foreach (IBinaryVectorMoveOperator op in Operators.OfType<IBinaryVectorMoveOperator>()) {
275        op.BinaryVectorParameter.ActualName = SolutionCreator.BinaryVectorParameter.ActualName;
276        op.BinaryVectorParameter.Hidden = true;
277      }
278      foreach (IKnapsackMoveEvaluator op in Operators.OfType<IKnapsackMoveEvaluator>()) {
279        op.KnapsackCapacityParameter.ActualName = KnapsackCapacityParameter.Name;
280        op.KnapsackCapacityParameter.Hidden = true;
281        op.PenaltyParameter.ActualName = PenaltyParameter.Name;
282        op.PenaltyParameter.Hidden = true;
283        op.WeightsParameter.ActualName = WeightsParameter.Name;
284        op.WeightsParameter.Hidden = true;
285        op.ValuesParameter.ActualName = ValuesParameter.Name;
286        op.ValuesParameter.Hidden = true;
287      }
288      foreach (var op in Operators.OfType<IBinaryVectorMultiNeighborhoodShakingOperator>()) {
289        op.BinaryVectorParameter.ActualName = SolutionCreator.BinaryVectorParameter.ActualName;
290        op.BinaryVectorParameter.Hidden = true;
291      }
292    }
293    #endregion
294
295    private void InitializeRandomKnapsackInstance() {
296      System.Random rand = new System.Random();
297
298      int itemCount = rand.Next(10, 100);
299      Weights = new IntArray(itemCount);
300      Values = new IntArray(itemCount);
301
302      double totalWeight = 0;
303
304      for (int i = 0; i < itemCount; i++) {
305        int value = rand.Next(1, 10);
306        int weight = rand.Next(1, 10);
307
308        Values[i] = value;
309        Weights[i] = weight;
310        totalWeight += weight;
311      }
312
313      int capacity = (int)Math.Round(0.7 * totalWeight);
314      KnapsackCapacity = new IntValue(capacity);
315    }
316  }
317}
Note: See TracBrowser for help on using the repository browser.