Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OptimizationNetworks/HeuristicLab.Problems.FacilityLocation.CplexSolver/3.3/FLPCplexSolver.cs @ 14595

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

#2205: Added OPL model for for the capacitated FLP (by vhauder) and a HeuristicLab algorithm to solve the model through CPLEX

File size: 5.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.Collections.Generic;
24using System.Diagnostics;
25using System.IO;
26using System.Linq;
27using System.Reflection;
28using System.Threading;
29using HeuristicLab.Common;
30using HeuristicLab.Core;
31using HeuristicLab.Data;
32using HeuristicLab.Encodings.IntegerVectorEncoding;
33using HeuristicLab.Optimization;
34using HeuristicLab.Parameters;
35using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
36using HeuristicLab.Random;
37using ILOG.CPLEX;
38using ILOG.OPL;
39
40namespace HeuristicLab.Problems.FacilityLocation.CplexSolver {
41  [Item("FLP CPLEX Solver", "Solves facility location problem (FLP) instances using CPLEX.")]
42  [Creatable(CreatableAttribute.Categories.SingleSolutionAlgorithms)]
43  [StorableClass]
44  public sealed class FLPCplexSolver : BasicAlgorithm {
45    public override bool SupportsPause {
46      get { return false; }
47    }
48
49    public override Type ProblemType {
50      get { return typeof(FacilityLocationProblem); }
51    }
52
53    public new FacilityLocationProblem Problem {
54      get { return (FacilityLocationProblem)base.Problem; }
55      set { base.Problem = value; }
56    }
57
58    [Storable]
59    private IFixedValueParameter<TimeSpanValue> maximumRuntimeParameter;
60
61    private bool supportsPause;
62
63    public IFixedValueParameter<TimeSpanValue> MaximumRuntimeParameter {
64      get { return maximumRuntimeParameter; }
65    }
66
67    [StorableConstructor]
68    private FLPCplexSolver(bool deserializing) : base(deserializing) { }
69    private FLPCplexSolver(FLPCplexSolver original, Cloner cloner)
70      : base(original, cloner) {
71      maximumRuntimeParameter = cloner.Clone(original.maximumRuntimeParameter);
72    }
73    public FLPCplexSolver() {
74      Parameters.Add(maximumRuntimeParameter = new FixedValueParameter<TimeSpanValue>("Maximum Runtime", "Specifies how long CPLEX should be allowed to run.", new TimeSpanValue(TimeSpan.FromSeconds(60))));
75      Problem = new FacilityLocationProblem();
76    }
77
78    public override IDeepCloneable Clone(Cloner cloner) {
79      return new FLPCplexSolver(this, cloner);
80    }
81
82    protected override void Run(CancellationToken cancellationToken) {
83      var factory = new OplFactory();
84      var cplex = factory.CreateCplex();
85
86      var errorHandler = factory.CreateOplErrorHandler();
87
88      var dataSource = new FLPDataSource(factory, Problem);
89      var model = Assembly.GetExecutingAssembly().GetManifestResourceNames().SingleOrDefault(x => x.EndsWith(@".FLP.mod"));
90      var modelStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(model);
91
92      var depots = Problem.DepotCapacitiesParameter.Value.Length;
93      var customers = Problem.CustomerDemandsParameter.Value.Length;
94
95      using (var reader = new StreamReader(modelStream))
96      using (var modelSource = factory.CreateOplModelSourceFromString(reader.ReadToEnd(), Path.GetFileNameWithoutExtension(model)))
97      using (var settings = factory.CreateOplSettings(errorHandler))
98      using (var def = factory.CreateOplModelDefinition(modelSource, settings))
99      using (var opl = factory.CreateOplModel(def, cplex)) {
100        opl.AddDataSource(dataSource);
101        opl.Generate();
102        cplex.SetParam(Cplex.DoubleParam.TiLim, MaximumRuntimeParameter.Value.Value.TotalSeconds);
103        //cplex.ExportModel("model.lp");
104        //opl.ConvertAllIntVars();
105        var solved = cplex.Solve();
106        var assignment = new IntegerVector(customers);
107        if (solved) {
108          Results.Add(new Result("BestQuality", new DoubleValue(cplex.ObjValue)));
109          Results.Add(new Result("Best Solution Optimal", new BoolValue(
110            opl.Cplex.GetCplexStatus().Equals(Cplex.CplexStatus.Optimal)
111            || opl.Cplex.GetCplexStatus().Equals(Cplex.CplexStatus.OptimalTol))));
112          Results.Add(new Result("Best Solution Feasible", new BoolValue(true)));
113
114          var sol = opl.GetElement(FLPDataSource.CustomerDepotAssignment).AsIntMap();
115         
116          for (var i = 0; i < depots; i++) {
117            var solI = sol.GetSub(i);
118            for (var j = 0; j < customers; j++) {
119              var solIJ = solI.Get(j);
120              if (solIJ == 0) continue;
121              assignment[j] = i;
122            }
123          }
124        } else {
125          var demands = Problem.CustomerDemandsParameter.Value;
126          var capacities = Problem.DepotCapacitiesParameter.Value;
127
128          assignment.Randomize(new FastRandom(), 0, depots); // output a random solution
129
130          Results.Add(new Result("Best Solution Optimal", new BoolValue(false)));
131          var feasible = assignment.Select((v, i) => new { Demand = demands[i], Depot = v }).GroupBy(x => x.Depot, x => x.Demand).All(x => capacities[x.Key] <= x.Sum());
132          Results.Add(new Result("Best Solution Feasible", new BoolValue(feasible)));
133          Results.Add(new Result("BestQuality", new DoubleValue(Problem.Evaluate(assignment))));
134        }
135        Results.Add(new Result("Best Solution", assignment));
136      }
137    }
138  }
139}
Note: See TracBrowser for help on using the repository browser.