Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ScatterSearch/HeuristicLab.Algorithms.ScatterSearch/3.3/Knapsack/KnapsackImprovementOperator.cs @ 7786

Last change on this file since 7786 was 7786, checked in by jkarder, 12 years ago

#1331:

  • fixed bug in path relinking selection
  • fixed bug in ScatterSearch.Prepare()
  • added custom interface (IImprovementOperator) for Scatter Search specific improvement operators
  • switched from diversity calculation to similarity calculation
  • separated IPathRelinker from ICrossover
  • changed TestFunctionsImprovementOperator to use reflection for evaluating functions
  • changed SolutionPoolUpdateMethod to use similarity calculation for solution comparison
  • improved TravelingSalesmanImprovementOperator
  • improved operator graph
  • removed specific operators used to evaluate TestFunctions problems
  • removed custom crossover operator (NChildCrossover)
  • added parameters and adjusted types
  • adjusted event handling
  • changed access levels
  • minor code improvements
File size: 5.6 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.Linq;
23using HeuristicLab.Common;
24using HeuristicLab.Core;
25using HeuristicLab.Data;
26using HeuristicLab.Encodings.BinaryVectorEncoding;
27using HeuristicLab.Operators;
28using HeuristicLab.Parameters;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30using HeuristicLab.Problems.Knapsack;
31
32namespace HeuristicLab.Algorithms.ScatterSearch.Knapsack {
33  /// <summary>
34  /// An operator that improves knapsack solutions.
35  /// </summary>
36  [Item("KnapsackImprovementOperator", "An operator that improves knapsack solutions.")]
37  [StorableClass]
38  public sealed class KnapsackImprovementOperator : SingleSuccessorOperator, IImprovementOperator {
39    #region Parameter properties
40    public ScopeParameter CurrentScopeParameter {
41      get { return (ScopeParameter)Parameters["CurrentScope"]; }
42    }
43    public ILookupParameter<IntValue> KnapsackCapacityParameter {
44      get { return (ILookupParameter<IntValue>)Parameters["KnapsackCapacity"]; }
45    }
46    public ILookupParameter<DoubleValue> PenaltyParameter {
47      get { return (ILookupParameter<DoubleValue>)Parameters["Penalty"]; }
48    }
49    public IValueLookupParameter<IItem> TargetParameter {
50      get { return (IValueLookupParameter<IItem>)Parameters["Target"]; }
51    }
52    public ILookupParameter<IntArray> ValuesParameter {
53      get { return (ILookupParameter<IntArray>)Parameters["Values"]; }
54    }
55    public ILookupParameter<IntArray> WeightsParameter {
56      get { return (ILookupParameter<IntArray>)Parameters["Weights"]; }
57    }
58    #endregion
59
60    #region Properties
61    private IScope CurrentScope {
62      get { return CurrentScopeParameter.ActualValue; }
63    }
64    private IntValue KnapsackCapacity {
65      get { return KnapsackCapacityParameter.ActualValue; }
66      set { KnapsackCapacityParameter.ActualValue = value; }
67    }
68    private DoubleValue Penalty {
69      get { return PenaltyParameter.ActualValue; }
70      set { PenaltyParameter.ActualValue = value; }
71    }
72    private IItem Target {
73      get { return TargetParameter.ActualValue; }
74    }
75    private IntArray Values {
76      get { return ValuesParameter.ActualValue; }
77      set { ValuesParameter.ActualValue = value; }
78    }
79    private IntArray Weights {
80      get { return WeightsParameter.ActualValue; }
81      set { WeightsParameter.ActualValue = value; }
82    }
83    #endregion
84
85    [StorableConstructor]
86    private KnapsackImprovementOperator(bool deserializing) : base(deserializing) { }
87    private KnapsackImprovementOperator(KnapsackImprovementOperator original, Cloner cloner) : base(original, cloner) { }
88    public KnapsackImprovementOperator()
89      : base() {
90      #region Create parameters
91      Parameters.Add(new ScopeParameter("CurrentScope"));
92      Parameters.Add(new LookupParameter<IntValue>("KnapsackCapacity"));
93      Parameters.Add(new LookupParameter<DoubleValue>("Penalty"));
94      Parameters.Add(new ValueLookupParameter<IItem>("Target"));
95      Parameters.Add(new LookupParameter<IntArray>("Values"));
96      Parameters.Add(new LookupParameter<IntArray>("Weights"));
97      #endregion
98      TargetParameter.ActualName = "KnapsackSolution"; // temporary solution for the knapsack problem
99    }
100
101    public override IDeepCloneable Clone(Cloner cloner) {
102      return new KnapsackImprovementOperator(this, cloner);
103    }
104
105    public override IOperation Apply() {
106      BinaryVector sol = CurrentScope.Variables[TargetParameter.ActualName].Value as BinaryVector;
107
108      // calculate value-to-weight ratio
109      double[] ratio = new double[Values.Length];
110      for (int i = 0; i < ratio.Length; i++)
111        ratio[i] = (double)Values[i] / (double)Weights[i];
112
113
114      // calculate order for ratio
115      int[] order = new int[ratio.Length];
116      ratio.Select((x, index) => new { Value = x, ValueIndex = index })
117           .OrderBy(x => x.Value)
118           .Select((x, index) => new { ValueIndex = x.ValueIndex, ItemIndex = index }).ToList()
119           .ForEach(x => order[x.ItemIndex] = x.ValueIndex);
120
121      int j = sol.Length - 1;
122      while (KnapsackEvaluator.Apply(sol, KnapsackCapacity, Penalty, Weights, Values)
123                              .SumWeights.Value > KnapsackCapacity.Value && j >= 0)
124        sol[order[j--]] = false;
125
126      // calculate weight
127      int weight = 0;
128      for (int i = 0; i < sol.Length; i++)
129        if (sol[i]) weight += Weights[i];
130
131      // improve solution
132      bool feasible = true; j = 0;
133      while (feasible && j < sol.Length) {
134        while (sol[order[j]]) j++;
135        if (weight + Weights[order[j]] <= KnapsackCapacity.Value) {
136          sol[order[j]] = true;
137          weight += Weights[order[j]];
138        } else feasible = false;
139      }
140
141      CurrentScope.Variables[TargetParameter.ActualName].Value = sol;
142
143      return base.Apply();
144    }
145  }
146}
Note: See TracBrowser for help on using the repository browser.