Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 4695 was 4513, checked in by swinkler, 14 years ago

Corrected comments and descriptions (#1182); formatted code.

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