Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1614: updated SlackMinimizationSolutionCreator

File size: 9.1 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    public IValueLookupParameter<IntValue> RandomWalkLengthParameter {
49      get { return (IValueLookupParameter<IntValue>)Parameters["RandomWalkLength"]; }
50    }
51
52    [StorableConstructor]
53    protected SlackMinimizationSolutionCreator(bool deserializing) : base(deserializing) { }
54    protected SlackMinimizationSolutionCreator(SlackMinimizationSolutionCreator original, Cloner cloner) : base(original, cloner) { }
55    public SlackMinimizationSolutionCreator()
56      : base() {
57      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)));
58      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)));
59      Parameters.Add(new ValueLookupParameter<IntValue>("Depth", "How deep the algorithm should look forward.", new IntValue(3)));
60      Parameters.Add(new ValueLookupParameter<IntValue>("RandomWalkLength", "The length of the random walk in the feasible region that is used to diversify the found assignments.", new IntValue(10)));
61    }
62
63    public override IDeepCloneable Clone(Cloner cloner) {
64      return new SlackMinimizationSolutionCreator(this, cloner);
65    }
66
67    [StorableHook(HookType.AfterDeserialization)]
68    private void AfterDeserialization() {
69      if (!Parameters.ContainsKey("Depth")) {
70        Parameters.Add(new ValueLookupParameter<IntValue>("Depth", "How deep the algorithm should look forward.", new IntValue(3)));
71      }
72      if (!Parameters.ContainsKey("RandomWalkLength")) {
73        Parameters.Add(new ValueLookupParameter<IntValue>("RandomWalkLength", "The length of the random walk in the feasible region that is used to diversify the found assignments.", new IntValue(10)));
74      }
75    }
76
77    public static IntegerVector CreateSolution(IRandom random, DoubleArray demands, DoubleArray capacities, int depth, int maximumTries, bool createMostFeasibleSolution, int randomWalkLength, CancellationToken cancel) {
78      IntegerVector result = null;
79      bool isFeasible = false;
80      int counter = 0;
81      double minViolation = double.MaxValue;
82      var slack = new DoubleArray(capacities.Length);
83      var assignment = new Dictionary<int, int>(demands.Length);
84
85      while (!isFeasible) {
86        cancel.ThrowIfCancellationRequested();
87        if (maximumTries > 0) {
88          counter++;
89          if (counter > maximumTries) {
90            if (createMostFeasibleSolution) break;
91            else throw new InvalidOperationException("A feasible solution could not be obtained after " + maximumTries + " attempts.");
92          }
93        }
94        assignment.Clear();
95        for (int i = 0; i < capacities.Length; i++) slack[i] = capacities[i];
96        var remainingEquipment = new HashSet<int>(Enumerable.Range(0, demands.Length));
97        while (remainingEquipment.Any()) {
98          var minimumDemand = remainingEquipment.Min(x => demands[x]);
99          var possibleLocations = Enumerable.Range(0, capacities.Length).Where(x => slack[x] >= minimumDemand);
100          if (!possibleLocations.Any()) break;
101          foreach (var location in possibleLocations.Shuffle(random)) {
102            var group = FindBestGroup(location, slack[location], remainingEquipment, demands, depth);
103            foreach (var eq in group) {
104              remainingEquipment.Remove(eq);
105              assignment[eq] = location;
106              slack[location] -= demands[eq];
107            }
108          }
109        }
110        if (assignment.Count != demands.Length) {
111          // complete the solution
112          while (remainingEquipment.Any()) {
113            var f = remainingEquipment.ChooseMax(x => demands[x]);
114            var l = Enumerable.Range(0, capacities.Length).ChooseMax(x => slack[x]);
115            remainingEquipment.Remove(f);
116            assignment.Add(f, l);
117            slack[l] -= demands[f];
118          }
119        }
120        RandomFeasibleWalk(random, assignment, demands, slack, randomWalkLength);
121        double violation = GQAPEvaluator.EvaluateOverbooking(slack, capacities);
122        isFeasible = violation == 0;
123        if (isFeasible || violation < minViolation) {
124          result = new IntegerVector(assignment.OrderBy(x => x.Key).Select(x => x.Value).ToArray());
125          minViolation = violation;
126        }
127      }
128      return result;
129    }
130
131    private static IEnumerable<int> FindBestGroup(int location, double slack, HashSet<int> remainingEquipment, DoubleArray demands, int depth = 3) {
132      var feasibleEquipment = remainingEquipment.Where(x => demands[x] <= slack).ToArray();
133
134      if (!feasibleEquipment.Any()) yield break;
135      if (depth == 0) {
136        var e = feasibleEquipment.ChooseMax(x => demands[x]);
137        yield return e;
138        yield break;
139      }
140
141      double bestSlack = slack;
142      int bestEquipment = -1;
143      int[] bestColleagues = new int[0];
144      foreach (var e in feasibleEquipment) {
145        remainingEquipment.Remove(e);
146        var colleagues = FindBestGroup(location, slack - demands[e], remainingEquipment, demands, depth - 1).ToArray();
147        var slackWithColleagues = slack - demands[e] - colleagues.Sum(x => demands[x]);
148        if (bestSlack > slackWithColleagues || (bestSlack == slackWithColleagues && colleagues.Length < bestColleagues.Length)) {
149          bestSlack = slackWithColleagues;
150          bestEquipment = e;
151          bestColleagues = colleagues;
152        }
153        remainingEquipment.Add(e);
154      }
155      yield return bestEquipment;
156      foreach (var a in bestColleagues) yield return a;
157    }
158
159    private static void RandomFeasibleWalk(IRandom random, Dictionary<int, int> assignment, DoubleArray demands, DoubleArray slack, int walkLength) {
160      for (int i = 0; i < walkLength; i++) {
161        var equipments = Enumerable.Range(0, demands.Length).Shuffle(random);
162        foreach (var e in equipments) {
163          var partners = Enumerable.Range(0, demands.Length)
164            .Where(x => slack[assignment[x]] + demands[x] - demands[e] >= 0
165                && slack[assignment[e]] + demands[e] - demands[x] >= 0);
166          if (!partners.Any()) continue;
167          var f = partners.ChooseUniformRandom(random);
168          int h = assignment[e];
169          assignment[e] = assignment[f];
170          assignment[f] = h;
171          slack[assignment[e]] += demands[f] - demands[e];
172          slack[assignment[f]] += demands[e] - demands[f];
173          break;
174        }
175      }
176    }
177
178    protected override IntegerVector CreateRandomSolution(IRandom random, DoubleArray demands, DoubleArray capacities) {
179      return CreateSolution(random, demands, capacities,
180        DepthParameter.ActualValue.Value,
181        MaximumTriesParameter.ActualValue.Value,
182        CreateMostFeasibleSolutionParameter.ActualValue.Value,
183        RandomWalkLengthParameter.ActualValue.Value,
184        CancellationToken);
185    }
186  }
187}
Note: See TracBrowser for help on using the repository browser.