Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GeneralizedQAP/HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms/3.3/LocalSolverNet/GQAPIntegerSolver.cs @ 15575

Last change on this file since 15575 was 15575, checked in by abeham, 6 years ago

#1614:

  • Added two LocalSolver models (binary and integer)
File size: 6.8 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.Threading;
24using HeuristicLab.Common;
25using HeuristicLab.Core;
26using HeuristicLab.Data;
27using HeuristicLab.Encodings.IntegerVectorEncoding;
28using HeuristicLab.Optimization;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30using localsolver;
31
32namespace HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms.LocalSolverNet {
33  [Item("LocalSolver Integer (GQAP)", "LocalSolver algorithm solving the GQAP using integer decision variables")]
34  [StorableClass]
35  [Creatable(CreatableAttribute.Categories.Algorithms)]
36  public sealed class GQAPIntegerSolver : ContextAlgorithm<LocalSolverContext, IntegerVectorEncoding> {
37    public override bool SupportsPause {
38      get { return false; }
39    }
40
41    public override Type ProblemType {
42      get { return typeof(GQAP); }
43    }
44
45    public new GQAP Problem {
46      get { return (GQAP)base.Problem; }
47      set { base.Problem = value; }
48    }
49
50    // LS Program variables
51    private LSExpression[] x;
52    private LSExpression obj;
53    private LocalSolver localSolver;
54
55
56    [StorableConstructor]
57    private GQAPIntegerSolver(bool deserializing) : base(deserializing) { }
58    private GQAPIntegerSolver(GQAPIntegerSolver original, Cloner cloner)
59    : base(original, cloner) {
60    }
61    public GQAPIntegerSolver() {
62    }
63
64    public override IDeepCloneable Clone(Cloner cloner) {
65      return new GQAPIntegerSolver(this, cloner);
66    }
67
68    private double prevObj;
69    private DateTime lastUpdate;
70    private CancellationToken token;
71
72    private void LocalSolverOnIterationTicked(LocalSolver ls, LSCallbackType type) {
73      IResult result;
74      Context.Iterations++;
75      if ((DateTime.UtcNow - lastUpdate) > TimeSpan.FromSeconds(1)) {
76        if (Results.TryGetValue("Iterations", out result))
77          ((IntValue)result.Value).Value = Context.Iterations;
78        else Results.Add(new Result("Iterations", new IntValue(Context.Iterations)));
79        lastUpdate = DateTime.UtcNow;
80      }
81
82      if (token.IsCancellationRequested) localSolver.Stop();
83
84      var curObj = obj.GetDoubleValue();
85
86      if (curObj >= prevObj) return;
87      prevObj = curObj;
88      Context.BestQuality = curObj;
89           
90      if (Results.TryGetValue("BestQuality", out result))
91        ((DoubleValue)result.Value).Value = Context.BestQuality;
92      else Results.Add(new Result("BestQuality", new DoubleValue(Context.BestQuality)));
93
94      var locations = Problem.ProblemInstance.Capacities.Length;
95      var best = new int[Problem.ProblemInstance.Demands.Length];
96      for (var i = 0; i < best.Length; i++) {
97        best[i] = (int)x[i].GetIntValue();
98      }
99      var bestVec = new IntegerVector(best);
100      var eval = Problem.ProblemInstance.Evaluate(bestVec);
101      Context.BestSolution = new GQAPSolution(bestVec, eval);
102
103      var scope = Context.ToScope(new GQAPSolution(new IntegerVector(best), (Evaluation)eval.Clone()), Problem.ProblemInstance.ToSingleObjective(eval));
104      Context.ReplaceIncumbent(scope);
105
106      if (Results.TryGetValue("BestSolution", out result))
107        result.Value = Context.BestSolution;
108      else Results.Add(new Result("BestSolution", Context.BestSolution));
109
110      Context.RunOperator(Analyzer, CancellationToken.None);
111    }
112
113    protected override void Initialize(CancellationToken cancellationToken) {
114      base.Initialize(cancellationToken);
115
116      prevObj = double.MaxValue;
117    }
118
119    protected override void Run(CancellationToken cancellationToken) {
120      token = cancellationToken;
121      lastUpdate = DateTime.UtcNow.AddSeconds(-1);
122      localSolver = new LocalSolver();
123
124      // Declares the optimization model
125      LSModel model = localSolver.GetModel();
126
127      var data = Problem.ProblemInstance;
128
129      // x[f] = location l, f ... facility/equipment
130      x = new LSExpression[data.Demands.Length];
131      for (int f = 0; f < data.Demands.Length; f++) {
132        x[f] = model.Int(0, data.Capacities.Length - 1);
133      }
134
135      // All locations contain not more equipments than there is capacity for
136      for (int l = 0; l < data.Capacities.Length; l++) {
137        var util = model.Sum();
138        for (var f = 0; f < data.Demands.Length; f++)
139          util.AddOperand((x[f] == l) * data.Demands[f]);
140        model.Constraint(util <= data.Capacities[l]);
141      }
142
143      // Create distances as an array to be accessed by an at operator
144      var distancesJagged = new double[data.Capacities.Length][];
145      for (var i = 0; i < data.Capacities.Length; i++) {
146        distancesJagged[i] = new double[data.Capacities.Length];
147        for (var j = 0; j < data.Capacities.Length; j++)
148          distancesJagged[i][j] = data.Distances[i, j];
149      }
150      var installJagged = new double[data.Demands.Length][];
151      for (var i = 0; i < data.Demands.Length; i++) {
152        installJagged[i] = new double[data.Capacities.Length];
153        for (var j = 0; j < data.Capacities.Length; j++)
154          installJagged[i][j] = data.InstallationCosts[i, j];
155      }
156      LSExpression distancesArray = model.Array(distancesJagged);
157      LSExpression installCostsArray = model.Array(installJagged);
158
159      // Minimize the sum of product distance*flow
160      obj = model.Sum();
161      for (int f1 = 0; f1 < data.Demands.Length; f1++) {
162        for (int f2 = 0; f2 < data.Demands.Length; f2++) {
163          obj.AddOperand(data.TransportationCosts * data.Weights[f1, f2] * distancesArray[x[f1], x[f2]]);
164        }
165        obj.AddOperand(installCostsArray[f1, x[f1]]);
166      }
167
168      model.Minimize(obj);
169
170      try {
171        model.Close();
172
173        // Parameterizes the solver.
174        LSPhase phase = localSolver.CreatePhase();
175        phase.SetTimeLimit((int)Math.Ceiling(MaximumRuntime.TotalSeconds));
176
177        localSolver.AddCallback(LSCallbackType.IterationTicked, LocalSolverOnIterationTicked);
178
179        localSolver.Solve();
180      } finally {
181        localSolver.Dispose();
182      }
183    }
184  }
185}
Note: See TracBrowser for help on using the repository browser.