Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1331:

  • added problem specific improvement operators (KnapsackImprovementOperator, TravelingSalesmanImprovementOperator)
  • added custom interface (IScatterSearchTargetProcessor) for Scatter Search specific operators that use a target parameter
  • added custom operator (OffspringProcessor) to process multiple children that were created by crossovers
  • extracted diversity calculation and added problem/encoding specific operators (BinaryVectorDiversityCalculator, PermutationDiversityCalculator) for it
  • added parameters and adjusted types
  • adjusted event handling
  • minor code improvements
File size: 6.5 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.Linq;
24using HeuristicLab.Common;
25using HeuristicLab.Core;
26using HeuristicLab.Data;
27using HeuristicLab.Encodings.BinaryVectorEncoding;
28using HeuristicLab.Operators;
29using HeuristicLab.Optimization;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.Problems.Knapsack;
33
34namespace HeuristicLab.Algorithms.ScatterSearch.Knapsack {
35  /// <summary>
36  /// An operator that improves knapsack solutions.
37  /// </summary>
38  [Item("KnapsackImprovementOperator", "An operator that improves knapsack solutions.")]
39  [StorableClass]
40  public sealed class KnapsackImprovementOperator : SingleSuccessorOperator, ILocalImprovementOperator, IScatterSearchTargetProcessor {
41
42    #region Problem properties
43    public Type ProblemType {
44      get { return typeof(KnapsackProblem); }
45    }
46    [Storable]
47    private KnapsackProblem problem;
48    public IProblem Problem {
49      get { return problem; }
50      set { problem = (KnapsackProblem)value; }
51    }
52    #endregion
53
54    #region Parameter properties
55    public ScopeParameter CurrentScopeParameter {
56      get { return (ScopeParameter)Parameters["CurrentScope"]; }
57    }
58    public IValueLookupParameter<IntArray> ValuesParameter {
59      get { return (IValueLookupParameter<IntArray>)Parameters["Values"]; }
60    }
61    public IValueLookupParameter<IntArray> WeightsParameter {
62      get { return (IValueLookupParameter<IntArray>)Parameters["Weights"]; }
63    }
64    public IValueLookupParameter<IntValue> KnapsackCapacityParameter {
65      get { return (IValueLookupParameter<IntValue>)Parameters["KnapsackCapacity"]; }
66    }
67    public IValueLookupParameter<IItem> TargetParameter {
68      get { return (IValueLookupParameter<IItem>)Parameters["Target"]; }
69    }
70    #region ILocalImprovementOperator Parameters
71    public IValueLookupParameter<IntValue> MaximumIterationsParameter {
72      get { return (IValueLookupParameter<IntValue>)Parameters["MaximumIterations"]; }
73    }
74    public ILookupParameter<IntValue> EvaluatedSolutionsParameter {
75      get { return (ILookupParameter<IntValue>)Parameters["EvaluatedSolutions"]; }
76    }
77    public ILookupParameter<ResultCollection> ResultsParameter {
78      get { return (ILookupParameter<ResultCollection>)Parameters["Results"]; }
79    }
80    #endregion
81    #endregion
82
83    #region Properties
84    private IScope CurrentScope {
85      get { return CurrentScopeParameter.ActualValue; }
86    }
87    private IntArray Values {
88      get { return ValuesParameter.ActualValue; }
89      set { ValuesParameter.ActualValue = value; }
90    }
91    private IntArray Weights {
92      get { return WeightsParameter.ActualValue; }
93      set { WeightsParameter.ActualValue = value; }
94    }
95    private IntValue KnapsackCapacity {
96      get { return KnapsackCapacityParameter.ActualValue; }
97      set { KnapsackCapacityParameter.ActualValue = value; }
98    }
99    private IItem Target {
100      get { return TargetParameter.ActualValue; }
101    }
102    #endregion
103
104    [StorableConstructor]
105    private KnapsackImprovementOperator(bool deserializing) : base(deserializing) { }
106    private KnapsackImprovementOperator(KnapsackImprovementOperator original, Cloner cloner)
107      : base(original, cloner) {
108      this.problem = cloner.Clone(original.problem);
109    }
110    public KnapsackImprovementOperator()
111      : base() {
112      #region Create parameters
113      Parameters.Add(new ScopeParameter("CurrentScope"));
114      Parameters.Add(new ValueLookupParameter<IntArray>("Values"));
115      Parameters.Add(new ValueLookupParameter<IntArray>("Weights"));
116      Parameters.Add(new ValueLookupParameter<IntValue>("KnapsackCapacity"));
117      Parameters.Add(new ValueLookupParameter<IItem>("Target"));
118      #endregion
119      TargetParameter.ActualName = "KnapsackSolution"; // temporary solution for the knapsack problem
120    }
121
122    public override IDeepCloneable Clone(Cloner cloner) {
123      return new KnapsackImprovementOperator(this, cloner);
124    }
125
126    public override IOperation Apply() {
127      var sol = CurrentScope.Variables[TargetParameter.ActualName].Value as BinaryVector;
128
129      // calculate value-to-weight ratio
130      double[] ratio = new double[Values.Length];
131      for (int i = 0; i < ratio.Length; i++) {
132        ratio[i] = (double)Values[i] / (double)Weights[i];
133      }
134
135      // calculate order for ratio
136      int[] order = new int[ratio.Length];
137      ratio.Select((x, index) => new { Value = x, ValueIndex = index })
138           .OrderBy(x => x.Value)
139           .Select((x, index) => new { ValueIndex = x.ValueIndex, ItemIndex = index }).ToList()
140           .ForEach(x => order[x.ItemIndex] = x.ValueIndex);
141
142      int j = sol.Length - 1;
143      while (KnapsackEvaluator.Apply(sol, KnapsackCapacity, new DoubleValue(1.0), Weights, Values).SumWeights.Value > KnapsackCapacity.Value && j >= 0) {
144        sol[order[j--]] = false;
145      }
146
147      // calculate weight
148      int lhs = 0;
149      for (int i = 0; i < sol.Length; i++) {
150        if (sol[i]) lhs += Weights[i];
151      }
152
153      // improve solution
154      bool feasible = true; j = 0;
155      while (feasible && j < sol.Length) {
156        while (sol[order[j]]) j++;
157        if (lhs + Weights[order[j]] <= KnapsackCapacity.Value) {
158          sol[order[j]] = true;
159          lhs += Weights[order[j]];
160        } else {
161          feasible = false;
162        }
163      }
164
165      CurrentScope.Variables[TargetParameter.ActualName].Value = sol;
166
167      return base.Apply();
168    }
169
170    private bool IsFeasiblse(BinaryVector sol) {
171      int sum = 0;
172      for (int i = 0; i < sol.Length; i++)
173        if (sol[i]) sum += Weights[i];
174      return sum <= KnapsackCapacity.Value;
175    }
176  }
177}
Note: See TracBrowser for help on using the repository browser.