Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2205_OptimizationNetworks/HeuristicLab.Problems.FacilityLocation.CplexSolver/3.3/FLPCplexSolver.cs @ 17456

Last change on this file since 17456 was 14649, checked in by jkarder, 8 years ago

#2205: worked on optimization networks

  • added lrp network 3
  • fixed bug in distance calculation
  • renamed FLP.mod to FLP_1.mod
  • activated cma analyzer per default
File size: 6.5 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.IO;
24using System.Linq;
25using System.Reflection;
26using System.Threading;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Data;
30using HeuristicLab.Encodings.IntegerVectorEncoding;
31using HeuristicLab.Optimization;
32using HeuristicLab.Parameters;
33using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
34using HeuristicLab.Random;
35using ILOG.CPLEX;
36using ILOG.OPL;
37
38namespace HeuristicLab.Problems.FacilityLocation.CplexSolver {
39  public enum FlpVariant { FLP_1, FLP_2 }
40
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    public IFixedValueParameter<TimeSpanValue> MaximumRuntimeParameter {
61      get { return maximumRuntimeParameter; }
62    }
63
64    public TimeSpan MaximumRuntime {
65      get { return maximumRuntimeParameter.Value.Value; }
66      set { maximumRuntimeParameter.Value.Value = value; }
67    }
68
69    [Storable]
70    private IFixedValueParameter<EnumValue<FlpVariant>> flpVariantParameter;
71    public IFixedValueParameter<EnumValue<FlpVariant>> FlpVariantParameter {
72      get { return flpVariantParameter; }
73    }
74
75    public FlpVariant FlpVariant {
76      get { return flpVariantParameter.Value.Value; }
77      set { flpVariantParameter.Value.Value = value; }
78    }
79
80    [StorableConstructor]
81    private FLPCplexSolver(bool deserializing) : base(deserializing) { }
82    private FLPCplexSolver(FLPCplexSolver original, Cloner cloner)
83      : base(original, cloner) {
84      maximumRuntimeParameter = cloner.Clone(original.maximumRuntimeParameter);
85      flpVariantParameter = cloner.Clone(original.flpVariantParameter);
86    }
87    public FLPCplexSolver() {
88      Parameters.Add(maximumRuntimeParameter = new FixedValueParameter<TimeSpanValue>("Maximum Runtime", "Specifies how long CPLEX should be allowed to run.", new TimeSpanValue(TimeSpan.FromSeconds(60))));
89      Parameters.Add(flpVariantParameter = new FixedValueParameter<EnumValue<FlpVariant>>("FLP Variant", "Which FLP variant should be run.", new EnumValue<FlpVariant>(FlpVariant.FLP_1)));
90      Problem = new FacilityLocationProblem();
91    }
92
93    public override IDeepCloneable Clone(Cloner cloner) {
94      return new FLPCplexSolver(this, cloner);
95    }
96
97    protected override void Run(CancellationToken cancellationToken) {
98      var factory = new OplFactory();
99      var cplex = factory.CreateCplex();
100
101
102      var model = Assembly.GetExecutingAssembly().GetManifestResourceNames().SingleOrDefault(x => x.EndsWith(@"." + FlpVariant.ToString() + ".mod"));
103      var modelStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(model);
104
105      var depots = Problem.DepotCapacitiesParameter.Value.Length;
106      var customers = Problem.CustomerDemandsParameter.Value.Length;
107
108      using (var reader = new StreamReader(modelStream))
109      using (var modelSource = factory.CreateOplModelSourceFromString(reader.ReadToEnd(), Path.GetFileNameWithoutExtension(model)))
110      using (var errorHandler = factory.CreateOplErrorHandler())
111      using (var settings = factory.CreateOplSettings(errorHandler))
112      using (var def = factory.CreateOplModelDefinition(modelSource, settings))
113      using (var opl = factory.CreateOplModel(def, cplex))
114      using (var dataSource = new FLPDataSource(factory, Problem)) {
115        opl.AddDataSource(dataSource);
116        opl.Generate();
117        cplex.SetParam(Cplex.DoubleParam.TiLim, MaximumRuntimeParameter.Value.Value.TotalSeconds);
118        var solved = cplex.Solve();
119        var assignment = new IntegerVector(customers);
120        if (solved) {
121          Results.Add(new Result("BestQuality", new DoubleValue(cplex.ObjValue)));
122          Results.Add(new Result("Best Solution Optimal", new BoolValue(
123            opl.Cplex.GetCplexStatus().Equals(Cplex.CplexStatus.Optimal)
124            || opl.Cplex.GetCplexStatus().Equals(Cplex.CplexStatus.OptimalTol))));
125          Results.Add(new Result("Best Solution Feasible", new BoolValue(true)));
126
127          var sol = opl.GetElement(FLPDataSource.CustomerDepotAssignment).AsIntMap();
128
129          for (var i = 0; i < depots; i++) {
130            var solI = sol.GetSub(i);
131            for (var j = 0; j < customers; j++) {
132              var solIJ = solI.Get(j);
133              if (solIJ == 0) continue;
134              assignment[j] = i;
135            }
136          }
137        } else {
138          var demands = Problem.CustomerDemandsParameter.Value;
139          var capacities = Problem.DepotCapacitiesParameter.Value;
140
141          assignment.Randomize(new FastRandom(), 0, depots); // output a random solution
142
143          Results.Add(new Result("Best Solution Optimal", new BoolValue(false)));
144          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());
145          Results.Add(new Result("Best Solution Feasible", new BoolValue(feasible)));
146          Results.Add(new Result("BestQuality", new DoubleValue(Problem.Evaluate(assignment))));
147        }
148        Results.Add(new Result("Best Solution", assignment));
149      }
150    }
151  }
152}
Note: See TracBrowser for help on using the repository browser.