Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2936_GQAPIntegration/HeuristicLab.Problems.GeneralizedQuadraticAssignment/3.3/SolutionCreators/RandomButFeasibleSolutionCreator.cs @ 17328

Last change on this file since 17328 was 16712, checked in by gkronber, 6 years ago

#2936: adapted branch to new persistence (works with HL trunk r16711)

File size: 5.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 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;
33using HEAL.Attic;
34
35namespace HeuristicLab.Problems.GeneralizedQuadraticAssignment {
36  [Item("RandomButFeasibleSolutionCreator", "Creates a random, but feasible solution to the Generalized Quadratic Assignment Problem.")]
37  [StorableType("3C194DAF-81A9-4FA3-AE7F-45951FC33DE1")]
38  public class RandomFeasibleSolutionCreator : GQAPStochasticSolutionCreator {
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
47    [StorableConstructor]
48    protected RandomFeasibleSolutionCreator(StorableConstructorFlag _) : base(_) { }
49    protected RandomFeasibleSolutionCreator(RandomFeasibleSolutionCreator original, Cloner cloner) : base(original, cloner) { }
50    public RandomFeasibleSolutionCreator()
51      : base() {
52      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)));
53      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)));
54    }
55
56    public override IDeepCloneable Clone(Cloner cloner) {
57      return new RandomFeasibleSolutionCreator(this, cloner);
58    }
59
60    public static IntegerVector CreateSolution(IRandom random, GQAPInstance problemInstance,
61      int maximumTries, bool createMostFeasibleSolution, CancellationToken cancel) {
62      var capacities = problemInstance.Capacities;
63      var demands = problemInstance.Demands;
64      IntegerVector result = null;
65      bool isFeasible = false;
66      int counter = 0;
67      double minViolation = double.MaxValue;
68      var slack = new double[capacities.Length];
69      var assignment = new int[demands.Length];
70
71      while (!isFeasible) {
72        cancel.ThrowIfCancellationRequested();
73        if (maximumTries > 0) {
74          counter++;
75          if (counter > maximumTries) {
76            if (createMostFeasibleSolution) break;
77            else throw new InvalidOperationException("A feasible solution could not be obtained after " + maximumTries + " attempts.");
78          }
79        }
80        for (int i = 0; i < capacities.Length; i++) slack[i] = capacities[i];
81        foreach (var equipment in Enumerable.Range(0, demands.Length).Shuffle(random)) {
82          var freeLocations = GetFreeLocations(equipment, demands, slack);
83          assignment[equipment] = freeLocations.SampleRandom(random);
84          slack[assignment[equipment]] -= demands[equipment];
85        }
86        double violation = slack.Select(x => x < 0 ? -x : 0).Sum();
87        isFeasible = violation == 0;
88        if (isFeasible || violation < minViolation) {
89          result = new IntegerVector(assignment);
90          minViolation = violation;
91        }
92      }
93      return result;
94    }
95
96    protected override IntegerVector CreateRandomSolution(IRandom random, GQAPInstance problemInstance) {
97      return CreateSolution(random, problemInstance,
98        MaximumTriesParameter.ActualValue.Value,
99        CreateMostFeasibleSolutionParameter.ActualValue.Value,
100        CancellationToken);
101    }
102
103    private static IEnumerable<int> GetFreeLocations(int equipment, DoubleArray demands, double[] freeCapacities) {
104      var freeLocations = freeCapacities
105        .Select((v, idx) => new KeyValuePair<int, double>(idx, v))
106        .Where(x => x.Value >= demands[equipment]);
107      if (!freeLocations.Any()) {
108        freeLocations = freeCapacities
109          .Select((v, idx) => new KeyValuePair<int, double>(idx, v))
110          .OrderByDescending(x => x.Value)
111          .Take(3); // if there are none, take the three where the free capacity is largest
112      }
113      return freeLocations.Select(x => x.Key);
114    }
115  }
116}
Note: See TracBrowser for help on using the repository browser.