-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathcbc.py
More file actions
2247 lines (1750 loc) · 77.9 KB
/
cbc.py
File metadata and controls
2247 lines (1750 loc) · 77.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Python-MIP interface to the COIN-OR Branch-and-Cut solver CBC"""
import logging
from typing import Dict, List, Tuple, Optional, Union
from sys import platform, maxsize
from os.path import dirname, isfile, exists
import os
import multiprocessing as multip
import numbers
from cffi import FFI
from mip.model import xsum
import mip
from mip.lists import EmptyVarSol, EmptyRowSol
from mip.exceptions import (
ParameterNotAvailable,
InvalidParameter,
MipBaseException,
)
from mip import (
Model,
Var,
Constr,
Column,
LinExpr,
VConstrList,
VVarList,
Solver,
MAXIMIZE,
SearchEmphasis,
CONTINUOUS,
BINARY,
INTEGER,
MINIMIZE,
EQUAL,
LESS_OR_EQUAL,
GREATER_OR_EQUAL,
OptimizationStatus,
LP_Method,
CutType,
CutPool,
)
logger = logging.getLogger(__name__)
warningMessages = 0
ffi = FFI()
has_cbc = False
os_is_64_bit = maxsize > 2**32
INF = float("inf")
cut_idx = 0
# for variables and rows
MAX_NAME_SIZE = 512
DEF_PUMPP = 30
try:
pathmip = dirname(mip.__file__)
pathlib = os.path.join(pathmip, "libraries")
libfile = ""
# if user wants to force the loading of an specific CBC library
# (for debugging purposes, for example)
if "PMIP_CBC_LIBRARY" in os.environ:
libfile = os.environ["PMIP_CBC_LIBRARY"]
pathlib = dirname(libfile)
if platform.lower().startswith("win"):
if pathlib not in os.environ["PATH"]:
os.environ["PATH"] += ";" + pathlib
else:
if "linux" in platform.lower():
if os_is_64_bit:
pathlibe = pathlib
libfile = os.path.join(pathlib, "cbc-c-linux-x86-64.so")
if not exists(libfile):
pathlibe = pathlib
libfile = os.path.join(pathlib, "cbc-c-linux-x86-64.so")
pathlib = pathlibe
else:
raise NotImplementedError("Linux 32 bits platform not supported.")
elif platform.lower().startswith("win"):
if os_is_64_bit:
pathlibe = os.path.join(pathlib, "win64")
libfile = os.path.join(pathlibe, "cbc-c-windows-x86-64.dll")
if exists(libfile):
if pathlibe not in os.environ["PATH"]:
os.environ["PATH"] = pathlibe + ";" + os.environ["PATH"]
else:
pathlibe = pathlib
libfile = os.path.join(pathlibe, "cbc-c-windows-x86-64.dll")
if pathlibe not in os.environ["PATH"]:
os.environ["PATH"] = pathlibe + ";" + os.environ["PATH"]
pathlib = pathlibe
else:
raise NotImplementedError("Win32 platform not supported.")
elif platform.lower().startswith("darwin") or platform.lower().startswith(
"macos"
):
if os_is_64_bit:
libfile = os.path.join(pathlib, "cbc-c-darwin-x86-64.dylib")
if not libfile:
raise NotImplementedError("You operating system/platform is not supported")
old_dir = os.getcwd()
os.chdir(pathlib)
cbclib = ffi.dlopen(libfile)
os.chdir(old_dir)
has_cbc = True
except Exception as e:
logger.error("An error occurred while loading the CBC library:\t " "{}\n".format(e))
has_cbc = False
if has_cbc:
ffi.cdef(
"""
typedef int(*cbc_progress_callback)(void *model,
int phase,
int step,
const char *phaseName,
double seconds,
double lb,
double ub,
int nint,
int *vecint,
void *cbData
);
typedef void(*cbc_callback)(void *model, int msgno, int ndouble,
const double *dvec, int nint, const int *ivec,
int nchar, char **cvec);
typedef void(*cbc_cut_callback)(void *osiSolver, void *osiCuts, void *appdata, int level, int npass);
typedef int (*cbc_incumbent_callback)(void *cbcModel,
double obj, int nz,
char **vnames, double *x, void *appData);
typedef void Cbc_Model;
void *Cbc_newModel();
void Cbc_readLp(Cbc_Model *model, const char *file);
int Cbc_readBasis(Cbc_Model *model, const char *filename);
int Cbc_writeBasis(Cbc_Model *model, const char *filename, char
writeValues, int formatType);
void Cbc_readMps(Cbc_Model *model, const char *file);
char Cbc_supportsGzip();
char Cbc_supportsBzip2();
void Cbc_writeLp(Cbc_Model *model, const char *file);
void Cbc_writeMps(Cbc_Model *model, const char *file);
int Cbc_getNumCols(Cbc_Model *model);
int Cbc_getNumRows(Cbc_Model *model);
int Cbc_getNumIntegers(Cbc_Model *model);
int Cbc_getNumElements(Cbc_Model *model);
int Cbc_getRowNz(Cbc_Model *model, int row);
int *Cbc_getRowIndices(Cbc_Model *model, int row);
double *Cbc_getRowCoeffs(Cbc_Model *model, int row);
double Cbc_getRowRHS(Cbc_Model *model, int row);
void Cbc_setRowRHS(Cbc_Model *model, int row, double rhs);
char Cbc_getRowSense(Cbc_Model *model, int row);
const double *Cbc_getRowActivity(Cbc_Model *model);
const double *Cbc_getRowSlack(Cbc_Model *model);
int Cbc_getColNz(Cbc_Model *model, int col);
int *Cbc_getColIndices(Cbc_Model *model, int col);
double *Cbc_getColCoeffs(Cbc_Model *model, int col);
void Cbc_addCol(Cbc_Model *model, const char *name,
double lb, double ub, double obj, char isInteger,
int nz, int *rows, double *coefs);
void Cbc_addRow(Cbc_Model *model, const char *name, int nz,
const int *cols, const double *coefs, char sense, double rhs);
void Cbc_addLazyConstraint(Cbc_Model *model, int nz,
int *cols, double *coefs, char sense, double rhs);
void Cbc_addSOS(Cbc_Model *model, int numRows, const int *rowStarts,
const int *colIndices, const double *weights, const int type);
int Cbc_numberSOS(Cbc_Model *model);
void Cbc_setObjCoeff(Cbc_Model *model, int index, double value);
double Cbc_getObjSense(Cbc_Model *model);
const double *Cbc_getObjCoefficients(Cbc_Model *model);
const double *Cbc_getColSolution(Cbc_Model *model);
const double *Cbc_getReducedCost(Cbc_Model *model);
double *Cbc_bestSolution(Cbc_Model *model);
int Cbc_numberSavedSolutions(Cbc_Model *model);
const double *Cbc_savedSolution(Cbc_Model *model, int whichSol);
double Cbc_savedSolutionObj(Cbc_Model *model, int whichSol);
double Cbc_getObjValue(Cbc_Model *model);
void Cbc_setObjSense(Cbc_Model *model, double sense);
int Cbc_isProvenOptimal(Cbc_Model *model);
int Cbc_isProvenInfeasible(Cbc_Model *model);
int Cbc_isContinuousUnbounded(Cbc_Model *model);
int Cbc_isAbandoned(Cbc_Model *model);
const double *Cbc_getColLower(Cbc_Model *model);
const double *Cbc_getColUpper(Cbc_Model *model);
double Cbc_getColObj(Cbc_Model *model, int colIdx);
double Cbc_getColLB(Cbc_Model *model, int colIdx);
double Cbc_getColUB(Cbc_Model *model, int colIdx);
void Cbc_setColLower(Cbc_Model *model, int index, double value);
void Cbc_setColUpper(Cbc_Model *model, int index, double value);
int Cbc_isInteger(Cbc_Model *model, int i);
void Cbc_getColName(Cbc_Model *model,
int iColumn, char *name, size_t maxLength);
void Cbc_getRowName(Cbc_Model *model,
int iRow, char *name, size_t maxLength);
void Cbc_setContinuous(Cbc_Model *model, int iColumn);
void Cbc_setInteger(Cbc_Model *model, int iColumn);
/*! Integer parameters */
enum IntParam {
INT_PARAM_PERT_VALUE = 0, /*! Method of perturbation, -5000 to 102, default 50 */
INT_PARAM_IDIOT = 1, /*! Parameter of the "idiot" method to try to produce an initial feasible basis. -1 let the solver decide if this should be applied; 0 deactivates it and >0 sets number of passes. */
INT_PARAM_STRONG_BRANCHING = 2, /*! Number of variables to be evaluated in strong branching. */
INT_PARAM_CUT_DEPTH = 3, /*! Sets the application of cuts to every depth multiple of this value. -1, the default value, let the solve decide. */
INT_PARAM_MAX_NODES = 4, /*! Maximum number of nodes to be explored in the search tree */
INT_PARAM_NUMBER_BEFORE = 5, /*! Number of branches before trusting pseudocodes computed in strong branching. */
INT_PARAM_FPUMP_ITS = 6, /*! Maximum number of iterations in the feasibility pump method. */
INT_PARAM_MAX_SOLS = 7, /*! Maximum number of solutions generated during the search. Stops the search when this number of solutions is found. */
INT_PARAM_CUT_PASS_IN_TREE = 8, /*! Maximum number of cuts passes in the search tree (with the exception of the root node). Default 1. */
INT_PARAM_THREADS = 9, /*! Number of threads that can be used in the branch-and-bound method.*/
INT_PARAM_CUT_PASS = 10, /*! Number of cut passes in the root node. Default -1, solver decides */
INT_PARAM_LOG_LEVEL = 11, /*! Verbosity level, from 0 to 2 */
INT_PARAM_MAX_SAVED_SOLS = 12, /*! Size of the pool to save the best solutions found during the search. */
INT_PARAM_MULTIPLE_ROOTS = 13, /*! Multiple root passes to get additional cuts and solutions. */
INT_PARAM_ROUND_INT_VARS = 14, /*! If integer variables should be round to remove small infeasibilities. This can increase the overall amount of infeasibilities in problems with both continuous and integer variables */
INT_PARAM_RANDOM_SEED = 15, /*! When solving LP and MIP, randomization is used to break ties in some decisions. This changes the random seed so that multiple executions can produce different results */
INT_PARAM_ELAPSED_TIME = 16, /*! When =1 use elapsed (wallclock) time, otherwise use CPU time */
INT_PARAM_CGRAPH = 17, /*! Conflict graph: controls if the conflict graph is created or not. 0: off, 1: auto, 2: on 3: fast weaker clique sep */
INT_PARAM_CLIQUE_MERGING = 18, /*! Clique merging options: 0: off , 1 auto , 2 before solving LP, 3 after solving LP and pre-processing */
INT_PARAM_MAX_NODES_NOT_IMPROV_FS = 19, /*! Maximum number of nodes processed without improving best solution, after a feasible solution is found */
};
#define N_INT_PARAMS 20
void Cbc_setIntParam(Cbc_Model *model, enum IntParam which, const int val);
/*! Double parameters
* */
enum DblParam {
DBL_PARAM_PRIMAL_TOL = 0, /*! Tollerance to consider a solution feasible in the linear programming solver. */
DBL_PARAM_DUAL_TOL = 1, /*! Tollerance for a solution to be considered optimal in the linear programming solver. */
DBL_PARAM_ZERO_TOL = 2, /*! Coefficients less that this value will be ignored when reading instances */
DBL_PARAM_INT_TOL = 3, /*! Maximum allowed distance from integer value for a variable to be considered integral */
DBL_PARAM_PRESOLVE_TOL = 4, /*! Tollerance used in the presolver, should be increased if the pre-solver is declaring infeasible a feasible problem */
DBL_PARAM_TIME_LIMIT = 5, /*! Time limit in seconds */
DBL_PARAM_PSI = 6, /*! Two dimensional princing factor in the Positive Edge pivot strategy. */
DBL_PARAM_CUTOFF = 7, /*! Only search for solutions with cost less-or-equal to this value. */
DBL_PARAM_ALLOWABLE_GAP = 8, /*! Allowable gap between the lower and upper bound to conclude the search */
DBL_PARAM_GAP_RATIO = 9, /*! Stops the search when the difference between the upper and lower bound is less than this fraction of the larger value */
DBL_PARAM_MAX_SECS_NOT_IMPROV_FS = 10, /*! Maximum processing time without improving best solution, after a feasible solution is found */
};
#define N_DBL_PARAMS 11
void Cbc_setDblParam(Cbc_Model *model, enum DblParam which, const double val);
void Cbc_setParameter(Cbc_Model *model, const char *name,
const char *value);
double Cbc_getCutoff(Cbc_Model *model);
void Cbc_setCutoff(Cbc_Model *model, double cutoff);
double Cbc_getAllowableGap(Cbc_Model *model);
void Cbc_setAllowableGap(Cbc_Model *model, double allowedGap);
double Cbc_getAllowableFractionGap(Cbc_Model *model);
void Cbc_setAllowableFractionGap(Cbc_Model *model,
double allowedFracionGap);
double Cbc_getAllowablePercentageGap(Cbc_Model *model);
void Cbc_setAllowablePercentageGap(Cbc_Model *model,
double allowedPercentageGap);
double Cbc_getMaximumSeconds(Cbc_Model *model);
void Cbc_setMaximumSeconds(Cbc_Model *model, double maxSeconds);
int Cbc_getMaximumNodes(Cbc_Model *model);
void Cbc_setMaximumNodes(Cbc_Model *model, int maxNodes);
int Cbc_getMaximumSolutions(Cbc_Model *model);
void Cbc_setMaximumSolutions(Cbc_Model *model, int maxSolutions);
int Cbc_getLogLevel(Cbc_Model *model);
void Cbc_setLogLevel(Cbc_Model *model, int logLevel);
double Cbc_getBestPossibleObjValue(Cbc_Model *model);
void Cbc_setMIPStart(Cbc_Model *model, int count,
const char **colNames, const double colValues[]);
void Cbc_setMIPStartI(Cbc_Model *model, int count, const int colIdxs[],
const double colValues[]);
enum LPMethod {
LPM_Auto = 0, /*! Solver will decide automatically which method to use */
LPM_Dual = 1, /*! Dual simplex */
LPM_Primal = 2, /*! Primal simplex */
LPM_Barrier = 3, /*! The barrier algorithm */
LPM_BarrierNoCross = 4 /*! Barrier algorithm, not to be followed by crossover */
};
void
Cbc_setLPmethod(Cbc_Model *model, enum LPMethod lpm );
void Cbc_updateConflictGraph( Cbc_Model *model );
const void *Cbc_conflictGraph( Cbc_Model *model );
int Cbc_solve(Cbc_Model *model);
int Cbc_solveLinearProgram(Cbc_Model *model);
/*! Type of cutting plane */
enum CutType {
CT_Probing = 0, /*! Cuts generated evaluating the impact of fixing bounds for integer variables */
CT_Gomory = 1, /*! Gomory cuts obtained from the tableau, implemented by John Forrest */
CT_GMI = 2, /*! Gomory cuts obtained from the tableau, implementation from Giacomo Nannicini focusing on safer cuts */
CT_LaGomory = 3, /*! Additional gomory cuts, simplification of 'A Relax-and-Cut Framework for Gomory's Mixed-Integer Cuts' by Matteo Fischetti & Domenico Salvagnin */
CT_RedSplit = 4, /*! Reduce and split cuts, implemented by Francois Margot */
CT_RedSplitG = 5, /*! Reduce and split cuts, implemented by Giacomo Nannicini */
CT_FlowCover = 6, /*! Flow cover cuts */
CT_MIR = 7, /*! Mixed-integer rounding cuts */
CT_TwoMIR = 8, /*! Two-phase Mixed-integer rounding cuts */
CT_LaTwoMIR = 9, /*! Lagrangean relaxation for two-phase Mixed-integer rounding cuts, as in CT_LaGomory */
CT_LiftAndProject = 10, /*! Lift and project cuts */
CT_ResidualCapacity = 11, /*! Residual capacity cuts */
CT_ZeroHalf = 12, /*! Zero-half cuts */
CT_Clique = 13, /*! Clique cuts */
CT_OddWheel = 14, /*! Lifted odd-hole inequalities */
CT_KnapsackCover = 15, /*! Knapsack cover cuts */
};
void Cbc_generateCuts( Cbc_Model *cbcModel, enum CutType ct, void *oc, int depth, int pass );
void Cbc_strengthenPacking(Cbc_Model *model);
void Cbc_strengthenPackingRows(Cbc_Model *model, size_t n, const size_t rows[]);
void *Cbc_getSolverPtr(Cbc_Model *model);
void *Cbc_deleteModel(Cbc_Model *model);
int Osi_getNumIntegers( void *osi );
const double *Osi_getReducedCost( void *osi );
const double *Osi_getObjCoefficients();
double Osi_getObjSense();
void *Osi_newSolver();
void Osi_deleteSolver( void *osi );
void Osi_initialSolve(void *osi);
void Osi_resolve(void *osi);
void Osi_branchAndBound(void *osi);
char Osi_isAbandoned(void *osi);
char Osi_isProvenOptimal(void *osi);
char Osi_isProvenPrimalInfeasible(void *osi);
char Osi_isProvenDualInfeasible(void *osi);
char Osi_isPrimalObjectiveLimitReached(void *osi);
char Osi_isDualObjectiveLimitReached(void *osi);
char Osi_isIterationLimitReached(void *osi);
double Osi_getObjValue( void *osi );
void Osi_setColUpper (void *osi, int elementIndex, double ub);
void Osi_setColLower(void *osi, int elementIndex, double lb);
int Osi_getNumCols( void *osi );
void Osi_getColName( void *osi, int i, char *name, int maxLen );
const double *Osi_getColLower( void *osi );
const double *Osi_getColUpper( void *osi );
int Osi_isInteger( void *osi, int col );
int Osi_getNumRows( void *osi );
int Osi_getRowNz(void *osi, int row);
const int *Osi_getRowIndices(void *osi, int row);
const double *Osi_getRowCoeffs(void *osi, int row);
double Osi_getRowRHS(void *osi, int row);
char Osi_getRowSense(void *osi, int row);
void Osi_setObjCoef(void *osi, int index, double obj);
void Osi_setObjSense(void *osi, double sense);
const double *Osi_getColSolution(void *osi);
void *OsiCuts_new();
void OsiCuts_addRowCut( void *osiCuts, int nz, const int *idx,
const double *coef, char sense, double rhs );
void OsiCuts_addGlobalRowCut( void *osiCuts, int nz, const int *idx,
const double *coef, char sense, double rhs );
int OsiCuts_sizeRowCuts( void *osiCuts );
int OsiCuts_nzRowCut( void *osiCuts, int iRowCut );
const int * OsiCuts_idxRowCut( void *osiCuts, int iRowCut );
const double *OsiCuts_coefRowCut( void *osiCuts, int iRowCut );
double OsiCuts_rhsRowCut( void *osiCuts, int iRowCut );
char OsiCuts_senseRowCut( void *osiCuts, int iRowCut );
void OsiCuts_delete( void *osiCuts );
void Osi_addCol(void *osi, const char *name, double lb, double ub,
double obj, char isInteger, int nz, int *rows, double *coefs);
void Osi_addRow(void *osi, const char *name, int nz,
const int *cols, const double *coefs, char sense, double rhs);
void Cbc_deleteRows(Cbc_Model *model, int numRows, const int rows[]);
void Cbc_deleteCols(Cbc_Model *model, int numCols, const int cols[]);
void Cbc_storeNameIndexes(Cbc_Model *model, char _store);
int Cbc_getColNameIndex(Cbc_Model *model, const char *name);
int Cbc_getRowNameIndex(Cbc_Model *model, const char *name);
void Cbc_problemName(Cbc_Model *model, int maxNumberCharacters,
char *array);
int Cbc_setProblemName(Cbc_Model *model, const char *array);
double Cbc_getPrimalTolerance(Cbc_Model *model);
void Cbc_setPrimalTolerance(Cbc_Model *model, double tol);
double Cbc_getDualTolerance(Cbc_Model *model);
void Cbc_setDualTolerance(Cbc_Model *model, double tol);
void Cbc_addCutCallback(Cbc_Model *model, cbc_cut_callback cutcb,
const char *name, void *appData, int howOften, char atSolution );
void Cbc_addIncCallback(
void *model, cbc_incumbent_callback inccb,
void *appData );
void Cbc_registerCallBack(Cbc_Model *model,
cbc_callback userCallBack);
void Cbc_addProgrCallback(void *model,
cbc_progress_callback prgcbc, void *appData);
void Cbc_clearCallBack(Cbc_Model *model);
const double *Cbc_getRowPrice(Cbc_Model *model);
const double *Osi_getRowPrice(void *osi);
double Osi_getIntegerTolerance(void *osi);
void Osi_checkCGraph( void *osi );
const void * Osi_CGraph( void *osi );
size_t CG_nodes( void *cgraph );
char CG_conflicting( void *cgraph, int n1, int n2 );
double CG_density( void *cgraph );
typedef struct {
size_t n;
const size_t *neigh;
} CGNeighbors;
CGNeighbors CG_conflictingNodes(Cbc_Model *model, void *cgraph, size_t node);
void Cbc_computeFeatures(Cbc_Model *model, double *features);
int Cbc_nFeatures();
const char *Cbc_featureName(int i);
void Cbc_reset(Cbc_Model *model);
"""
)
CHAR_ONE = "{}".format(chr(1)).encode("utf-8")
CHAR_ZERO = "\0".encode("utf-8")
DBL_PARAM_PRIMAL_TOL = 0
DBL_PARAM_DUAL_TOL = 1
DBL_PARAM_ZERO_TOL = 2
DBL_PARAM_INT_TOL = 3
DBL_PARAM_PRESOLVE_TOL = 4
DBL_PARAM_TIME_LIMIT = 5
DBL_PARAM_PSI = 6
DBL_PARAM_CUTOFF = 7
DBL_PARAM_ALLOWABLE_GAP = 8
DBL_PARAM_GAP_RATIO = 9
DBL_PARAM_MAX_SECS_NOT_IMPROV_FS = 10
INT_PARAM_PERT_VALUE = 0
INT_PARAM_IDIOT = 1
INT_PARAM_STRONG_BRANCHING = 2
INT_PARAM_CUT_DEPTH = 3
INT_PARAM_MAX_NODES = 4
INT_PARAM_NUMBER_BEFORE = 5
INT_PARAM_FPUMP_ITS = 6
INT_PARAM_MAX_SOLS = 7
INT_PARAM_CUT_PASS_IN_TREE = 8
INT_PARAM_THREADS = 9
INT_PARAM_CUT_PASS = 10
INT_PARAM_LOG_LEVEL = 11
INT_PARAM_MAX_SAVED_SOLS = 12
INT_PARAM_MULTIPLE_ROOTS = 13
INT_PARAM_ROUND_INT_VARS = 14
INT_PARAM_RANDOM_SEED = 15
INT_PARAM_ELAPSED_TIME = 16
INT_PARAM_CGRAPH = 17
INT_PARAM_CLIQUE_MERGING = 18
INT_PARAM_MAX_NODES_NOT_IMPROV_FS = 19
Osi_getNumCols = cbclib.Osi_getNumCols
Osi_getColSolution = cbclib.Osi_getColSolution
Osi_getIntegerTolerance = cbclib.Osi_getIntegerTolerance
Osi_isInteger = cbclib.Osi_isInteger
Osi_isProvenOptimal = cbclib.Osi_isProvenOptimal
Cbc_setIntParam = cbclib.Cbc_setIntParam
Cbc_setDblParam = cbclib.Cbc_setDblParam
Cbc_getSolverPtr = cbclib.Cbc_getSolverPtr
Cbc_generateCuts = cbclib.Cbc_generateCuts
Cbc_solveLinearProgram = cbclib.Cbc_solveLinearProgram
Cbc_reset = cbclib.Cbc_reset
Cbc_computeFeatures = cbclib.Cbc_computeFeatures
Cbc_nFeatures = cbclib.Cbc_nFeatures
Cbc_featureName = cbclib.Cbc_featureName
OsiCuts_new = cbclib.OsiCuts_new
OsiCuts_addRowCut = cbclib.OsiCuts_addRowCut
OsiCuts_addGlobalRowCut = cbclib.OsiCuts_addGlobalRowCut
OsiCuts_sizeRowCuts = cbclib.OsiCuts_sizeRowCuts
OsiCuts_nzRowCut = cbclib.OsiCuts_nzRowCut
OsiCuts_idxRowCut = cbclib.OsiCuts_idxRowCut
OsiCuts_coefRowCut = cbclib.OsiCuts_coefRowCut
OsiCuts_rhsRowCut = cbclib.OsiCuts_rhsRowCut
OsiCuts_senseRowCut = cbclib.OsiCuts_senseRowCut
OsiCuts_delete = cbclib.OsiCuts_delete
def cbc_set_parameter(model: Solver, param: str, value: str):
cbclib.Cbc_setParameter(model._model, param.encode("utf-8"), value.encode("utf-8"))
class SolverCbc(Solver):
def __init__(self, model: Model, name: str, sense: str):
super().__init__(model, name, sense)
self._model = cbclib.Cbc_newModel()
cbclib.Cbc_storeNameIndexes(self._model, CHAR_ONE)
self.iidx_space = 4096
self.iidx = ffi.new("int[%d]" % self.iidx_space)
self.dvec = ffi.new("double[%d]" % self.iidx_space)
self._objconst = 0.0
# to not add cut generators twice when reoptimizing
self.added_cut_callback = False
self.added_inc_callback = False
# setting objective sense
if sense == MAXIMIZE:
cbclib.Cbc_setObjSense(self._model, -1.0)
self.emphasis = SearchEmphasis.DEFAULT
self.__threads = 0
self.__verbose = 1
# pre-allocate temporary space to query names
self.__name_space = ffi.new("char[{}]".format(MAX_NAME_SIZE))
# in cut generation
self.__name_spacec = ffi.new("char[{}]".format(MAX_NAME_SIZE))
self.__log = (
[]
) # type: List[Tuple[numbers.Real, Tuple[numbers.Real, numbers.Real]]]
self.set_problem_name(name)
self.__pumpp = DEF_PUMPP
# where solution will be stored
self.__x = EmptyVarSol(model)
self.__rc = EmptyVarSol(model)
self.__pi = EmptyRowSol(model)
self.__slack = EmptyRowSol(model)
self.__obj_val = None
self.__obj_bound = None
self.__num_solutions = 0
def __clear_sol(self: "SolverCbc"):
self.__x = EmptyVarSol(self.model)
self.__rc = EmptyVarSol(self.model)
self.__pi = EmptyRowSol(self.model)
self.__slack = EmptyRowSol(self.model)
self.__obj_val = None
self.__obj_bound = None
self.__num_solutions = 0
def add_var(
self,
obj: numbers.Real = 0,
lb: numbers.Real = 0,
ub: numbers.Real = float("inf"),
coltype: str = "C",
column: Optional[Column] = None,
name: str = "",
):
if column is None:
vind = ffi.NULL
vval = ffi.NULL
numnz = 0
else:
numnz = len(column.constrs)
vind = ffi.new("int[]", [c.idx for c in column.constrs])
vval = ffi.new("double[]", [coef for coef in column.coeffs])
isInt = (
CHAR_ONE if coltype.upper() == "B" or coltype.upper() == "I" else CHAR_ZERO
)
cbclib.Cbc_addCol(
self._model,
name.encode("utf-8"),
lb,
ub,
obj,
isInt,
numnz,
vind,
vval,
)
def update_conflict_graph(self: "SolverCbc"):
cbclib.Cbc_updateConflictGraph(self._model)
def cgraph_density(self: "SolverCbc") -> float:
cg = cbclib.Cbc_conflictGraph(self._model)
if cg == ffi.NULL:
return 0.0
return cbclib.CG_density(cg)
def conflicting(
self: "SolverCbc",
e1: Union["LinExpr", "Var"],
e2: Union["LinExpr", "Var"],
) -> bool:
idx1, idx2 = (None, None)
if isinstance(e1, Var):
idx1 = e1.idx
elif isinstance(e1, LinExpr):
if len(e1.expr) == 1 and e1.sense == EQUAL:
v1 = next(iter(e1.expr.keys()))
if abs(e1.const) <= 1e-15:
idx1 = v1.idx + v1.model.num_cols
elif abs(e1.const + 1.0) <= 1e-15:
idx1 = v1.idx
else:
raise InvalidParameter(
"LinExpr should contain an "
"assignment to a binary variable, "
"e.g.: x1 == 1"
)
else:
raise InvalidParameter(
"LinExpr should contain an "
"assignment to a binary variable, "
"e.g.: x1 == 1"
)
else:
raise TypeError("type {} not supported".format(type(e1)))
if isinstance(e2, Var):
idx2 = e2.idx
elif isinstance(e2, LinExpr):
if len(e2.expr) == 1 and e2.sense == EQUAL:
v2 = next(iter(e2.expr.keys()))
if abs(e2.const) <= 1e-15:
idx2 = v2.idx + v2.model.num_cols
elif abs(e2.const + 1.0) <= 1e-15:
idx2 = v2.idx
else:
raise InvalidParameter(
"LinExpr should contain an "
"assignment to a binary variable, "
"e.g.: x1 == 1"
)
else:
raise InvalidParameter(
"LinExpr should contain an "
"assignment to a binary variable, "
"e.g.: x1 == 1"
)
else:
raise TypeError("type {} not supported".format(type(e2)))
cg = cbclib.Cbc_conflictGraph(self._model)
if cg == ffi.NULL:
return False
return cbclib.CG_conflicting(cg, idx1, idx2) == CHAR_ONE
def conflicting_nodes(
self: "SolverCbc", v1: Union["Var", "LinExpr"]
) -> Tuple[List["Var"], List["Var"]]:
"""Returns all assignment conflicting with the assignment in v1 in the
conflict graph.
"""
cg = cbclib.Cbc_conflictGraph(self._model)
if cg == ffi.NULL:
return (list(), list())
idx1 = None
if isinstance(v1, Var):
idx1 = v1.idx
elif isinstance(v1, LinExpr):
if len(v1.expr) == 1 and v1.sense == EQUAL:
var = next(iter(v1.expr.keys()))
if abs(v1.const) <= 1e-15:
idx1 = var.idx + var.model.num_cols
elif abs(v1.const + 1.0) <= 1e-15:
idx1 = var.idx
else:
raise InvalidParameter(
"LinExpr should contain an "
"assignment to a binary variable, "
"e.g.: x1 == 1"
)
else:
raise InvalidParameter(
"LinExpr should contain an "
"assignment to a binary variable, "
"e.g.: x1 == 1"
)
else:
raise TypeError("type {} not supported".format(type(v1)))
cgn = cbclib.CG_conflictingNodes(self._model, cg, idx1)
n = cgn.n
neighs = cgn.neigh
cols = self.model.num_cols
l1, l0 = list(), list()
for i in range(n):
if cgn.neigh[i] < cols:
l1.append(self.model.vars[neighs[i]])
else:
l0.append(self.model.vars[neighs[i] - cols])
return (l1, l0)
def get_objective_const(self) -> numbers.Real:
return self._objconst
def get_objective(self) -> LinExpr:
obj = cbclib.Cbc_getObjCoefficients(self._model)
if obj == ffi.NULL:
raise ParameterNotAvailable("Error getting objective function coefficients")
return (
xsum(
obj[j] * self.model.vars[j]
for j in range(self.num_cols())
if abs(obj[j]) >= 1e-15
)
+ self._objconst
)
def set_objective(self, lin_expr: "LinExpr", sense: str = "") -> None:
# collecting variable coefficients
c = ffi.new("double[]", [0.0 for i in range(self.num_cols())])
for var, coeff in lin_expr.expr.items():
c[var.idx] = coeff
for i in range(self.num_cols()):
cbclib.Cbc_setObjCoeff(self._model, i, c[i])
# objective function constant
self._objconst = lin_expr.const
# setting objective sense
if MAXIMIZE in (lin_expr.sense, sense):
cbclib.Cbc_setObjSense(self._model, -1.0)
elif MINIMIZE in (lin_expr.sense, sense):
cbclib.Cbc_setObjSense(self._model, 1.0)
def relax(self):
for var in self.model.vars:
if cbclib.Cbc_isInteger(self._model, var.idx):
cbclib.Cbc_setContinuous(self._model, var.idx)
def get_max_seconds(self) -> numbers.Real:
return cbclib.Cbc_getMaximumSeconds(self._model)
def set_max_seconds(self, max_seconds: numbers.Real):
cbclib.Cbc_setMaximumSeconds(self._model, max_seconds)
def get_max_solutions(self) -> int:
return cbclib.Cbc_getMaximumSolutions(self._model)
def set_max_solutions(self, max_solutions: int):
cbclib.Cbc_setMaximumSolutions(self._model, max_solutions)
def get_max_nodes(self) -> int:
return cbclib.Cbc_getMaximumNodes(self._model)
def set_max_nodes(self, max_nodes: int):
cbclib.Cbc_setMaximumNodes(self._model, max_nodes)
def get_verbose(self) -> int:
return self.__verbose
def set_verbose(self, verbose: int):
self.__verbose = verbose
def var_set_var_type(self, var: "Var", value: str):
cv = var.var_type
if value == cv:
return
if cv == CONTINUOUS:
if value == INTEGER or value == BINARY:
cbclib.Cbc_setInteger(self._model, var.idx)
else:
if value == CONTINUOUS:
cbclib.Cbc_setContinuous(self._model, var.idx)
if value == BINARY:
# checking bounds
if var.lb != 0.0:
var.lb = 0.0
if var.ub != 1.0:
var.ub = 1.0
def var_set_obj(self, var: "Var", value: numbers.Real):
cbclib.Cbc_setObjCoeff(self._model, var.idx, value)
def generate_cuts(
self,
cut_types: Optional[List[CutType]] = None,
depth: int = 0,
npass: int = 0,
max_cuts: int = maxsize,
min_viol: numbers.Real = 1e-4,
) -> CutPool:
cp = CutPool()
cbc_model = self._model
osi_solver = Cbc_getSolverPtr(cbc_model)
osi_cuts = OsiCuts_new()
nbin = 0
for v in self.model.vars:
if v.var_type == BINARY:
nbin += 1
if not cut_types:
cut_types = [
CutType.GOMORY,
CutType.MIR,
CutType.TWO_MIR,
CutType.KNAPSACK_COVER,
CutType.CLIQUE,
CutType.ZERO_HALF,
CutType.ODD_WHEEL,
]
for cut_type in cut_types:
if self.__verbose >= 1:
logger.info(
"searching for violated " "{} cuts ... ".format(cut_type.name)
)
if nbin == 0:
if cut_type in [CutType.CLIQUE, CutType.ODD_WHEEL]:
continue
nc1 = OsiCuts_sizeRowCuts(osi_cuts)
Cbc_generateCuts(
self._model,
int(cut_type.value),
osi_cuts,
int(depth),
int(npass),
)
nc2 = OsiCuts_sizeRowCuts(osi_cuts)
if self.__verbose >= 1:
logger.info("{} found.\n".format(nc2 - nc1))
if OsiCuts_sizeRowCuts(osi_cuts) >= max_cuts:
break
for i in range(OsiCuts_sizeRowCuts(osi_cuts)):
rhs = OsiCuts_rhsRowCut(osi_cuts, i)
rsense = OsiCuts_senseRowCut(osi_cuts, i).decode("utf-8").upper()
sense = ""
if rsense == "E":
sense = EQUAL
elif rsense == "L":
sense = LESS_OR_EQUAL
elif rsense == "G":
sense = GREATER_OR_EQUAL
else:
raise ValueError("Unknow sense: {}".format(rsense))
idx = OsiCuts_idxRowCut(osi_cuts, i)
coef = OsiCuts_coefRowCut(osi_cuts, i)
nz = OsiCuts_nzRowCut(osi_cuts, i)
model = self.model
levars = [model.vars[idx[j]] for j in range(nz)]
lecoefs = [coef[j] for j in range(nz)]
cut = LinExpr(levars, lecoefs, -rhs, sense)
if cut.violation < min_viol:
continue
cp.add(cut)
OsiCuts_delete(osi_cuts)
return cp