Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GeneralizedQAP/HeuristicLab.Problems.GeneralizedQuadraticAssignment/3.3/SolutionCreators/SlackMinimizationSolutionCreator.cs @ 7593

Last change on this file since 7593 was 7593, checked in by abeham, 12 years ago

#1614

  • Investigation in different solution creator that result in feasible solutions even for 95% fill level instances
  • Added option for all solution creators to produce the least infeasible solution if no feasible solution could be found
  • Added maximum tries parameter to all creators
File size: 8.8 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.Collections.Generic;
24using System.Linq;
25using System.Threading;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Encodings.IntegerVectorEncoding;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.Problems.GeneralizedQuadraticAssignment.Common;
33
34namespace HeuristicLab.Problems.GeneralizedQuadraticAssignment {
35  [Item("SlackMinimizationSolutionCreator", "A heuristic that creates a solution to the Generalized Quadratic Assignment Problem by minimizing the amount of slack.")]
36  [StorableClass]
37  public class SlackMinimizationSolutionCreator : GQAPStochasticSolutionCreator {
38
39    public IValueLookupParameter<IntValue> MaximumTriesParameter {
40      get { return (IValueLookupParameter<IntValue>)Parameters["MaximumTries"]; }
41    }
42    public IValueLookupParameter<BoolValue> CreateMostFeasibleSolutionParameter {
43      get { return (IValueLookupParameter<BoolValue>)Parameters["CreateMostFeasibleSolution"]; }
44    }
45    public IValueLookupParameter<IntValue> DepthParameter {
46      get { return (IValueLookupParameter<IntValue>)Parameters["Depth"]; }
47    }
48
49    [StorableConstructor]
50    protected SlackMinimizationSolutionCreator(bool deserializing) : base(deserializing) { }
51    protected SlackMinimizationSolutionCreator(SlackMinimizationSolutionCreator original, Cloner cloner) : base(original, cloner) { }
52    public SlackMinimizationSolutionCreator()
53      : base() {
54      Parameters.Add(new ValueLookupParameter<IntValue>("MaximumTries", "The maximum number of tries to create a feasible solution after which an exception is thrown. If it is set to 0 or a negative value there will be an infinite number of attempts to create a feasible solution.", new IntValue(100000)));
55      Parameters.Add(new ValueLookupParameter<BoolValue>("CreateMostFeasibleSolution", "If this is set to true the operator will always succeed, and outputs the solution with the least violation instead of throwing an exception.", new BoolValue(false)));
56      Parameters.Add(new ValueLookupParameter<IntValue>("Depth", "How deep the algorithm should look forward.", new IntValue(3)));
57    }
58
59    public override IDeepCloneable Clone(Cloner cloner) {
60      return new SlackMinimizationSolutionCreator(this, cloner);
61    }
62
63    [StorableHook(HookType.AfterDeserialization)]
64    private void AfterDeserialization() {
65      if (!Parameters.ContainsKey("Depth")) {
66        Parameters.Add(new ValueLookupParameter<IntValue>("Depth", "How deep the algorithm should look forward.", new IntValue(3)));
67      }
68    }
69
70    public static IntegerVector CreateSolution(IRandom random, DoubleArray demands, DoubleArray capacities, int depth, int maximumTries, bool createMostFeasibleSolution, CancellationToken cancel) {
71      IntegerVector result = null;
72      bool isFeasible = false;
73      int counter = 0;
74      double minViolation = double.MaxValue;
75      var slack = new DoubleArray(capacities.Length);
76      var assignment = new Dictionary<int, int>(demands.Length);
77
78      while (!isFeasible) {
79        cancel.ThrowIfCancellationRequested();
80        if (maximumTries > 0) {
81          counter++;
82          if (counter > maximumTries) {
83            if (createMostFeasibleSolution) break;
84            else throw new InvalidOperationException("A feasible solution could not be obtained after " + maximumTries + " attempts.");
85          }
86        }
87        assignment.Clear();
88        for (int i = 0; i < capacities.Length; i++) slack[i] = capacities[i];
89        var remainingEquipment = new HashSet<int>(Enumerable.Range(0, demands.Length));
90        while (remainingEquipment.Any()) {
91          var equipment = remainingEquipment.ChooseProportionalRandom(random, 1, x => demands[x], true, true).Single();
92          remainingEquipment.Remove(equipment);
93
94          var freeLocations = GetLocationsByFillLevel(equipment, demands[equipment], slack);
95          if (!freeLocations.Any()) break;
96          double bestSlack = double.MaxValue;
97          int bestLocation = -1;
98          int[] additionalEquipment = new int[0];
99          foreach (var location in freeLocations.Shuffle(random)) {
100            HashSet<int> newEquipment;
101            var estimatedSlack = EstimatePotentialSlack(location.Key, location.Value, remainingEquipment, demands, out newEquipment, depth);
102            if (estimatedSlack < bestSlack || (estimatedSlack == bestSlack && newEquipment.Count < additionalEquipment.Length)) {
103              bestSlack = estimatedSlack;
104              bestLocation = location.Key;
105              additionalEquipment = newEquipment.ToArray();
106            }
107          }
108          assignment[equipment] = bestLocation;
109          slack[bestLocation] -= demands[equipment];
110          foreach (var eq in additionalEquipment) {
111            remainingEquipment.Remove(eq);
112            assignment[eq] = bestLocation;
113            slack[bestLocation] -= demands[eq];
114          }
115        }
116        if (assignment.Count != demands.Length) {
117          // complete the solution
118          while (remainingEquipment.Any()) {
119            var f = remainingEquipment.ChooseMax(x => demands[x]);
120            var l = Enumerable.Range(0, capacities.Length).ChooseMax(x => slack[x]);
121            remainingEquipment.Remove(f);
122            assignment.Add(f, l);
123            slack[l] -= demands[f];
124          }
125        }
126        double violation = GQAPEvaluator.EvaluateOverbooking(slack, capacities);
127        isFeasible = violation == 0;
128        if (isFeasible || violation < minViolation) {
129          result = new IntegerVector(assignment.OrderBy(x => x.Key).Select(x => x.Value).ToArray());
130          minViolation = violation;
131        }
132      }
133      return result;
134    }
135
136    private static double EstimatePotentialSlack(int location, double slack, HashSet<int> remainingEquipment, DoubleArray demands, out HashSet<int> addedEquipment, int depth = 3) {
137      var feasibleEquipment = remainingEquipment.Where(x => demands[x] < slack).ToArray();
138      addedEquipment = new HashSet<int>();
139
140      if (!feasibleEquipment.Any()) return slack;
141      if (depth == 0) {
142        var e = feasibleEquipment.ChooseMax(x => demands[x]);
143        addedEquipment.Add(e);
144        return slack - demands[e];
145      }
146
147      double bestSlack = slack;
148      int minSlackEquipment = -1;
149      foreach (var e in feasibleEquipment) {
150        remainingEquipment.Remove(e);
151        HashSet<int> childEquipment;
152        var potentialSlack = EstimatePotentialSlack(location, slack - demands[e], remainingEquipment, demands, out childEquipment, depth - 1);
153        if (bestSlack > potentialSlack || (bestSlack == potentialSlack && childEquipment.Count < addedEquipment.Count)) {
154          bestSlack = potentialSlack;
155          minSlackEquipment = e;
156          addedEquipment.Clear();
157          foreach (var child in childEquipment) addedEquipment.Add(child);
158        }
159        remainingEquipment.Add(e);
160      }
161      if (minSlackEquipment > -1)
162        addedEquipment.Add(minSlackEquipment);
163      return bestSlack;
164    }
165
166    protected override IntegerVector CreateRandomSolution(IRandom random, DoubleArray demands, DoubleArray capacities) {
167      return CreateSolution(random, demands, capacities,
168        DepthParameter.ActualValue.Value,
169        MaximumTriesParameter.ActualValue.Value,
170        CreateMostFeasibleSolutionParameter.ActualValue.Value,
171        CancellationToken);
172    }
173
174    private static IEnumerable<KeyValuePair<int, double>> GetLocationsByFillLevel(int equipment, double demand, DoubleArray slack) {
175      var freeLocations = slack
176        .Select((v, idx) => new KeyValuePair<int, double>(idx, v))
177        .Where(x => x.Value >= demand);
178      if (!freeLocations.Any()) {
179        return Enumerable.Empty<KeyValuePair<int, double>>();
180      }
181      return freeLocations.Select(x => new KeyValuePair<int, double>(x.Key, slack[x.Key] - demand)).OrderBy(x => x.Value);
182    }
183  }
184}
Note: See TracBrowser for help on using the repository browser.