Free cookie consent management tool by TermsFeed Policy Generator

source: branches/1614_GeneralizedQAP/HeuristicLab.Problems.GeneralizedQuadraticAssignment/3.3/SolutionCreators/SlackMinimizationSolutionCreator.cs @ 16724

Last change on this file since 16724 was 15555, checked in by abeham, 7 years ago

#1614: finished checking the implementation against the paper

File size: 8.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2017 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.Random;
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    public static IntegerVector CreateSolution(IRandom random, GQAPInstance problemInstance,
68      int depth, int maximumTries, bool createMostFeasibleSolution, int randomWalkLength, CancellationToken cancel) {
69      var capacities = problemInstance.Capacities;
70      var demands = problemInstance.Demands;
71
72      IntegerVector result = null;
73      bool isFeasible = false;
74      int counter = 0;
75      double minViolation = double.MaxValue;
76      var slack = new double[capacities.Length];
77      var assignment = new Dictionary<int, int>(demands.Length);
78
79      while (!isFeasible) {
80        cancel.ThrowIfCancellationRequested();
81        if (maximumTries > 0) {
82          counter++;
83          if (counter > maximumTries) {
84            if (createMostFeasibleSolution) break;
85            else throw new InvalidOperationException("A feasible solution could not be obtained after " + maximumTries + " attempts.");
86          }
87        }
88        assignment.Clear();
89        for (int i = 0; i < capacities.Length; i++) slack[i] = capacities[i];
90        var remainingEquipment = new HashSet<int>(Enumerable.Range(0, demands.Length));
91        while (remainingEquipment.Any()) {
92          var minimumDemand = remainingEquipment.Min(x => demands[x]);
93          var possibleLocations = Enumerable.Range(0, capacities.Length).Where(x => slack[x] >= minimumDemand);
94          if (!possibleLocations.Any()) break;
95          foreach (var location in possibleLocations.Shuffle(random)) {
96            var group = FindBestGroup(location, slack[location], remainingEquipment, demands, depth);
97            foreach (var eq in group) {
98              remainingEquipment.Remove(eq);
99              assignment[eq] = location;
100              slack[location] -= demands[eq];
101            }
102          }
103        }
104        if (assignment.Count != demands.Length) {
105          // complete the solution
106          while (remainingEquipment.Any()) {
107            var f = remainingEquipment.MaxItems(x => demands[x]).SampleRandom(random);
108            var l = Enumerable.Range(0, capacities.Length).MaxItems(x => slack[x]).SampleRandom(random);
109            remainingEquipment.Remove(f);
110            assignment.Add(f, l);
111            slack[l] -= demands[f];
112          }
113        } else RandomFeasibleWalk(random, assignment, demands, slack, randomWalkLength);
114        double violation = slack.Select(x => x < 0 ? -x : 0).Sum();
115        isFeasible = violation == 0;
116        if (isFeasible || violation < minViolation) {
117          result = new IntegerVector(assignment.OrderBy(x => x.Key).Select(x => x.Value).ToArray());
118          minViolation = violation;
119        }
120      }
121      return result;
122    }
123
124    private static IEnumerable<int> FindBestGroup(int location, double slack, HashSet<int> remainingEquipment, DoubleArray demands, int depth = 3) {
125      var feasibleEquipment = remainingEquipment.Where(x => demands[x] <= slack).ToArray();
126
127      if (!feasibleEquipment.Any()) yield break;
128      if (depth == 0) {
129        var e = feasibleEquipment.MaxItems(x => demands[x]).First();
130        yield return e;
131        yield break;
132      }
133
134      double bestSlack = slack;
135      int bestEquipment = -1;
136      int[] bestColleagues = new int[0];
137      foreach (var e in feasibleEquipment) {
138        remainingEquipment.Remove(e);
139        var colleagues = FindBestGroup(location, slack - demands[e], remainingEquipment, demands, depth - 1).ToArray();
140        var slackWithColleagues = slack - demands[e] - colleagues.Sum(x => demands[x]);
141        if (bestSlack > slackWithColleagues || (bestSlack == slackWithColleagues && colleagues.Length < bestColleagues.Length)) {
142          bestSlack = slackWithColleagues;
143          bestEquipment = e;
144          bestColleagues = colleagues;
145        }
146        remainingEquipment.Add(e);
147      }
148      yield return bestEquipment;
149      foreach (var a in bestColleagues) yield return a;
150    }
151
152    private static void RandomFeasibleWalk(IRandom random, Dictionary<int, int> assignment, DoubleArray demands, double[] slack, int walkLength) {
153      for (int i = 0; i < walkLength; i++) {
154        var equipments = Enumerable.Range(0, demands.Length).Shuffle(random);
155        foreach (var e in equipments) {
156          var partners = Enumerable.Range(0, demands.Length)
157            .Where(x => slack[assignment[x]] + demands[x] - demands[e] >= 0
158                && slack[assignment[e]] + demands[e] - demands[x] >= 0);
159          if (!partners.Any()) continue;
160          var f = partners.SampleRandom(random);
161          int h = assignment[e];
162          assignment[e] = assignment[f];
163          assignment[f] = h;
164          slack[assignment[e]] += demands[f] - demands[e];
165          slack[assignment[f]] += demands[e] - demands[f];
166          break;
167        }
168      }
169    }
170
171    protected override IntegerVector CreateRandomSolution(IRandom random, GQAPInstance problemInstance) {
172      return CreateSolution(random, problemInstance,
173        DepthParameter.ActualValue.Value,
174        MaximumTriesParameter.ActualValue.Value,
175        CreateMostFeasibleSolutionParameter.ActualValue.Value,
176        RandomWalkLengthParameter.ActualValue.Value,
177        CancellationToken);
178    }
179  }
180}
Note: See TracBrowser for help on using the repository browser.