Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.Knapsack/3.3/KnapsackProblem.cs @ 3494

Last change on this file since 3494 was 3467, checked in by svonolfe, 15 years ago

Added simple view for the KnapsackProblem (#917)

File size: 15.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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.Drawing;
25using System.Linq;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Encodings.BinaryVectorEncoding;
30using HeuristicLab.Optimization;
31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33using HeuristicLab.PluginInfrastructure;
34using HeuristicLab.Problems.Knapsack.Visualizers;
35
36namespace HeuristicLab.Problems.Knapsack {
37  [Item("KnapsackProblem", "Represents a Knapsack Problem.")]
38  [Creatable("Problems")]
39  [StorableClass]
40  public sealed class KnapsackProblem : ParameterizedNamedItem, ISingleObjectiveProblem {
41    public override Image ItemImage {
42      get { return HeuristicLab.Common.Resources.VS2008ImageLibrary.Type; }
43    }
44
45    #region Parameter Properties
46    public ValueParameter<BoolValue> MaximizationParameter {
47      get { return (ValueParameter<BoolValue>)Parameters["Maximization"]; }
48    }
49    IParameter ISingleObjectiveProblem.MaximizationParameter {
50      get { return MaximizationParameter; }
51    }
52    public ValueParameter<IntValue> KnapsackCapacityParameter {
53      get { return (ValueParameter<IntValue>)Parameters["KnapsackCapacity"]; }
54    }
55    public ValueParameter<IntArray> WeightsParameter {
56      get { return (ValueParameter<IntArray>)Parameters["Weights"]; }
57    }
58    public ValueParameter<IntArray> ValuesParameter {
59      get { return (ValueParameter<IntArray>)Parameters["Values"]; }
60    }
61    public ValueParameter<DoubleValue> PenaltyParameter {
62      get { return (ValueParameter<DoubleValue>)Parameters["Penalty"]; }
63    }
64    public ValueParameter<IBinaryVectorCreator> SolutionCreatorParameter {
65      get { return (ValueParameter<IBinaryVectorCreator>)Parameters["SolutionCreator"]; }
66    }
67    IParameter IProblem.SolutionCreatorParameter {
68      get { return SolutionCreatorParameter; }
69    }
70    public ValueParameter<IKnapsackEvaluator> EvaluatorParameter {
71      get { return (ValueParameter<IKnapsackEvaluator>)Parameters["Evaluator"]; }
72    }
73    IParameter IProblem.EvaluatorParameter {
74      get { return EvaluatorParameter; }
75    }
76    public OptionalValueParameter<IKnapsackSolutionsVisualizer> VisualizerParameter {
77      get { return (OptionalValueParameter<IKnapsackSolutionsVisualizer>)Parameters["Visualizer"]; }
78    }
79    IParameter IProblem.VisualizerParameter {
80      get { return VisualizerParameter; }
81    } 
82    public OptionalValueParameter<DoubleValue> BestKnownQualityParameter {
83      get { return (OptionalValueParameter<DoubleValue>)Parameters["BestKnownQuality"]; }
84    }
85    IParameter ISingleObjectiveProblem.BestKnownQualityParameter {
86      get { return BestKnownQualityParameter; }
87    }
88    #endregion
89
90    #region Properties
91    public IntValue KnapsackCapacity {
92      get { return KnapsackCapacityParameter.Value; }
93      set { KnapsackCapacityParameter.Value = value; }
94    }
95    public IntArray Weights {
96      get { return WeightsParameter.Value; }
97      set { WeightsParameter.Value = value; }
98    }
99    public IntArray Values {
100      get { return ValuesParameter.Value; }
101      set { ValuesParameter.Value = value; }
102    }
103    public DoubleValue Penalty {
104      get { return PenaltyParameter.Value; }
105      set { PenaltyParameter.Value = value; }
106    }
107    public IBinaryVectorCreator SolutionCreator {
108      get { return SolutionCreatorParameter.Value; }
109      set { SolutionCreatorParameter.Value = value; }
110    }
111    ISolutionCreator IProblem.SolutionCreator {
112      get { return SolutionCreatorParameter.Value; }
113    }
114    public IKnapsackEvaluator Evaluator {
115      get { return EvaluatorParameter.Value; }
116      set { EvaluatorParameter.Value = value; }
117    }
118    ISingleObjectiveEvaluator ISingleObjectiveProblem.Evaluator {
119      get { return EvaluatorParameter.Value; }
120    }
121    IEvaluator IProblem.Evaluator {
122      get { return EvaluatorParameter.Value; }
123    }
124    public IKnapsackSolutionsVisualizer Visualizer {
125      get { return VisualizerParameter.Value; }
126      set { VisualizerParameter.Value = value; }
127    }
128    ISolutionsVisualizer IProblem.Visualizer {
129      get { return VisualizerParameter.Value; }
130    }
131    public DoubleValue BestKnownQuality {
132      get { return BestKnownQualityParameter.Value; }
133      set { BestKnownQualityParameter.Value = value; }
134    }
135    private List<IBinaryVectorOperator> operators;
136    public IEnumerable<IOperator> Operators {
137      get { return operators.Cast<IOperator>(); }
138    }
139    #endregion
140
141    private void InitializeRandomKnapsackInstance() {
142      System.Random rand = new System.Random();
143
144      int itemCount = rand.Next(10, 100);
145      int capacity = itemCount * 5;
146
147      KnapsackCapacity = new IntValue(capacity);
148      Weights = new IntArray(itemCount);
149      Values = new IntArray(itemCount);
150
151      for (int i = 0; i < itemCount; i++ ) {
152        int value = rand.Next(1, 10);
153        int weight = rand.Next(1, 10);
154
155        Values[i] = value;
156        Weights[i] = weight;
157      }
158    }
159
160    public KnapsackProblem()
161      : base() {
162      RandomBinaryVectorCreator creator = new RandomBinaryVectorCreator();
163      KnapsackEvaluator evaluator = new KnapsackEvaluator();
164      IKnapsackSolutionsVisualizer visualizer = new BestKnapsackVisualizer();
165
166      Parameters.Add(new ValueParameter<BoolValue>("Maximization", "Set to true as the Knapsack Problem is a maximization problem.", new BoolValue(true)));
167      Parameters.Add(new ValueParameter<IntValue>("KnapsackCapacity", "Capacity of the Knapsack.", new IntValue(0)));
168      Parameters.Add(new ValueParameter<IntArray>("Weights", "The weights of the items.", new IntArray(5)));
169      Parameters.Add(new ValueParameter<IntArray>("Values", "The values of the items.", new IntArray(5)));
170      Parameters.Add(new ValueParameter<DoubleValue>("Penalty", "The penalty value for each unit of overweight.", new DoubleValue(1)));
171      Parameters.Add(new ValueParameter<IBinaryVectorCreator>("SolutionCreator", "The operator which should be used to create new Knapsack solutions.", creator));
172      Parameters.Add(new ValueParameter<IKnapsackEvaluator>("Evaluator", "The operator which should be used to evaluate Knapsack solutions.", evaluator));
173      Parameters.Add(new OptionalValueParameter<DoubleValue>("BestKnownQuality", "The quality of the best known solution of this Knapsack instance."));
174      Parameters.Add(new ValueParameter<IKnapsackSolutionsVisualizer>("Visualizer", "The operator which should be used to visualize Knapsack solutions.", visualizer));
175
176      creator.BinaryVectorParameter.ActualName = "KnapsackSolution";
177      evaluator.QualityParameter.ActualName = "NumberOfOnes";
178
179      InitializeRandomKnapsackInstance();
180     
181      ParameterizeSolutionCreator();
182      ParameterizeEvaluator();
183      ParameterizeVisualizer();
184
185      Initialize();
186    }
187
188    [StorableConstructor]
189    private KnapsackProblem(bool deserializing) : base() { }
190
191    public override IDeepCloneable Clone(Cloner cloner) {
192      KnapsackProblem clone = (KnapsackProblem)base.Clone(cloner);
193      clone.Initialize();
194      return clone;
195    }
196
197    #region Events
198    public event EventHandler SolutionCreatorChanged;
199    private void OnSolutionCreatorChanged() {
200      if (SolutionCreatorChanged != null)
201        SolutionCreatorChanged(this, EventArgs.Empty);
202    }
203    public event EventHandler EvaluatorChanged;
204    private void OnEvaluatorChanged() {
205      if (EvaluatorChanged != null)
206        EvaluatorChanged(this, EventArgs.Empty);
207    }
208    public event EventHandler VisualizerChanged;
209    private void OnVisualizerChanged() {
210      if (VisualizerChanged != null)
211        VisualizerChanged(this, EventArgs.Empty);
212    }
213
214    public event EventHandler OperatorsChanged;
215    private void OnOperatorsChanged() {
216      if (OperatorsChanged != null)
217        OperatorsChanged(this, EventArgs.Empty);
218    }
219
220    private void SolutionCreatorParameter_ValueChanged(object sender, EventArgs e) {
221      SolutionCreator.BinaryVectorParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
222      ParameterizeSolutionCreator();
223      ParameterizeEvaluator();
224      ParameterizeVisualizer();
225      ParameterizeOperators();
226      OnSolutionCreatorChanged();
227    }
228    private void SolutionCreator_PermutationParameter_ActualNameChanged(object sender, EventArgs e) {
229      ParameterizeEvaluator();
230      ParameterizeVisualizer();
231      ParameterizeOperators();
232    }
233    private void EvaluatorParameter_ValueChanged(object sender, EventArgs e) {
234      ParameterizeEvaluator();
235      ParameterizeVisualizer();
236      OnEvaluatorChanged();
237    }
238    void KnapsackCapacityParameter_ValueChanged(object sender, EventArgs e) {
239      ParameterizeEvaluator();
240      ParameterizeVisualizer();
241    }
242    void WeightsParameter_ValueChanged(object sender, EventArgs e) {
243      ParameterizeEvaluator();
244      ParameterizeVisualizer();
245      ParameterizeSolutionCreator();
246
247      WeightsParameter.Value.Reset += new EventHandler(WeightsValue_Reset);
248    }
249    void WeightsValue_Reset(object sender, EventArgs e) {
250      ParameterizeSolutionCreator();
251
252      if (WeightsParameter.Value != null && ValuesParameter.Value != null)
253        ((IStringConvertibleArray)ValuesParameter.Value).Length = WeightsParameter.Value.Length;
254    }
255    void ValuesParameter_ValueChanged(object sender, EventArgs e) {
256      ParameterizeEvaluator();
257      ParameterizeVisualizer();
258      ParameterizeSolutionCreator();
259
260      ValuesParameter.Value.Reset += new EventHandler(ValuesValue_Reset);
261    }
262    void ValuesValue_Reset(object sender, EventArgs e) {
263      ParameterizeSolutionCreator();
264
265      if (WeightsParameter.Value != null && ValuesParameter.Value != null)
266        ((IStringConvertibleArray)WeightsParameter.Value).Length = ValuesParameter.Value.Length;
267    }
268    void PenaltyParameter_ValueChanged(object sender, EventArgs e) {
269      ParameterizeEvaluator();
270    }
271    void VisualizerParameter_ValueChanged(object sender, EventArgs e) {
272      OnVisualizerChanged();
273    }
274    void OneBitflipMoveParameter_ActualNameChanged(object sender, EventArgs e) {
275      string name = ((ILookupParameter<OneBitflipMove>)sender).ActualName;
276      foreach (IOneBitflipMoveOperator op in Operators.OfType<IOneBitflipMoveOperator>()) {
277        op.OneBitflipMoveParameter.ActualName = name;
278      }
279    }
280    #endregion
281
282    #region Helpers
283    [StorableHook(HookType.AfterDeserialization)]
284    private void Initialize() {
285      InitializeOperators();
286      SolutionCreatorParameter.ValueChanged += new EventHandler(SolutionCreatorParameter_ValueChanged);
287      SolutionCreator.BinaryVectorParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
288      EvaluatorParameter.ValueChanged += new EventHandler(EvaluatorParameter_ValueChanged);
289      KnapsackCapacityParameter.ValueChanged += new EventHandler(KnapsackCapacityParameter_ValueChanged);
290      WeightsParameter.ValueChanged += new EventHandler(WeightsParameter_ValueChanged);
291      WeightsParameter.Value.Reset += new EventHandler(WeightsValue_Reset);
292      ValuesParameter.ValueChanged += new EventHandler(ValuesParameter_ValueChanged);
293      ValuesParameter.Value.Reset += new EventHandler(ValuesValue_Reset);
294      PenaltyParameter.ValueChanged += new EventHandler(PenaltyParameter_ValueChanged);
295      VisualizerParameter.ValueChanged += new EventHandler(VisualizerParameter_ValueChanged);
296    }
297    private void ParameterizeSolutionCreator() {
298      if(SolutionCreator.LengthParameter.Value == null ||
299        SolutionCreator.LengthParameter.Value.Value != WeightsParameter.Value.Length)
300        SolutionCreator.LengthParameter.Value = new IntValue(WeightsParameter.Value.Length);
301    }
302    private void ParameterizeEvaluator() {
303      if (Evaluator is KnapsackEvaluator) {
304        KnapsackEvaluator knapsackEvaluator =
305          (KnapsackEvaluator)Evaluator;
306        knapsackEvaluator.BinaryVectorParameter.ActualName = SolutionCreator.BinaryVectorParameter.ActualName;
307        knapsackEvaluator.KnapsackCapacityParameter.ActualName = KnapsackCapacityParameter.Name;
308        knapsackEvaluator.WeightsParameter.ActualName = WeightsParameter.Name;
309        knapsackEvaluator.ValuesParameter.ActualName = ValuesParameter.Name;
310        knapsackEvaluator.PenaltyParameter.ActualName = PenaltyParameter.Name;
311      }
312    }
313    private void ParameterizeVisualizer() {
314      if (Visualizer is IKnapsackSolutionsVisualizer) {
315        IKnapsackSolutionsVisualizer visualizer =
316          (IKnapsackSolutionsVisualizer)Visualizer;
317        visualizer.BinaryVectorParameter.ActualName = SolutionCreator.BinaryVectorParameter.ActualName;
318        visualizer.KnapsackCapacityParameter.ActualName = KnapsackCapacityParameter.Name;
319        visualizer.WeightsParameter.ActualName = WeightsParameter.Name;
320        visualizer.ValuesParameter.ActualName = ValuesParameter.Name;
321      }
322    }
323    private void InitializeOperators() {
324      operators = new List<IBinaryVectorOperator>();
325      foreach (IBinaryVectorOperator op in ApplicationManager.Manager.GetInstances<IBinaryVectorOperator>()) {
326        if (!(op is ISingleObjectiveMoveEvaluator) || (op is IKnapsackMoveEvaluator)) {
327          operators.Add(op);
328        }
329      }
330      ParameterizeOperators();
331      InitializeMoveGenerators();
332    }
333    private void InitializeMoveGenerators() {
334      foreach (IOneBitflipMoveOperator op in Operators.OfType<IOneBitflipMoveOperator>()) {
335        if (op is IMoveGenerator) {
336          op.OneBitflipMoveParameter.ActualNameChanged += new EventHandler(OneBitflipMoveParameter_ActualNameChanged);
337        }
338      }
339    }
340    private void ParameterizeOperators() {
341      foreach (IBinaryVectorCrossover op in Operators.OfType<IBinaryVectorCrossover>()) {
342        op.ParentsParameter.ActualName = SolutionCreator.BinaryVectorParameter.ActualName;
343        op.ChildParameter.ActualName = SolutionCreator.BinaryVectorParameter.ActualName;
344      }
345      foreach (IBinaryVectorManipulator op in Operators.OfType<IBinaryVectorManipulator>()) {
346        op.BinaryVectorParameter.ActualName = SolutionCreator.BinaryVectorParameter.ActualName;
347      }
348      foreach (IBinaryVectorMoveOperator op in Operators.OfType<IBinaryVectorMoveOperator>()) {
349        op.BinaryVectorParameter.ActualName = SolutionCreator.BinaryVectorParameter.ActualName;
350      }
351      foreach (IKnapsackMoveEvaluator op in Operators.OfType<IKnapsackMoveEvaluator>()) {
352        op.KnapsackCapacityParameter.ActualName = KnapsackCapacityParameter.Name;
353        op.PenaltyParameter.ActualName = PenaltyParameter.Name;
354        op.WeightsParameter.ActualName = WeightsParameter.Name;
355        op.ValuesParameter.ActualName = ValuesParameter.Name;
356      }
357    }
358    #endregion
359  }
360}
Note: See TracBrowser for help on using the repository browser.