Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3667 was 3667, checked in by svonolfe, 15 years ago
  • Updated OneMax analyzer
  • Updated Knapsack analyzer
  • Fixed bug in OneMax and TF analyzer views

(#999)

File size: 14.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.Analyzers;
35
36namespace HeuristicLab.Problems.Knapsack {
37  [Item("Knapsack Problem", "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<DoubleValue> BestKnownQualityParameter {
77      get { return (OptionalValueParameter<DoubleValue>)Parameters["BestKnownQuality"]; }
78    }
79    IParameter ISingleObjectiveProblem.BestKnownQualityParameter {
80      get { return BestKnownQualityParameter; }
81    }
82    #endregion
83
84    #region Properties
85    public IntValue KnapsackCapacity {
86      get { return KnapsackCapacityParameter.Value; }
87      set { KnapsackCapacityParameter.Value = value; }
88    }
89    public IntArray Weights {
90      get { return WeightsParameter.Value; }
91      set { WeightsParameter.Value = value; }
92    }
93    public IntArray Values {
94      get { return ValuesParameter.Value; }
95      set { ValuesParameter.Value = value; }
96    }
97    public DoubleValue Penalty {
98      get { return PenaltyParameter.Value; }
99      set { PenaltyParameter.Value = value; }
100    }
101    public IBinaryVectorCreator SolutionCreator {
102      get { return SolutionCreatorParameter.Value; }
103      set { SolutionCreatorParameter.Value = value; }
104    }
105    ISolutionCreator IProblem.SolutionCreator {
106      get { return SolutionCreatorParameter.Value; }
107    }
108    public IKnapsackEvaluator Evaluator {
109      get { return EvaluatorParameter.Value; }
110      set { EvaluatorParameter.Value = value; }
111    }
112    ISingleObjectiveEvaluator ISingleObjectiveProblem.Evaluator {
113      get { return EvaluatorParameter.Value; }
114    }
115    IEvaluator IProblem.Evaluator {
116      get { return EvaluatorParameter.Value; }
117    }
118    public DoubleValue BestKnownQuality {
119      get { return BestKnownQualityParameter.Value; }
120      set { BestKnownQualityParameter.Value = value; }
121    }
122    private List<IOperator> operators;
123    public IEnumerable<IOperator> Operators {
124      get { return operators.Cast<IOperator>(); }
125    }
126    private BestKnapsackSolutionAnalyzer BestKnapsackSolutionAnalyzer {
127      get { return operators.OfType<BestKnapsackSolutionAnalyzer>().FirstOrDefault(); }
128    }
129    #endregion
130
131    private void InitializeRandomKnapsackInstance() {
132      System.Random rand = new System.Random();
133
134      int itemCount = rand.Next(10, 100);
135      Weights = new IntArray(itemCount);
136      Values = new IntArray(itemCount);
137
138      double totalWeight = 0;
139
140      for (int i = 0; i < itemCount; i++ ) {
141        int value = rand.Next(1, 10);
142        int weight = rand.Next(1, 10);
143
144        Values[i] = value;
145        Weights[i] = weight;
146        totalWeight += weight;
147      }
148
149      int capacity = (int)Math.Round(0.7 * totalWeight);
150      KnapsackCapacity = new IntValue(capacity);
151    }
152
153    public KnapsackProblem()
154      : base() {
155      RandomBinaryVectorCreator creator = new RandomBinaryVectorCreator();
156      KnapsackEvaluator evaluator = new KnapsackEvaluator();
157
158      Parameters.Add(new ValueParameter<BoolValue>("Maximization", "Set to true as the Knapsack Problem is a maximization problem.", new BoolValue(true)));
159      Parameters.Add(new ValueParameter<IntValue>("KnapsackCapacity", "Capacity of the Knapsack.", new IntValue(0)));
160      Parameters.Add(new ValueParameter<IntArray>("Weights", "The weights of the items.", new IntArray(5)));
161      Parameters.Add(new ValueParameter<IntArray>("Values", "The values of the items.", new IntArray(5)));
162      Parameters.Add(new ValueParameter<DoubleValue>("Penalty", "The penalty value for each unit of overweight.", new DoubleValue(1)));
163      Parameters.Add(new ValueParameter<IBinaryVectorCreator>("SolutionCreator", "The operator which should be used to create new Knapsack solutions.", creator));
164      Parameters.Add(new ValueParameter<IKnapsackEvaluator>("Evaluator", "The operator which should be used to evaluate Knapsack solutions.", evaluator));
165      Parameters.Add(new OptionalValueParameter<DoubleValue>("BestKnownQuality", "The quality of the best known solution of this Knapsack instance."));
166
167      creator.BinaryVectorParameter.ActualName = "KnapsackSolution";
168
169      InitializeRandomKnapsackInstance();
170     
171      ParameterizeSolutionCreator();
172      ParameterizeEvaluator();
173
174      Initialize();
175    }
176
177    [StorableConstructor]
178    private KnapsackProblem(bool deserializing) : base() { }
179
180    public override IDeepCloneable Clone(Cloner cloner) {
181      KnapsackProblem clone = (KnapsackProblem)base.Clone(cloner);
182      clone.Initialize();
183      return clone;
184    }
185
186    #region Events
187    public event EventHandler SolutionCreatorChanged;
188    private void OnSolutionCreatorChanged() {
189      if (SolutionCreatorChanged != null)
190        SolutionCreatorChanged(this, EventArgs.Empty);
191    }
192    public event EventHandler EvaluatorChanged;
193    private void OnEvaluatorChanged() {
194      if (EvaluatorChanged != null)
195        EvaluatorChanged(this, EventArgs.Empty);
196    }
197
198    public event EventHandler OperatorsChanged;
199    private void OnOperatorsChanged() {
200      if (OperatorsChanged != null)
201        OperatorsChanged(this, EventArgs.Empty);
202    }
203
204    private void SolutionCreatorParameter_ValueChanged(object sender, EventArgs e) {
205      SolutionCreator.BinaryVectorParameter.ActualNameChanged += new EventHandler(SolutionCreator_BinaryVectorParameter_ActualNameChanged);
206      ParameterizeSolutionCreator();
207      ParameterizeEvaluator();
208      ParameterizeAnalyzer();
209      ParameterizeOperators();
210      OnSolutionCreatorChanged();
211    }
212    private void SolutionCreator_BinaryVectorParameter_ActualNameChanged(object sender, EventArgs e) {
213      ParameterizeEvaluator();
214      ParameterizeAnalyzer();
215      ParameterizeOperators();
216    }
217    private void EvaluatorParameter_ValueChanged(object sender, EventArgs e) {
218      ParameterizeEvaluator();
219      ParameterizeAnalyzer();
220      OnEvaluatorChanged();
221    }
222    void KnapsackCapacityParameter_ValueChanged(object sender, EventArgs e) {
223      ParameterizeEvaluator();
224      ParameterizeAnalyzer();
225    }
226    void WeightsParameter_ValueChanged(object sender, EventArgs e) {
227      ParameterizeEvaluator();
228      ParameterizeAnalyzer();
229      ParameterizeSolutionCreator();
230
231      WeightsParameter.Value.Reset += new EventHandler(WeightsValue_Reset);
232    }
233    void WeightsValue_Reset(object sender, EventArgs e) {
234      ParameterizeSolutionCreator();
235
236      if (WeightsParameter.Value != null && ValuesParameter.Value != null)
237        ((IStringConvertibleArray)ValuesParameter.Value).Length = WeightsParameter.Value.Length;
238    }
239    void ValuesParameter_ValueChanged(object sender, EventArgs e) {
240      ParameterizeEvaluator();
241      ParameterizeAnalyzer();
242      ParameterizeSolutionCreator();
243
244      ValuesParameter.Value.Reset += new EventHandler(ValuesValue_Reset);
245    }
246    void ValuesValue_Reset(object sender, EventArgs e) {
247      ParameterizeSolutionCreator();
248
249      if (WeightsParameter.Value != null && ValuesParameter.Value != null)
250        ((IStringConvertibleArray)WeightsParameter.Value).Length = ValuesParameter.Value.Length;
251    }
252    void PenaltyParameter_ValueChanged(object sender, EventArgs e) {
253      ParameterizeEvaluator();
254    }
255    void OneBitflipMoveParameter_ActualNameChanged(object sender, EventArgs e) {
256      string name = ((ILookupParameter<OneBitflipMove>)sender).ActualName;
257      foreach (IOneBitflipMoveOperator op in Operators.OfType<IOneBitflipMoveOperator>()) {
258        op.OneBitflipMoveParameter.ActualName = name;
259      }
260    }
261    #endregion
262
263    #region Helpers
264    [StorableHook(HookType.AfterDeserialization)]
265    private void Initialize() {
266      InitializeOperators();
267      SolutionCreatorParameter.ValueChanged += new EventHandler(SolutionCreatorParameter_ValueChanged);
268      SolutionCreator.BinaryVectorParameter.ActualNameChanged += new EventHandler(SolutionCreator_BinaryVectorParameter_ActualNameChanged);
269      EvaluatorParameter.ValueChanged += new EventHandler(EvaluatorParameter_ValueChanged);
270      KnapsackCapacityParameter.ValueChanged += new EventHandler(KnapsackCapacityParameter_ValueChanged);
271      WeightsParameter.ValueChanged += new EventHandler(WeightsParameter_ValueChanged);
272      WeightsParameter.Value.Reset += new EventHandler(WeightsValue_Reset);
273      ValuesParameter.ValueChanged += new EventHandler(ValuesParameter_ValueChanged);
274      ValuesParameter.Value.Reset += new EventHandler(ValuesValue_Reset);
275      PenaltyParameter.ValueChanged += new EventHandler(PenaltyParameter_ValueChanged);
276    }
277    private void ParameterizeSolutionCreator() {
278      if(SolutionCreator.LengthParameter.Value == null ||
279        SolutionCreator.LengthParameter.Value.Value != WeightsParameter.Value.Length)
280        SolutionCreator.LengthParameter.Value = new IntValue(WeightsParameter.Value.Length);
281    }
282    private void ParameterizeEvaluator() {
283      if (Evaluator is KnapsackEvaluator) {
284        KnapsackEvaluator knapsackEvaluator =
285          (KnapsackEvaluator)Evaluator;
286        knapsackEvaluator.BinaryVectorParameter.ActualName = SolutionCreator.BinaryVectorParameter.ActualName;
287        knapsackEvaluator.KnapsackCapacityParameter.ActualName = KnapsackCapacityParameter.Name;
288        knapsackEvaluator.WeightsParameter.ActualName = WeightsParameter.Name;
289        knapsackEvaluator.ValuesParameter.ActualName = ValuesParameter.Name;
290        knapsackEvaluator.PenaltyParameter.ActualName = PenaltyParameter.Name;
291      }
292    }
293    private void ParameterizeAnalyzer() {
294      BestKnapsackSolutionAnalyzer.BinaryVectorParameter.ActualName = SolutionCreator.BinaryVectorParameter.ActualName;
295      BestKnapsackSolutionAnalyzer.KnapsackCapacityParameter.ActualName = KnapsackCapacityParameter.Name;
296      BestKnapsackSolutionAnalyzer.WeightsParameter.ActualName = WeightsParameter.Name;
297      BestKnapsackSolutionAnalyzer.ValuesParameter.ActualName = ValuesParameter.Name;
298      BestKnapsackSolutionAnalyzer.ResultsParameter.ActualName = "Results";
299    }
300    private void InitializeOperators() {
301      operators = new List<IOperator>();
302      operators.Add(new BestKnapsackSolutionAnalyzer());
303      ParameterizeAnalyzer();
304      foreach (IBinaryVectorOperator op in ApplicationManager.Manager.GetInstances<IBinaryVectorOperator>()) {
305        if (!(op is ISingleObjectiveMoveEvaluator) || (op is IKnapsackMoveEvaluator)) {
306          operators.Add(op);
307        }
308      }
309      ParameterizeOperators();
310      InitializeMoveGenerators();
311    }
312    private void InitializeMoveGenerators() {
313      foreach (IOneBitflipMoveOperator op in Operators.OfType<IOneBitflipMoveOperator>()) {
314        if (op is IMoveGenerator) {
315          op.OneBitflipMoveParameter.ActualNameChanged += new EventHandler(OneBitflipMoveParameter_ActualNameChanged);
316        }
317      }
318    }
319    private void ParameterizeOperators() {
320      foreach (IBinaryVectorCrossover op in Operators.OfType<IBinaryVectorCrossover>()) {
321        op.ParentsParameter.ActualName = SolutionCreator.BinaryVectorParameter.ActualName;
322        op.ChildParameter.ActualName = SolutionCreator.BinaryVectorParameter.ActualName;
323      }
324      foreach (IBinaryVectorManipulator op in Operators.OfType<IBinaryVectorManipulator>()) {
325        op.BinaryVectorParameter.ActualName = SolutionCreator.BinaryVectorParameter.ActualName;
326      }
327      foreach (IBinaryVectorMoveOperator op in Operators.OfType<IBinaryVectorMoveOperator>()) {
328        op.BinaryVectorParameter.ActualName = SolutionCreator.BinaryVectorParameter.ActualName;
329      }
330      foreach (IKnapsackMoveEvaluator op in Operators.OfType<IKnapsackMoveEvaluator>()) {
331        op.KnapsackCapacityParameter.ActualName = KnapsackCapacityParameter.Name;
332        op.PenaltyParameter.ActualName = PenaltyParameter.Name;
333        op.WeightsParameter.ActualName = WeightsParameter.Name;
334        op.ValuesParameter.ActualName = ValuesParameter.Name;
335      }
336    }
337    #endregion
338  }
339}
Note: See TracBrowser for help on using the repository browser.