Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GeneralizedQAP/HeuristicLab.Problems.GeneralizedQuadraticAssignment/3.3/SolutionCreators/RandomButFeasibleSolutionCreator.cs @ 12214

Last change on this file since 12214 was 7970, checked in by abeham, 13 years ago

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

File size: 5.6 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("RandomButFeasibleSolutionCreator", "Creates a random, but feasible solution to the Generalized Quadratic Assignment Problem.")]
36  [StorableClass]
37  public class RandomFeasibleSolutionCreator : 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 RandomFeasibleSolutionCreator(bool deserializing) : base(deserializing) { }
52    protected RandomFeasibleSolutionCreator(RandomFeasibleSolutionCreator original, Cloner cloner) : base(original, cloner) { }
53    public RandomFeasibleSolutionCreator()
54      : base() {
55      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)));
56      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)));
57      Parameters.Add(new ValueLookupParameter<IGQAPEvaluator>("Evaluator", "The evaluator that is used to evaluate GQAP solutions."));
58    }
59
60    public override IDeepCloneable Clone(Cloner cloner) {
61      return new RandomFeasibleSolutionCreator(this, cloner);
62    }
63
64    public static IntegerVector CreateSolution(IRandom random, DoubleArray demands,
65      DoubleArray capacities, IGQAPEvaluator evaluator,
66      int maximumTries, bool createMostFeasibleSolution, CancellationToken cancel) {
67      IntegerVector result = null;
68      bool isFeasible = false;
69      int counter = 0;
70      double minViolation = double.MaxValue;
71      var slack = new DoubleArray(capacities.Length);
72      var assignment = new IntegerVector(demands.Length);
73
74      while (!isFeasible) {
75        cancel.ThrowIfCancellationRequested();
76        if (maximumTries > 0) {
77          counter++;
78          if (counter > maximumTries) {
79            if (createMostFeasibleSolution) break;
80            else throw new InvalidOperationException("A feasible solution could not be obtained after " + maximumTries + " attempts.");
81          }
82        }
83        for (int i = 0; i < capacities.Length; i++) slack[i] = capacities[i];
84        foreach (var equipment in Enumerable.Range(0, demands.Length).Shuffle(random)) {
85          var freeLocations = GetFreeLocations(equipment, demands, slack);
86          assignment[equipment] = freeLocations.SampleRandom(random);
87          slack[assignment[equipment]] -= demands[equipment];
88        }
89        double violation = evaluator.EvaluateOverbooking(slack, capacities);
90        isFeasible = violation == 0;
91        if (isFeasible || violation < minViolation) {
92          result = (IntegerVector)assignment.Clone();
93          minViolation = violation;
94        }
95      }
96      return result;
97    }
98
99    protected override IntegerVector CreateRandomSolution(IRandom random, DoubleArray demands, DoubleArray capacities) {
100      return CreateSolution(random, demands, capacities,
101        EvaluatorParameter.ActualValue,
102        MaximumTriesParameter.ActualValue.Value,
103        CreateMostFeasibleSolutionParameter.ActualValue.Value,
104        CancellationToken);
105    }
106
107    private static IEnumerable<int> GetFreeLocations(int equipment, DoubleArray demands, DoubleArray freeCapacities) {
108      var freeLocations = freeCapacities
109        .Select((v, idx) => new KeyValuePair<int, double>(idx, v))
110        .Where(x => x.Value >= demands[equipment]);
111      if (!freeLocations.Any()) {
112        freeLocations = freeCapacities
113          .Select((v, idx) => new KeyValuePair<int, double>(idx, v))
114          .OrderByDescending(x => x.Value)
115          .Take(3); // if there are none, take the three where the free capacity is largest
116      }
117      return freeLocations.Select(x => x.Key);
118    }
119  }
120}
Note: See TracBrowser for help on using the repository browser.