Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GeneralizedQAP/HeuristicLab.Problems.GeneralizedQuadraticAssignment/3.3/SolutionCreators/GreedyRandomizedSolutionCreator.cs @ 9056

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

#1614: restructured architecture to allow for different evaluator with different penalty strategies

File size: 7.7 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.Random;
33
34namespace HeuristicLab.Problems.GeneralizedQuadraticAssignment {
35  [Item("GreedyRandomizedSolutionCreator", "Creates a solution according to the procedure described in Mateus, G., Resende, M., and Silva, R. 2011. GRASP with path-relinking for the generalized quadratic assignment problem. Journal of Heuristics 17, Springer Netherlands, pp. 527-565.")]
36  [StorableClass]
37  public class GreedyRandomizedSolutionCreator : GQAPStochasticSolutionCreator,
38    IEvaluatorAwareGQAPOperator {
39
40    public IValueLookupParameter<IntValue> MaximumTriesParameter {
41      get { return (IValueLookupParameter<IntValue>)Parameters["MaximumTries"]; }
42    }
43    public IValueLookupParameter<BoolValue> CreateMostFeasibleSolutionParameter {
44      get { return (IValueLookupParameter<BoolValue>)Parameters["CreateMostFeasibleSolution"]; }
45    }
46    public IValueLookupParameter<IGQAPEvaluator> EvaluatorParameter {
47      get { return (IValueLookupParameter<IGQAPEvaluator>)Parameters["Evaluator"]; }
48    }
49
50    [StorableConstructor]
51    protected GreedyRandomizedSolutionCreator(bool deserializing) : base(deserializing) { }
52    protected GreedyRandomizedSolutionCreator(GreedyRandomizedSolutionCreator original, Cloner cloner)
53      : base(original, cloner) { }
54    public GreedyRandomizedSolutionCreator()
55      : base() {
56      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.", new IntValue(100000)));
57      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)));
58      Parameters.Add(new ValueLookupParameter<IGQAPEvaluator>("Evaluator", "The evaluator that is used to evaluate GQAP solutions."));
59    }
60
61    public override IDeepCloneable Clone(Cloner cloner) {
62      return new GreedyRandomizedSolutionCreator(this, cloner);
63    }
64
65    public static IntegerVector CreateSolution(IRandom random, DoubleArray demands, DoubleArray capacities,
66      IGQAPEvaluator evaluator,
67      int maximumTries, bool createMostFeasibleSolution, CancellationToken cancelToken) {
68      int tries = 0;
69      var assignment = new Dictionary<int, int>(demands.Length);
70      DoubleArray slack = new DoubleArray(capacities.Length);
71      double minViolation = double.MaxValue;
72      Dictionary<int, int> bestAssignment = null;
73      HashSet<int> CF = new HashSet<int>(), // set of chosen facilities / equipments
74          T = new HashSet<int>(), // set of facilities / equpiments that can be assigned to the set of chosen locations (CL)
75          CL = new HashSet<int>(), // set of chosen locations
76          F = new HashSet<int>(Enumerable.Range(0, demands.Length)), // set of (initially) all facilities / equipments
77          L = new HashSet<int>(Enumerable.Range(0, capacities.Length)); // set of (initially) all locations
78
79      while (maximumTries <= 0 || tries < maximumTries) {
80        cancelToken.ThrowIfCancellationRequested();
81
82        assignment.Clear();
83        for (int i = 0; i < capacities.Length; i++) slack[i] = capacities[i];
84        CF.Clear();
85        T.Clear();
86        CL.Clear();
87        F.Clear(); F.UnionWith(Enumerable.Range(0, demands.Length));
88        L.Clear(); L.UnionWith(Enumerable.Range(0, capacities.Length));
89
90        double threshold = 1.0;
91        do {
92          if (L.Any() && random.NextDouble() < threshold) {
93            int l = L.SampleRandom(random);
94            L.Remove(l);
95            CL.Add(l);
96            T = new HashSet<int>(WithDemandEqualOrLess(F, GetMaximumSlack(slack, CL), demands));
97          }
98          if (T.Any()) {
99            int f = T.SampleRandom(random);
100            T.Remove(f);
101            F.Remove(f);
102            CF.Add(f);
103            int l = WithSlackGreaterOrEqual(CL, demands[f], slack).SampleRandom(random);
104            assignment.Add(f, l);
105            slack[l] -= demands[f];
106            T = new HashSet<int>(WithDemandEqualOrLess(F, GetMaximumSlack(slack, CL), demands));
107            threshold = 1.0 - (double)T.Count / Math.Max(F.Count, 1.0);
108          }
109        } while (T.Any() || L.Any());
110        if (maximumTries > 0) tries++;
111        if (!F.Any()) {
112          bestAssignment = assignment;
113          break;
114        } else if (createMostFeasibleSolution) {
115          // complete the solution and remember the one with least violation
116          foreach (var l in L.ToArray()) {
117            CL.Add(l);
118            L.Remove(l);
119          }
120          while (F.Any()) {
121            var f = F.MaxItems(x => demands[x]).SampleRandom(random);
122            var l = CL.MaxItems(x => slack[x]).SampleRandom(random);
123            F.Remove(f);
124            assignment.Add(f, l);
125            slack[l] -= demands[f];
126          }
127          double violation = evaluator.EvaluateOverbooking(slack, capacities);
128          if (violation < minViolation) {
129            bestAssignment = assignment;
130            assignment = new Dictionary<int, int>(demands.Length);
131            minViolation = violation;
132          }
133        }
134      }
135
136      if (bestAssignment == null || bestAssignment.Count != demands.Length) throw new InvalidOperationException(String.Format("No solution could be found in {0} tries.", maximumTries));
137
138      return new IntegerVector(bestAssignment.OrderBy(x => x.Key).Select(x => x.Value).ToArray());
139    }
140
141    protected override IntegerVector CreateRandomSolution(IRandom random, DoubleArray demands, DoubleArray capacities) {
142      return CreateSolution(random, demands, capacities,
143        EvaluatorParameter.ActualValue,
144        MaximumTriesParameter.ActualValue.Value,
145        CreateMostFeasibleSolutionParameter.ActualValue.Value,
146        CancellationToken);
147    }
148
149    private static IEnumerable<int> WithDemandEqualOrLess(IEnumerable<int> facilities, double maximum, DoubleArray demands) {
150      foreach (int f in facilities) {
151        if (demands[f] <= maximum) yield return f;
152      }
153    }
154
155    private static double GetMaximumSlack(DoubleArray slack, HashSet<int> CL) {
156      return slack.Select((val, idx) => new { idx, val }).Where(x => CL.Contains(x.idx)).Select(x => x.val).Max();
157    }
158
159    private static IEnumerable<int> WithSlackGreaterOrEqual(HashSet<int> locations, double minimum, DoubleArray slack) {
160      foreach (int l in locations) {
161        if (slack[l] >= minimum) yield return l;
162      }
163    }
164  }
165}
Note: See TracBrowser for help on using the repository browser.