LotSizingDataModel.Solver.Cplex 2.1.0
IBM ILOG CPLEX adapter and installation discovery integration.
Loading...
Searching...
No Matches
CplexSolverAdapter.cs
Go to the documentation of this file.
1using System;
2using System.Collections.Generic;
3using System.Diagnostics;
4using System.IO;
5using System.Linq;
6using System.Threading;
7using System.Threading.Tasks;
8using ILOG.CPLEX;
9using NativeCplex = global::ILOG.CPLEX.Cplex;
10using LotSizingDataModel.Solver.Adapters;
11using LotSizingDataModel.Solver.Common;
12using LotSizingDataModel.Solver.Execution;
13using LotSizingDataModel.Solver.Modeling;
14using LotSizingDataModel.Solver.Mapping;
15using LotSizingDataModel.Solver.Monitoring;
16
18
19/// <summary>
20/// Solves generic linear and mixed-integer linear models with
21/// IBM ILOG CPLEX.
22/// </summary>
23public sealed class CplexSolverAdapter :
24 MathematicalModelSolverPluginBase
25{
26 private readonly object _nativeSyncRoot =
27 new();
28
29 private NativeCplex.Aborter? _activeAborter;
30
31 /// <summary>
32 /// Initializes the CPLEX solver adapter.
33 /// </summary>
35 : base(
36 [
37 SolverCapability.LinearProgramming,
38 SolverCapability.MixedIntegerLinearProgramming,
39 SolverCapability.Interruption,
40 SolverCapability.LpExport,
41 SolverCapability.MpsExport,
42 SolverCapability.OptimalityGapReporting,
43 SolverCapability.SearchStatistics
44 ])
45 {
46 }
47
48 /// <summary>
49 /// Gets the generic solver kind.
50 /// </summary>
51 public override SolverKind SolverKind =>
52 SolverKind.Cplex;
53
54 /// <summary>
55 /// Gets the solver display name.
56 /// </summary>
57 public override string SolverName =>
58 "IBM ILOG CPLEX";
59
60 /// <summary>
61 /// Gets the native solver version when available.
62 /// </summary>
63 public override string SolverVersion
64 {
65 get
66 {
67 try
68 {
69 var cplex =
70 new NativeCplex();
71
72 try
73 {
74 return cplex.Version;
75 }
76 finally
77 {
78 cplex.End();
79 }
80 }
81 catch
82 {
83 return string.Empty;
84 }
85 }
86 }
87
88 /// <summary>
89 /// Gets the unique adapter identifier.
90 /// </summary>
91 public override string AdapterId =>
92 "LotSizingDataModel.Solver.Cplex";
93
94 /// <summary>
95 /// Gets the adapter display name.
96 /// </summary>
97 public override string AdapterName =>
98 "LotSizingDataModel CPLEX Adapter";
99
100 /// <summary>
101 /// Gets the adapter implementation version.
102 /// </summary>
103 public override string AdapterVersion =>
104 "1.0.0";
105
106 /// <summary>
107 /// Gets the minimum supported CPLEX version.
108 /// </summary>
109 public override string MinimumSupportedSolverVersion =>
110 "22.1.1";
111
112 /// <summary>
113 /// Checks whether CPLEX can be instantiated and therefore
114 /// loaded by the current process.
115 /// </summary>
116 public override ValueTask<SolverAvailabilityInfo>
118 CancellationToken cancellationToken = default)
119 {
120 cancellationToken.ThrowIfCancellationRequested();
121
122 CplexInstallationDiscoveryResult installationDiscovery =
124
125 try
126 {
127 var cplex =
128 new NativeCplex();
129
130 try
131 {
132 var availability =
133 new SolverAvailabilityInfo(
134 SolverKind.Cplex,
135 SolverAvailabilityStatus.Available)
136 {
137 SolverName =
139
141 cplex.Version
142 };
143
144 if (installationDiscovery.Installation is not null)
145 {
146 availability.InstallationPath =
147 installationDiscovery.Installation.RootDirectory;
148
149 availability.ManagedAssemblyPath =
150 installationDiscovery.Installation
151 .ManagedAssemblyDirectory;
152
153 availability.AddDiagnostic(
154 $"Compatible CPLEX installation family " +
155 $"'{installationDiscovery.Installation.Version}' " +
156 $"was discovered from " +
157 $"'{installationDiscovery.Installation.DiscoverySource}'.");
158 }
159
160 foreach (
161 string diagnostic
162 in installationDiscovery.Diagnostics)
163 {
164 availability.AddDiagnostic(
165 diagnostic);
166 }
167
168 availability.AddDiagnostic(
169 "The CPLEX managed and native runtime " +
170 "libraries were loaded successfully.");
171
172 return ValueTask.FromResult(
173 availability);
174 }
175 finally
176 {
177 cplex.End();
178 }
179 }
180 catch (Exception exception)
181 {
182 SolverAvailabilityStatus status =
183 installationDiscovery.IsFound
184 ? SolverAvailabilityStatus.LoadFailure
185 : SolverAvailabilityStatus.NotInstalled;
186
187 var availability =
188 new SolverAvailabilityInfo(
189 SolverKind.Cplex,
190 status)
191 {
192 SolverName =
194 };
195
196 if (installationDiscovery.Installation is not null)
197 {
198 availability.InstallationPath =
199 installationDiscovery.Installation.RootDirectory;
200
201 availability.ManagedAssemblyPath =
202 installationDiscovery.Installation
203 .ManagedAssemblyDirectory;
204 }
205
206 foreach (
207 string diagnostic
208 in installationDiscovery.Diagnostics)
209 {
210 availability.AddDiagnostic(
211 diagnostic);
212 }
213
214 availability.AddDiagnostic(
215 exception.Message);
216
217 return ValueTask.FromResult(
218 availability);
219 }
220 }
221
222 /// <summary>
223 /// Translates and solves one generic mathematical model.
224 /// </summary>
225 protected override async ValueTask<MathematicalModelSolveResult>
227 MathematicalModelSolveRequest request,
228 CancellationToken cancellationToken)
229 {
230 ArgumentNullException.ThrowIfNull(request);
231 ArgumentNullException.ThrowIfNull(request.Model);
232
233 var stopwatch =
234 Stopwatch.StartNew();
235
236 await PublishProgressAsync(
237 request,
238 new SolverProgressSnapshot
239 {
240 Stage =
241 SolverProgressStage.BuildingModel,
242
243 ElapsedSeconds =
244 stopwatch.Elapsed.TotalSeconds,
245
246 Message =
247 "Translating the generic mathematical model " +
248 "to IBM ILOG Concert."
249 },
250 cancellationToken);
251
252 var translator =
254
255 CplexModelTranslationResult translation =
256 translator.Translate(
257 request.Model);
258
259 NativeCplex cplex =
260 translation.Cplex;
261
262 var aborter =
263 new NativeCplex.Aborter();
264
265 cplex.Use(
266 aborter);
267
268 SetActiveAborter(
269 aborter);
270
271 try
272 {
273 var parameterMapper =
275
276 IReadOnlyList<string> parameterDiagnostics =
277 parameterMapper.Apply(
278 cplex,
279 request.Parameters);
280
281 if (request.Parameters.ExportModel)
282 {
283 string path =
284 ResolveExportPath(
285 request.Parameters.ExportModelPath);
286
287 cplex.ExportModel(
288 path);
289 }
290
291 using CancellationTokenRegistration cancellationRegistration =
292 cancellationToken.Register(
293 static state =>
294 {
295 ((NativeCplex.Aborter)state!).Abort();
296 },
297 aborter);
298
299 await PublishProgressAsync(
300 request,
301 new SolverProgressSnapshot
302 {
303 Stage =
304 SolverProgressStage.Searching,
305
306 ElapsedSeconds =
307 stopwatch.Elapsed.TotalSeconds,
308
309 Message =
310 "CPLEX optimization started."
311 },
312 cancellationToken);
313
314 bool hasSolution =
315 await Task.Run(
316 () => cplex.Solve(),
317 CancellationToken.None);
318
319 var result =
320 BuildResult(
321 request.Model,
322 translation,
323 cplex,
324 hasSolution,
325 stopwatch.Elapsed,
326 cancellationToken.IsCancellationRequested);
327
328 if (result.IsOptimal && result.ObjectiveValue is double optimum && !cancellationToken.IsCancellationRequested)
329 await MinimizeProductionSetupsAsync(request, translation, result, optimum, stopwatch, cancellationToken);
330
331 stopwatch.Stop();
332 result.SolveDuration = stopwatch.Elapsed;
333
334 foreach (string diagnostic in parameterDiagnostics)
335 {
336 result.AddDiagnostic(
337 diagnostic);
338 }
339
340 await PublishProgressAsync(
341 request,
342 new SolverProgressSnapshot
343 {
344 Stage =
345 SolverProgressStage.Completed,
346
347 ElapsedSeconds =
348 stopwatch.Elapsed.TotalSeconds,
349
350 IncumbentObjective =
351 result.ObjectiveValue,
352
353 BestBound =
354 result.BestBound,
355
356 AbsoluteGap =
357 result.AbsoluteGap,
358
359 RelativeGap =
360 result.RelativeGap,
361
362 ExploredNodeCount =
363 result.ExploredNodeCount,
364
365 IterationCount =
366 result.IterationCount,
367
368 Message =
369 $"CPLEX terminated with reason " +
370 $"'{result.TerminationReason}'."
371 },
372 CancellationToken.None);
373
374 return result;
375 }
376 finally
377 {
378 ClearActiveAborter(
379 aborter);
380
381 try
382 {
383 cplex.Remove(
384 aborter);
385 }
386 catch
387 {
388 // Model disposal remains the priority.
389 }
390
391 aborter.End();
392 cplex.End();
393 }
394 }
395
396 /// <summary>
397 /// Requests native CPLEX interruption.
398 /// </summary>
399 protected override void RequestNativeStop()
400 {
401 NativeCplex.Aborter? aborter;
402
403 lock (_nativeSyncRoot)
404 {
405 aborter =
406 _activeAborter;
407 }
408
409 aborter?.Abort();
410 }
411
412 private static async Task MinimizeProductionSetupsAsync(
413 MathematicalModelSolveRequest request,
414 CplexModelTranslationResult translation,
415 MathematicalModelSolveResult primary,
416 double optimum,
417 Stopwatch stopwatch,
418 CancellationToken cancellationToken)
419 {
420 if (request.Model is not { } model)
421 return;
422
423 var setups = model.Variables.Where(variable =>
424 variable.VariableType == MathematicalVariableType.Binary &&
425 variable.DomainKey?.StartsWith(MathematicalDecisionCategory.Setup + "|", StringComparison.Ordinal) == true)
426 .ToArray();
427 var originalCount = setups.Count(variable => primary.FindVariableValue(variable.Id)?.Value > 0.5);
428 if (originalCount == 0)
429 return;
430
431 var cplex = translation.Cplex;
432 if (request.Parameters.TimeLimitSeconds is double limit)
433 {
434 var remaining = limit - stopwatch.Elapsed.TotalSeconds;
435 if (remaining <= 0)
436 return;
437 cplex.SetParam(NativeCplex.Param.TimeLimit, remaining);
438 }
439
440 var objective = request.Model.Objective.Expression;
441 var cost = cplex.LinearNumExpr();
442 foreach (var term in objective.Terms)
443 cost.AddTerm(term.Coefficient, translation.GetVariable(term.VariableId));
444 cplex.AddEq(cost, optimum - objective.Constant, "preserve_primary_objective");
445 var setupCount = cplex.LinearNumExpr();
446 foreach (var variable in setups)
447 setupCount.AddTerm(1, translation.GetVariable(variable.Id));
448 var nativeObjective = cplex.GetObjective();
449 nativeObjective.Sense = ILOG.Concert.ObjectiveSense.Minimize;
450 nativeObjective.Expr = setupCount;
451
452 var found = await Task.Run(() => cplex.Solve(), CancellationToken.None);
453 if (!found || cancellationToken.IsCancellationRequested)
454 {
455 primary.AddDiagnostic("Production setup tie-break did not return a usable solution; primary optimum retained.");
456 return;
457 }
458
459 var values = request.Model.Variables.ToDictionary(variable => variable.Id,
460 variable => cplex.GetValue(translation.GetVariable(variable.Id)));
461 var actualCost = objective.Constant + objective.Terms.Sum(term => term.Coefficient * values[term.VariableId]);
462 var actualCount = setups.Count(variable => values[variable.Id] > 0.5);
463 if (Math.Abs(actualCost - optimum) > 1e-8 || actualCount >= originalCount)
464 return;
465
466 primary.VariableValues.Clear();
467 foreach (var variable in request.Model.Variables)
468 primary.AddVariableValue(new MathematicalVariableValue(variable.Id, values[variable.Id], variable.Name, variable.DomainKey));
469 primary.AddDiagnostic($"Production setup tie-break: {originalCount} → {actualCount} at unchanged primary objective {optimum:G17}.");
470 }
471
472 private static MathematicalModelSolveResult BuildResult(
473 MathematicalModel model,
474 CplexModelTranslationResult translation,
475 NativeCplex cplex,
476 bool hasSolution,
477 TimeSpan solveDuration,
478 bool cancellationRequested)
479 {
480 var result =
481 new MathematicalModelSolveResult
482 {
483 SolverKind =
484 SolverKind.Cplex,
485
486 SolverName =
487 "IBM ILOG CPLEX",
488
490 cplex.Version,
491
492 SolveDuration =
493 solveDuration,
494
495 HasFeasibleSolution =
496 hasSolution,
497
498 IsOptimal =
499 string.Equals(
500 cplex.GetStatus().ToString(),
501 "Optimal",
502 StringComparison.OrdinalIgnoreCase),
503
504 TerminationReason =
505 MapTerminationReason(
506 cplex.GetStatus().ToString(),
507 cplex.GetCplexStatus().ToString(),
508 hasSolution,
509 cancellationRequested),
510
511 ExploredNodeCount =
512 cplex.Nnodes64,
513
514 IterationCount =
515 cplex.Niterations64
516 };
517
518 if (hasSolution)
519 {
520 result.ObjectiveValue =
521 cplex.ObjValue;
522
523 foreach (MathematicalVariable variable in model.Variables)
524 {
525 double value =
526 cplex.GetValue(
527 translation.GetVariable(
528 variable.Id));
529
530 result.AddVariableValue(
531 new MathematicalVariableValue(
532 variable.Id,
533 value,
534 variable.Name,
535 variable.DomainKey));
536 }
537
538 TryPopulateMipStatistics(
539 result,
540 cplex);
541 }
542
543 result.AddDiagnostic(
544 $"CPLEX status: {cplex.GetStatus()}.");
545
546 result.AddDiagnostic(
547 $"CPLEX detailed status: {cplex.GetCplexStatus()}.");
548
549 return result;
550 }
551
552 private static void TryPopulateMipStatistics(
553 MathematicalModelSolveResult result,
554 NativeCplex cplex)
555 {
556 try
557 {
558 result.BestBound =
559 cplex.GetBestObjValue();
560
561 if (result.ObjectiveValue.HasValue &&
562 result.BestBound.HasValue)
563 {
564 result.AbsoluteGap =
565 Math.Abs(
566 result.ObjectiveValue.Value -
567 result.BestBound.Value);
568
569 result.RelativeGap =
570 result.AbsoluteGap.Value /
571 (1e-10 +
572 Math.Abs(
573 result.ObjectiveValue.Value));
574 }
575 }
576 catch
577 {
578 // LPs and some termination states may not expose
579 // MIP-specific bound information.
580 }
581 }
582
583 private static SolverTerminationReason MapTerminationReason(
584 string status,
585 string subStatus,
586 bool hasSolution,
587 bool cancellationRequested)
588 {
589 if (cancellationRequested)
590 {
591 return SolverTerminationReason.UserInterrupted;
592 }
593
594 if (status.Equals(
595 "Optimal",
596 StringComparison.OrdinalIgnoreCase))
597 {
598 return SolverTerminationReason.Optimal;
599 }
600
601 if (status.Equals(
602 "Infeasible",
603 StringComparison.OrdinalIgnoreCase))
604 {
605 return SolverTerminationReason.Infeasible;
606 }
607
608 if (status.Equals(
609 "Unbounded",
610 StringComparison.OrdinalIgnoreCase))
611 {
612 return SolverTerminationReason.Unbounded;
613 }
614
615 if (status.Contains(
616 "InfeasibleOrUnbounded",
617 StringComparison.OrdinalIgnoreCase))
618 {
619 return SolverTerminationReason.InfeasibleOrUnbounded;
620 }
621
622 if (subStatus.Contains(
623 "TimeLim",
624 StringComparison.OrdinalIgnoreCase))
625 {
626 return SolverTerminationReason.TimeLimit;
627 }
628
629 if (subStatus.Contains(
630 "NodeLim",
631 StringComparison.OrdinalIgnoreCase))
632 {
633 return SolverTerminationReason.NodeLimit;
634 }
635
636 if (subStatus.Contains(
637 "ItLim",
638 StringComparison.OrdinalIgnoreCase))
639 {
640 return SolverTerminationReason.IterationLimit;
641 }
642
643 if (subStatus.Contains(
644 "SolLim",
645 StringComparison.OrdinalIgnoreCase))
646 {
647 return SolverTerminationReason.SolutionLimit;
648 }
649
650 return hasSolution
651 ? SolverTerminationReason.Feasible
652 : SolverTerminationReason.Unknown;
653 }
654
655 private static string ResolveExportPath(
656 string configuredPath)
657 {
658 if (string.IsNullOrWhiteSpace(
659 configuredPath))
660 {
661 return Path.GetFullPath(
662 "LotSizingModel.lp");
663 }
664
665 string path =
666 Path.GetFullPath(
667 configuredPath);
668
669 string? directory =
670 Path.GetDirectoryName(
671 path);
672
673 if (!string.IsNullOrWhiteSpace(
674 directory))
675 {
676 Directory.CreateDirectory(
677 directory);
678 }
679
680 return path;
681 }
682
683 private void SetActiveAborter(
684 NativeCplex.Aborter aborter)
685 {
686 lock (_nativeSyncRoot)
687 {
688 _activeAborter =
689 aborter;
690 }
691 }
692
693 private void ClearActiveAborter(
694 NativeCplex.Aborter aborter)
695 {
696 lock (_nativeSyncRoot)
697 {
698 if (ReferenceEquals(
699 _activeAborter,
700 aborter))
701 {
702 _activeAborter =
703 null;
704 }
705 }
706 }
707}
global::ILOG.CPLEX.Cplex NativeCplex
Represents the result of compatible CPLEX installation discovery.
CplexInstallationInfo? Installation
Gets the selected compatible installation.
string RootDirectory
Gets the CPLEX Studio root directory.
Describes and discovers supported IBM ILOG CPLEX installations.
static CplexInstallationDiscoveryResult Discover()
Finds the newest compatible CPLEX installation visible to the current process.
Stores the native CPLEX model objects created from one solver-independent mathematical model.
INumVar GetVariable(int variableId)
Resolves a native variable by generic mathematical identifier.
Translates a solver-independent linear mathematical model to IBM ILOG Concert/CPLEX objects.
Maps normalized solver parameters to stable CPLEX parameters.
override string MinimumSupportedSolverVersion
Gets the minimum supported CPLEX version.
override SolverKind SolverKind
Gets the generic solver kind.
override string AdapterName
Gets the adapter display name.
override string AdapterVersion
Gets the adapter implementation version.
override string SolverVersion
Gets the native solver version when available.
override async ValueTask< MathematicalModelSolveResult > SolveCoreAsync(MathematicalModelSolveRequest request, CancellationToken cancellationToken)
Translates and solves one generic mathematical model.
override ValueTask< SolverAvailabilityInfo > CheckAvailabilityAsync(CancellationToken cancellationToken=default)
Checks whether CPLEX can be instantiated and therefore loaded by the current process.
override string SolverName
Gets the solver display name.
CplexSolverAdapter()
Initializes the CPLEX solver adapter.
override void RequestNativeStop()
Requests native CPLEX interruption.
override string AdapterId
Gets the unique adapter identifier.