Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GP-MoveOperators/HeuristicLab.Problems.Knapsack/3.3/KnapsackProblem.cs @ 10781

Last change on this file since 10781 was 8660, checked in by gkronber, 12 years ago

#1847 merged r8205:8635 from trunk into branch

File size: 15.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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      RegisterEventHandlers();
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      RegisterEventHandlers();
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      RegisterEventHandlers();
197    }
198
199    private void RegisterEventHandlers() {
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 KnapsackImprovementOperator());
247      Operators.Add(new KnapsackPathRelinker());
248      Operators.Add(new KnapsackSimultaneousPathRelinker());
249      Operators.Add(new KnapsackSimilarityCalculator());
250
251      Operators.Add(new BestKnapsackSolutionAnalyzer());
252      ParameterizeAnalyzer();
253      foreach (IBinaryVectorOperator op in ApplicationManager.Manager.GetInstances<IBinaryVectorOperator>()) {
254        if (!(op is ISingleObjectiveMoveEvaluator) || (op is IKnapsackMoveEvaluator)) {
255          Operators.Add(op);
256        }
257      }
258      ParameterizeOperators();
259      InitializeMoveGenerators();
260    }
261    private void InitializeMoveGenerators() {
262      foreach (IOneBitflipMoveOperator op in Operators.OfType<IOneBitflipMoveOperator>()) {
263        if (op is IMoveGenerator) {
264          op.OneBitflipMoveParameter.ActualNameChanged += new EventHandler(OneBitflipMoveParameter_ActualNameChanged);
265        }
266      }
267    }
268    private void ParameterizeOperators() {
269      foreach (IBinaryVectorCrossover op in Operators.OfType<IBinaryVectorCrossover>()) {
270        op.ParentsParameter.ActualName = SolutionCreator.BinaryVectorParameter.ActualName;
271        op.ParentsParameter.Hidden = true;
272        op.ChildParameter.ActualName = SolutionCreator.BinaryVectorParameter.ActualName;
273        op.ChildParameter.Hidden = true;
274      }
275      foreach (IBinaryVectorManipulator op in Operators.OfType<IBinaryVectorManipulator>()) {
276        op.BinaryVectorParameter.ActualName = SolutionCreator.BinaryVectorParameter.ActualName;
277        op.BinaryVectorParameter.Hidden = true;
278      }
279      foreach (IBinaryVectorMoveOperator op in Operators.OfType<IBinaryVectorMoveOperator>()) {
280        op.BinaryVectorParameter.ActualName = SolutionCreator.BinaryVectorParameter.ActualName;
281        op.BinaryVectorParameter.Hidden = true;
282      }
283      foreach (IKnapsackMoveEvaluator op in Operators.OfType<IKnapsackMoveEvaluator>()) {
284        op.KnapsackCapacityParameter.ActualName = KnapsackCapacityParameter.Name;
285        op.KnapsackCapacityParameter.Hidden = true;
286        op.PenaltyParameter.ActualName = PenaltyParameter.Name;
287        op.PenaltyParameter.Hidden = true;
288        op.WeightsParameter.ActualName = WeightsParameter.Name;
289        op.WeightsParameter.Hidden = true;
290        op.ValuesParameter.ActualName = ValuesParameter.Name;
291        op.ValuesParameter.Hidden = true;
292      }
293      foreach (IBinaryVectorMultiNeighborhoodShakingOperator op in Operators.OfType<IBinaryVectorMultiNeighborhoodShakingOperator>()) {
294        op.BinaryVectorParameter.ActualName = SolutionCreator.BinaryVectorParameter.ActualName;
295        op.BinaryVectorParameter.Hidden = true;
296      }
297      foreach (ISingleObjectiveImprovementOperator op in Operators.OfType<ISingleObjectiveImprovementOperator>()) {
298        op.SolutionParameter.ActualName = SolutionCreator.BinaryVectorParameter.ActualName;
299        op.SolutionParameter.Hidden = true;
300      }
301      foreach (ISingleObjectivePathRelinker op in Operators.OfType<ISingleObjectivePathRelinker>()) {
302        op.ParentsParameter.ActualName = SolutionCreator.BinaryVectorParameter.ActualName;
303        op.ParentsParameter.Hidden = true;
304      }
305      foreach (KnapsackSimilarityCalculator op in Operators.OfType<KnapsackSimilarityCalculator>()) {
306        op.SolutionVariableName = SolutionCreator.BinaryVectorParameter.ActualName;
307        op.QualityVariableName = Evaluator.QualityParameter.ActualName;
308      }
309    }
310    #endregion
311
312    private void InitializeRandomKnapsackInstance() {
313      System.Random rand = new System.Random();
314
315      int itemCount = rand.Next(10, 100);
316      Weights = new IntArray(itemCount);
317      Values = new IntArray(itemCount);
318
319      double totalWeight = 0;
320
321      for (int i = 0; i < itemCount; i++) {
322        int value = rand.Next(1, 10);
323        int weight = rand.Next(1, 10);
324
325        Values[i] = value;
326        Weights[i] = weight;
327        totalWeight += weight;
328      }
329
330      int capacity = (int)Math.Round(0.7 * totalWeight);
331      KnapsackCapacity = new IntValue(capacity);
332    }
333  }
334}
Note: See TracBrowser for help on using the repository browser.