Examples
Examples
EXAMPLE TOUR
1 Introduction 7
2 Example tour 8
2.1 A list of the Gurobi examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.2 Load and solve a model from a le . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.3 Build a model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.4 Additional modeling elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.5 Modify a model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.6 Change parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.7 Automated parameter tuning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.8 Diagnose and cope with infeasibility . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.9 MIP starts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.10 Model-data separation in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.11 Callbacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2
tune_c.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
workforce1_c.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
workforce2_c.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
workforce3_c.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
workforce4_c.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
workforce5_c.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
3.2 C++ Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
callback_c++.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
dense_c++.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
diet_c++.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
facility_c++.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
feasopt_c++.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
xanddive_c++.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
genconstr_c++.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
lp_c++.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
lpmethod_c++.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
lpmod_c++.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
mip1_c++.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
mip2_c++.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
multiobj_c++.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
params_c++.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
piecewise_c++.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
poolsearch_c++.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
sensitivity_c++.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
qcp_c++.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
qp_c++.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
sos_c++.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
sudoku_c++.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
tsp_c++.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
tune_c++.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
workforce1_c++.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
workforce2_c++.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
workforce3_c++.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
workforce4_c++.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
workforce5_c++.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
3.3 Java Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
Callback.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
Dense.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
Diet.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
Facility.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
Feasopt.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
Fixanddive.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
Genconstr.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
Lp.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
Lpmethod.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
3
Lpmod.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
Mip1.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
Mip2.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
Multiobj.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
Params.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
Piecewise.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
Poolsearch.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
Qcp.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
Qp.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
Sensitivity.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
Sos.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
Sudoku.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Tsp.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
Tune.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
Workforce1.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
Workforce2.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
Workforce3.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
Workforce4.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
Workforce5.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
3.4 C# Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
callback_cs.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
dense_cs.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
diet_cs.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
facility_cs.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
feasopt_cs.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
xanddive_cs.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
genconstr_cs.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
lp_cs.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
lpmethod_cs.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
lpmod_cs.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
mip1_cs.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
mip2_cs.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
multiobj_cs.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
params_cs.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
piecewise_cs.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
poolsearch_cs.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380
qcp_cs.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
qp_cs.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385
sensitivity_cs.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
sos_cs.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
sudoku_cs.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
tsp_cs.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
tune_cs.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
workforce1_cs.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
workforce2_cs.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406
4
workforce3_cs.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
workforce4_cs.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
workforce5_cs.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
3.5 Visual Basic Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
callback_vb.vb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
dense_vb.vb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
diet_vb.vb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
facility_vb.vb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432
feasopt_vb.vb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
xanddive_vb.vb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
genconstr_vb.vb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
lp_vb.vb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
lpmethod_vb.vb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
lpmod_vb.vb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
mip1_vb.vb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
mip2_vb.vb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454
multiobj_vb.vb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
params_vb.vb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
piecewise_vb.vb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
poolsearch_vb.vb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
qcp_vb.vb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
qp_vb.vb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
sensitivity_vb.vb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473
sos_vb.vb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476
sudoku_vb.vb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478
tsp_vb.vb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
tune_vb.vb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
workforce1_vb.vb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
workforce2_vb.vb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492
workforce3_vb.vb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496
workforce4_vb.vb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
workforce5_vb.vb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504
3.6 Python Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509
callback.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509
custom.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513
dense.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514
diet.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516
diet2.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
diet3.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
diet4.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522
dietmodel.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
facility.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526
feasopt.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529
xanddive.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531
genconstr.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
5
lp.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536
lpmethod.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
lpmod.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
mip1.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
mip2.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542
multiobj.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544
netow.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 547
params.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 550
piecewise.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551
poolsearch.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
portfolio.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557
qcp.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
qp.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
sensitivity.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563
sos.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565
sudoku.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 566
tsp.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569
tune.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572
workforce1.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
workforce2.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
workforce3.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 579
workforce4.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
workforce5.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 586
3.7 MATLAB Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589
diet.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589
intlinprog.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592
linprog.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596
lp.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599
lp2.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 600
mip1.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 601
piecewise.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 602
qcp.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 604
qp.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 606
sos.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 607
3.8 R Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 608
lp.R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 608
lp2.R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 610
mip.R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 611
piecewise.R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 612
qcp.R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 614
qp.R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 615
sos.R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 616
6
Introduction
The GurobiTM distribution includes an extensive set of examples that illustrate commonly used
features of the Gurobi libraries. Most examples have versions for C, C++, C#, Java, Visual Basic,
and Python. A few, however, illustrate features that are specic to the Python interface.
The distribution also includes examples for our MATLAB
R and R interfaces. Note, however,
that our interfaces to these languages are built around the assumption that you will use the rich
matrix-oriented capabilities of the underlying languages to build your optimization models. Thus,
our examples for these languages don't attempt to show you how to build models. We have instead
chosen to provide a few simple examples that demonstrate how to pass matrices into our interface.
This document provides a brief tour of these examples. We won't go through each example in
detail. Instead, we'll start with an Overview of the set of tasks that you are likely to want to perform
with the Gurobi Optimizer. Later sections will then describe how specic examples accomplish each
of these tasks. Alternatively, we provide a Structured List of all of our examples, which you can use
to dive directly into an example of interest to you. In either case, we suggest that you browse the
example source code (in a text editor, or in another browser window) while reading this document.
This document includes Source Code for all of the examples, in all available languages. Source les
are also available in the examples directory of the Gurobi distribution.
If you would like further details on any of the Gurobi routines used in these examples, please
consult the Gurobi Reference Manual.
7
Example tour
This document provides a quick guided tour of the Gurobi examples; we will try to highlight some
of the most important features of these examples. Full source code is provided in this document, so
you are free to explore the examples in full detail.
Wherever possible, we try to discuss the examples in a manner that is independent of pro-
gramming languages. We will refer to each example using a brief, language independent name.
You will need to map this name to the specic source le name for your language. For example,
the facility example corresponds to six dierent implementations, one in C (facility_c.c), one
in C++ (facility_c++.cpp), one in Java (Facility.java), one in C# (facility_cs.cs), one in Visual
Basic (facility_vb.vb), and one in Python (facility.py). If you would like to look at the language
implementation for a particular example, please refer to the appropriate example source le.
Topics covered in the examples
The easiest place to start your introduction to the Gurobi examples is probably with the examples
that load and solve a model from a le. These demonstrate the most basic capabilities of the Gurobi
libraries. They also demonstrate the use of model attributes, which are an important concept in
the Gurobi optimizer.
Once you are comfortable with these examples, you should move on to the examples that build
a model from scratch. These show you how to create variables and constraints, and add them to
an optimization model.
The next topic covered in this document is model modication. The Gurobi distribution includes
examples that add and remove constraints, add variables, and change variable types, bounds and
objective coecients. You modify a model in much the same way that you build a model from
scratch, but there are some important dierences involving the use of the solution information.
Next, this document covers parameter changes. The params example shows you how to change
parameters, and in particular how to use dierent parameter settings for dierent models.
On a related note, the tuning section demonstrates the use of our automated tuning tool. This
tool searches for parameter settings that improve performance on a particular model.
The infeasibility section considers a few examples that cope with model infeasibility. Some use
an Irreducible Inconsistent Subsystem (IIS) to handle the infeasibility, while others relax constraints.
One useful MIP feature that is worth understanding is MIP starts. A MIP start allows you to
specify a known feasible solution to the MIP solver. The solution provides a bound on the objective
of the best possible solution, which can help to limit the MIP search. The solution also provides a
potential start point for the local search heuristics that are utilized by the Gurobi MIP solver.
It is possible to achieve model-data separation when using our Python interface, as is often done
in modeling languages, but you need to make use of Python modules to do so. The model-data
separation section provides an example of how this is done. It considers three versions of the diet
example. All three use the same function to formulate and solve the actual optimization model, but
they obtain model data from very dierent places.
The nal topic we cover in this document is Gurobi callbacks. Callbacks allow the user to obtain
periodic progress information related to the optimization.
8
2.1 A list of the Gurobi examples
We recommend that you begin by reading the overview of the examples (which begins in the next
section). However, if you'd like to dive directly into a specic example, the following is a list of all
of the examples included in the Gurobi distribution, organized by basic function. The source for the
examples can be found by following the provided links, or in the examples directory of the Gurobi
distribution.
Read a model from a le
• lp - A very simple example that reads a continuous model from a le, optimizes it, and writes
the solution to a le. If the model is infeasible, it writes an Irreducible Inconsistent Subsystem
(IIS) instead. C, C++, C#, Java, Python, VB.
• mip2 - Reads a MIP model from a le, optimizes it, and then solves the xed version of the
MIP model. C, C++, C#, Java, Python, VB.
• qp - Builds a trivial QP model, solves it, converts it to an MIQP model, and solves it again.
C, C++, C#, Java, MATLAB, Python, R, VB.
• qcp - Builds and solves a trivial QCP model. C, C++, C#, Java, MATLAB, Python, R, VB.
• sos - Builds and solves a trivial SOS model. C, C++, C#, Java, MATLAB, Python, R, VB.
• dense - Solves a model stored using dense matrices. We don't recommend using dense ma-
trices, but this example may be helpful if your data is already in this format. C, C++, C#,
Java, Python, VB.
• genconstr - Demonstrates the use of general constraints. C, C++, C#, Java, Python, VB.
• multiobj - Demonstrates the use of multi-objective optimization. C, C++, C#, Java, Python,
VB.
• piecewise - Demonstrates the use of piecewise-linear objective functions. C, C++, C#, Java,
MATLAB, Python, R, VB.
• poolsearch - Demonstrates the use of solution pools. C, C++, C#, Java, Python, VB.
• diet2, diet3, diet4, dietmodel - Python-only variants of the diet example that illustrate
model-data separation. diet2.py, diet3.py, diet4.py, dietmodel.py.
9
• facility - Simple facility location model: given a set of plants and a set of warehouses, with
transportation costs between them, this example nds the least expensive set of plants to open
in order to satisfy product demand. This example demonstrates the use of MIP starts the
example computes an initial, heuristic solution and passes that solution to the MIP solver. C,
C++, C#, Java, Python, VB.
• portfolio - A Python-only example that solves a nancial portfolio optimization model, where
the historical return data is stored using the pandas package and the result is plotted using the
matplotlib package. It demonstrates the use of pandas, NumPy, and Matplotlib in conjunction
with Gurobi. Python.
• sudoku - Reads a Sudoku puzzle dataset from a le, builds a MIP model to solve that model,
solves it, and prints the solution. C, C++, C#, Java, Python, VB.
• workforce1 - Formulates and solves a workforce scheduling model. If the model is infeasible,
the example computes and prints an Irreducible Inconsistent Subsystem (IIS). C, C++, C#,
Java, Python, VB.
• workforce3 - A dierent enhancement of workforce1. This example solves the same work-
force scheduling model, but if the model is infeasible, it adds articial variables to each con-
straint and minimizes the sum of the articial variables. This corresponds to nding the
minimum total change in the right-hand side vector required in order to make the model
feasible. Demonstrates variable addition. C, C++, C#, Java, Python, VB.
10
Illustrating specic features
• feasopt - Reads a MIP model from a le, adds articial slack variables to relax each constraint,
and then minimizes the sum of the articial variables. It then computes the same relaxation
using the feasibility relaxation feature. The example demonstrates simple model modication
by adding slack variables. It also demonstrates the feasibility relaxation feature. C, C++,
C#, Java, Python, VB.
• lpmethod - Demonstrates the use of dierent LP algorithms. Reads a continuous model from
a le and solves it using multiple algorithms, reporting which is the quickest for that model.
C, C++, C#, Java, Python, VB.
• lpmod - Demonstrates the use of advanced starts in LP. Reads a continuous model from a
le, solves it, and then modies one variable bound. The resulting model is then solved in two
dierent ways: starting from the solution of the original model, or restarting from scratch. C,
C++, C#, Java, Python, VB.
• params - Demonstrates the use of Gurobi parameters. Reads a MIP model from a le, and
then spends 5 seconds solving the model with each of four dierent values of the MIPFocus
parameter. It compares the optimality gaps for the four dierent runs, and continues with
the MIPFocus value that produced the smallest gap. C, C++, C#, Java, Python, VB.
• sensitivity - MIP sensitivity analysis. Reads a MIP model, solves it, and then computes the
objective impact of xing each binary variable in the model to 0 or 1. Demonstrates simple
MIP model modication by changing variable bounds. C, C++, C#, Java, Python, VB.
• tune - Uses the parameter tuning tool to search for improved parameter settings for a model.
C, C++, C#, Java, Python, VB.
• xanddive - Implements a simple MIP heuristic. It reads a MIP model from a le, relaxes the
integrality conditions, and then solves the relaxation. It then chooses a set of integer variables
that take integer or nearly integer values in the relaxation, xes them to the nearest integer,
and solves the relaxation again. This process is repeated until the relaxation is either integer
feasible or linearly infeasible. The example demonstrates dierent types of model modication
(relaxing integrality conditions, changing variable bounds, etc.). C, C++, C#, Java, Python,
VB.
• callback - Demonstrates the use of Gurobi callbacks. C, C++, C#, Java, Python, VB.
11
lp_vb.vb) and mip2 (mip2_c.c, mip2_c++.cpp, mip2_cs.cs, Mip2.java, mip2.py, mip2_vb.vb)
examples are simple illustratations of how this is done in the various supported Gurobi languages.
While the specics vary from one language to another, the basic structure remains the same for all
languages.
After initializing the Gurobi environment, the examples begin by reading the model from the
specied le. In C, you call the GRBreadmodel() function:
error = GRBreadmodel(masterenv, argv[1], &model);
In C++, this is done by constructing a GRBModel object:
GRBModel model = GRBModel(env, argv[1]);
In C# and Java, this is also done by constructing a GRBModel object:
GRBModel model = new GRBModel(env, args[0]);
In Python, this is done via the read global function:
model = read(sys.argv[1])
The next step is to invoke the Gurobi optimizer on the model. In C, you call GRBoptimize()
on the model variable:
error = GRBoptimize(model);
In C++, Java, and Python, this is accomplished by calling the optimize method on the model
object:
model.optimize();
In C#, the rst letter of the method name is capitalized:
model.Optimize();
A successful optimize call populates a set of solution attributes in the model. For example, once
the call completes, the X variable attribute contains the solution value for each variable. Similarly,
for continuous models, the Pi constraint attribute contains the dual value for each constraint.
The examples then retrieve the value of the model Status attribute to determine the result of
the optimization. In the lp example, an optimal solution is written to a solution le (model.sol).
There are many other things you can do once you have read and solved the model. For example,
lp checks the solution status which is highly recommended. If the model is found to be infeasible,
this example computes an Irreducible Inconsistent Subsystem (IIS) to isolate the source of the
infeasibility.
12
error = GRBnewmodel(env, &model, "mip1", 0, NULL, NULL, NULL, NULL);
You can optionally create a set of variables when you create the model, as well as specifying bounds,
objective coecients, and names for these variables. These examples add new variables separately.
In C++, C#, and Java, you create a new model using the GRBModel constructor. In Java, this
looks like:
In Python, the class is called Model, and its constructor is similar to the GRBModel constructor for
C++ and Java.
Once the model has been created, the typical next step is to add variables. In C, you use the
GRBaddvars function to add one or more variables:
error = GRBaddvars(model, 3, 0, NULL, NULL, NULL, obj, NULL, NULL, vtype, NULL);
In C++, Java, and Python, you use the addVar method on the Model object (AddVar in C#). In
Java, this looks like:
The new variable's lower bound, upper bound, objective coecient, type, and name are specied
as arguments. In C++ and Python, you can omit these arguments and use default values; see the
Gurobi Reference Manual for details.
The next step is to add constraints to the model. Linear constraints are added through the
GRBaddconstr function in C:
To add a linear constraint in C, you must specify a list of variable indices and coecients for the
left-hand side, a sense for the constraint (e.g., GRB_LESS_EQUAL), and a right-hand side constant.
You can also give the constraint a name; if you omit the name, Gurobi will assign a default name
for the constraint.
In C++, C#, Java, and Python, you build a linear constraint by rst building linear expressions
for the left- and right-hand sides. In Java, which doesn't support operator overloading, you build
an expression as follows:
You then use the addConstr method on the GRBModel object to add a constraint using these linear
expressions for the left- and right-hand sides:
For C++, C#, and Python, the standard mathematical operators such as +, *, <= have been
overloaded so that the linear expression resembles a traditional mathematical expression. In C++:
13
Once the model has been built, the typical next step is to optimize it (using GRBoptimize in
C, model.optimize in C++, Java, and Python, or model.Optimize in C#). You can then query
the X attribute on the variables to retrieve the solution (and the VarName attribute to retrieve the
variable name for each variable). In C, the X attribute is retrieved as follows:
In C++:
In Java:
System.out.println(x.get(GRB.StringAttr.VarName) +
" " + x.get(GRB.DoubleAttr.X));
System.out.println(y.get(GRB.StringAttr.VarName) +
" " + y.get(GRB.DoubleAttr.X));
System.out.println(z.get(GRB.StringAttr.VarName) +
" " + z.get(GRB.DoubleAttr.X));
In C#:
Console.WriteLine(x.Get(GRB.StringAttr.VarName) +
" " + x.Get(GRB.DoubleAttr.X));
Console.WriteLine(y.Get(GRB.StringAttr.VarName) +
" " + y.Get(GRB.DoubleAttr.X));
Console.WriteLine(z.Get(GRB.StringAttr.VarName) +
" " + z.Get(GRB.DoubleAttr.X));
In Python:
for v in m.getVars():
print(v.varName, v.x)
14
We should point out one important subtlely in our interface. We use a lazy update approach to
building and modifying a model. When you make changes, they are added to a queue. The queue is
only ushed when you optimize the model (or write it to a le). In the uncommon situation where
you want to query information about your model before optimizing it, you should call the update
method before making your query.
15
minVar.ub = 0
The model is re-solved simply by calling the optimize method again. For a continuous model, this
starts the optimization from the previous solution. To illustrate the dierence when solving the
model from an initial, unsolved state, the lpmod example calls the reset function. In C:
error = GRBresetmodel(model);
m.reset()
In C#:
m.Reset()
When we call the optimize method after resetting the model, optimization starts from scratch.
Although the dierence in computation time is insignicant for this tiny example, a warm start can
make a big dierence for larger models.
xanddive
The fixanddive example provides another example of bound modication. In this case, we repeat-
edly modify a set of variable bounds, utilizing warm starts each time. In C, variables are xed as
follows:
for i in range(nfix):
v = fractional[i]
fixval = int(v.x + 0.5)
v.lb = fixval
v.ub = fixval
Again, the subsequent call to optimize starts from the previous solution.
sensitivity
The sensitivity example computes the amount by which the optimal objective changes if each
binary variable is xed at either 0 or 1. For each binary variable, the example creates and solves a
copy of the model with new upper and lower bounds. This example is a MIP, so Gurobi can not
make use of advanced start information. As a result, the model is solved from scratch after each
bound modication.
16
feasopt
The last modication example we consider is feasopt, which adds variables to existing constraints
and also changes the optimization objective. Setting the objective to zero is straightforward: simply
call setObjective with a zero argument:
m.setObjective(0)
Adding new variables is somewhat more complex. In the example, we want to add articial vari-
able(s) to each constraint in order to allow the constraint to be relaxed. We use two articial
variables for equality constraints and one for inequality constraints. The Python code for adding a
single articial variable to constraint c is:
model.set(GRB_IntParam_MIPFocus, i);
In Java:
model.set(GRB.IntParam.MIPFocus, i);
In C#:
model.Parameters.MIPFocus = 1
or
model.Set(GRB.IntParam.MIPFocus, i);
In Python:
model.Params.MIPFocus = i
17
We should add a comment on how parameter settings propagate between dierent models. When
we set the TimeLimit parameter on the base model, then make a copy of that model, the parameter
setting is carried over to the copy. When we set the MIPFocus parameter on the copy, that parameter
change has no eect on the other copies, nor on the original model.
error = GRBtunemodel(model);
In Java:
model.tune();
This routine solves the model multiple times, with dierent parameter settings, to nd settings that
improve performance.
Once tuning is complete, you would then use GetTuneResult to retrieve the result. In C:
model.getTuneResult(0);
The numerical argument indicates which tuning result to retrieve (0 is the best result, 1 is the
second-best, etc.). This routine loads the requested parameter set into the environment associated
with the argument model.
Once the tune parameter settings have been loaded into the model, you can then call Optimize
to use these parameters to solve the model, or you can call Write to write these parameters to a
.prm le.
18
Subsystem (IIS). The user can then inspect this information to understand and hopefully address
the source of the infeasibility in the model.
Example workforce2 is similar, except that if the model is infeasible, the example repeatedly
identies an IIS and removes one of the associated constraints from the model until the model
becomes feasible. Note that it is sucient to remove one constraint from the IIS to address that
source of infeasibility, but that one IIS may not capture all sources of infeasibility. It is therefore
necessary to repeat the process until the model is feasible.
Example workforce3 takes a dierent approach to addressing infeasibility. Rather than iden-
tifying and removing IIS members, it allows the constraints of the model to be relaxed. Like the
feasopt example, an articial variable is added to each constraint. The example sets the objective
on the original variables to zero, and then solves a model that minimizes the total magnitude of the
constraint relaxation.
The feasopt example demonstrates another approach to relaxing an infeasible model. It com-
putes a feasibility relaxation for the infeasible model. A feasibility relaxation is a model that, when
solved, minimizes the amount by which the solution violates the bounds and linear constraints of
the original model. This method is invoked as follows:
In C:
error = GRBfeasrelax(feasmodel, GRB_FEASRELAX_LINEAR, 1,
NULL, NULL, rhspen, &feasobj);
In C++:
feasmodel1.feasRelax(GRB_FEASRELAX_LINEAR, true, false, true);
In C#:
feasmodel1.FeasRelax(GRB.FEASRELAX_LINEAR, true, false, true);
In Java:
feasmodel1.feasRelax(GRB.FEASRELAX_LINEAR, true, false, true);
In Python:
feasmodel1.FeasRelaxS(0, True, False, True);
The arguments to this method select the objective function for the relaxed model, the specic
set of bounds and constraints that are allowed to be relaxed, and the penalties for relaxing specic
bounds and constraints.
19
plant has a maximum production capacity and a xed operating cost. Additionally, there is a cost
associated with shipping products from a plant to a warehouse. The goal is to decide which plants
should satisfy the demand for the product, given the associated capacities and costs.
The example uses a simple heuristic for choosing an initial solution: it closes the plant with the
highest xed cost. The associated solution may not be optimal, but it could produce a reasonable
starting solution for the MIP optimization. The MIP start is passed to the MIP solver by setting
the Start attribute before the optimization begins. In C, we set the start attribute to open all
plants using the following code:
for (p = 0; p < nPlants; ++p)
{
error = GRBsetdblattrelement(model, "Start", opencol(p), 1.0);
if (error) goto QUIT;
}
In Python:
for p in range(nPlants):
open[p].start = 1.0
When you run the example, the MIP solver reports that the start produced a feasible initial
solution:
Loaded MIP start with objective 210500
This initial solution turns out to be optimal for the sample data. Although the computation
dierence is insignicant for this tiny example, providing a good starting solution can sometimes
help for more dicult models.
Note that the MIP start in this example only species values for some of the variables the
variables that determine which plants to leave open and which plants to close. The Gurobi MIP
solve uses whatever start information is provided to try to construct a complete solution.
20
import dietmodel
dietmodel.solve(categories, minNutrition, maxNutrition, foods, cost, nutritionValues)
The rst statement imports the dietmodel module, which must be stored in le dietmodel.py
in the current directory. The second passes the model data to the solve function in the newly
imported module.
2.11 Callbacks
Example: callback
The nal example we consider is callback, which demonstrates the use of Gurobi callbacks.
Callbacks are used to report on the progress of the optimization or to modify the behavior of the
Gurobi solver. To use a callback, the user writes a routine that implements the desired behavior.
The routine is passed to the Gurobi optimizer when optimization begins, and the routine is called
regularly during the optimization process. One argument of the user routine is a where value, which
indicates from where in the optimization process the callback is invoked. The user callback routine
can call the optimization library to query certain values. We refer the reader to the callback section
of the Gurobi Reference Manual for more precise details.
Our callback example implements a simple termination scheme: the user passes a node count
into the callback, and the callback asks the optimizer to terminate when that node count is reached.
This is implemented in C as follows:
nodecnt = model.cbGet(GRB.Callback.MIP_NODCNT)
if nodecnt > model._mynodelimit:
model.terminate()
To obtain the current node count, the user routine calls the cbget routine (the GRBcbget function
in C, or the cbGet method on the model object in C++, C#, Java, and Python).
Our callback example also prints progress information. In C:
nodecnt = model.cbGet(GRB.Callback.MIP_NODCNT)
if nodecnt % 100 == 0:
print(int(nodecnt), "...")
Again, the user callback calls the cbGet routine to query the state of the optimization.
21
Example Source Code
We have included source code for all of the distributed examples in this section. The identical
example source code is included in the examples directory in the Gurobi distribution.
3.1 C Examples
This section includes source code for all of the Gurobi C examples. The same source code can be
found in the examples/c directory of the Gurobi distribution.
callback_c.c
/* Copyright 2016, Gurobi Optimization, Inc. */
/*
This example reads a model from a file, sets up a callback that
monitors optimization progress and implements a custom
termination strategy, and outputs progress information to the
screen and to a log file.
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "gurobi_c.h"
struct callback_data {
double lastiter;
double lastnode;
22
double *solution;
FILE *logfile;
};
int __stdcall
mycallback(GRBmodel *model,
void *cbdata,
int where,
void *usrdata)
{
struct callback_data *mydata = (struct callback_data *) usrdata;
if (where == GRB_CB_POLLING) {
/* Ignore polling callback */
} else if (where == GRB_CB_PRESOLVE) {
/* Presolve callback */
int cdels, rdels;
GRBcbget(cbdata, where, GRB_CB_PRE_COLDEL, &cdels);
GRBcbget(cbdata, where, GRB_CB_PRE_ROWDEL, &rdels);
if (cdels || rdels) {
printf("%7d columns and %7d rows are removed\n", cdels, rdels);
}
} else if (where == GRB_CB_SIMPLEX) {
/* Simplex callback */
double itcnt, obj, pinf, dinf;
int ispert;
char ch;
GRBcbget(cbdata, where, GRB_CB_SPX_ITRCNT, &itcnt);
if (itcnt - mydata->lastiter >= 100) {
mydata->lastiter = itcnt;
GRBcbget(cbdata, where, GRB_CB_SPX_OBJVAL, &obj);
GRBcbget(cbdata, where, GRB_CB_SPX_ISPERT, &ispert);
GRBcbget(cbdata, where, GRB_CB_SPX_PRIMINF, &pinf);
GRBcbget(cbdata, where, GRB_CB_SPX_DUALINF, &dinf);
if (ispert == 0) ch = ' ';
else if (ispert == 1) ch = 'S';
else ch = 'P';
printf("%7.0f %14.7e%c %13.6e %13.6e\n", itcnt, obj, ch, pinf, dinf);
}
} else if (where == GRB_CB_MIP) {
/* General MIP callback */
double nodecnt, objbst, objbnd, actnodes, itcnt;
int solcnt, cutcnt;
23
GRBcbget(cbdata, where, GRB_CB_MIP_NODCNT, &nodecnt);
GRBcbget(cbdata, where, GRB_CB_MIP_OBJBST, &objbst);
GRBcbget(cbdata, where, GRB_CB_MIP_OBJBND, &objbnd);
GRBcbget(cbdata, where, GRB_CB_MIP_SOLCNT, &solcnt);
if (nodecnt - mydata->lastnode >= 100) {
mydata->lastnode = nodecnt;
GRBcbget(cbdata, where, GRB_CB_MIP_NODLFT, &actnodes);
GRBcbget(cbdata, where, GRB_CB_MIP_ITRCNT, &itcnt);
GRBcbget(cbdata, where, GRB_CB_MIP_CUTCNT, &cutcnt);
printf("%7.0f %7.0f %8.0f %13.6e %13.6e %7d %7d\n",
nodecnt, actnodes, itcnt, objbst, objbnd, solcnt, cutcnt);
}
if (fabs(objbst - objbnd) < 0.1 * (1.0 + fabs(objbst))) {
printf("Stop early - 10%% gap achieved\n");
GRBterminate(model);
}
if (nodecnt >= 10000 && solcnt) {
printf("Stop early - 10000 nodes explored\n");
GRBterminate(model);
}
} else if (where == GRB_CB_MIPSOL) {
/* MIP solution callback */
double nodecnt, obj;
int solcnt;
GRBcbget(cbdata, where, GRB_CB_MIPSOL_NODCNT, &nodecnt);
GRBcbget(cbdata, where, GRB_CB_MIPSOL_OBJ, &obj);
GRBcbget(cbdata, where, GRB_CB_MIPSOL_SOLCNT, &solcnt);
GRBcbget(cbdata, where, GRB_CB_MIPSOL_SOL, mydata->solution);
printf("**** New solution at node %.0f, obj %g, sol %d, x[0] = %.2f ****\n",
nodecnt, obj, solcnt, mydata->solution[0]);
} else if (where == GRB_CB_MIPNODE) {
int status;
/* MIP node callback */
printf("**** New node ****\n");
GRBcbget(cbdata, where, GRB_CB_MIPNODE_STATUS, &status);
if (status == GRB_OPTIMAL) {
GRBcbget(cbdata, where, GRB_CB_MIPNODE_REL, mydata->solution);
GRBcbsolution(cbdata, mydata->solution, NULL);
}
} else if (where == GRB_CB_BARRIER) {
/* Barrier callback */
int itcnt;
double primobj, dualobj, priminf, dualinf, compl;
GRBcbget(cbdata, where, GRB_CB_BARRIER_ITRCNT, &itcnt);
GRBcbget(cbdata, where, GRB_CB_BARRIER_PRIMOBJ, &primobj);
24
GRBcbget(cbdata, where, GRB_CB_BARRIER_DUALOBJ, &dualobj);
GRBcbget(cbdata, where, GRB_CB_BARRIER_PRIMINF, &priminf);
GRBcbget(cbdata, where, GRB_CB_BARRIER_DUALINF, &dualinf);
GRBcbget(cbdata, where, GRB_CB_BARRIER_COMPL, &compl);
printf("%d %.4e %.4e %.4e %.4e %.4e\n",
itcnt, primobj, dualobj, priminf, dualinf, compl);
} else if (where == GRB_CB_MESSAGE) {
/* Message callback */
char *msg;
GRBcbget(cbdata, where, GRB_CB_MSG_STRING, &msg);
fprintf(mydata->logfile, "%s", msg);
}
return 0;
}
int
main(int argc,
char *argv[])
{
GRBenv *env = NULL;
GRBmodel *model = NULL;
int error = 0;
int numvars, solcount, optimstatus, j;
double objval, x;
char *varname;
struct callback_data mydata;
mydata.lastiter = -GRB_INFINITY;
mydata.lastnode = -GRB_INFINITY;
mydata.solution = NULL;
mydata.logfile = NULL;
if (argc < 2) {
fprintf(stderr, "Usage: callback_c filename\n");
goto QUIT;
}
/* Create environment */
25
error = GRBloadenv(&env, NULL);
if (error) goto QUIT;
mydata.solution = malloc(numvars*sizeof(double));
if (mydata.solution == NULL) {
fprintf(stderr, "Failed to allocate memory\n");
exit(1);
}
/* Solve model */
error = GRBoptimize(model);
if (error) goto QUIT;
printf("\nOptimization complete\n");
26
error = GRBgetintattr(model, GRB_INT_ATTR_STATUS, &optimstatus);
if (error) goto QUIT;
if (solcount == 0) {
printf("No solution found, optimization status = %d\n", optimstatus);
goto QUIT;
}
QUIT:
/* Error reporting */
if (error) {
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
}
if (mydata.logfile)
fclose(mydata.logfile);
/* Free solution */
if (mydata.solution)
free(mydata.solution);
/* Free model */
GRBfreemodel(model);
27
/* Free environment */
GRBfreeenv(env);
return 0;
}
28
dense_c.c
/* Copyright 2016, Gurobi Optimization, Inc. */
#include <stdlib.h>
#include <stdio.h>
#include "gurobi_c.h"
/*
Solve an LP/QP/MILP/MIQP represented using dense matrices. This
routine assumes that A and Q are both stored in row-major order.
It returns 1 if the optimization succeeds. When successful,
it returns the optimal objective value in 'objvalP', and the
optimal solution vector in 'solution'.
*/
static int
dense_optimize(GRBenv *env,
int rows,
int cols,
double *c, /* linear portion of objective function */
double *Q, /* quadratic portion of objective function */
double *A, /* constraint matrix */
char *sense, /* constraint senses */
double *rhs, /* RHS vector */
double *lb, /* variable lower bounds */
double *ub, /* variable upper bounds */
char *vtype, /* variable types (continuous, binary, etc.) */
double *solution,
double *objvalP)
{
GRBmodel *model = NULL;
int i, j, optimstatus;
int error = 0;
29
int success = 0;
/* Populate A matrix */
/* Populate Q matrix */
if (Q) {
for (i = 0; i < cols; i++) {
for (j = 0; j < cols; j++) {
if (Q[i*cols+j] != 0) {
error = GRBaddqpterms(model, 1, &i, &j, &Q[i*cols+j]);
if (error) goto QUIT;
}
}
}
}
/* Optimize model */
error = GRBoptimize(model);
if (error) goto QUIT;
30
error = GRBgetintattr(model, GRB_INT_ATTR_STATUS, &optimstatus);
if (error) goto QUIT;
if (optimstatus == GRB_OPTIMAL) {
success = 1;
}
QUIT:
/* Error reporting */
if (error) {
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
}
/* Free model */
GRBfreemodel(model);
return success;
}
int
main(int argc,
char *argv[])
{
GRBenv *env = NULL;
int error = 0;
double c[] = {1, 1, 0};
double Q[3][3] = {{1, 1, 0}, {0, 1, 1}, {0, 0, 1}};
double A[2][3] = {{1, 2, 3}, {1, 1, 0}};
char sense[] = {'>', '>'};
double rhs[] = {4, 1};
double lb[] = {0, 0, 0};
double sol[3];
int solved;
31
double objval;
/* Create environment */
if (solved)
printf("Solved: x=%.4f, y=%.4f, z=%.4f\n", sol[0], sol[1], sol[2]);
QUIT:
/* Free environment */
GRBfreeenv(env);
return 0;
}
32
diet_c.c
/* Copyright 2016, Gurobi Optimization, Inc. */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "gurobi_c.h"
int
main(int argc,
char *argv[])
{
GRBenv *env = NULL;
GRBmodel *model = NULL;
int error = 0;
int i, j;
int *cbeg, *cind, idx;
double *cval, *rhs;
char *sense;
/* Set of foods */
const int nFoods = 9;
char* Foods[] =
{ "hamburger", "chicken", "hot dog", "fries",
"macaroni", "pizza", "salad", "milk", "ice cream" };
double cost[] =
{ 2.49, 2.89, 1.50, 1.89, 2.09, 1.99, 2.49, 0.89, 1.59 };
33
double nutritionValues[][4] = {
{ 410, 24, 26, 730 },
{ 420, 32, 10, 1190 },
{ 560, 20, 32, 1800 },
{ 380, 4, 19, 270 },
{ 320, 12, 10, 930 },
{ 320, 15, 12, 820 },
{ 320, 31, 12, 1230 },
{ 100, 8, 2.5, 125 },
{ 330, 8, 10, 180 }
};
/* Create environment */
error = GRBloadenv(&env, "diet.log");
if (error) goto QUIT;
34
/* Nutrition constraints */
cbeg = malloc(sizeof(int) * nCategories);
if (!cbeg) goto QUIT;
cind = malloc(sizeof(int) * nCategories * (nFoods + 1));
if (!cind) goto QUIT;
cval = malloc(sizeof(double) * nCategories * (nFoods + 1));
if (!cval) goto QUIT;
rhs = malloc(sizeof(double) * nCategories);
if (!rhs) goto QUIT;
sense = malloc(sizeof(char) * nCategories);
if (!sense) goto QUIT;
idx = 0;
for (i = 0; i < nCategories; ++i)
{
cbeg[i] = idx;
rhs[i] = 0.0;
sense[i] = GRB_EQUAL;
for (j = 0; j < nFoods; ++j)
{
cind[idx] = j;
cval[idx++] = nutritionValues[j][i];
}
cind[idx] = nFoods + i;
cval[idx++] = -1.0;
}
/* Solve */
error = GRBoptimize(model);
if (error) goto QUIT;
error = printSolution(model, nCategories, nFoods);
if (error) goto QUIT;
35
/* Solve */
error = GRBoptimize(model);
if (error) goto QUIT;
error = printSolution(model, nCategories, nFoods);
if (error) goto QUIT;
QUIT:
/* Error reporting */
if (error)
{
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
}
/* Free data */
free(cbeg);
free(cind);
free(cval);
free(rhs);
free(sense);
/* Free model */
GRBfreemodel(model);
/* Free environment */
GRBfreeenv(env);
return 0;
}
36
if (error) return error;
if (status == GRB_OPTIMAL)
{
error = GRBgetdblattr(model, "ObjVal", &obj);
if (error) return error;
printf("\nCost: %f\n\nBuy:\n", obj);
for (j = 0; j < nFoods; ++j)
{
error = GRBgetdblattrelement(model, "X", j, &x);
if (error) return error;
if (x > 0.0001)
{
error = GRBgetstrattrelement(model, "VarName", j, &vname);
if (error) return error;
printf("%s %f\n", vname, x);
}
}
printf("\nNutrition:\n");
for (i = 0; i < nCategories; ++i)
{
error = GRBgetdblattrelement(model, "X", i + nFoods, &x);
if (error) return error;
error = GRBgetstrattrelement(model, "VarName", i + nFoods, &vname);
if (error) return error;
printf("%s %f\n", vname, x);
}
}
else
{
printf("No solution\n");
}
return 0;
}
37
facility_c.c
/* Copyright 2016, Gurobi Optimization, Inc. */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "gurobi_c.h"
#define opencol(p) p
#define transportcol(w,p) nPlants*(w+1)+p
#define MAXSTR 128
int
main(int argc,
char *argv[])
{
GRBenv *env = NULL;
GRBmodel *model = NULL;
int error = 0;
int p, w, col;
int *cbeg = NULL;
int *cind = NULL;
int idx, rowct;
double *cval = NULL;
double *rhs = NULL;
char *sense = NULL;
char vname[MAXSTR];
int cnamect = 0;
char **cname = NULL;
double maxFixed = -GRB_INFINITY, sol, obj;
38
/* Warehouse demand in thousands of units */
double Demand[] = { 15, 18, 14, 20 };
/* Create environment */
error = GRBloadenv(&env, "facility.log");
if (error) goto QUIT;
39
for (p = 0; p < nPlants; ++p)
{
col = transportcol(w, p);
error = GRBsetdblattrelement(model, "Obj", col, TransCosts[w][p]);
if (error) goto QUIT;
sprintf(vname, "Trans%i.%i", p, w);
error = GRBsetstrattrelement(model, "VarName", col, vname);
if (error) goto QUIT;
}
}
/* Production constraints
Note that the limit sets the production to zero if
the plant is closed */
idx = 0;
for (p = 0; p < nPlants; ++p)
{
cbeg[p] = idx;
rhs[p] = 0.0;
sense[p] = GRB_LESS_EQUAL;
cname[p] = malloc(sizeof(char) * MAXSTR);
if (!cname[p]) goto QUIT;
cnamect++;
sprintf(cname[p], "Capacity%i", p);
for (w = 0; w < nWarehouses; ++w)
{
40
cind[idx] = transportcol(w, p);
cval[idx++] = 1.0;
}
cind[idx] = opencol(p);
cval[idx++] = -Capacity[p];
}
error = GRBaddconstrs(model, nPlants, idx, cbeg, cind, cval, sense,
rhs, cname);
if (error) goto QUIT;
/* Demand constraints */
idx = 0;
for (w = 0; w < nWarehouses; ++w)
{
cbeg[w] = idx;
sense[w] = GRB_EQUAL;
sprintf(cname[w], "Demand%i", w);
for (p = 0; p < nPlants; ++p)
{
cind[idx] = transportcol(w, p);
cval[idx++] = 1.0;
}
}
error = GRBaddconstrs(model, nWarehouses, idx, cbeg, cind, cval, sense,
Demand, cname);
if (error) goto QUIT;
/* Guess at the starting point: close the plant with the highest
fixed costs; open all others */
41
}
for (p = 0; p < nPlants; ++p)
{
if (FixedCosts[p] == maxFixed)
{
error = GRBsetdblattrelement(model, "Start", opencol(p), 0.0);
if (error) goto QUIT;
printf("Closing plant %i\n\n", p);
break;
}
}
/* Solve */
error = GRBoptimize(model);
if (error) goto QUIT;
/* Print solution */
error = GRBgetdblattr(model, "ObjVal", &obj);
if (error) goto QUIT;
printf("\nTOTAL COSTS: %f\n", obj);
printf("SOLUTION:\n");
for (p = 0; p < nPlants; ++p)
{
error = GRBgetdblattrelement(model, "X", opencol(p), &sol);
if (error) goto QUIT;
if (sol > 0.99)
{
printf("Plant %i open:\n", p);
for (w = 0; w < nWarehouses; ++w)
{
error = GRBgetdblattrelement(model, "X", transportcol(w, p), &sol);
if (error) goto QUIT;
if (sol > 0.0001)
{
printf(" Transport %f units to warehouse %i\n", sol, w);
}
}
}
else
42
{
printf("Plant %i closed!\n", p);
}
}
QUIT:
/* Error reporting */
if (error)
{
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
}
/* Free data */
free(cbeg);
free(cind);
free(cval);
free(rhs);
free(sense);
for (p = 0; p < cnamect; ++p) {
free(cname[p]);
}
free(cname);
/* Free model */
GRBfreemodel(model);
/* Free environment */
GRBfreeenv(env);
return 0;
}
43
feasopt_c.c
/* Copyright 2016, Gurobi Optimization, Inc. */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "gurobi_c.h"
int
main(int argc,
char *argv[])
{
GRBenv *env = NULL;
GRBmodel *model = NULL;
GRBmodel *feasmodel = NULL;
double *rhspen = NULL;
int error = 0;
int i, j;
int numvars, numconstrs;
char sense;
int vind[1];
double vval[1];
double feasobj;
char *cname, *vname;
if (argc < 2)
{
fprintf(stderr, "Usage: feasopt_c filename\n");
exit(1);
}
44
if (error) goto QUIT;
feasmodel = GRBcopymodel(model);
if (error) goto QUIT;
/* clear objective */
error = GRBgetintattr(model, "NumVars", &numvars);
if (error) goto QUIT;
for (j = 0; j < numvars; ++j)
{
error = GRBsetdblattrelement(model, "Obj", j, 0.0);
if (error) goto QUIT;
}
45
strcat(vname, cname);
vind[0] = i;
vval[0] = 1.0;
error = GRBaddvar(model, 1, vind, vval, 1.0, 0.0, GRB_INFINITY,
GRB_CONTINUOUS, vname);
if (error) goto QUIT;
free(vname);
}
}
error = GRBoptimize(model);
if (error) goto QUIT;
error = GRBoptimize(feasmodel);
if (error) goto QUIT;
QUIT:
46
/* Error reporting */
if (error)
{
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
}
if (rhspen) free(rhspen);
GRBfreemodel(model);
GRBfreemodel(feasmodel);
GRBfreeenv(env);
return 0;
}
47
xanddive_c.c
/* Copyright 2016, Gurobi Optimization, Inc. */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "gurobi_c.h"
typedef struct
{
int index;
double X;
}
var_t ;
int
main(int argc,
char *argv[])
{
GRBenv *env = NULL, *modelenv = NULL;
GRBmodel *model = NULL;
int error = 0;
int j, iter, nfix;
int numvars, numintvars, numfractional;
int *intvars = NULL;
int status;
char vtype, *vname;
double sol, obj, fixval;
var_t *fractional = NULL;
if (argc < 2)
{
fprintf(stderr, "Usage: fixanddive_c filename\n");
exit(1);
}
48
error = GRBloadenv(&env, "fixanddive.log");
if (error) goto QUIT;
/* Read model */
error = GRBreadmodel(env, argv[1], &model);
if (error) goto QUIT;
modelenv = GRBgetenv(model);
if (!modelenv) goto QUIT;
error = GRBsetintparam(modelenv, "OutputFlag", 0);
if (error) goto QUIT;
error = GRBoptimize(model);
if (error) goto QUIT;
49
integer value */
numfractional = 0;
for (j = 0; j < numintvars; ++j)
{
error = GRBgetdblattrelement(model, "X", intvars[j], &sol);
if (error) goto QUIT;
if (fabs(sol - floor(sol + 0.5)) > 1e-5)
{
fractional[numfractional].index = intvars[j];
fractional[numfractional++].X = sol;
}
}
if (numfractional == 0)
{
printf("Found feasible solution - objective %f\n", obj);
break;
}
error = GRBoptimize(model);
if (error) goto QUIT;
50
/* Check optimization result */
QUIT:
/* Error reporting */
if (error)
{
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
}
/* Free data */
free(intvars);
free(fractional);
/* Free model */
GRBfreemodel(model);
/* Free environment */
GRBfreeenv(env);
return 0;
}
51
frac2 = fabs(sol2 - floor(sol2 + 0.5));
return (frac1 < frac2) ? -1 : ((frac1 == frac2) ? 0 : 1);
}
52
genconstr_c.c
/* Copyright 2016, Gurobi Optimization, Inc. */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "gurobi_c.h"
53
int
main(void)
{
GRBenv *env = NULL;
GRBmodel *model = NULL;
int error = 0;
int cind[NVARS];
double cval[NVARS];
char buffer[MAXSTR];
int col, i, status, nSolutions;
double objval;
/* Example data */
const int Clauses[][3] = {{LIT(0), NOTLIT(1), LIT(2)},
{LIT(1), NOTLIT(2), LIT(3)},
{LIT(2), NOTLIT(3), LIT(0)},
{LIT(3), NOTLIT(0), LIT(1)},
{NOTLIT(0), NOTLIT(1), LIT(2)},
{NOTLIT(1), NOTLIT(2), LIT(3)},
{NOTLIT(2), NOTLIT(3), LIT(0)},
{NOTLIT(3), NOTLIT(0), LIT(1)}};
/* Create environment */
error = GRBloadenv(&env, "genconstr_c.log");
if (error) goto QUIT;
col = NOTLIT(i);
sprintf(buffer, "notX%d", i);
54
error = GRBsetcharattrelement(model, "VType", col, GRB_BINARY);
if (error) goto QUIT;
55
}
/* Save problem */
error = GRBwrite(model, "genconstr_c.mps");
if (error) goto QUIT;
/* Optimize */
error = GRBoptimize(model);
if (error) goto QUIT;
/* Status checking */
error = GRBgetintattr(model, "Status", &status);
if (error) goto QUIT;
if (status == GRB_INF_OR_UNBD ||
status == GRB_INFEASIBLE ||
status == GRB_UNBOUNDED ) {
printf("The model cannot be solved "
"because it is infeasible or unbounded\n");
goto QUIT;
}
if (status != GRB_OPTIMAL) {
printf("Optimization was stopped with status %i\n", status);
goto QUIT;
56
}
/* Print result */
error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &objval);
if (error) goto QUIT;
QUIT:
return error;
}
57
lp_c.c
/* Copyright 2016, Gurobi Optimization, Inc. */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "gurobi_c.h"
int
main(int argc,
char *argv[])
{
GRBenv *masterenv = NULL;
GRBmodel *model = NULL;
GRBenv *modelenv = NULL;
int error = 0;
int optimstatus;
double objval;
if (argc < 2) {
fprintf(stderr, "Usage: lp_c filename\n");
exit(1);
}
/* Create environment */
/* Solve model */
error = GRBoptimize(model);
if (error) goto QUIT;
58
/* Capture solution information */
if (optimstatus == GRB_INF_OR_UNBD) {
modelenv = GRBgetenv(model);
if (!modelenv) {
fprintf(stderr, "Error: could not get model environment\n");
goto QUIT;
}
error = GRBoptimize(model);
if (error) goto QUIT;
if (optimstatus == GRB_OPTIMAL) {
error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &objval);
if (error) goto QUIT;
printf("Optimal objective: %.4e\n\n", objval);
} else if (optimstatus == GRB_INFEASIBLE) {
printf("Model is infeasible\n\n");
error = GRBcomputeIIS(model);
if (error) goto QUIT;
59
QUIT:
/* Error reporting */
if (error) {
printf("ERROR: %s\n", GRBgeterrormsg(masterenv));
exit(1);
}
/* Free model */
GRBfreemodel(model);
/* Free environment */
GRBfreeenv(masterenv);
return 0;
}
60
lpmethod_c.c
/* Copyright 2016, Gurobi Optimization, Inc. */
#include <stdlib.h>
#include <stdio.h>
#include "gurobi_c.h"
int
main(int argc,
char *argv[])
{
GRBenv *env = NULL, *menv;
GRBmodel *m = NULL;
int error = 0;
int i;
int optimstatus;
int bestMethod = -1;
double bestTime;
if (argc < 2)
{
fprintf(stderr, "Usage: lpmethod_c filename\n");
exit(1);
}
/* Read model */
error = GRBreadmodel(env, argv[1], &m);
if (error) goto QUIT;
menv = GRBgetenv(m);
error = GRBgetdblparam(menv, "TimeLimit", &bestTime);
if (error) goto QUIT;
61
error = GRBoptimize(m);
if (error) goto QUIT;
error = GRBgetintattr(m, "Status", &optimstatus);
if (error) goto QUIT;
if (optimstatus == GRB_OPTIMAL) {
error = GRBgetdblattr(m, "Runtime", &bestTime);
if (error) goto QUIT;
bestMethod = i;
/* Reduce the TimeLimit parameter to save time
with other methods */
error = GRBsetdblparam(menv, "TimeLimit", bestTime);
if (error) goto QUIT;
}
}
QUIT:
/* Error reporting */
if (error)
{
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
}
/* Free model */
GRBfreemodel(m);
/* Free environment */
GRBfreeenv(env);
return 0;
}
62
lpmod_c.c
/* Copyright 2016, Gurobi Optimization, Inc. */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "gurobi_c.h"
int
main(int argc,
char *argv[])
{
GRBenv *env = NULL;
GRBmodel *model = NULL;
int error = 0;
int j;
int numvars, isMIP, status, minVar = 0;
double minVal = GRB_INFINITY, sol, lb;
char *varname;
double warmCount, warmTime, coldCount, coldTime;
if (argc < 2)
{
fprintf(stderr, "Usage: lpmod_c filename\n");
exit(1);
}
63
goto QUIT;
}
error = GRBoptimize(model);
if (error) goto QUIT;
if (status != GRB_OPTIMAL)
{
printf("Optimization was stopped with status %i\n", status);
goto QUIT;
}
64
/* Solve from this starting point */
error = GRBoptimize(model);
if (error) goto QUIT;
QUIT:
/* Error reporting */
if (error)
{
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
}
/* Free model */
GRBfreemodel(model);
65
/* Free environment */
GRBfreeenv(env);
return 0;
}
66
mip1_c.c
/* Copyright 2016, Gurobi Optimization, Inc. */
/* This example formulates and solves the following simple MIP model:
maximize x + y + 2 z
subject to x + 2 y + 3 z <= 4
x + y >= 1
x, y, z binary
*/
#include <stdlib.h>
#include <stdio.h>
#include "gurobi_c.h"
int
main(int argc,
char *argv[])
{
GRBenv *env = NULL;
GRBmodel *model = NULL;
int error = 0;
double sol[3];
int ind[3];
double val[3];
double obj[3];
char vtype[3];
int optimstatus;
double objval;
/* Create environment */
/* Add variables */
67
error = GRBaddvars(model, 3, 0, NULL, NULL, NULL, obj, NULL, NULL, vtype,
NULL);
if (error) goto QUIT;
ind[0] = 0; ind[1] = 1;
val[0] = 1; val[1] = 1;
/* Optimize model */
error = GRBoptimize(model);
if (error) goto QUIT;
68
printf("\nOptimization complete\n");
if (optimstatus == GRB_OPTIMAL) {
printf("Optimal objective: %.4e\n", objval);
QUIT:
/* Error reporting */
if (error) {
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
}
/* Free model */
GRBfreemodel(model);
/* Free environment */
GRBfreeenv(env);
return 0;
}
69
mip2_c.c
/* Copyright 2016, Gurobi Optimization, Inc. */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "gurobi_c.h"
int
main(int argc,
char *argv[])
{
GRBenv *env = NULL;
GRBmodel *model = NULL;
GRBmodel *fixed = NULL;
int error = 0;
int ismip;
int j, k, solcount, numvars;
double objn, vobj, xn;
int optimstatus, foptimstatus;
double objval, fobjval;
char *varname;
double x;
if (argc < 2) {
fprintf(stderr, "Usage: mip2_c filename\n");
exit(1);
}
/* Create environment */
70
/* Read model from file */
if (ismip == 0) {
printf("Model is not a MIP\n");
goto QUIT;
}
menv = GRBgetenv(model);
if (!menv) {
fprintf(stderr, "Error: could not get model environment\n");
goto QUIT;
}
/* Solve model */
error = GRBoptimize(model);
if (error) goto QUIT;
printf("\nOptimization complete\n");
if (optimstatus == GRB_OPTIMAL) {
error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &objval);
if (error) goto QUIT;
printf("Optimal objective: %.4e\n\n", objval);
} else if (optimstatus == GRB_INF_OR_UNBD) {
printf("Model is infeasible or unbounded\n\n");
goto QUIT;
} else if (optimstatus == GRB_INFEASIBLE) {
printf("Model is infeasible\n\n");
goto QUIT;
} else if (optimstatus == GRB_UNBOUNDED) {
printf("Model is unbounded\n\n");
goto QUIT;
71
} else {
printf("Optimization was stopped with status = %d\n\n", optimstatus);
goto QUIT;
}
printf("\n");
for ( k = 0; k < solcount; ++k ) {
error = GRBsetintparam(menv, "SolutionNumber", k);
objn = 0.0;
for ( j = 0; j < numvars; ++j ) {
error = GRBgetdblattrelement(model, "Obj", j, &vobj);
if (error) goto QUIT;
error = GRBgetdblattrelement(model, "Xn", j, &xn);
if (error) goto QUIT;
objn += vobj * xn;
}
printf("Solution %i has objective: %f\n", k, objn);
}
printf("\n");
fixed = GRBfixedmodel(model);
if (!fixed) {
fprintf(stderr, "Error: could not create fixed model\n");
goto QUIT;
}
fenv = GRBgetenv(fixed);
if (!fenv) {
fprintf(stderr, "Error: could not get fixed model environment\n");
goto QUIT;
}
72
error = GRBsetintparam(fenv, "PRESOLVE", 0);
if (error) goto QUIT;
error = GRBoptimize(fixed);
if (error) goto QUIT;
if (foptimstatus != GRB_OPTIMAL) {
fprintf(stderr, "Error: fixed model isn't optimal\n");
goto QUIT;
}
QUIT:
/* Error reporting */
if (error) {
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
}
/* Free models */
73
GRBfreemodel(model);
GRBfreemodel(fixed);
/* Free environment */
GRBfreeenv(env);
return 0;
}
74
multiobj_c.c
/* Copyright 2016, Gurobi Optimization, Inc. */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "gurobi_c.h"
int
main(void)
{
GRBenv *env = NULL;
GRBenv *menv = NULL;
GRBmodel *model = NULL;
int error = 0;
int *cbeg = NULL;
int *cind = NULL;
double *cval = NULL;
char buffer[MAXSTR];
int e, i, status, nSolutions;
double objn;
/* Sample data */
const int groundSetSize = 20;
const int nSubsets = 4;
const int Budget = 12;
double Set[][20] =
{ { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1 },
{ 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0 },
{ 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0 } };
int SetObjPriority[] = {3, 2, 2, 1};
double SetObjWeight[] = {1.0, 0.25, 1.25, 1.0};
/* Create environment */
error = GRBloadenv(&env, "multiobj_c.log");
if (error) goto QUIT;
75
/* Create initial model */
error = GRBnewmodel(env, &model, "multiobj_c", groundSetSize, NULL,
NULL, NULL, NULL, NULL);
if (error) goto QUIT;
76
error = GRBsetintparam(menv, GRB_INT_PAR_POOLSOLUTIONS, 100);
if (error) goto QUIT;
/* Save problem */
error = GRBwrite(model, "multiobj_c.lp");
if (error) goto QUIT;
error = GRBwrite(model, "multiobj_c.mps");
if (error) goto QUIT;
/* Optimize */
error = GRBoptimize(model);
if (error) goto QUIT;
/* Status checking */
77
error = GRBgetintattr(model, "Status", &status);
if (error) goto QUIT;
if (status == GRB_INF_OR_UNBD ||
status == GRB_INFEASIBLE ||
status == GRB_UNBOUNDED ) {
printf("The model cannot be solved "
"because it is infeasible or unbounded\n");
goto QUIT;
}
if (status != GRB_OPTIMAL) {
printf("Optimization was stopped with status %i\n", status);
goto QUIT;
}
78
printf(" %6g", objn);
}
printf("\n");
}
QUIT:
return error;
}
79
params_c.c
/* Copyright 2016, Gurobi Optimization, Inc. */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "gurobi_c.h"
int
main(int argc,
char *argv[])
{
GRBenv *env = NULL, *modelenv = NULL, *bestenv = NULL;
GRBmodel *model = NULL, *bestmodel = NULL;
int error = 0;
int ismip, i, mipfocus;
double bestgap, gap;
if (argc < 2)
{
fprintf(stderr, "Usage: params_c filename\n");
exit(1);
}
80
/* Set a 5 second time limit */
modelenv = GRBgetenv(model);
if (!modelenv) {
printf("Cannot retrieve model environment\n");
exit(1);
}
error = GRBsetdblparam(modelenv, "TimeLimit", 5);
if (error) goto QUIT;
/* Finally, free the extra model, reset the time limit and
continue to solve the best model to optimality */
81
GRBfreemodel(model);
bestenv = GRBgetenv(bestmodel);
if (!bestenv) {
printf("Cannot retrieve best model environment\n");
exit(1);
}
error = GRBsetdblparam(bestenv, "TimeLimit", GRB_INFINITY);
if (error) goto QUIT;
error = GRBoptimize(bestmodel);
if (error) goto QUIT;
error = GRBgetintparam(bestenv, "MIPFocus", &mipfocus);
if (error) goto QUIT;
QUIT:
/* Error reporting */
if (error)
{
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
}
GRBfreemodel(bestmodel);
/* Free environment */
GRBfreeenv(env);
return 0;
}
82
piecewise_c.c
/* Copyright 2016, Gurobi Optimization, Inc. */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "gurobi_c.h"
int
main(int argc,
char *argv[])
{
GRBenv *env = NULL;
GRBmodel *model = NULL;
int error = 0;
double lb, ub;
int npts, i;
double *ptu = NULL;
double *ptf = NULL;
double *ptg = NULL;
int ind[3];
double val[3];
int ismip;
double objval;
double sol[3];
/* Create environment */
83
error = GRBloadenv(&env, NULL);
if (error) goto QUIT;
/* Add variables */
lb = 0.0; ub = 1.0;
npts = 101;
ptu = (double *) malloc(npts * sizeof(double));
ptf = (double *) malloc(npts * sizeof(double));
ptg = (double *) malloc(npts * sizeof(double));
84
val[0] = 1; val[1] = 2; val[2] = 3;
ind[0] = 0; ind[1] = 1;
val[0] = 1; val[1] = 1;
/* Optimize model as an LP */
error = GRBoptimize(model);
if (error) goto QUIT;
error = GRBoptimize(model);
if (error) goto QUIT;
85
if (error) goto QUIT;
error = GRBgetdblattr(model, "ObjVal", &objval);
if (error) goto QUIT;
error = GRBgetdblattrarray(model, "X", 0, 3, sol);
if (error) goto QUIT;
QUIT:
/* Error reporting */
if (error) {
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
}
/* Free data */
free(ptu);
free(ptf);
free(ptg);
/* Free model */
GRBfreemodel(model);
/* Free environment */
GRBfreeenv(env);
return 0;
}
86
poolsearch_c.c
/* Copyright 2016, Gurobi Optimization, Inc. */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "gurobi_c.h"
int main(void)
{
GRBenv *env = NULL;
GRBenv *menv = NULL;
GRBmodel *model = NULL;
int error = 0;
char buffer[MAXSTR];
int e, status, nSolutions, prlen;
double objval, *cval = NULL;
int *cind = NULL;
/* Sample data */
const int groundSetSize = 10;
double objCoef[10] =
{32, 32, 15, 15, 6, 6, 1, 1, 1, 1};
double knapsackCoef[10] =
{16, 16, 8, 8, 4, 4, 2, 2, 1, 1};
double Budget = 33;
/* Create environment */
error = GRBloadenv(&env, "poolsearch_c.log");
if (error) goto QUIT;
87
if (!menv) {
fprintf(stderr, "Error: could not get model environment\n");
goto QUIT;
}
/* Limit the search space by setting a gap for the worst possible solution that will be accept
error = GRBsetdblparam(menv, GRB_DBL_PAR_POOLGAP, 0.10);
if (error) goto QUIT;
88
error = GRBsetintparam(menv, GRB_INT_PAR_POOLSEARCHMODE, 2);
if (error) goto QUIT;
/* save problem */
error = GRBwrite(model, "poolsearch_c.lp");
if (error) goto QUIT;
error = GRBwrite(model, "poolsearch_c.mps");
if (error) goto QUIT;
/* Optimize */
error = GRBoptimize(model);
if (error) goto QUIT;
/* Status checking */
error = GRBgetintattr(model, "Status", &status);
if (error) goto QUIT;
if (status == GRB_INF_OR_UNBD ||
status == GRB_INFEASIBLE ||
status == GRB_UNBOUNDED ) {
printf("The model cannot be solved "
"because it is infeasible or unbounded\n");
goto QUIT;
}
if (status != GRB_OPTIMAL) {
printf("Optimization was stopped with status %d\n", status);
goto QUIT;
}
89
if (error) goto QUIT;
printf("\nNumber of solutions found: %d\nValues:", nSolutions);
QUIT:
if (model != NULL) GRBfreemodel(model);
if (env != NULL) GRBfreeenv(env);
if (cind != NULL) free(cind);
if (cval != NULL) free(cval);
return error;
}
90
qcp_c.c
/* Copyright 2016, Gurobi Optimization, Inc. */
/* This example formulates and solves the following simple QCP model:
maximize x
subject to x + y + z = 1
x^2 + y^2 <= z^2 (second-order cone)
x^2 <= yz (rotated second-order cone)
*/
#include <stdlib.h>
#include <stdio.h>
#include "gurobi_c.h"
int
main(int argc,
char *argv[])
{
GRBenv *env = NULL;
GRBmodel *model = NULL;
int error = 0;
double sol[3];
int ind[3];
double val[3];
double obj[] = {1, 0, 0};
int qrow[3];
int qcol[3];
double qval[3];
int optimstatus;
double objval;
/* Create environment */
/* Add variables */
91
error = GRBaddvars(model, 3, 0, NULL, NULL, NULL, obj, NULL, NULL, NULL,
NULL);
if (error) goto QUIT;
/* Linear constraint: x + y + z = 1 */
/* Optimize model */
error = GRBoptimize(model);
if (error) goto QUIT;
92
/* Capture solution information */
printf("\nOptimization complete\n");
if (optimstatus == GRB_OPTIMAL) {
printf("Optimal objective: %.4e\n", objval);
QUIT:
/* Error reporting */
if (error) {
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
}
/* Free model */
GRBfreemodel(model);
/* Free environment */
GRBfreeenv(env);
return 0;
}
93
qp_c.c
/* Copyright 2016, Gurobi Optimization, Inc. */
#include <stdlib.h>
#include <stdio.h>
#include "gurobi_c.h"
int
main(int argc,
char *argv[])
{
GRBenv *env = NULL;
GRBmodel *model = NULL;
int error = 0;
double sol[3];
int ind[3];
double val[3];
int qrow[5];
int qcol[5];
double qval[5];
char vtype[3];
int optimstatus;
double objval;
/* Create environment */
/* Add variables */
94
error = GRBaddvars(model, 3, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL);
if (error) goto QUIT;
ind[0] = 0; ind[1] = 1;
val[0] = 1; val[1] = 1;
/* Optimize model */
error = GRBoptimize(model);
if (error) goto QUIT;
95
error = GRBgetintattr(model, GRB_INT_ATTR_STATUS, &optimstatus);
if (error) goto QUIT;
printf("\nOptimization complete\n");
if (optimstatus == GRB_OPTIMAL) {
printf("Optimal objective: %.4e\n", objval);
/* Optimize model */
error = GRBoptimize(model);
if (error) goto QUIT;
96
if (error) goto QUIT;
printf("\nOptimization complete\n");
if (optimstatus == GRB_OPTIMAL) {
printf("Optimal objective: %.4e\n", objval);
QUIT:
/* Error reporting */
if (error) {
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
}
/* Free model */
GRBfreemodel(model);
/* Free environment */
GRBfreeenv(env);
return 0;
}
97
sensitivity_c.c
/* Copyright 2016, Gurobi Optimization, Inc. */
#include <stdlib.h>
#include <stdio.h>
#include "gurobi_c.h"
int
main(int argc,
char *argv[])
{
GRBenv *env = NULL, *modelenv = NULL;
GRBmodel *model = NULL;
int error = 0;
int ismip, status, numvars, i, j;
double origobjval, lb, ub, objval;
double *origx = NULL;
char vtype, *vname;
if (argc < 2)
{
fprintf(stderr, "Usage: sensitivity_c filename\n");
exit(1);
}
/* Create environment */
98
exit(1);
}
error = GRBoptimize(model);
if (error) goto QUIT;
modelenv = GRBgetenv(model);
if (!modelenv) {
printf("Cannot retrieve model environment\n");
exit(1);
}
error = GRBsetintparam(modelenv, "OutputFlag", 0);
if (error) goto QUIT;
99
if (error) goto QUIT;
if (lb == 0 && ub == 1
&& (vtype == GRB_BINARY || vtype == GRB_INTEGER)) {
error = GRBoptimize(model);
if (error) goto QUIT;
100
}
QUIT:
/* Error reporting */
if (error)
{
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
}
/* Free data */
free(origx);
/* Free model */
GRBfreemodel(model);
/* Free environment */
GRBfreeenv(env);
return 0;
}
101
sos_c.c
/* Copyright 2016, Gurobi Optimization, Inc. */
/* This example creates a very simple Special Ordered Set (SOS) model.
The model consists of 3 continuous variables, no linear constraints,
and a pair of SOS constraints of type 1. */
#include <stdlib.h>
#include <stdio.h>
#include "gurobi_c.h"
int
main(int argc,
char *argv[])
{
GRBenv *env = NULL;
GRBmodel *model = NULL;
int error = 0;
double x[3];
double obj[3];
double ub[3];
int sostype[2];
int sosbeg[2];
int sosind[4];
double soswt[4];
int optimstatus;
double objval;
/* Create environment */
/* Add variables */
102
if (error) goto QUIT;
sosind[0] = 0; sosind[1] = 1;
soswt[0] = 1.0; soswt[1] = 2.0;
sosbeg[0] = 0; sostype[0] = GRB_SOS_TYPE1;
sosind[2] = 0; sosind[3] = 2;
soswt[2] = 1.0; soswt[3] = 2.0;
sosbeg[1] = 2; sostype[1] = GRB_SOS_TYPE1;
/* Optimize model */
error = GRBoptimize(model);
if (error) goto QUIT;
printf("\nOptimization complete\n");
if (optimstatus == GRB_OPTIMAL) {
printf("Optimal objective: %.4e\n", objval);
103
} else if (optimstatus == GRB_INF_OR_UNBD) {
printf("Model is infeasible or unbounded\n");
} else {
printf("Optimization was stopped early\n");
}
QUIT:
/* Error reporting */
if (error) {
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
}
/* Free model */
GRBfreemodel(model);
/* Free environment */
GRBfreeenv(env);
return 0;
}
104
sudoku_c.c
/* Copyright 2016, Gurobi Optimization, Inc. */
/*
Sudoku example.
The Sudoku board is a 9x9 grid, which is further divided into a 3x3 grid
of 3x3 grids. Each cell in the grid must take a value from 0 to 9.
No two grid cells in the same row, column, or 3x3 subgrid may take the
same value.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "gurobi_c.h"
#define SUBDIM 3
#define DIM (SUBDIM*SUBDIM)
int
main(int argc,
char *argv[])
{
FILE *fp = NULL;
GRBenv *env = NULL;
GRBmodel *model = NULL;
int board[DIM][DIM];
char inputline[100];
int ind[DIM];
double val[DIM];
double lb[DIM*DIM*DIM];
char vtype[DIM*DIM*DIM];
char *names[DIM*DIM*DIM];
char namestorage[10*DIM*DIM*DIM];
char *cursor;
int optimstatus;
105
double objval;
int zero = 0;
int i, j, v, ig, jg, count;
int error = 0;
if (argc < 2) {
fprintf(stderr, "Usage: sudoku_c datafile\n");
exit(1);
}
fp = fopen(argv[1], "r");
if (fp == NULL) {
fprintf(stderr, "Error: unable to open input file %s\n", argv[1]);
exit(1);
}
cursor = namestorage;
for (i = 0; i < DIM; i++) {
for (j = 0; j < DIM; j++) {
for (v = 0; v < DIM; v++) {
if (board[i][j] == v)
lb[i*DIM*DIM+j*DIM+v] = 1;
else
lb[i*DIM*DIM+j*DIM+v] = 0;
vtype[i*DIM*DIM+j*DIM+v] = GRB_BINARY;
names[i*DIM*DIM+j*DIM+v] = cursor;
sprintf(names[i*DIM*DIM+j*DIM+v], "x[%d,%d,%d]", i, j, v+1);
cursor += strlen(names[i*DIM*DIM+j*DIM+v]) + 1;
}
106
}
}
/* Create environment */
107
for (i = 0; i < DIM; i++) {
for (j = 0; j < DIM; j++) {
ind[j] = i*DIM*DIM + j*DIM + v;
val[j] = 1.0;
}
/* Optimize model */
error = GRBoptimize(model);
if (error) goto QUIT;
108
error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &objval);
if (error) goto QUIT;
printf("\nOptimization complete\n");
if (optimstatus == GRB_OPTIMAL)
printf("Optimal objective: %.4e\n", objval);
else if (optimstatus == GRB_INF_OR_UNBD)
printf("Model is infeasible or unbounded\n");
else
printf("Optimization was stopped early\n");
printf("\n");
QUIT:
/* Error reporting */
if (error) {
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
}
/* Free model */
GRBfreemodel(model);
/* Free environment */
GRBfreeenv(env);
return 0;
}
109
tsp_c.c
/* Copyright 2016, Gurobi Optimization, Inc. */
/*
Solve a traveling salesman problem on a randomly generated set of
points using lazy constraints. The base MIP model only includes
'degree-2' constraints, requiring each node to have exactly
two incident edges. Solutions to this model may contain subtours -
tours that don't visit every node. The lazy constraint callback
adds new constraints to cut them off.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "gurobi_c.h"
struct callback_data {
int n;
};
static void
findsubtour(int n,
double *sol,
int *tourlenP,
int *tour)
{
int i, node, len, start;
int bestind, bestlen;
int *seen = NULL;
110
for (i = 0; i < n; i++)
seen[i] = 0;
start = 0;
bestlen = n+1;
bestind = -1;
while (start < n) {
for (node = 0; node < n; node++)
if (seen[node] == 0)
break;
if (node == n)
break;
for (len = 0; len < n; len++) {
tour[start+len] = node;
seen[node] = 1;
for (i = 0; i < n; i++) {
if (sol[node*n+i] > 0.5 && !seen[i]) {
node = i;
break;
}
}
if (i == n) {
len++;
if (len < bestlen) {
bestlen = len;
bestind = start;
}
start += len;
break;
}
}
}
free(seen);
}
111
int __stdcall
subtourelim(GRBmodel *model,
void *cbdata,
int where,
void *usrdata)
{
struct callback_data *mydata = (struct callback_data *) usrdata;
int n = mydata->n;
int *tour = NULL;
double *sol = NULL;
int i, j, len, nz;
int error = 0;
if (where == GRB_CB_MIPSOL) {
sol = (double *) malloc(n*n*sizeof(double));
tour = (int *) malloc(n*sizeof(int));
if (sol == NULL || tour == NULL) {
fprintf(stderr, "Out of memory\n");
exit(1);
}
if (len < n) {
int *ind = NULL;
double *val = NULL;
nz = 0;
for (i = 0; i < len; i++)
for (j = i+1; j < len; j++)
ind[nz++] = tour[i]*n+tour[j];
for (i = 0; i < nz; i++)
val[i] = 1.0;
112
error = GRBcblazy(cbdata, nz, ind, val, GRB_LESS_EQUAL, len-1);
free(ind);
free(val);
}
free(sol);
free(tour);
}
return error;
}
static double
distance(double *x,
double *y,
int i,
int j)
{
double dx = x[i] - x[j];
double dy = y[i] - y[j];
int
main(int argc,
char *argv[])
{
GRBenv *env = NULL;
GRBmodel *model = NULL;
int i, j, len, n, solcount;
int error = 0;
char name[100];
double *x = NULL;
double *y = NULL;
int *ind = NULL;
double *val = NULL;
struct callback_data mydata;
if (argc < 2) {
fprintf(stderr, "Usage: tsp_c size\n");
113
exit(1);
}
n = atoi(argv[1]);
if (n == 0) {
fprintf(stderr, "Argument must be a positive integer.\n");
} else if (n > 100) {
printf("It will be a challenge to solve a TSP this large.\n");
}
x = (double *) malloc(n*sizeof(double));
y = (double *) malloc(n*sizeof(double));
ind = (int *) malloc(n*sizeof(int));
val = (double *) malloc(n*sizeof(double));
/* Create environment */
114
error = GRBaddvar(model, 0, NULL, NULL, distance(x, y, i, j)/2,
0.0, 1.0, GRB_BINARY, name);
if (error) goto QUIT;
}
}
/* Degree-2 constraints */
/* Symmetric TSP */
mydata.n = n;
115
if (error) goto QUIT;
/* Optimize model */
error = GRBoptimize(model);
if (error) goto QUIT;
/* Extract solution */
if (solcount > 0) {
int *tour = NULL;
double *sol = NULL;
/* Print tour */
printf("Tour: ");
for (i = 0; i < len; i++)
printf("%d ", tour[i]);
printf("\n");
free(tour);
free(sol);
}
QUIT:
116
/* Free data */
free(x);
free(y);
free(ind);
free(val);
/* Error reporting */
if (error) {
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
}
/* Free model */
GRBfreemodel(model);
/* Free environment */
GRBfreeenv(env);
return 0;
}
117
tune_c.c
/* Copyright 2016, Gurobi Optimization, Inc. */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "gurobi_c.h"
int
main(int argc,
char *argv[])
{
GRBenv *env = NULL;
GRBmodel *model = NULL;
int tuneresultcount;
int error = 0;
if (argc < 2) {
fprintf(stderr, "Usage: tune_c filename\n");
exit(1);
}
/* Create environment */
error = GRBtunemodel(model);
if (error) goto QUIT;
118
/* Get the number of tuning results */
if (tuneresultcount > 0) {
error = GRBoptimize(model);
if (error) goto QUIT;
}
QUIT:
/* Error reporting */
if (error) {
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
}
/* Free model */
GRBfreemodel(model);
/* Free environment */
GRBfreeenv(env);
return 0;
}
119
workforce1_c.c
/* Copyright 2016, Gurobi Optimization, Inc. */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "gurobi_c.h"
int
main(int argc,
char *argv[])
{
GRBenv *env = NULL;
GRBmodel *model = NULL;
int error = 0, status;
int s, w, col;
int *cbeg = NULL;
int *cind = NULL;
int idx;
double *cval = NULL;
char *sense = NULL;
char vname[MAXSTR];
double obj;
int i, iis, numconstrs;
char *cname;
/* Sample data */
const int nShifts = 14;
const int nWorkers = 7;
120
char* Workers[] =
{ "Amy", "Bob", "Cathy", "Dan", "Ed", "Fred", "Gu" };
/* Create environment */
error = GRBloadenv(&env, "workforce1.log");
if (error) goto QUIT;
121
}
}
/* Optimize */
error = GRBoptimize(model);
if (error) goto QUIT;
error = GRBgetintattr(model, "Status", &status);
if (error) goto QUIT;
if (status == GRB_UNBOUNDED)
{
printf("The model cannot be solved because it is unbounded\n");
goto QUIT;
}
if (status == GRB_OPTIMAL)
122
{
error = GRBgetdblattr(model, "ObjVal", &obj);
if (error) goto QUIT;
printf("The optimal objective is %f\n", obj);
goto QUIT;
}
if ((status != GRB_INF_OR_UNBD) && (status != GRB_INFEASIBLE))
{
printf("Optimization was stopped with status %i\n", status);
goto QUIT;
}
/* do IIS */
printf("The model is infeasible; computing IIS\n");
error = GRBcomputeIIS(model);
if (error) goto QUIT;
printf("\nThe following constraint(s) cannot be satisfied:\n");
error = GRBgetintattr(model, "NumConstrs", &numconstrs);
if (error) goto QUIT;
for (i = 0; i < numconstrs; ++i)
{
error = GRBgetintattrelement(model, "IISConstr", i, &iis);
if (error) goto QUIT;
if (iis)
{
error = GRBgetstrattrelement(model, "ConstrName", i, &cname);
if (error) goto QUIT;
printf("%s\n", cname);
}
}
QUIT:
/* Error reporting */
if (error)
{
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
}
/* Free data */
123
free(cbeg);
free(cind);
free(cval);
free(sense);
/* Free model */
GRBfreemodel(model);
/* Free environment */
GRBfreeenv(env);
return 0;
}
124
workforce2_c.c
/* Copyright 2016, Gurobi Optimization, Inc. */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "gurobi_c.h"
int
main(int argc,
char *argv[])
{
GRBenv *env = NULL;
GRBmodel *model = NULL;
int error = 0, status;
int s, w, col;
int *cbeg = NULL;
int *cind = NULL;
int idx;
double *cval = NULL;
char *sense = NULL;
char vname[MAXSTR];
double obj;
int i, iis, numconstrs, numremoved = 0;
char *cname;
char **removed = NULL;
/* Sample data */
const int nShifts = 14;
const int nWorkers = 7;
125
"Sun14" };
char* Workers[] =
{ "Amy", "Bob", "Cathy", "Dan", "Ed", "Fred", "Gu" };
/* Create environment */
error = GRBloadenv(&env, "workforce2.log");
if (error) goto QUIT;
126
if (error) goto QUIT;
}
}
/* Optimize */
error = GRBoptimize(model);
if (error) goto QUIT;
error = GRBgetintattr(model, "Status", &status);
if (error) goto QUIT;
if (status == GRB_UNBOUNDED)
{
printf("The model cannot be solved because it is unbounded\n");
goto QUIT;
}
127
if (status == GRB_OPTIMAL)
{
error = GRBgetdblattr(model, "ObjVal", &obj);
if (error) goto QUIT;
printf("The optimal objective is %f\n", obj);
goto QUIT;
}
if ((status != GRB_INF_OR_UNBD) && (status != GRB_INFEASIBLE))
{
printf("Optimization was stopped with status %i\n", status);
goto QUIT;
}
/* do IIS */
printf("The model is infeasible; computing IIS\n");
128
printf("\n");
error = GRBoptimize(model);
if (error) goto QUIT;
error = GRBgetintattr(model, "Status", &status);
if (error) goto QUIT;
if (status == GRB_UNBOUNDED)
{
printf("The model cannot be solved because it is unbounded\n");
goto QUIT;
}
if (status == GRB_OPTIMAL)
{
break;
}
if ((status != GRB_INF_OR_UNBD) && (status != GRB_INFEASIBLE))
{
printf("Optimization was stopped with status %i\n", status);
goto QUIT;
}
}
QUIT:
/* Error reporting */
if (error)
{
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
}
/* Free data */
free(cbeg);
free(cind);
129
free(cval);
free(sense);
for (i=0; i<numremoved; ++i)
{
free(removed[i]);
}
free(removed);
/* Free model */
GRBfreemodel(model);
/* Free environment */
GRBfreeenv(env);
return 0;
}
130
workforce3_c.c
/* Copyright 2016, Gurobi Optimization, Inc. */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "gurobi_c.h"
int
main(int argc,
char *argv[])
{
GRBenv *env = NULL;
GRBmodel *model = NULL;
int error = 0, status;
int s, w, col;
int *cbeg = NULL;
int *cind = NULL;
int idx;
double *cval = NULL;
char *sense = NULL;
char vname[MAXSTR];
double obj;
int i, j, orignumvars, numvars, numconstrs;
double *rhspen = NULL;
double sol;
char *sname;
/* Sample data */
const int nShifts = 14;
const int nWorkers = 7;
131
{ "Mon1", "Tue2", "Wed3", "Thu4", "Fri5", "Sat6",
"Sun7", "Mon8", "Tue9", "Wed10", "Thu11", "Fri12", "Sat13",
"Sun14" };
char* Workers[] =
{ "Amy", "Bob", "Cathy", "Dan", "Ed", "Fred", "Gu" };
/* Create environment */
error = GRBloadenv(&env, "workforce3.log");
if (error) goto QUIT;
132
if (error) goto QUIT;
error = GRBsetstrattrelement(model, "VarName", col, vname);
if (error) goto QUIT;
}
}
/* Optimize */
error = GRBoptimize(model);
if (error) goto QUIT;
error = GRBgetintattr(model, "Status", &status);
if (error) goto QUIT;
if (status == GRB_UNBOUNDED)
{
printf("The model cannot be solved because it is unbounded\n");
133
goto QUIT;
}
if (status == GRB_OPTIMAL)
{
error = GRBgetdblattr(model, "ObjVal", &obj);
if (error) goto QUIT;
printf("The optimal objective is %f\n", obj);
goto QUIT;
}
if ((status != GRB_INF_OR_UNBD) && (status != GRB_INFEASIBLE))
{
printf("Optimization was stopped with status %i\n", status);
goto QUIT;
}
134
goto QUIT;
}
printf("\nSlack values:\n");
error = GRBgetintattr(model, "NumVars", &numvars);
if (error) goto QUIT;
for (j = orignumvars; j < numvars; ++j)
{
error = GRBgetdblattrelement(model, "X", j, &sol);
if (error) goto QUIT;
if (sol > 1e-6)
{
error = GRBgetstrattrelement(model, "VarName", j, &sname);
if (error) goto QUIT;
printf("%s = %f\n", sname, sol);
}
}
QUIT:
/* Error reporting */
if (error)
{
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
}
/* Free data */
free(cbeg);
free(cind);
free(cval);
free(sense);
free(rhspen);
/* Free model */
GRBfreemodel(model);
/* Free environment */
GRBfreeenv(env);
135
return 0;
}
136
workforce4_c.c
/* Copyright 2016, Gurobi Optimization, Inc. */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "gurobi_c.h"
int
main(int argc,
char *argv[])
{
GRBenv *env = NULL;
GRBmodel *model = NULL;
int error = 0, status;
int s, w, col;
int *cbeg = NULL;
int *cind = NULL;
int idx;
double *cval = NULL;
char *sense = NULL;
char vname[MAXSTR], cname[MAXSTR];
double val;
137
/* Sample data */
const int nShifts = 14;
const int nWorkers = 7;
/* Create environment */
error = GRBloadenv(&env, "workforce4.log");
if (error) goto QUIT;
138
sprintf(vname, "%s.%s", Workers[w], Shifts[s]);
error = GRBsetcharattrelement(model, "VType", col, GRB_BINARY);
if (error) goto QUIT;
error = GRBsetdblattrelement(model, "UB", col, availability[w][s]);
if (error) goto QUIT;
error = GRBsetstrattrelement(model, "VarName", col, vname);
if (error) goto QUIT;
}
}
139
/* Constraint: assign exactly shiftRequirements[s] workers
to each shift s, plus the slack */
idx = 0;
for (s = 0; s < nShifts; ++s)
{
cbeg[s] = idx;
sense[s] = GRB_EQUAL;
for (w = 0; w < nWorkers; ++w)
{
cind[idx] = xcol(w, s);
cval[idx++] = 1.0;
}
cind[idx] = slackcol(s);
cval[idx++] = 1.0;
}
error = GRBaddconstrs(model, nShifts, idx, cbeg, cind, cval, sense,
shiftRequirements, Shifts);
if (error) goto QUIT;
140
error = GRBaddconstr(model, idx, cind, cval, GRB_EQUAL, 0.0, cname);
if (error) goto QUIT;
}
/* Optimize */
error = solveAndPrint(model, nShifts, nWorkers, Workers, &status);
if (error) goto QUIT;
if (status != GRB_OPTIMAL) goto QUIT;
141
cval[idx++] = -nWorkers;
error = GRBaddconstr(model, idx, cind, cval, GRB_EQUAL, 0.0, "avgShifts");
if (error) goto QUIT;
/* Objective: minimize the sum of the square of the difference from the
average number of shifts worked */
error = GRBsetdblattrelement(model, "Obj", totSlackcol, 0.0);
if (error) goto QUIT;
/* Optimize */
error = solveAndPrint(model, nShifts, nWorkers, Workers, &status);
if (error) goto QUIT;
if (status != GRB_OPTIMAL) goto QUIT;
QUIT:
/* Error reporting */
if (error)
{
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
142
}
/* Free data */
free(cbeg);
free(cind);
free(cval);
free(sense);
/* Free model */
GRBfreemodel(model);
/* Free environment */
GRBfreeenv(env);
return 0;
}
error = GRBoptimize(model);
if (error) return error;
143
}
/* Print total slack and the number of shifts worked for each worker */
error = GRBgetdblattrelement(model, "X", totSlackcol, &val);
if (error) return error;
144
workforce5_c.c
/* Copyright 2016, Gurobi Optimization, Inc. */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "gurobi_c.h"
int
main(int argc,
char *argv[])
{
GRBenv *env = NULL;
GRBenv *menv = NULL;
GRBmodel *model = NULL;
int error = 0, status;
int s, w, col;
int *cbeg = NULL;
int *cind = NULL;
int idx;
double *cval = NULL;
char *sense = NULL;
145
char vname[MAXSTR], cname[MAXSTR];
/* Sample data */
const int nShifts = 14;
const int nWorkers = 8;
/* Create environment */
error = GRBloadenv(&env, "workforce5.log");
if (error) goto QUIT;
146
/* Initialize assignment decision variables:
x[w][s] == 1 if worker w is assigned to shift s.
This is no longer a pure assignment model, so we must
use binary variables. */
for (w = 0; w < nWorkers; ++w)
{
for (s = 0; s < nShifts; ++s)
{
col = xcol(w, s);
sprintf(vname, "%s.%s", Workers[w], Shifts[s]);
error = GRBsetcharattrelement(model, "VType", col, GRB_BINARY);
if (error) goto QUIT;
error = GRBsetdblattrelement(model, "UB", col, availability[w][s]);
if (error) goto QUIT;
error = GRBsetstrattrelement(model, "VarName", col, vname);
if (error) goto QUIT;
}
}
147
error = GRBsetstrattrelement(model, "VarName", maxShiftcol, vname);
148
for (w = 0; w < nWorkers; ++w)
{
idx = 0;
for (s = 0; s < nShifts; ++s)
{
cind[idx] = xcol(w,s);
cval[idx++] = 1.0;
}
sprintf(cname, "totShifts%s", Workers[w]);
cind[idx] = totShiftscol(w);
cval[idx++] = -1.0;
error = GRBaddconstr(model, idx, cind, cval, GRB_EQUAL, 0.0, cname);
if (error) goto QUIT;
}
149
if (error) goto QUIT;
cind[0] = totSlackcol;
cval[0] = 1.0;
error = GRBsetdblattrlist(model, GRB_DBL_ATTR_OBJN, 1, cind, cval);
if (error) goto QUIT;
/* Save problem */
error = GRBwrite(model, "workforce5.lp");
if (error) goto QUIT;
error = GRBwrite(model, "workforce5.mps");
if (error) goto QUIT;
/* Optimize */
error = solveAndPrint(model, nShifts, nWorkers, Workers, &status);
if (error) goto QUIT;
if (status != GRB_OPTIMAL) goto QUIT;
QUIT:
/* Error reporting */
if (error)
{
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
}
/* Free data */
150
free(cbeg);
free(cind);
free(cval);
free(sense);
/* Free model */
GRBfreemodel(model);
/* Free environment */
GRBfreeenv(env);
return 0;
}
error = GRBoptimize(model);
if (error) return error;
/* Print total slack and the number of shifts worked for each worker */
error = GRBgetdblattrelement(model, "X", totSlackcol, &val);
151
if (error) return error;
152
3.2 C++ Examples
This section includes source code for all of the Gurobi C++ examples. The same source code can
be found in the examples/c++ directory of the Gurobi distribution.
callback_c++.cpp
/* Copyright 2016, Gurobi Optimization, Inc. */
/*
This example reads a model from a file, sets up a callback that
monitors optimization progress and implements a custom
termination strategy, and outputs progress information to the
screen and to a log file.
#include "gurobi_c++.h"
#include <fstream>
#include <cmath>
using namespace std;
153
protected:
void callback () {
try {
if (where == GRB_CB_POLLING) {
// Ignore polling callback
} else if (where == GRB_CB_PRESOLVE) {
// Presolve callback
int cdels = getIntInfo(GRB_CB_PRE_COLDEL);
int rdels = getIntInfo(GRB_CB_PRE_ROWDEL);
if (cdels || rdels) {
cout << cdels << " columns and " << rdels
<< " rows are removed" << endl;
}
} else if (where == GRB_CB_SIMPLEX) {
// Simplex callback
double itcnt = getDoubleInfo(GRB_CB_SPX_ITRCNT);
if (itcnt - lastiter >= 100) {
lastiter = itcnt;
double obj = getDoubleInfo(GRB_CB_SPX_OBJVAL);
int ispert = getIntInfo(GRB_CB_SPX_ISPERT);
double pinf = getDoubleInfo(GRB_CB_SPX_PRIMINF);
double dinf = getDoubleInfo(GRB_CB_SPX_DUALINF);
char ch;
if (ispert == 0) ch = ' ';
else if (ispert == 1) ch = 'S';
else ch = 'P';
cout << itcnt << " " << obj << ch << " "
<< pinf << " " << dinf << endl;
}
} else if (where == GRB_CB_MIP) {
// General MIP callback
double nodecnt = getDoubleInfo(GRB_CB_MIP_NODCNT);
double objbst = getDoubleInfo(GRB_CB_MIP_OBJBST);
double objbnd = getDoubleInfo(GRB_CB_MIP_OBJBND);
int solcnt = getIntInfo(GRB_CB_MIP_SOLCNT);
if (nodecnt - lastnode >= 100) {
lastnode = nodecnt;
int actnodes = (int) getDoubleInfo(GRB_CB_MIP_NODLFT);
int itcnt = (int) getDoubleInfo(GRB_CB_MIP_ITRCNT);
int cutcnt = getIntInfo(GRB_CB_MIP_CUTCNT);
cout << nodecnt << " " << actnodes << " " << itcnt
<< " " << objbst << " " << objbnd << " "
<< solcnt << " " << cutcnt << endl;
}
if (fabs(objbst - objbnd) < 0.1 * (1.0 + fabs(objbst))) {
154
cout << "Stop early - 10% gap achieved" << endl;
abort();
}
if (nodecnt >= 10000 && solcnt) {
cout << "Stop early - 10000 nodes explored" << endl;
abort();
}
} else if (where == GRB_CB_MIPSOL) {
// MIP solution callback
int nodecnt = (int) getDoubleInfo(GRB_CB_MIPSOL_NODCNT);
double obj = getDoubleInfo(GRB_CB_MIPSOL_OBJ);
int solcnt = getIntInfo(GRB_CB_MIPSOL_SOLCNT);
double* x = getSolution(vars, numvars);
cout << "**** New solution at node " << nodecnt
<< ", obj " << obj << ", sol " << solcnt
<< ", x[0] = " << x[0] << " ****" << endl;
delete[] x;
} else if (where == GRB_CB_MIPNODE) {
// MIP node callback
cout << "**** New node ****" << endl;
if (getIntInfo(GRB_CB_MIPNODE_STATUS) == GRB_OPTIMAL) {
double* x = getNodeRel(vars, numvars);
setSolution(vars, x, numvars);
delete[] x;
}
} else if (where == GRB_CB_BARRIER) {
// Barrier callback
int itcnt = getIntInfo(GRB_CB_BARRIER_ITRCNT);
double primobj = getDoubleInfo(GRB_CB_BARRIER_PRIMOBJ);
double dualobj = getDoubleInfo(GRB_CB_BARRIER_DUALOBJ);
double priminf = getDoubleInfo(GRB_CB_BARRIER_PRIMINF);
double dualinf = getDoubleInfo(GRB_CB_BARRIER_DUALINF);
double cmpl = getDoubleInfo(GRB_CB_BARRIER_COMPL);
cout << itcnt << " " << primobj << " " << dualobj << " "
<< priminf << " " << dualinf << " " << cmpl << endl;
} else if (where == GRB_CB_MESSAGE) {
// Message callback
string msg = getStringInfo(GRB_CB_MSG_STRING);
*logfile << msg;
}
} catch (GRBException e) {
cout << "Error number: " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
} catch (...) {
cout << "Error during callback" << endl;
155
}
}
};
int
main(int argc,
char *argv[])
{
if (argc < 2) {
cout << "Usage: callback_c++ filename" << endl;
return 1;
}
GRBEnv *env = 0;
GRBVar *vars = 0;
try {
// Create environment
env = new GRBEnv();
model.setCallback(&cb);
156
if (model.get(GRB_IntAttr_SolCount) == 0) {
cout << "No solution found, optimization status = "
<< model.get(GRB_IntAttr_Status) << endl;
} else {
cout << "Solution found, objective = "
<< model.get(GRB_DoubleAttr_ObjVal) << endl;
for (int j = 0; j < numvars; j++) {
GRBVar v = vars[j];
double x = v.get(GRB_DoubleAttr_X);
if (x != 0.0) {
cout << v.get(GRB_StringAttr_VarName) << " " << x << endl;
}
}
}
} catch (GRBException e) {
cout << "Error number: " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
} catch (...) {
cout << "Error during optimization" << endl;
}
delete[] vars;
delete env;
return 0;
}
157
dense_c++.cpp
/* Copyright 2016, Gurobi Optimization, Inc. */
#include "gurobi_c++.h"
using namespace std;
static bool
dense_optimize(GRBEnv* env,
int rows,
int cols,
double* c, /* linear portion of objective function */
double* Q, /* quadratic portion of objective function */
double* A, /* constraint matrix */
char* sense, /* constraint senses */
double* rhs, /* RHS vector */
double* lb, /* variable lower bounds */
double* ub, /* variable upper bounds */
char* vtype, /* variable types (continuous, binary, etc.) */
double* solution,
double* objvalP)
{
GRBModel model = GRBModel(*env);
int i, j;
bool success = false;
/* Populate A matrix */
158
for (j = 0; j < cols; j++)
if (A[i*cols+j] != 0)
lhs += A[i*cols+j]*vars[j];
model.addConstr(lhs, sense[i], rhs[i]);
}
GRBQuadExpr obj = 0;
model.setObjective(obj);
model.optimize();
model.write("dense.lp");
if (model.get(GRB_IntAttr_Status) == GRB_OPTIMAL) {
*objvalP = model.get(GRB_DoubleAttr_ObjVal);
for (i = 0; i < cols; i++)
solution[i] = vars[i].get(GRB_DoubleAttr_X);
success = true;
}
delete[] vars;
return success;
}
int
main(int argc,
char *argv[])
{
GRBEnv* env = 0;
try {
env = new GRBEnv();
double c[] = {1, 1, 0};
double Q[3][3] = {{1, 1, 0}, {0, 1, 1}, {0, 0, 1}};
double A[2][3] = {{1, 2, 3}, {1, 1, 0}};
char sense[] = {'>', '>'};
double rhs[] = {4, 1};
159
double lb[] = {0, 0, 0};
bool success;
double objval, sol[3];
cout << "x: " << sol[0] << " y: " << sol[1] << " z: " << sol[2] << endl;
} catch(GRBException e) {
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
} catch(...) {
cout << "Exception during optimization" << endl;
}
delete env;
return 0;
}
160
diet_c++.cpp
/* Copyright 2016, Gurobi Optimization, Inc. */
#include "gurobi_c++.h"
using namespace std;
int
main(int argc,
char *argv[])
{
GRBEnv* env = 0;
GRBVar* nutrition = 0;
GRBVar* buy = 0;
try
{
// Set of foods
const int nFoods = 9;
string Foods[] =
{ "hamburger", "chicken", "hot dog", "fries",
"macaroni", "pizza", "salad", "milk", "ice cream" };
double cost[] =
{ 2.49, 2.89, 1.50, 1.89, 2.09, 1.99, 2.49, 0.89, 1.59 };
161
{ 320, 12, 10, 930 }, // macaroni
{ 320, 15, 12, 820 }, // pizza
{ 320, 31, 12, 1230 }, // salad
{ 100, 8, 2.5, 125 }, // milk
{ 330, 8, 10, 180 } // ice cream
};
// Model
env = new GRBEnv();
GRBModel model = GRBModel(*env);
model.set(GRB_StringAttr_ModelName, "diet");
// Nutrition constraints
for (int i = 0; i < nCategories; ++i)
{
GRBLinExpr ntot = 0;
for (int j = 0; j < nFoods; ++j)
{
ntot += nutritionValues[j][i] * buy[j];
}
model.addConstr(ntot == nutrition[i], Categories[i]);
}
// Solve
model.optimize();
printSolution(model, nCategories, nFoods, buy, nutrition);
// Solve
model.optimize();
printSolution(model, nCategories, nFoods, buy, nutrition);
162
}
catch (GRBException e)
{
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
}
catch (...)
{
cout << "Exception during optimization" << endl;
}
delete[] nutrition;
delete[] buy;
delete env;
return 0;
}
163
facility_c++.cpp
/* Copyright 2016, Gurobi Optimization, Inc. */
#include "gurobi_c++.h"
#include <sstream>
using namespace std;
int
main(int argc,
char *argv[])
{
GRBEnv* env = 0;
GRBVar* open = 0;
GRBVar** transport = 0;
int transportCt = 0;
try
{
164
{ 2500, 2600, 3400, 3000, 4000 },
{ 1200, 1800, 2600, 4100, 3000 },
{ 2200, 2600, 3100, 3700, 3200 }
};
// Model
env = new GRBEnv();
GRBModel model = GRBModel(*env);
model.set(GRB_StringAttr_ModelName, "facility");
int p;
for (p = 0; p < nPlants; ++p)
{
ostringstream vname;
vname << "Open" << p;
open[p].set(GRB_DoubleAttr_Obj, FixedCosts[p]);
open[p].set(GRB_StringAttr_VarName, vname.str());
}
// Production constraints
// Note that the right-hand limit sets the production to zero if
165
// the plant is closed
for (p = 0; p < nPlants; ++p)
{
GRBLinExpr ptot = 0;
for (w = 0; w < nWarehouses; ++w)
{
ptot += transport[w][p];
}
ostringstream cname;
cname << "Capacity" << p;
model.addConstr(ptot <= Capacity[p] * open[p], cname.str());
}
// Demand constraints
for (w = 0; w < nWarehouses; ++w)
{
GRBLinExpr dtot = 0;
for (p = 0; p < nPlants; ++p)
{
dtot += transport[w][p];
}
ostringstream cname;
cname << "Demand" << w;
model.addConstr(dtot == Demand[w], cname.str());
}
// Guess at the starting point: close the plant with the highest
// fixed costs; open all others
166
for (p = 0; p < nPlants; ++p)
{
if (FixedCosts[p] == maxFixed)
{
open[p].set(GRB_DoubleAttr_Start, 0.0);
cout << "Closing plant " << p << endl << endl;
break;
}
}
// Solve
model.optimize();
// Print solution
cout << "\nTOTAL COSTS: " << model.get(GRB_DoubleAttr_ObjVal) << endl;
cout << "SOLUTION:" << endl;
for (p = 0; p < nPlants; ++p)
{
if (open[p].get(GRB_DoubleAttr_X) > 0.99)
{
cout << "Plant " << p << " open:" << endl;
for (w = 0; w < nWarehouses; ++w)
{
if (transport[w][p].get(GRB_DoubleAttr_X) > 0.0001)
{
cout << " Transport " <<
transport[w][p].get(GRB_DoubleAttr_X) <<
" units to warehouse " << w << endl;
}
}
}
else
{
cout << "Plant " << p << " closed!" << endl;
}
}
}
catch (GRBException e)
{
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
167
}
catch (...)
{
cout << "Exception during optimization" << endl;
}
delete[] open;
for (int i = 0; i < transportCt; ++i) {
delete[] transport[i];
}
delete[] transport;
delete env;
return 0;
}
168
feasopt_c++.cpp
/* Copyright 2016, Gurobi Optimization, Inc. */
#include "gurobi_c++.h"
using namespace std;
int
main(int argc,
char *argv[])
{
if (argc < 2)
{
cout << "Usage: feasopt_c++ filename" << endl;
return 1;
}
GRBEnv* env = 0;
GRBConstr* c = 0;
try
{
env = new GRBEnv();
GRBModel feasmodel = GRBModel(*env, argv[1]);
// clear objective
feasmodel.setObjective(GRBLinExpr(0.0));
169
double coef = -1.0;
feasmodel.addVar(0.0, GRB_INFINITY, 1.0, GRB_CONTINUOUS, 1,
&c[i], &coef, "ArtN_" +
c[i].get(GRB_StringAttr_ConstrName));
}
if (sense != '<')
{
double coef = 1.0;
feasmodel.addVar(0.0, GRB_INFINITY, 1.0, GRB_CONTINUOUS, 1,
&c[i], &coef, "ArtP_" +
c[i].get(GRB_StringAttr_ConstrName));
}
}
delete[] c;
delete env;
return 0;
}
170
xanddive_c++.cpp
/* Copyright 2016, Gurobi Optimization, Inc. */
#include "gurobi_c++.h"
#include <algorithm>
#include <cmath>
#include <deque>
using namespace std;
int
main(int argc,
char *argv[])
{
if (argc < 2)
{
cout << "Usage: fixanddive_c++ filename" << endl;
return 1;
}
GRBEnv* env = 0;
GRBVar* x = 0;
try
{
// Read model
env = new GRBEnv();
GRBModel model = GRBModel(*env, argv[1]);
171
}
}
model.set(GRB_IntParam_OutputFlag, 0);
model.optimize();
deque<GRBVar*> fractional;
for (size_t j = 0; j < intvars.size(); ++j)
{
double sol = fabs(intvars[j]->get(GRB_DoubleAttr_X));
if (fabs(sol - floor(sol + 0.5)) > 1e-5)
{
fractional.push_back(intvars[j]);
}
}
cout << "Iteration " << iter << ", obj " <<
model.get(GRB_DoubleAttr_ObjVal) << ", fractional " <<
fractional.size() << endl;
if (fractional.size() == 0)
{
cout << "Found feasible solution - objective " <<
model.get(GRB_DoubleAttr_ObjVal) << endl;
break;
}
172
double fixval = floor(v->get(GRB_DoubleAttr_X) + 0.5);
v->set(GRB_DoubleAttr_LB, fixval);
v->set(GRB_DoubleAttr_UB, fixval);
cout << " Fix " << v->get(GRB_StringAttr_VarName) << " to " <<
fixval << " ( rel " << v->get(GRB_DoubleAttr_X) << " )" <<
endl;
}
model.optimize();
if (model.get(GRB_IntAttr_Status) != GRB_OPTIMAL)
{
cout << "Relaxation is infeasible" << endl;
break;
}
}
}
catch (GRBException e)
{
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
}
catch (...)
{
cout << "Error during optimization" << endl;
}
delete[] x;
delete env;
return 0;
}
173
genconstr_c++.cpp
/* Copyright 2016, Gurobi Optimization, Inc. */
#include "gurobi_c++.h"
#include <sstream>
#include <iomanip>
using namespace std;
#define n 4
#define NLITERALS 4 // same as n
#define NCLAUSES 8
#define NOBJ 2
int
main(void)
{
GRBEnv *env = 0;
174
try{
// Example data
// e.g. {0, n+1, 2} means clause (x0 or ~x1 or x2)
const int Clauses[][3] = {{ 0, n+1, 2}, { 1, n+2, 3},
{ 2, n+3, 0}, { 3, n+0, 1},
{n+0, n+1, 2}, {n+1, n+2, 3},
{n+2, n+3, 0}, {n+3, n+0, 1}};
// Create environment
env = new GRBEnv("genconstr_c++.log");
GRBVar Lit[NLITERALS];
GRBVar NotLit[NLITERALS];
for (i = 0; i < NLITERALS; i++) {
ostringstream vname;
vname << "X" << i;
Lit[i] = model.addVar(0.0, 1.0, 0.0, GRB_BINARY, vname.str());
vname.str("");
vname << "notX" << i;
NotLit[i] = model.addVar(0.0, 1.0, 0.0, GRB_BINARY, vname.str());
}
GRBVar Cla[NCLAUSES];
for (i = 0; i < NCLAUSES; i++) {
ostringstream vname;
vname << "Clause" << i;
Cla[i] = model.addVar(0.0, 1.0, 0.0, GRB_BINARY, vname.str());
}
GRBVar Obj[NOBJ];
for (i = 0; i < NOBJ; i++) {
ostringstream vname;
vname << "Obj" << i;
Obj[i] = model.addVar(0.0, 1.0, 1.0, GRB_BINARY, vname.str());
}
175
// Link Xi and notXi
GRBLinExpr lhs;
for (i = 0; i < NLITERALS; i++) {
ostringstream cname;
cname << "CNSTR_X" << i;
lhs = 0;
lhs += Lit[i];
lhs += NotLit[i];
model.addConstr(lhs == 1.0, cname.str());
}
// Save problem
model.write("genconstr_c++.mps");
model.write("genconstr_c++.lp");
// Optimize
model.optimize();
// Status checking
status = model.get(GRB_IntAttr_Status);
176
if (status == GRB_INF_OR_UNBD ||
status == GRB_INFEASIBLE ||
status == GRB_UNBOUNDED ) {
cout << "The model cannot be solved " <<
"because it is infeasible or unbounded" << endl;
return 1;
}
if (status != GRB_OPTIMAL) {
cout << "Optimization was stopped with status " << status << endl;
return 1;
}
// Print result
double objval = model.get(GRB_DoubleAttr_ObjVal);
} catch (GRBException e) {
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
}
catch (...) {
cout << "Exception during optimization" << endl;
}
// Free environment
delete env;
return 0;
}
177
lp_c++.cpp
/* Copyright 2016, Gurobi Optimization, Inc. */
#include "gurobi_c++.h"
using namespace std;
int
main(int argc,
char *argv[])
{
if (argc < 2) {
cout << "Usage: lp_c++ filename" << endl;
return 1;
}
try {
GRBEnv env = GRBEnv();
GRBModel model = GRBModel(env, argv[1]);
model.optimize();
if (optimstatus == GRB_INF_OR_UNBD) {
model.set(GRB_IntParam_Presolve, 0);
model.optimize();
optimstatus = model.get(GRB_IntAttr_Status);
}
if (optimstatus == GRB_OPTIMAL) {
double objval = model.get(GRB_DoubleAttr_ObjVal);
cout << "Optimal objective: " << objval << endl;
} else if (optimstatus == GRB_INFEASIBLE) {
cout << "Model is infeasible" << endl;
model.computeIIS();
model.write("model.ilp");
178
} else if (optimstatus == GRB_UNBOUNDED) {
cout << "Model is unbounded" << endl;
} else {
cout << "Optimization was stopped with status = "
<< optimstatus << endl;
}
} catch(GRBException e) {
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
} catch (...) {
cout << "Error during optimization" << endl;
}
return 0;
}
179
lpmethod_c++.cpp
/* Copyright 2016, Gurobi Optimization, Inc. */
#include "gurobi_c++.h"
using namespace std;
int
main(int argc,
char *argv[])
{
if (argc < 2)
{
cout << "Usage: lpmethod_c++ filename" << endl;
return 1;
}
try {
// Read model
GRBEnv env = GRBEnv();
GRBModel m = GRBModel(env, argv[1]);
180
cout << "Solved in " << bestTime
<< " seconds with Method: " << bestMethod << endl;
}
} catch(GRBException e) {
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
} catch(...) {
cout << "Exception during optimization" << endl;
}
return 0;
}
181
lpmod_c++.cpp
/* Copyright 2016, Gurobi Optimization, Inc. */
#include "gurobi_c++.h"
using namespace std;
int
main(int argc,
char *argv[])
{
if (argc < 2)
{
cout << "Usage: lpmod_c++ filename" << endl;
return 1;
}
GRBEnv* env = 0;
GRBVar* v = 0;
try
{
// Read model and determine whether it is an LP
env = new GRBEnv();
GRBModel model = GRBModel(*env, argv[1]);
if (model.get(GRB_IntAttr_IsMIP) != 0)
{
cout << "The model is not a linear program" << endl;
return 1;
}
model.optimize();
182
}
if (status != GRB_OPTIMAL)
{
cout << "Optimization was stopped with status " << status << endl;
return 0;
}
cout << "\n*** Warm start: " << warmCount << " iterations, " <<
183
warmTime << " seconds" << endl;
cout << "*** Cold start: " << coldCount << " iterations, " <<
coldTime << " seconds" << endl;
}
catch (GRBException e)
{
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
}
catch (...)
{
cout << "Error during optimization" << endl;
}
delete[] v;
delete env;
return 0;
}
184
mip1_c++.cpp
/* Copyright 2016, Gurobi Optimization, Inc. */
/* This example formulates and solves the following simple MIP model:
maximize x + y + 2 z
subject to x + 2 y + 3 z <= 4
x + y >= 1
x, y, z binary
*/
#include "gurobi_c++.h"
using namespace std;
int
main(int argc,
char *argv[])
{
try {
GRBEnv env = GRBEnv();
// Create variables
model.setObjective(x + y + 2 * z, GRB_MAXIMIZE);
// Optimize model
model.optimize();
185
cout << x.get(GRB_StringAttr_VarName) << " "
<< x.get(GRB_DoubleAttr_X) << endl;
cout << y.get(GRB_StringAttr_VarName) << " "
<< y.get(GRB_DoubleAttr_X) << endl;
cout << z.get(GRB_StringAttr_VarName) << " "
<< z.get(GRB_DoubleAttr_X) << endl;
} catch(GRBException e) {
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
} catch(...) {
cout << "Exception during optimization" << endl;
}
return 0;
}
186
mip2_c++.cpp
/* Copyright 2016, Gurobi Optimization, Inc. */
#include "gurobi_c++.h"
#include <cmath>
using namespace std;
int
main(int argc,
char *argv[])
{
if (argc < 2) {
cout << "Usage: mip2_c++ filename" << endl;
return 1;
}
GRBEnv *env = 0;
GRBVar *vars = 0, *fvars = 0;
try {
env = new GRBEnv();
GRBModel model = GRBModel(*env, argv[1]);
if (model.get(GRB_IntAttr_IsMIP) == 0) {
throw GRBException("Model is not a MIP");
}
model.optimize();
187
return 0;
} else if (optimstatus == GRB_UNBOUNDED) {
cout << "Model is unbounded" << endl;
return 0;
} else {
cout << "Optimization was stopped with status = "
<< optimstatus << endl;
return 0;
}
cout << "Solution " << k << " has objective: " << objn << endl;
}
cout << endl;
model.set(GRB_IntParam_OutputFlag, 1);
fixed.set(GRB_IntParam_Presolve, 0);
fixed.optimize();
if (foptimstatus != GRB_OPTIMAL) {
cerr << "Error: fixed model isn't optimal" << endl;
return 0;
}
188
double fobjval = fixed.get(GRB_DoubleAttr_ObjVal);
} catch(GRBException e) {
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
} catch (...) {
cout << "Error during optimization" << endl;
}
delete[] fvars;
delete[] vars;
delete env;
return 0;
}
189
multiobj_c++.cpp
/* Copyright 2016, Gurobi Optimization, Inc. */
#include "gurobi_c++.h"
#include <sstream>
#include <iomanip>
using namespace std;
int
main(void)
{
GRBEnv *env = 0;
GRBVar *Elem = 0;
int e, i, status, nSolutions;
try{
// Sample data
const int groundSetSize = 20;
const int nSubsets = 4;
const int Budget = 12;
double Set[][20] =
{ { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1 },
{ 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0 },
{ 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0 } };
int SetObjPriority[] = {3, 2, 2, 1};
double SetObjWeight[] = {1.0, 0.25, 1.25, 1.0};
// Create environment
env = new GRBEnv("multiobj_c++.log");
190
Elem[e].set(GRB_StringAttr_VarName, vname.str());
}
ostringstream vname;
vname << "Set" << i;
model.set(GRB_StringAttr_ObjNName, vname.str());
model.set(GRB_DoubleAttr_ObjNRelTol, 0.01);
model.set(GRB_DoubleAttr_ObjNAbsTol, 1.0 + i);
model.set(GRB_DoubleAttr_ObjN, Elem, Set[i], groundSetSize);
}
// Save problem
model.write("multiobj_c++.lp");
// Optimize
model.optimize();
// Status checking
status = model.get(GRB_IntAttr_Status);
if (status == GRB_INF_OR_UNBD ||
191
status == GRB_INFEASIBLE ||
status == GRB_UNBOUNDED ) {
cout << "The model cannot be solved " <<
"because it is infeasible or unbounded" << endl;
return 1;
}
if (status != GRB_OPTIMAL) {
cout << "Optimization was stopped with status " << status << endl;
return 1;
}
}
catch (GRBException e) {
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
}
192
catch (...) {
cout << "Exception during optimization" << endl;
}
// Free environment/vars
delete[] Elem;
delete env;
return 0;
}
193
params_c++.cpp
/* Copyright 2016, Gurobi Optimization, Inc. */
#include "gurobi_c++.h"
using namespace std;
int
main(int argc,
char *argv[])
{
if (argc < 2)
{
cout << "Usage: params_c++ filename" << endl;
return 1;
}
GRBEnv* env = 0;
GRBModel *bestModel = 0, *m = 0;
try
{
// Read model and verify that it is a MIP
env = new GRBEnv();
m = new GRBModel(*env, argv[1]);
if (m->get(GRB_IntAttr_IsMIP) == 0)
{
cout << "The model is not an integer program" << endl;
return 1;
}
194
m->set(GRB_IntParam_MIPFocus, i);
m->optimize();
if (bestModel->get(GRB_DoubleAttr_MIPGap) >
m->get(GRB_DoubleAttr_MIPGap))
{
swap(bestModel, m);
}
}
// Finally, delete the extra model, reset the time limit and
// continue to solve the best model to optimality
delete m;
m = 0;
bestModel->set(GRB_DoubleParam_TimeLimit, GRB_INFINITY);
bestModel->optimize();
cout << "Solved with MIPFocus: " <<
bestModel->get(GRB_IntParam_MIPFocus) << endl;
}
catch (GRBException e)
{
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
}
catch (...)
{
cout << "Error during optimization" << endl;
}
delete bestModel;
delete m;
delete env;
return 0;
}
195
piecewise_c++.cpp
/* Copyright 2016, Gurobi Optimization, Inc. */
#include "gurobi_c++.h"
#include <cmath>
using namespace std;
int
main(int argc,
char *argv[])
{
double *ptu = NULL;
double *ptf = NULL;
double *ptg = NULL;
try {
// Create environment
// Create variables
196
GRBVar x = model.addVar(lb, ub, 0.0, GRB_CONTINUOUS, "x");
GRBVar y = model.addVar(lb, ub, 0.0, GRB_CONTINUOUS, "y");
GRBVar z = model.addVar(lb, ub, 0.0, GRB_CONTINUOUS, "z");
model.setObjective(-y);
// Optimize model as an LP
model.optimize();
197
cout << "Obj: " << model.get(GRB_DoubleAttr_ObjVal) << endl;
model.optimize();
} catch(GRBException e) {
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
} catch(...) {
cout << "Exception during optimization" << endl;
}
delete[] ptu;
delete[] ptf;
delete[] ptg;
return 0;
}
198
poolsearch_c++.cpp
/* Copyright 2016, Gurobi Optimization, Inc. */
#include "gurobi_c++.h"
#include <sstream>
#include <iomanip>
using namespace std;
int main(void)
{
GRBEnv *env = 0;
GRBVar *Elem = 0;
int e, status, nSolutions;
try {
// Sample data
const int groundSetSize = 10;
double objCoef[10] =
{32, 32, 15, 15, 6, 6, 1, 1, 1, 1};
double knapsackCoef[10] =
{16, 16, 8, 8, 4, 4, 2, 2, 1, 1};
double Budget = 33;
// Create environment
env = new GRBEnv("poolsearch_c++.log");
199
// Constraint: limit total number of elements to be picked to be at most
// Budget
GRBLinExpr lhs;
lhs = 0;
for (e = 0; e < groundSetSize; e++) {
lhs += Elem[e] * knapsackCoef[e];
}
model.addConstr(lhs <= Budget, "Budget");
// Limit the search space by setting a gap for the worst possible solution that will be acce
model.set(GRB_DoubleParam_PoolGap, 0.10);
// save problem
model.write("poolsearch_c++.lp");
// Optimize
model.optimize();
// Status checking
status = model.get(GRB_IntAttr_Status);
if (status == GRB_INF_OR_UNBD ||
status == GRB_INFEASIBLE ||
status == GRB_UNBOUNDED ) {
cout << "The model cannot be solved " <<
"because it is infeasible or unbounded" << endl;
return 1;
}
if (status != GRB_OPTIMAL) {
cout << "Optimization was stopped with status " << status << endl;
return 1;
}
200
if (Elem[e].get(GRB_DoubleAttr_X) < .9) continue;
cout << " El" << e;
}
cout << endl;
cout << "Selected elements in fourth best solution:" << endl << "\t";
for (e = 0; e < groundSetSize; e++) {
if (Elem[e].get(GRB_DoubleAttr_Xn) < .9) continue;
cout << " El" << e;
}
cout << endl;
}
}
catch (GRBException e) {
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
}
catch (...) {
cout << "Exception during optimization" << endl;
}
// Free environment/vars
delete[] Elem;
delete env;
return 0;
}
201
sensitivity_c++.cpp
/* Copyright 2016, Gurobi Optimization, Inc. */
#include "gurobi_c++.h"
using namespace std;
int
main(int argc,
char *argv[])
{
if (argc < 2) {
cout << "Usage: sensitivity_c++ filename" << endl;
return 1;
}
try {
// Create environment
if (model.get(GRB_IntAttr_IsMIP) == 0) {
cout << "Model is not a MIP" << endl;
return 1;
}
model.optimize();
if (model.get(GRB_IntAttr_Status) != GRB_OPTIMAL) {
cout << "Optimization ended with status "
<< model.get(GRB_IntAttr_Status) << endl;
return 1;
202
}
model.set(GRB_IntParam_OutputFlag, 0);
model.optimize();
if (model.get(GRB_IntAttr_Status) == GRB_OPTIMAL) {
203
cout << "Objective sensitivity for variable "
<< v.get(GRB_StringAttr_VarName) << " is "
<< (model.get(GRB_DoubleAttr_ObjVal) - origObjVal) << endl;
} else {
cout << "Objective sensitivity for variable "
<< v.get(GRB_StringAttr_VarName) << " is infinite" << endl;
}
v.set(GRB_DoubleAttr_LB, 0.0);
v.set(GRB_DoubleAttr_UB, 1.0);
}
}
} catch (GRBException e) {
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
} catch (...) {
cout << "Error during optimization" << endl;
}
delete[] vars;
delete[] origX;
return 0;
}
204
qcp_c++.cpp
/* Copyright 2016, Gurobi Optimization, Inc. */
/* This example formulates and solves the following simple QCP model:
maximize x
subject to x + y + z = 1
x^2 + y^2 <= z^2 (second-order cone)
x^2 <= yz (rotated second-order cone)
*/
#include "gurobi_c++.h"
using namespace std;
int
main(int argc,
char *argv[])
{
try {
GRBEnv env = GRBEnv();
// Create variables
// Set objective
GRBLinExpr obj = x;
model.setObjective(obj, GRB_MAXIMIZE);
model.addConstr(x + y + z == 1, "c0");
205
// Optimize model
model.optimize();
} catch(GRBException e) {
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
} catch(...) {
cout << "Exception during optimization" << endl;
}
return 0;
}
206
qp_c++.cpp
/* Copyright 2016, Gurobi Optimization, Inc. */
#include "gurobi_c++.h"
using namespace std;
int
main(int argc,
char *argv[])
{
try {
GRBEnv env = GRBEnv();
// Create variables
// Set objective
// Optimize model
207
model.optimize();
x.set(GRB_CharAttr_VType, GRB_INTEGER);
y.set(GRB_CharAttr_VType, GRB_INTEGER);
z.set(GRB_CharAttr_VType, GRB_INTEGER);
// Optimize model
model.optimize();
} catch(GRBException e) {
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
} catch(...) {
cout << "Exception during optimization" << endl;
}
return 0;
}
208
sos_c++.cpp
/* Copyright 2016, Gurobi Optimization, Inc. */
/* This example creates a very simple Special Ordered Set (SOS) model.
The model consists of 3 continuous variables, no linear constraints,
and a pair of SOS constraints of type 1. */
#include "gurobi_c++.h"
using namespace std;
int
main(int argc,
char *argv[])
{
GRBEnv *env = 0;
GRBVar *x = 0;
try {
env = new GRBEnv();
// Create variables
// Optimize model
209
model.optimize();
} catch(GRBException e) {
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
} catch(...) {
cout << "Exception during optimization" << endl;
}
delete[] x;
delete env;
return 0;
}
210
sudoku_c++.cpp
/* Copyright 2016, Gurobi Optimization, Inc. */
/*
Sudoku example.
The Sudoku board is a 9x9 grid, which is further divided into a 3x3 grid
of 3x3 grids. Each cell in the grid must take a value from 0 to 9.
No two grid cells in the same row, column, or 3x3 subgrid may take the
same value.
#include "gurobi_c++.h"
#include <sstream>
using namespace std;
#define sd 3
#define n (sd*sd)
int
main(int argc,
char *argv[])
{
try {
GRBEnv env = GRBEnv();
GRBModel model = GRBModel(env);
GRBVar vars[n][n][n];
int i, j, v;
211
string s = "G_" + itos(i) + "_" + itos(j) + "_" + itos(v);
vars[i][j][v] = model.addVar(0.0, 1.0, 0.0, GRB_BINARY, s);
}
}
}
// Add constraints
212
for (v = 0; v < n; v++) {
for (int i0 = 0; i0 < sd; i0++) {
for (int j0 = 0; j0 < sd; j0++) {
GRBLinExpr expr = 0;
for (int i1 = 0; i1 < sd; i1++) {
for (int j1 = 0; j1 < sd; j1++) {
expr += vars[i0*sd+i1][j0*sd+j1][v];
}
}
char input[10];
for (i = 0; i < n; i++) {
cin >> input;
for (j = 0; j < n; j++) {
int val = (int) input[j] - 48 - 1; // 0-based
if (val >= 0)
vars[i][j][val].set(GRB_DoubleAttr_LB, 1.0);
}
}
// Optimize model
model.optimize();
model.write("sudoku.lp");
213
}
cout << endl;
}
cout << endl;
} catch(GRBException e) {
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
} catch (...) {
cout << "Error during optimization" << endl;
}
return 0;
}
214
tsp_c++.cpp
/* Copyright 2016, Gurobi Optimization, Inc. */
#include "gurobi_c++.h"
#include <cassert>
#include <cstdlib>
#include <cmath>
#include <sstream>
using namespace std;
215
findsubtour(n, x, &len, tour);
if (len < n) {
// Add subtour elimination constraint
GRBLinExpr expr = 0;
for (i = 0; i < len; i++)
for (j = i+1; j < len; j++)
expr += vars[tour[i]][tour[j]];
addLazy(expr <= len-1);
}
void
findsubtour(int n,
double** sol,
int* tourlenP,
int* tour)
{
bool* seen = new bool[n];
int bestind, bestlen;
int i, node, len, start;
start = 0;
bestlen = n+1;
bestind = -1;
216
node = 0;
while (start < n) {
for (node = 0; node < n; node++)
if (!seen[node])
break;
if (node == n)
break;
for (len = 0; len < n; len++) {
tour[start+len] = node;
seen[node] = true;
for (i = 0; i < n; i++) {
if (sol[node][i] > 0.5 && !seen[i]) {
node = i;
break;
}
}
if (i == n) {
len++;
if (len < bestlen) {
bestlen = len;
bestind = start;
}
start += len;
break;
}
}
}
delete[] seen;
}
double
distance(double* x,
double* y,
int i,
int j)
{
double dx = x[i]-x[j];
double dy = y[i]-y[j];
217
return sqrt(dx*dx+dy*dy);
}
int
main(int argc,
char *argv[])
{
if (argc < 2) {
cout << "Usage: tsp_c++ size" << endl;
return 1;
}
int n = atoi(argv[1]);
double* x = new double[n];
double* y = new double[n];
int i;
for (i = 0; i < n; i++) {
x[i] = ((double) rand())/RAND_MAX;
y[i] = ((double) rand())/RAND_MAX;
}
try {
int j;
model.set(GRB_IntParam_LazyConstraints, 1);
218
GRB_BINARY, "x_"+itos(i)+"_"+itos(j));
vars[j][i] = vars[i][j];
}
}
// Degree-2 constraints
// Optimize model
model.optimize();
// Extract solution
if (model.get(GRB_IntAttr_SolCount) > 0) {
double **sol = new double*[n];
for (i = 0; i < n; i++)
sol[i] = model.get(GRB_DoubleAttr_X, vars[i], n);
219
for (i = 0; i < n; i++)
delete[] sol[i];
delete[] sol;
delete[] tour;
}
} catch (GRBException e) {
cout << "Error number: " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
} catch (...) {
cout << "Error during optimization" << endl;
}
220
tune_c++.cpp
/* Copyright 2016, Gurobi Optimization, Inc. */
#include "gurobi_c++.h"
#include <cmath>
using namespace std;
int
main(int argc,
char *argv[])
{
if (argc < 2) {
cout << "Usage: tune_c++ filename" << endl;
return 1;
}
GRBEnv *env = 0;
try {
env = new GRBEnv();
model.set(GRB_IntParam_TuneResults, 1);
model.tune();
if (resultcount > 0) {
model.getTuneResult(0);
221
// Write tuned parameters to a file
model.write("tune.prm");
model.optimize();
}
} catch(GRBException e) {
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
} catch (...) {
cout << "Error during tuning" << endl;
}
delete env;
return 0;
}
222
workforce1_c++.cpp
/* Copyright 2016, Gurobi Optimization, Inc. */
#include "gurobi_c++.h"
#include <sstream>
using namespace std;
int
main(int argc,
char *argv[])
{
GRBEnv* env = 0;
GRBConstr* c = 0;
GRBVar** x = 0;
int xCt = 0;
try
{
// Sample data
const int nShifts = 14;
const int nWorkers = 7;
223
{ 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0 },
{ 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 },
{ 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1 },
{ 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1 },
{ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } };
// Model
env = new GRBEnv();
GRBModel model = GRBModel(*env);
model.set(GRB_StringAttr_ModelName, "assignment");
224
// Optimize
model.optimize();
int status = model.get(GRB_IntAttr_Status);
if (status == GRB_UNBOUNDED)
{
cout << "The model cannot be solved "
<< "because it is unbounded" << endl;
return 1;
}
if (status == GRB_OPTIMAL)
{
cout << "The optimal objective is " <<
model.get(GRB_DoubleAttr_ObjVal) << endl;
return 0;
}
if ((status != GRB_INF_OR_UNBD) && (status != GRB_INFEASIBLE))
{
cout << "Optimization was stopped with status " << status << endl;
return 1;
}
// do IIS
cout << "The model is infeasible; computing IIS" << endl;
model.computeIIS();
cout << "\nThe following constraint(s) "
<< "cannot be satisfied:" << endl;
c = model.getConstrs();
for (int i = 0; i < model.get(GRB_IntAttr_NumConstrs); ++i)
{
if (c[i].get(GRB_IntAttr_IISConstr) == 1)
{
cout << c[i].get(GRB_StringAttr_ConstrName) << endl;
}
}
}
catch (GRBException e)
{
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
}
catch (...)
{
cout << "Exception during optimization" << endl;
}
225
delete[] c;
for (int i = 0; i < xCt; ++i) {
delete[] x[i];
}
delete[] x;
delete env;
return 0;
}
226
workforce2_c++.cpp
/* Copyright 2016, Gurobi Optimization, Inc. */
#include "gurobi_c++.h"
#include <sstream>
#include <deque>
using namespace std;
int
main(int argc,
char *argv[])
{
GRBEnv* env = 0;
GRBConstr* c = 0;
GRBVar** x = 0;
int xCt = 0;
try
{
// Sample data
const int nShifts = 14;
const int nWorkers = 7;
227
{ 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0 },
{ 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 },
{ 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1 },
{ 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1 },
{ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } };
// Model
env = new GRBEnv();
GRBModel model = GRBModel(*env);
model.set(GRB_StringAttr_ModelName, "assignment");
228
// Optimize
model.optimize();
int status = model.get(GRB_IntAttr_Status);
if (status == GRB_UNBOUNDED)
{
cout << "The model cannot be solved "
<< "because it is unbounded" << endl;
return 1;
}
if (status == GRB_OPTIMAL)
{
cout << "The optimal objective is " <<
model.get(GRB_DoubleAttr_ObjVal) << endl;
return 0;
}
if ((status != GRB_INF_OR_UNBD) && (status != GRB_INFEASIBLE))
{
cout << "Optimization was stopped with status " << status << endl;
return 1;
}
// do IIS
cout << "The model is infeasible; computing IIS" << endl;
deque<string> removed;
229
cout << endl;
model.optimize();
status = model.get(GRB_IntAttr_Status);
if (status == GRB_UNBOUNDED)
{
cout << "The model cannot be solved because it is unbounded" << endl;
return 0;
}
if (status == GRB_OPTIMAL)
{
break;
}
if ((status != GRB_INF_OR_UNBD) && (status != GRB_INFEASIBLE))
{
cout << "Optimization was stopped with status " << status << endl;
return 1;
}
}
cout << "\nThe following constraints were removed "
<< "to get a feasible LP:" << endl;
}
catch (GRBException e)
{
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
}
catch (...)
{
cout << "Exception during optimization" << endl;
}
delete[] c;
for (int i = 0; i < xCt; ++i) {
delete[] x[i];
}
230
delete[] x;
delete env;
return 0;
}
231
workforce3_c++.cpp
/* Copyright 2016, Gurobi Optimization, Inc. */
#include "gurobi_c++.h"
#include <sstream>
using namespace std;
int
main(int argc,
char *argv[])
{
GRBEnv* env = 0;
GRBConstr* c = 0;
GRBVar** x = 0;
GRBVar* vars = 0;
int xCt = 0;
try
{
// Sample data
const int nShifts = 14;
const int nWorkers = 7;
232
{ { 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1 },
{ 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0 },
{ 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 },
{ 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1 },
{ 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1 },
{ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } };
// Model
env = new GRBEnv();
GRBModel model = GRBModel(*env);
model.set(GRB_StringAttr_ModelName, "assignment");
233
// Optimize
model.optimize();
int status = model.get(GRB_IntAttr_Status);
if (status == GRB_UNBOUNDED)
{
cout << "The model cannot be solved "
<< "because it is unbounded" << endl;
return 1;
}
if (status == GRB_OPTIMAL)
{
cout << "The optimal objective is " <<
model.get(GRB_DoubleAttr_ObjVal) << endl;
return 0;
}
if ((status != GRB_INF_OR_UNBD) && (status != GRB_INFEASIBLE))
{
cout << "Optimization was stopped with status " << status << endl;
return 1;
}
234
GRBVar sv = vars[i];
if (sv.get(GRB_DoubleAttr_X) > 1e-6)
{
cout << sv.get(GRB_StringAttr_VarName) << " = " <<
sv.get(GRB_DoubleAttr_X) << endl;
}
}
}
catch (GRBException e)
{
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
}
catch (...)
{
cout << "Exception during optimization" << endl;
}
delete[] c;
for (int i = 0; i < xCt; ++i) {
delete[] x[i];
}
delete[] x;
delete[] vars;
delete env;
return 0;
}
235
workforce4_c++.cpp
/* Copyright 2016, Gurobi Optimization, Inc. */
#include "gurobi_c++.h"
#include <sstream>
using namespace std;
int
main(int argc,
char *argv[])
{
GRBEnv* env = 0;
GRBVar** x = 0;
GRBVar* slacks = 0;
GRBVar* totShifts = 0;
GRBVar* diffShifts = 0;
int xCt = 0;
try
{
// Sample data
const int nShifts = 14;
const int nWorkers = 7;
236
// Worker availability: 0 if the worker is unavailable for a shift
double availability[][nShifts] =
{ { 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1 },
{ 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0 },
{ 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 },
{ 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1 },
{ 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1 },
{ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } };
// Model
env = new GRBEnv();
GRBModel model = GRBModel(*env);
model.set(GRB_StringAttr_ModelName, "assignment");
// Slack variables for each shift constraint so that the shifts can
// be satisfied
slacks = model.addVars(nShifts);
for (s = 0; s < nShifts; ++s) {
ostringstream vname;
237
// Variable to represent the total slack
GRBVar totSlack = model.addVar(0, GRB_INFINITY, 0, GRB_CONTINUOUS,
"totSlack");
GRBLinExpr lhs;
238
model.addConstr(lhs == totShifts[w], vname.str());
}
// Optimize
int status = solveAndPrint(model, totSlack, nWorkers, Workers, totShifts);
if (status != GRB_OPTIMAL)
return 1;
239
model.addConstr(lhs == diffShifts[w], vname.str());
}
// Objective: minimize the sum of the square of the difference from the
// average number of shifts worked
GRBQuadExpr qobj;
for (w = 0; w < nWorkers; ++w) {
qobj += diffShifts[w] * diffShifts[w];
}
model.setObjective(qobj);
// Optimize
status = solveAndPrint(model, totSlack, nWorkers, Workers, totShifts);
if (status != GRB_OPTIMAL)
return 1;
}
catch (GRBException e) {
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
}
catch (...) {
cout << "Exception during optimization" << endl;
}
return 0;
}
240
if ((status == GRB_INF_OR_UNBD) ||
(status == GRB_INFEASIBLE) ||
(status == GRB_UNBOUNDED) ) {
cout << "The model cannot be solved " <<
"because it is infeasible or unbounded" << endl;
return status;
}
if (status != GRB_OPTIMAL) {
cout << "Optimization was stopped with status " << status << endl;
return status;
}
// Print total slack and the number of shifts worked for each worker
cout << endl << "Total slack required: " <<
totSlack.get(GRB_DoubleAttr_X) << endl;
for (int w = 0; w < nWorkers; ++w) {
cout << Workers[w] << " worked " <<
totShifts[w].get(GRB_DoubleAttr_X) << " shifts" << endl;
}
cout << endl;
return status;
}
241
workforce5_c++.cpp
/* Copyright 2016, Gurobi Optimization, Inc. */
#include "gurobi_c++.h"
#include <sstream>
using namespace std;
int
main(int argc,
char *argv[])
{
GRBEnv *env = 0;
GRBVar **x = 0;
GRBVar *slacks = 0;
GRBVar *totShifts = 0;
int xCt = 0;
int s, w;
try {
// Sample data
const int nShifts = 14;
const int nWorkers = 8;
242
{ 3, 2, 4, 4, 5, 6, 5, 2, 2, 3, 4, 6, 7, 5 };
// Create environment
env = new GRBEnv("workforce5_c++.log");
243
// Variable to represent the total slack
GRBVar totSlack = model.addVar(0, GRB_INFINITY, 0, GRB_CONTINUOUS,
"totSlack");
GRBLinExpr lhs;
ostringstream vname;
vname << "totShifts" << Workers[w];
model.addConstr(lhs == totShifts[w], vname.str());
244
}
// Save problem
model.write("workforce5++.lp");
// Optimize
int status = solveAndPrint(model, totSlack, nWorkers, Workers, totShifts);
245
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
}
catch (...) {
cout << "Exception during optimization" << endl;
}
if ((status == GRB_INF_OR_UNBD) ||
(status == GRB_INFEASIBLE) ||
(status == GRB_UNBOUNDED) ) {
cout << "The model cannot be solved " <<
"because it is infeasible or unbounded" << endl;
return status;
}
if (status != GRB_OPTIMAL) {
cout << "Optimization was stopped with status " << status << endl;
return status;
}
// Print total slack and the number of shifts worked for each worker
cout << endl << "Total slack required: " <<
totSlack.get(GRB_DoubleAttr_X) << endl;
for (int w = 0; w < nWorkers; ++w) {
cout << Workers[w] << " worked " <<
totShifts[w].get(GRB_DoubleAttr_X) << " shifts" << endl;
}
cout << endl;
246
return status;
}
247
3.3 Java Examples
This section includes source code for all of the Gurobi Java examples. The same source code can
be found in the examples/java directory of the Gurobi distribution.
Callback.java
/* Copyright 2016, Gurobi Optimization, Inc. */
/*
This example reads a model from a file, sets up a callback that
monitors optimization progress and implements a custom
termination strategy, and outputs progress information to the
screen and to a log file.
import gurobi.*;
import java.io.FileWriter;
import java.io.IOException;
248
// Ignore polling callback
} else if (where == GRB.CB_PRESOLVE) {
// Presolve callback
int cdels = getIntInfo(GRB.CB_PRE_COLDEL);
int rdels = getIntInfo(GRB.CB_PRE_ROWDEL);
if (cdels != 0 || rdels != 0) {
System.out.println(cdels + " columns and " + rdels
+ " rows are removed");
}
} else if (where == GRB.CB_SIMPLEX) {
// Simplex callback
double itcnt = getDoubleInfo(GRB.CB_SPX_ITRCNT);
if (itcnt - lastiter >= 100) {
lastiter = itcnt;
double obj = getDoubleInfo(GRB.CB_SPX_OBJVAL);
int ispert = getIntInfo(GRB.CB_SPX_ISPERT);
double pinf = getDoubleInfo(GRB.CB_SPX_PRIMINF);
double dinf = getDoubleInfo(GRB.CB_SPX_DUALINF);
char ch;
if (ispert == 0) ch = ' ';
else if (ispert == 1) ch = 'S';
else ch = 'P';
System.out.println(itcnt + " " + obj + ch + " "
+ pinf + " " + dinf);
}
} else if (where == GRB.CB_MIP) {
// General MIP callback
double nodecnt = getDoubleInfo(GRB.CB_MIP_NODCNT);
double objbst = getDoubleInfo(GRB.CB_MIP_OBJBST);
double objbnd = getDoubleInfo(GRB.CB_MIP_OBJBND);
int solcnt = getIntInfo(GRB.CB_MIP_SOLCNT);
if (nodecnt - lastnode >= 100) {
lastnode = nodecnt;
int actnodes = (int) getDoubleInfo(GRB.CB_MIP_NODLFT);
int itcnt = (int) getDoubleInfo(GRB.CB_MIP_ITRCNT);
int cutcnt = getIntInfo(GRB.CB_MIP_CUTCNT);
System.out.println(nodecnt + " " + actnodes + " "
+ itcnt + " " + objbst + " " + objbnd + " "
+ solcnt + " " + cutcnt);
}
if (Math.abs(objbst - objbnd) < 0.1 * (1.0 + Math.abs(objbst))) {
System.out.println("Stop early - 10% gap achieved");
abort();
}
if (nodecnt >= 10000 && solcnt > 0) {
249
System.out.println("Stop early - 10000 nodes explored");
abort();
}
} else if (where == GRB.CB_MIPSOL) {
// MIP solution callback
int nodecnt = (int) getDoubleInfo(GRB.CB_MIPSOL_NODCNT);
double obj = getDoubleInfo(GRB.CB_MIPSOL_OBJ);
int solcnt = getIntInfo(GRB.CB_MIPSOL_SOLCNT);
double[] x = getSolution(vars);
System.out.println("**** New solution at node " + nodecnt
+ ", obj " + obj + ", sol " + solcnt
+ ", x[0] = " + x[0] + " ****");
} else if (where == GRB.CB_MIPNODE) {
// MIP node callback
System.out.println("**** New node ****");
if (getIntInfo(GRB.CB_MIPNODE_STATUS) == GRB.OPTIMAL) {
double[] x = getNodeRel(vars);
setSolution(vars, x);
}
} else if (where == GRB.CB_BARRIER) {
// Barrier callback
int itcnt = getIntInfo(GRB.CB_BARRIER_ITRCNT);
double primobj = getDoubleInfo(GRB.CB_BARRIER_PRIMOBJ);
double dualobj = getDoubleInfo(GRB.CB_BARRIER_DUALOBJ);
double priminf = getDoubleInfo(GRB.CB_BARRIER_PRIMINF);
double dualinf = getDoubleInfo(GRB.CB_BARRIER_DUALINF);
double cmpl = getDoubleInfo(GRB.CB_BARRIER_COMPL);
System.out.println(itcnt + " " + primobj + " " + dualobj + " "
+ priminf + " " + dualinf + " " + cmpl);
} else if (where == GRB.CB_MESSAGE) {
// Message callback
String msg = getStringInfo(GRB.CB_MSG_STRING);
if (msg != null) logfile.write(msg);
}
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode());
System.out.println(e.getMessage());
e.printStackTrace();
} catch (Exception e) {
System.out.println("Error during callback");
e.printStackTrace();
}
}
250
if (args.length < 1) {
System.out.println("Usage: java Callback filename");
System.exit(1);
}
try {
// Create environment
GRBEnv env = new GRBEnv();
model.setCallback(cb);
System.out.println("");
System.out.println("Optimization complete");
if (model.get(GRB.IntAttr.SolCount) == 0) {
System.out.println("No solution found, optimization status = "
+ model.get(GRB.IntAttr.Status));
} else {
System.out.println("Solution found, objective = "
+ model.get(GRB.DoubleAttr.ObjVal));
251
}
}
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode());
System.out.println(e.getMessage());
e.printStackTrace();
} catch (Exception e) {
System.out.println("Error during optimization");
e.printStackTrace();
} finally {
// Close log file
if (logfile != null) {
try { logfile.close(); } catch (IOException e) {}
}
}
}
}
252
Dense.java
/* Copyright 2016, Gurobi Optimization, Inc. */
import gurobi.*;
try {
GRBModel model = new GRBModel(env);
// Populate A matrix
253
GRBLinExpr expr = new GRBLinExpr();
for (int j = 0; j < cols; j++)
if (A[i][j] != 0)
expr.addTerm(A[i][j], vars[j]);
model.addConstr(expr, sense[i], rhs[i], "");
}
// Populate objective
// Solve model
model.optimize();
// Extract solution
if (model.get(GRB.IntAttr.Status) == GRB.Status.OPTIMAL) {
success = true;
model.dispose();
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
e.printStackTrace();
}
return success;
}
254
public static void main(String[] args) {
try {
GRBEnv env = new GRBEnv();
if (success) {
System.out.println("x: " + sol[0] + ", y: " + sol[1] + ", z: " + sol[2]);
}
// Dispose of environment
env.dispose();
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
e.printStackTrace();
}
}
}
255
Diet.java
/* Copyright 2016, Gurobi Optimization, Inc. */
import gurobi.*;
// Set of foods
String Foods[] =
new String[] { "hamburger", "chicken", "hot dog", "fries",
"macaroni", "pizza", "salad", "milk", "ice cream" };
int nFoods = Foods.length;
double cost[] =
new double[] { 2.49, 2.89, 1.50, 1.89, 2.09, 1.99, 2.49, 0.89,
1.59 };
// Model
256
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env);
model.set(GRB.StringAttr.ModelName, "diet");
// Nutrition constraints
for (int i = 0; i < nCategories; ++i) {
GRBLinExpr ntot = new GRBLinExpr();
for (int j = 0; j < nFoods; ++j) {
ntot.addTerm(nutritionValues[j][i], buy[j]);
}
model.addConstr(ntot, GRB.EQUAL, nutrition[i], Categories[i]);
}
// Solve
model.optimize();
printSolution(model, buy, nutrition);
// Solve
model.optimize();
printSolution(model, buy, nutrition);
257
// Dispose of model and environment
model.dispose();
env.dispose();
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
}
}
258
Facility.java
/* Copyright 2016, Gurobi Optimization, Inc. */
import gurobi.*;
// Model
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env);
model.set(GRB.StringAttr.ModelName, "facility");
259
// Plant open decision variables: open[p] == 1 if plant p is open.
GRBVar[] open = new GRBVar[nPlants];
for (int p = 0; p < nPlants; ++p) {
open[p] = model.addVar(0, 1, FixedCosts[p], GRB.BINARY, "Open" + p);
}
// Production constraints
// Note that the right-hand limit sets the production to zero if
// the plant is closed
for (int p = 0; p < nPlants; ++p) {
GRBLinExpr ptot = new GRBLinExpr();
for (int w = 0; w < nWarehouses; ++w) {
ptot.addTerm(1.0, transport[w][p]);
}
GRBLinExpr limit = new GRBLinExpr();
limit.addTerm(Capacity[p], open[p]);
model.addConstr(ptot, GRB.LESS_EQUAL, limit, "Capacity" + p);
}
// Demand constraints
for (int w = 0; w < nWarehouses; ++w) {
GRBLinExpr dtot = new GRBLinExpr();
for (int p = 0; p < nPlants; ++p) {
dtot.addTerm(1.0, transport[w][p]);
}
model.addConstr(dtot, GRB.EQUAL, Demand[w], "Demand" + w);
}
// Guess at the starting point: close the plant with the highest
// fixed costs; open all others
260
// First, open all plants
for (int p = 0; p < nPlants; ++p) {
open[p].set(GRB.DoubleAttr.Start, 1.0);
}
// Solve
model.optimize();
// Print solution
System.out.println("\nTOTAL COSTS: " + model.get(GRB.DoubleAttr.ObjVal));
System.out.println("SOLUTION:");
for (int p = 0; p < nPlants; ++p) {
if (open[p].get(GRB.DoubleAttr.X) > 0.99) {
System.out.println("Plant " + p + " open:");
for (int w = 0; w < nWarehouses; ++w) {
if (transport[w][p].get(GRB.DoubleAttr.X) > 0.0001) {
System.out.println(" Transport " +
transport[w][p].get(GRB.DoubleAttr.X) +
" units to warehouse " + w);
}
}
} else {
System.out.println("Plant " + p + " closed!");
}
}
261
// Dispose of model and environment
model.dispose();
env.dispose();
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
}
}
}
262
Feasopt.java
/* Copyright 2016, Gurobi Optimization, Inc. */
import gurobi.*;
if (args.length < 1) {
System.out.println("Usage: java Feasopt filename");
System.exit(1);
}
try {
GRBEnv env = new GRBEnv();
GRBModel feasmodel = new GRBModel(env, args[0]);
// Clear objective
feasmodel.setObjective(new GRBLinExpr());
263
double[] coeffs = new double[] { 1 };
feasmodel.addVar(0.0, GRB.INFINITY, 1.0, GRB.CONTINUOUS, constrs,
coeffs, "ArtP_" +
c[i].get(GRB.StringAttr.ConstrName));
}
}
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
}
}
}
264
Fixanddive.java
/* Copyright 2016, Gurobi Optimization, Inc. */
import gurobi.*;
import java.util.*;
if (args.length < 1) {
System.out.println("Usage: java Fixanddive filename");
System.exit(1);
}
265
try {
// Read model
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env, args[0]);
model.set(GRB.IntParam.OutputFlag, 0);
model.optimize();
if (fractional.size() == 0) {
System.out.println("Found feasible solution - objective " +
model.get(GRB.DoubleAttr.ObjVal));
break;
}
266
// Fix the first quartile to the nearest integer value
model.optimize();
if (model.get(GRB.IntAttr.Status) != GRB.Status.OPTIMAL) {
System.out.println("Relaxation is infeasible");
break;
}
}
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
}
}
267
Genconstr.java
/* Copyright 2016, Gurobi Optimization, Inc. */
We do this by introducing two variables for each literal (itself and its
negated value), a variable for each clause, and then two
variables for indicating if we can satisfy four, and another to identify
the minimum of the clauses (so if it one, we can satisfy all clauses)
and put these two variables in the objective.
i.e. the Objective function will be
thus, the objective value will be two if and only if we can satisfy all
clauses; one if and only if at least four clauses can be satisfied, and
zero otherwise.
*/
import gurobi.*;
try {
// Example data:
// e.g. {0, n+1, 2} means clause (x0 or ~x1 or x2)
268
int Clauses[][] = new int[][]
{{ 0, n+1, 2}, { 1, n+2, 3},
{ 2, n+3, 0}, { 3, n+0, 1},
{n+0, n+1, 2}, {n+1, n+2, 3},
{n+2, n+3, 0}, {n+3, n+0, 1}};
// Create environment
GRBEnv env = new GRBEnv("Genconstr.log");
269
GRBVar[] clause = new GRBVar[3];
for (int j = 0; j < 3; j++) {
if (Clauses[i][j] >= n) clause[j] = NotLit[Clauses[i][j]-n];
else clause[j] = Lit[Clauses[i][j]];
}
model.addGenConstrOr(Cla[i], clause, "CNSTR_Clause" + String.valueOf(i));
}
// Save problem
model.write("Genconstr.mps");
model.write("Genconstr.lp");
// Optimize
model.optimize();
// Status checking
status = model.get(GRB.IntAttr.Status);
if (status == GRB.INF_OR_UNBD ||
status == GRB.INFEASIBLE ||
status == GRB.UNBOUNDED ) {
System.out.println("The model cannot be solved " +
"because it is infeasible or unbounded");
System.exit(1);
}
if (status != GRB.OPTIMAL) {
System.out.println("Optimization was stopped with status " + status);
System.exit(1);
}
// Print result
double objval = model.get(GRB.DoubleAttr.ObjVal);
270
System.out.println("Logical expression is satisfiable");
else if (objval > 0.9)
System.out.println("At least four clauses can be satisfied");
else
System.out.println("Not even three clauses can be satisfied");
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
}
}
}
271
Lp.java
/* Copyright 2016, Gurobi Optimization, Inc. */
import gurobi.*;
public class Lp {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: java Lp filename");
System.exit(1);
}
try {
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env, args[0]);
model.optimize();
if (optimstatus == GRB.Status.INF_OR_UNBD) {
model.set(GRB.IntParam.Presolve, 0);
model.optimize();
optimstatus = model.get(GRB.IntAttr.Status);
}
if (optimstatus == GRB.Status.OPTIMAL) {
double objval = model.get(GRB.DoubleAttr.ObjVal);
System.out.println("Optimal objective: " + objval);
} else if (optimstatus == GRB.Status.INFEASIBLE) {
System.out.println("Model is infeasible");
272
System.out.println("Optimization was stopped with status = "
+ optimstatus);
}
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
}
}
}
273
Lpmethod.java
/* Copyright 2016, Gurobi Optimization, Inc. */
import gurobi.*;
if (args.length < 1) {
System.out.println("Usage: java Lpmethod filename");
System.exit(1);
}
try {
// Read model
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env, args[0]);
274
// Dispose of model and environment
model.dispose();
env.dispose();
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". "
+ e.getMessage());
}
}
}
275
Lpmod.java
/* Copyright 2016, Gurobi Optimization, Inc. */
import gurobi.*;
if (args.length < 1) {
System.out.println("Usage: java Lpmod filename");
System.exit(1);
}
try {
// Read model and determine whether it is an LP
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env, args[0]);
if (model.get(GRB.IntAttr.IsMIP) != 0) {
System.out.println("The model is not a linear program");
System.exit(1);
}
model.optimize();
if (status == GRB.Status.INF_OR_UNBD ||
status == GRB.Status.INFEASIBLE ||
status == GRB.Status.UNBOUNDED ) {
System.out.println("The model cannot be solved because it is "
+ "infeasible or unbounded");
System.exit(1);
}
if (status != GRB.Status.OPTIMAL) {
System.out.println("Optimization was stopped with status " + status);
System.exit(0);
}
276
// Find the smallest variable value
double minVal = GRB.INFINITY;
GRBVar minVar = null;
for (GRBVar v : model.getVars()) {
double sol = v.get(GRB.DoubleAttr.X);
if ((sol > 0.0001) && (sol < minVal) &&
(v.get(GRB.DoubleAttr.LB) == 0.0)) {
minVal = sol;
minVar = v;
}
}
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
277
}
}
}
278
Mip1.java
/* Copyright 2016, Gurobi Optimization, Inc. */
/* This example formulates and solves the following simple MIP model:
maximize x + y + 2 z
subject to x + 2 y + 3 z <= 4
x + y >= 1
x, y, z binary
*/
import gurobi.*;
// Create variables
// Optimize model
279
model.optimize();
System.out.println(x.get(GRB.StringAttr.VarName)
+ " " +x.get(GRB.DoubleAttr.X));
System.out.println(y.get(GRB.StringAttr.VarName)
+ " " +y.get(GRB.DoubleAttr.X));
System.out.println(z.get(GRB.StringAttr.VarName)
+ " " +z.get(GRB.DoubleAttr.X));
model.dispose();
env.dispose();
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
}
}
}
280
Mip2.java
/* Copyright 2016, Gurobi Optimization, Inc. */
import gurobi.*;
if (args.length < 1) {
System.out.println("Usage: java Mip2 filename");
System.exit(1);
}
try {
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env, args[0]);
if (model.get(GRB.IntAttr.IsMIP) == 0) {
System.out.println("Model is not a MIP");
System.exit(1);
}
model.optimize();
281
return;
}
System.out.println();
for (int k = 0; k < model.get(GRB.IntAttr.SolCount); ++k) {
model.set(GRB.IntParam.SolutionNumber, k);
double objn = 0.0;
fixed.set(GRB.IntParam.Presolve, 0);
fixed.optimize();
if (foptimstatus != GRB.Status.OPTIMAL) {
System.err.println("Error: fixed model isn't optimal");
return;
}
282
double[] x = fixed.get(GRB.DoubleAttr.X, fvars);
String[] vnames = fixed.get(GRB.StringAttr.VarName, fvars);
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". "
+ e.getMessage());
}
}
}
283
Multiobj.java
/* Copyright 2016, Gurobi Optimization, Inc. */
import gurobi.*;
try {
// Sample data
int groundSetSize = 20;
int nSubsets = 4;
int Budget = 12;
double Set[][] = new double[][]
{ { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1 },
{ 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0 },
{ 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0 } };
int SetObjPriority[] = new int[] {3, 2, 2, 1};
double SetObjWeight[] = new double[] {1.0, 0.25, 1.25, 1.0};
int e, i, status, nSolutions;
// Create environment
GRBEnv env = new GRBEnv("Multiobj.log");
284
lhs.addTerm(1.0, Elem[e]);
}
model.addConstr(lhs, GRB.LESS_EQUAL, Budget, "Budget");
// Save problem
model.write("Multiobj.lp");
// Optimize
model.optimize();
// Status checking
status = model.get(GRB.IntAttr.Status);
if (status == GRB.INF_OR_UNBD ||
status == GRB.INFEASIBLE ||
status == GRB.UNBOUNDED ) {
System.out.println("The model cannot be solved " +
"because it is infeasible or unbounded");
System.exit(1);
}
if (status != GRB.OPTIMAL) {
System.out.println("Optimization was stopped with status " + status);
System.exit(1);
285
}
System.out.print("\tSet" + i);
for (e = 0; e < nSolutions; e++) {
System.out.print(" ");
model.set(GRB.IntParam.SolutionNumber, e);
double val = model.get(GRB.DoubleAttr.ObjNVal);
System.out.print(" " + val);
}
System.out.println();
}
model.dispose();
env.dispose();
} catch (GRBException e) {
System.out.println("Error code = " + e.getErrorCode());
System.out.println(e.getMessage());
}
}
}
286
Params.java
/* Copyright 2016, Gurobi Optimization, Inc. */
import gurobi.*;
if (args.length < 1) {
System.out.println("Usage: java Params filename");
System.exit(1);
}
try {
// Read model and verify that it is a MIP
GRBEnv env = new GRBEnv();
GRBModel m = new GRBModel(env, args[0]);
if (m.get(GRB.IntAttr.IsMIP) == 0) {
System.out.println("The model is not an integer program");
System.exit(1);
}
287
}
}
// Finally, delete the extra model, reset the time limit and
// continue to solve the best model to optimality
m.dispose();
bestModel.set(GRB.DoubleParam.TimeLimit, GRB.INFINITY);
bestModel.optimize();
System.out.println("Solved with MIPFocus: " +
bestModel.get(GRB.IntParam.MIPFocus));
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
}
}
}
288
Piecewise.java
/* Copyright 2016, Gurobi Optimization, Inc. */
import gurobi.*;
// Create environment
// Create variables
289
GRBLinExpr obj = new GRBLinExpr();
obj.addTerm(-1.0, y);
model.setObjective(obj);
// Optimize model as an LP
model.optimize();
System.out.println(x.get(GRB.StringAttr.VarName)
+ " " +x.get(GRB.DoubleAttr.X));
System.out.println(y.get(GRB.StringAttr.VarName)
+ " " +y.get(GRB.DoubleAttr.X));
System.out.println(z.get(GRB.StringAttr.VarName)
+ " " +z.get(GRB.DoubleAttr.X));
290
System.out.println("Obj: " + model.get(GRB.DoubleAttr.ObjVal));
System.out.println();
model.optimize();
System.out.println(x.get(GRB.StringAttr.VarName)
+ " " +x.get(GRB.DoubleAttr.X));
System.out.println(y.get(GRB.StringAttr.VarName)
+ " " +y.get(GRB.DoubleAttr.X));
System.out.println(z.get(GRB.StringAttr.VarName)
+ " " +z.get(GRB.DoubleAttr.X));
model.dispose();
env.dispose();
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
}
}
}
291
Poolsearch.java
/* Copyright 2016, Gurobi Optimization, Inc. */
import gurobi.*;
try{
// Sample data
int groundSetSize = 10;
double objCoef[] = new double[] {32, 32, 15, 15, 6, 6, 1, 1, 1, 1};
double knapsackCoef[] = new double[] {16, 16, 8, 8, 4, 4, 2, 2, 1, 1};
double Budget = 33;
int e, status, nSolutions;
// Create environment
GRBEnv env = new GRBEnv("Poolsearch.log");
292
model.set(GRB.IntAttr.ModelSense, GRB.MAXIMIZE);
// Limit the search space by setting a gap for the worst possible solution that will be ac
model.set(GRB.DoubleParam.PoolGap, 0.10);
// save problem
model.write("Poolsearch.lp");
// Optimize
model.optimize();
// Status checking
status = model.get(GRB.IntAttr.Status);
if (status == GRB.INF_OR_UNBD ||
status == GRB.INFEASIBLE ||
status == GRB.UNBOUNDED ) {
System.out.println("The model cannot be solved " +
"because it is infeasible or unbounded");
System.exit(1);
}
if (status != GRB.OPTIMAL) {
System.out.println("Optimization was stopped with status " + status);
System.exit(1);
}
293
// Print objective values of solutions
for (e = 0; e < nSolutions; e++) {
model.set(GRB.IntParam.SolutionNumber, e);
System.out.print(model.get(GRB.DoubleAttr.PoolObjVal) + " ");
if (e%15 == 14) System.out.println();
}
System.out.println();
model.dispose();
env.dispose();
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
}
}
294
Qcp.java
/* Copyright 2016, Gurobi Optimization, Inc. */
/* This example formulates and solves the following simple QCP model:
maximize x
subject to x + y + z = 1
x^2 + y^2 <= z^2 (second-order cone)
x^2 <= yz (rotated second-order cone)
*/
import gurobi.*;
// Create variables
// Set objective
295
// Add rotated cone: x^2 <= yz
// Optimize model
model.optimize();
System.out.println(x.get(GRB.StringAttr.VarName)
+ " " +x.get(GRB.DoubleAttr.X));
System.out.println(y.get(GRB.StringAttr.VarName)
+ " " +y.get(GRB.DoubleAttr.X));
System.out.println(z.get(GRB.StringAttr.VarName)
+ " " +z.get(GRB.DoubleAttr.X));
model.dispose();
env.dispose();
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
}
}
}
296
Qp.java
/* Copyright 2016, Gurobi Optimization, Inc. */
import gurobi.*;
public class Qp {
public static void main(String[] args) {
try {
GRBEnv env = new GRBEnv("qp.log");
GRBModel model = new GRBModel(env);
// Create variables
// Set objective
297
expr = new GRBLinExpr();
expr.addTerm(1.0, x); expr.addTerm(1.0, y);
model.addConstr(expr, GRB.GREATER_EQUAL, 1.0, "c1");
// Optimize model
model.optimize();
System.out.println(x.get(GRB.StringAttr.VarName)
+ " " +x.get(GRB.DoubleAttr.X));
System.out.println(y.get(GRB.StringAttr.VarName)
+ " " +y.get(GRB.DoubleAttr.X));
System.out.println(z.get(GRB.StringAttr.VarName)
+ " " +z.get(GRB.DoubleAttr.X));
x.set(GRB.CharAttr.VType, GRB.INTEGER);
y.set(GRB.CharAttr.VType, GRB.INTEGER);
z.set(GRB.CharAttr.VType, GRB.INTEGER);
// Optimize again
model.optimize();
System.out.println(x.get(GRB.StringAttr.VarName)
+ " " +x.get(GRB.DoubleAttr.X));
System.out.println(y.get(GRB.StringAttr.VarName)
+ " " +y.get(GRB.DoubleAttr.X));
System.out.println(z.get(GRB.StringAttr.VarName)
+ " " +z.get(GRB.DoubleAttr.X));
model.dispose();
env.dispose();
298
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
}
}
}
299
Sensitivity.java
/* Copyright 2016, Gurobi Optimization, Inc. */
import gurobi.*;
if (args.length < 1) {
System.out.println("Usage: java Sensitivity filename");
System.exit(1);
}
try {
// Create environment
if (model.get(GRB.IntAttr.IsMIP) == 0) {
System.out.println("Model is not a MIP");
System.exit(1);
}
model.optimize();
if (model.get(GRB.IntAttr.Status) != GRB.OPTIMAL) {
System.out.println("Optimization ended with status "
+ model.get(GRB.IntAttr.Status));
System.exit(1);
}
300
double origObjVal = model.get(GRB.DoubleAttr.ObjVal);
GRBVar[] vars = model.getVars();
double[] origX = model.get(GRB.DoubleAttr.X, vars);
model.set(GRB.IntParam.OutputFlag, 0);
model.optimize();
if (model.get(GRB.IntAttr.Status) == GRB.OPTIMAL) {
System.out.println("Objective sensitivity for variable "
+ v.get(GRB.StringAttr.VarName) + " is "
+ (model.get(GRB.DoubleAttr.ObjVal) - origObjVal));
} else {
System.out.println("Objective sensitivity for variable "
301
+ v.get(GRB.StringAttr.VarName) + " is infinite");
}
v.set(GRB.DoubleAttr.LB, 0.0);
v.set(GRB.DoubleAttr.UB, 1.0);
}
}
model.dispose();
env.dispose();
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode());
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
302
Sos.java
/* Copyright 2016, Gurobi Optimization, Inc. */
/* This example creates a very simple Special Ordered Set (SOS) model.
The model consists of 3 continuous variables, no linear constraints,
and a pair of SOS constraints of type 1. */
import gurobi.*;
// Create variables
// Optimize model
model.optimize();
303
// Dispose of model and environment
model.dispose();
env.dispose();
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
}
}
}
304
Sudoku.java
/* Copyright 2016, Gurobi Optimization, Inc. */
/*
Sudoku example.
The Sudoku board is a 9x9 grid, which is further divided into a 3x3 grid
of 3x3 grids. Each cell in the grid must take a value from 0 to 9.
No two grid cells in the same row, column, or 3x3 subgrid may take the
same value.
import gurobi.*;
import java.io.*;
if (args.length < 1) {
System.out.println("Usage: java Sudoku filename");
System.exit(1);
}
try {
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env);
305
+ "_" + String.valueOf(v);
vars[i][j][v] = model.addVar(0.0, 1.0, 0.0, GRB.BINARY, st);
}
}
}
// Add constraints
GRBLinExpr expr;
306
// Each value appears once per sub-grid
if (val >= 0)
vars[i][j][val].set(GRB.DoubleAttr.LB, 1.0);
}
// read the endline byte
fis.read();
}
// Optimize model
model.optimize();
307
System.out.println();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int v = 0; v < n; v++) {
if (x[i][j][v] > 0.5) {
System.out.print(v+1);
}
}
}
System.out.println();
}
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
} catch (IOException e) {
System.out.println("IO Error");
}
}
}
308
Tsp.java
/* Copyright 2016, Gurobi Optimization, Inc. */
import gurobi.*;
if (tour.length < n) {
// Add subtour elimination constraint
GRBLinExpr expr = new GRBLinExpr();
for (int i = 0; i < tour.length; i++)
for (int j = i+1; j < tour.length; j++)
expr.addTerm(1.0, vars[tour[i]][tour[j]]);
addLazy(expr, GRB.LESS_EQUAL, tour.length-1);
}
}
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
e.printStackTrace();
}
}
309
// Given an integer-feasible solution 'sol', return the smallest
// sub-tour (as a list of node indices).
start = 0;
bestlen = n+1;
bestind = -1;
node = 0;
while (start < n) {
for (node = 0; node < n; node++)
if (!seen[node])
break;
if (node == n)
break;
for (len = 0; len < n; len++) {
tour[start+len] = node;
seen[node] = true;
for (i = 0; i < n; i++) {
if (sol[node][i] > 0.5 && !seen[i]) {
node = i;
break;
}
}
if (i == n) {
len++;
if (len < bestlen) {
bestlen = len;
bestind = start;
}
start += len;
break;
}
}
}
310
int result[] = new int[bestlen];
for (i = 0; i < bestlen; i++)
result[i] = tour[bestind+i];
return result;
}
if (args.length < 1) {
System.out.println("Usage: java Tsp ncities");
System.exit(1);
}
int n = Integer.parseInt(args[0]);
try {
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env);
model.set(GRB.IntParam.LazyConstraints, 1);
// Create variables
311
GRBVar[][] vars = new GRBVar[n][n];
// Degree-2 constraints
model.setCallback(new Tsp(vars));
model.optimize();
if (model.get(GRB.IntAttr.SolCount) > 0) {
int[] tour = findsubtour(model.get(GRB.DoubleAttr.X, vars));
assert tour.length == n;
System.out.print("Tour: ");
for (int i = 0; i < tour.length; i++)
System.out.print(String.valueOf(tour[i]) + " ");
System.out.println();
}
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
e.printStackTrace();
312
}
}
}
313
Tune.java
/* Copyright 2016, Gurobi Optimization, Inc. */
import gurobi.*;
if (args.length < 1) {
System.out.println("Usage: java Tune filename");
System.exit(1);
}
try {
GRBEnv env = new GRBEnv();
if (resultcount > 0) {
314
model.dispose();
env.dispose();
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". "
+ e.getMessage());
}
}
}
315
Workforce1.java
/* Copyright 2016, Gurobi Optimization, Inc. */
import gurobi.*;
// Sample data
// Sets of days and workers
String Shifts[] =
new String[] { "Mon1", "Tue2", "Wed3", "Thu4", "Fri5", "Sat6",
"Sun7", "Mon8", "Tue9", "Wed10", "Thu11", "Fri12", "Sat13",
"Sun14" };
String Workers[] =
new String[] { "Amy", "Bob", "Cathy", "Dan", "Ed", "Fred", "Gu" };
// Model
316
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env);
model.set(GRB.StringAttr.ModelName, "assignment");
// Optimize
model.optimize();
int status = model.get(GRB.IntAttr.Status);
if (status == GRB.Status.UNBOUNDED) {
System.out.println("The model cannot be solved "
+ "because it is unbounded");
return;
}
if (status == GRB.Status.OPTIMAL) {
System.out.println("The optimal objective is " +
model.get(GRB.DoubleAttr.ObjVal));
return;
}
if (status != GRB.Status.INF_OR_UNBD &&
status != GRB.Status.INFEASIBLE ){
System.out.println("Optimization was stopped with status " + status);
317
return;
}
// Compute IIS
System.out.println("The model is infeasible; computing IIS");
model.computeIIS();
System.out.println("\nThe following constraint(s) "
+ "cannot be satisfied:");
for (GRBConstr c : model.getConstrs()) {
if (c.get(GRB.IntAttr.IISConstr) == 1) {
System.out.println(c.get(GRB.StringAttr.ConstrName));
}
}
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
}
}
}
318
Workforce2.java
/* Copyright 2016, Gurobi Optimization, Inc. */
import gurobi.*;
import java.util.*;
// Sample data
// Sets of days and workers
String Shifts[] =
new String[] { "Mon1", "Tue2", "Wed3", "Thu4", "Fri5", "Sat6",
"Sun7", "Mon8", "Tue9", "Wed10", "Thu11", "Fri12", "Sat13",
"Sun14" };
String Workers[] =
new String[] { "Amy", "Bob", "Cathy", "Dan", "Ed", "Fred", "Gu" };
// Model
319
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env);
model.set(GRB.StringAttr.ModelName, "assignment");
// Optimize
model.optimize();
int status = model.get(GRB.IntAttr.Status);
if (status == GRB.Status.UNBOUNDED) {
System.out.println("The model cannot be solved "
+ "because it is unbounded");
return;
}
if (status == GRB.Status.OPTIMAL) {
System.out.println("The optimal objective is " +
model.get(GRB.DoubleAttr.ObjVal));
return;
}
if (status != GRB.Status.INF_OR_UNBD &&
status != GRB.Status.INFEASIBLE ) {
System.out.println("Optimization was stopped with status " + status);
320
return;
}
// Do IIS
System.out.println("The model is infeasible; computing IIS");
LinkedList<String> removed = new LinkedList<String>();
System.out.println();
model.optimize();
status = model.get(GRB.IntAttr.Status);
if (status == GRB.Status.UNBOUNDED) {
System.out.println("The model cannot be solved "
+ "because it is unbounded");
return;
}
if (status == GRB.Status.OPTIMAL) {
break;
}
if (status != GRB.Status.INF_OR_UNBD &&
status != GRB.Status.INFEASIBLE ) {
System.out.println("Optimization was stopped with status " +
status);
return;
}
}
321
}
System.out.println();
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
}
}
}
322
Workforce3.java
/* Copyright 2016, Gurobi Optimization, Inc. */
import gurobi.*;
// Sample data
// Sets of days and workers
String Shifts[] =
new String[] { "Mon1", "Tue2", "Wed3", "Thu4", "Fri5", "Sat6",
"Sun7", "Mon8", "Tue9", "Wed10", "Thu11", "Fri12", "Sat13",
"Sun14" };
String Workers[] =
new String[] { "Amy", "Bob", "Cathy", "Dan", "Ed", "Fred", "Gu" };
// Model
323
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env);
model.set(GRB.StringAttr.ModelName, "assignment");
// Optimize
model.optimize();
int status = model.get(GRB.IntAttr.Status);
if (status == GRB.UNBOUNDED) {
System.out.println("The model cannot be solved "
+ "because it is unbounded");
return;
}
if (status == GRB.OPTIMAL) {
System.out.println("The optimal objective is " +
model.get(GRB.DoubleAttr.ObjVal));
return;
}
if (status != GRB.INF_OR_UNBD &&
status != GRB.INFEASIBLE ) {
System.out.println("Optimization was stopped with status " + status);
324
return;
}
System.out.println("\nSlack values:");
GRBVar[] vars = model.getVars();
for (int i = orignumvars; i < model.get(GRB.IntAttr.NumVars); ++i) {
GRBVar sv = vars[i];
if (sv.get(GRB.DoubleAttr.X) > 1e-6) {
System.out.println(sv.get(GRB.StringAttr.VarName) + " = " +
sv.get(GRB.DoubleAttr.X));
}
}
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
}
}
}
325
Workforce4.java
/* Copyright 2016, Gurobi Optimization, Inc. */
import gurobi.*;
// Sample data
// Sets of days and workers
String Shifts[] =
new String[] { "Mon1", "Tue2", "Wed3", "Thu4", "Fri5", "Sat6",
"Sun7", "Mon8", "Tue9", "Wed10", "Thu11", "Fri12", "Sat13",
"Sun14" };
String Workers[] =
new String[] { "Amy", "Bob", "Cathy", "Dan", "Ed", "Fred", "Gu" };
// Model
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env);
326
model.set(GRB.StringAttr.ModelName, "assignment");
// Slack variables for each shift constraint so that the shifts can
// be satisfied
GRBVar[] slacks = new GRBVar[nShifts];
for (int s = 0; s < nShifts; ++s) {
slacks[s] =
model.addVar(0, GRB.INFINITY, 0, GRB.CONTINUOUS,
Shifts[s] + "Slack");
}
GRBLinExpr lhs;
327
}
// Optimize
int status =
solveAndPrint(model, totSlack, nWorkers, Workers, totShifts);
if (status != GRB.Status.OPTIMAL ) {
return;
}
328
GRB.CONTINUOUS, Workers[w] + "Diff");
}
// Objective: minimize the sum of the square of the difference from the
// average number of shifts worked
GRBQuadExpr qobj = new GRBQuadExpr();
for (int w = 0; w < nWorkers; ++w) {
qobj.addTerm(1.0, diffShifts[w], diffShifts[w]);
}
model.setObjective(qobj);
// Optimize
status =
solveAndPrint(model, totSlack, nWorkers, Workers, totShifts);
if (status != GRB.Status.OPTIMAL ) {
return;
}
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
}
}
329
private static int solveAndPrint(GRBModel model, GRBVar totSlack,
int nWorkers, String[] Workers,
GRBVar[] totShifts) throws GRBException {
model.optimize();
int status = model.get(GRB.IntAttr.Status);
if (status == GRB.Status.INF_OR_UNBD ||
status == GRB.Status.INFEASIBLE ||
status == GRB.Status.UNBOUNDED ) {
System.out.println("The model cannot be solved "
+ "because it is infeasible or unbounded");
return status;
}
if (status != GRB.Status.OPTIMAL ) {
System.out.println("Optimization was stopped with status " + status);
return status;
}
// Print total slack and the number of shifts worked for each worker
System.out.println("\nTotal slack required: " +
totSlack.get(GRB.DoubleAttr.X));
for (int w = 0; w < nWorkers; ++w) {
System.out.println(Workers[w] + " worked " +
totShifts[w].get(GRB.DoubleAttr.X) + " shifts");
}
System.out.println("\n");
return status;
}
330
Workforce5.java
/* Copyright 2016, Gurobi Optimization, Inc. */
import gurobi.*;
try {
// Sample data
// Sets of days and workers
String Shifts[] =
new String[] { "Mon1", "Tue2", "Wed3", "Thu4", "Fri5", "Sat6",
"Sun7", "Mon8", "Tue9", "Wed10", "Thu11", "Fri12", "Sat13",
"Sun14" };
String Workers[] =
new String[] { "Amy", "Bob", "Cathy", "Dan", "Ed", "Fred", "Gu", "Tobi" };
331
// Create environment
GRBEnv env = new GRBEnv();
// Slack variables for each shift constraint so that the shifts can
// be satisfied
GRBVar[] slacks = new GRBVar[nShifts];
for (int s = 0; s < nShifts; ++s) {
slacks[s] =
model.addVar(0, GRB.INFINITY, 0, GRB.CONTINUOUS,
Shifts[s] + "Slack");
}
GRBLinExpr lhs;
332
for (int s = 0; s < nShifts; ++s) {
lhs = new GRBLinExpr();
lhs.addTerm(1.0, slacks[s]);
for (int w = 0; w < nWorkers; ++w) {
lhs.addTerm(1.0, x[w][s]);
}
model.addConstr(lhs, GRB.EQUAL, shiftRequirements[s], Shifts[s]);
}
333
model.set(GRB.DoubleAttr.ObjNWeight, 1.0);
model.set(GRB.StringAttr.ObjNName, "TotalSlack");
model.set(GRB.DoubleAttr.ObjNRelTol, 0.1);
model.set(GRB.DoubleAttr.ObjNAbsTol, 2.0);
totSlack.set(GRB.DoubleAttr.ObjN, 1.0);
// Save problem
model.write("Workforce5.lp");
// Optimize
int status = solveAndPrint(model, totSlack, nWorkers, Workers, totShifts);
if (status != GRB.OPTIMAL)
return;
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
}
}
model.optimize();
int status = model.get(GRB.IntAttr.Status);
if (status == GRB.Status.INF_OR_UNBD ||
status == GRB.Status.INFEASIBLE ||
status == GRB.Status.UNBOUNDED ) {
System.out.println("The model cannot be solved "
+ "because it is infeasible or unbounded");
return status;
334
}
if (status != GRB.Status.OPTIMAL ) {
System.out.println("Optimization was stopped with status " + status);
return status;
}
// Print total slack and the number of shifts worked for each worker
System.out.println("\nTotal slack required: " +
totSlack.get(GRB.DoubleAttr.X));
for (int w = 0; w < nWorkers; ++w) {
System.out.println(Workers[w] + " worked " +
totShifts[w].get(GRB.DoubleAttr.X) + " shifts");
}
System.out.println("\n");
return status;
}
335
3.4 C# Examples
This section includes source code for all of the Gurobi C# examples. The same source code can be
found in the examples/c# directory of the Gurobi distribution.
callback_cs.cs
/* Copyright 2016, Gurobi Optimization, Inc. */
/*
This example reads a model from a file, sets up a callback that
monitors optimization progress and implements a custom
termination strategy, and outputs progress information to the
screen and to a log file.
using System;
using System.IO;
using Gurobi;
336
{
try {
if (where == GRB.Callback.POLLING) {
// Ignore polling callback
} else if (where == GRB.Callback.PRESOLVE) {
// Presolve callback
int cdels = GetIntInfo(GRB.Callback.PRE_COLDEL);
int rdels = GetIntInfo(GRB.Callback.PRE_ROWDEL);
if (cdels != 0 || rdels != 0) {
Console.WriteLine(cdels + " columns and " + rdels
+ " rows are removed");
}
} else if (where == GRB.Callback.SIMPLEX) {
// Simplex callback
double itcnt = GetDoubleInfo(GRB.Callback.SPX_ITRCNT);
if (itcnt - lastiter >= 100) {
lastiter = itcnt;
double obj = GetDoubleInfo(GRB.Callback.SPX_OBJVAL);
int ispert = GetIntInfo(GRB.Callback.SPX_ISPERT);
double pinf = GetDoubleInfo(GRB.Callback.SPX_PRIMINF);
double dinf = GetDoubleInfo(GRB.Callback.SPX_DUALINF);
char ch;
if (ispert == 0) ch = ' ';
else if (ispert == 1) ch = 'S';
else ch = 'P';
Console.WriteLine(itcnt + " " + obj + ch + " "
+ pinf + " " + dinf);
}
} else if (where == GRB.Callback.MIP) {
// General MIP callback
double nodecnt = GetDoubleInfo(GRB.Callback.MIP_NODCNT);
double objbst = GetDoubleInfo(GRB.Callback.MIP_OBJBST);
double objbnd = GetDoubleInfo(GRB.Callback.MIP_OBJBND);
int solcnt = GetIntInfo(GRB.Callback.MIP_SOLCNT);
if (nodecnt - lastnode >= 100) {
lastnode = nodecnt;
int actnodes = (int) GetDoubleInfo(GRB.Callback.MIP_NODLFT);
int itcnt = (int) GetDoubleInfo(GRB.Callback.MIP_ITRCNT);
int cutcnt = GetIntInfo(GRB.Callback.MIP_CUTCNT);
Console.WriteLine(nodecnt + " " + actnodes + " "
+ itcnt + " " + objbst + " " + objbnd + " "
+ solcnt + " " + cutcnt);
}
if (Math.Abs(objbst - objbnd) < 0.1 * (1.0 + Math.Abs(objbst))) {
Console.WriteLine("Stop early - 10% gap achieved");
337
Abort();
}
if (nodecnt >= 10000 && solcnt > 0) {
Console.WriteLine("Stop early - 10000 nodes explored");
Abort();
}
} else if (where == GRB.Callback.MIPSOL) {
// MIP solution callback
int nodecnt = (int) GetDoubleInfo(GRB.Callback.MIPSOL_NODCNT);
double obj = GetDoubleInfo(GRB.Callback.MIPSOL_OBJ);
int solcnt = GetIntInfo(GRB.Callback.MIPSOL_SOLCNT);
double[] x = GetSolution(vars);
Console.WriteLine("**** New solution at node " + nodecnt
+ ", obj " + obj + ", sol " + solcnt
+ ", x[0] = " + x[0] + " ****");
} else if (where == GRB.Callback.MIPNODE) {
// MIP node callback
Console.WriteLine("**** New node ****");
if (GetIntInfo(GRB.Callback.MIPNODE_STATUS) == GRB.Status.OPTIMAL) {
double[] x = GetNodeRel(vars);
SetSolution(vars, x);
}
} else if (where == GRB.Callback.BARRIER) {
// Barrier callback
int itcnt = GetIntInfo(GRB.Callback.BARRIER_ITRCNT);
double primobj = GetDoubleInfo(GRB.Callback.BARRIER_PRIMOBJ);
double dualobj = GetDoubleInfo(GRB.Callback.BARRIER_DUALOBJ);
double priminf = GetDoubleInfo(GRB.Callback.BARRIER_PRIMINF);
double dualinf = GetDoubleInfo(GRB.Callback.BARRIER_DUALINF);
double cmpl = GetDoubleInfo(GRB.Callback.BARRIER_COMPL);
Console.WriteLine(itcnt + " " + primobj + " " + dualobj + " "
+ priminf + " " + dualinf + " " + cmpl);
} else if (where == GRB.Callback.MESSAGE) {
// Message callback
string msg = GetStringInfo(GRB.Callback.MSG_STRING);
if (msg != null) logfile.Write(msg);
}
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode);
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
} catch (Exception e) {
Console.WriteLine("Error during callback");
Console.WriteLine(e.StackTrace);
}
338
}
try {
// Create environment
GRBEnv env = new GRBEnv();
model.SetCallback(cb);
Console.WriteLine("");
Console.WriteLine("Optimization complete");
if (model.SolCount == 0) {
Console.WriteLine("No solution found, optimization status = "
+ model.Status);
} else {
Console.WriteLine("Solution found, objective = " + model.ObjVal);
339
for (int j = 0; j < vars.Length; j++) {
if (x[j] != 0.0) Console.WriteLine(vnames[j] + " " + x[j]);
}
}
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode);
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
} catch (Exception e) {
Console.WriteLine("Error during optimization");
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
} finally {
// Close log file
if (logfile != null) logfile.Close();
}
}
}
340
dense_cs.cs
/* Copyright 2016, Gurobi Optimization, Inc. */
using System;
using Gurobi;
class dense_cs {
try {
GRBModel model = new GRBModel(env);
// Populate A matrix
341
for (int i = 0; i < rows; i++) {
GRBLinExpr expr = new GRBLinExpr();
for (int j = 0; j < cols; j++)
if (A[i,j] != 0)
expr.AddTerm(A[i,j], vars[j]); // Note: '+=' would be much slower
model.AddConstr(expr, sense[i], rhs[i], "");
}
// Populate objective
// Solve model
model.Optimize();
// Extract solution
if (model.Status == GRB.Status.OPTIMAL) {
success = true;
model.Dispose();
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
}
return success;
}
342
try {
GRBEnv env = new GRBEnv();
if (success) {
Console.WriteLine("x: " + sol[0] + ", y: " + sol[1] + ", z: " + sol[2]);
}
// Dispose of environment
env.Dispose();
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
}
}
}
343
diet_cs.cs
/* Copyright 2016, Gurobi Optimization, Inc. */
using System;
using Gurobi;
class diet_cs
{
static void Main()
{
try {
// Set of foods
string[] Foods =
new string[] { "hamburger", "chicken", "hot dog", "fries",
"macaroni", "pizza", "salad", "milk", "ice cream" };
int nFoods = Foods.Length;
double[] cost =
new double[] { 2.49, 2.89, 1.50, 1.89, 2.09, 1.99, 2.49, 0.89,
1.59 };
344
// Model
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env);
model.ModelName = "diet";
// Nutrition constraints
for (int i = 0; i < nCategories; ++i) {
GRBLinExpr ntot = 0.0;
for (int j = 0; j < nFoods; ++j)
ntot.AddTerm(nutritionValues[j,i], buy[j]);
model.AddConstr(ntot == nutrition[i], Categories[i]);
}
// Solve
model.Optimize();
PrintSolution(model, buy, nutrition);
// Solve
model.Optimize();
PrintSolution(model, buy, nutrition);
345
// Dispose of model and env
model.Dispose();
env.Dispose();
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode + ". " +
e.Message);
}
}
346
facility_cs.cs
/* Copyright 2016, Gurobi Optimization, Inc. */
using System;
using Gurobi;
class facility_cs
{
static void Main()
{
try {
// Model
GRBEnv env = new GRBEnv();
347
GRBModel model = new GRBModel(env);
model.ModelName = "facility";
// Production constraints
// Note that the right-hand limit sets the production to zero if
// the plant is closed
for (int p = 0; p < nPlants; ++p) {
GRBLinExpr ptot = 0.0;
for (int w = 0; w < nWarehouses; ++w)
ptot.AddTerm(1.0, transport[w,p]);
model.AddConstr(ptot <= Capacity[p] * open[p], "Capacity" + p);
}
// Demand constraints
for (int w = 0; w < nWarehouses; ++w) {
GRBLinExpr dtot = 0.0;
for (int p = 0; p < nPlants; ++p)
dtot.AddTerm(1.0, transport[w,p]);
model.AddConstr(dtot == Demand[w], "Demand" + w);
}
// Guess at the starting point: close the plant with the highest
// fixed costs; open all others
348
// First, open all plants
for (int p = 0; p < nPlants; ++p) {
open[p].Start = 1.0;
}
// Solve
model.Optimize();
// Print solution
Console.WriteLine("\nTOTAL COSTS: " + model.ObjVal);
Console.WriteLine("SOLUTION:");
for (int p = 0; p < nPlants; ++p) {
if (open[p].X > 0.99) {
Console.WriteLine("Plant " + p + " open:");
for (int w = 0; w < nWarehouses; ++w) {
if (transport[w,p].X > 0.0001) {
Console.WriteLine(" Transport " +
transport[w,p].X + " units to warehouse " + w);
}
}
} else {
Console.WriteLine("Plant " + p + " closed!");
}
}
349
model.Dispose();
env.Dispose();
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
}
}
}
350
feasopt_cs.cs
/* Copyright 2016, Gurobi Optimization, Inc. */
using Gurobi;
using System;
class feasopt_cs
{
static void Main(string[] args)
{
if (args.Length < 1) {
Console.Out.WriteLine("Usage: feasopt_cs filename");
return;
}
try {
GRBEnv env = new GRBEnv();
GRBModel feasmodel = new GRBModel(env, args[0]);
// Clear objective
feasmodel.SetObjective(new GRBLinExpr());
351
GRBConstr[] constrs = new GRBConstr[] { c[i] };
double[] coeffs = new double[] { 1 };
feasmodel.AddVar(0.0, GRB.INFINITY, 1.0, GRB.CONTINUOUS, constrs,
coeffs, "ArtP_" +
c[i].ConstrName);
}
}
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
}
}
}
352
xanddive_cs.cs
/* Copyright 2016, Gurobi Optimization, Inc. */
using System;
using System.Collections.Generic;
using Gurobi;
class fixanddive_cs
{
// Comparison class used to sort variable list based on relaxation
// fractionality
353
Console.Out.WriteLine("Usage: fixanddive_cs filename");
return;
}
try {
// Read model
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env, args[0]);
model.Parameters.OutputFlag = 0;
model.Optimize();
if (fractional.Count == 0) {
Console.WriteLine("Found feasible solution - objective " +
model.ObjVal);
354
break;
}
fractional.Sort(new FractionalCompare());
int nfix = Math.Max(fractional.Count / 4, 1);
for (int i = 0; i < nfix; ++i) {
GRBVar v = fractional[i];
double fixval = Math.Floor(v.X + 0.5);
v.LB = fixval;
v.UB = fixval;
Console.WriteLine(" Fix " + v.VarName +
" to " + fixval + " ( rel " + v.X + " )");
}
model.Optimize();
if (model.Status != GRB.Status.OPTIMAL) {
Console.WriteLine("Relaxation is infeasible");
break;
}
}
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode + ". " +
e.Message);
}
}
}
355
genconstr_cs.cs
/* Copyright 2016, Gurobi Optimization, Inc. */
We do this by introducing two variables for each literal (itself and its
negated value), a variable for each clause, and then two
variables for indicating if we can satisfy four, and another to identify
the minimum of the clauses (so if it one, we can satisfy all clauses)
and put these two variables in the objective.
i.e. the Objective function will be
thus, the objective value will be two if and only if we can satisfy all
clauses; one if and only if at least four clauses can be satisfied, and
zero otherwise.
*/
using System;
using Gurobi;
class genconstr_cs {
try {
// Example data:
// e.g. {0, n+1, 2} means clause (x0 or ~x1 or x2)
356
int[,] Clauses = new int[,]
{{ 0, n+1, 2}, { 1, n+2, 3},
{ 2, n+3, 0}, { 3, n+0, 1},
{n+0, n+1, 2}, {n+1, n+2, 3},
{n+2, n+3, 0}, {n+3, n+0, 1}};
int i, status;
// Create environment
GRBEnv env = new GRBEnv("genconstr_cs.log");
357
GRBVar[] clause = new GRBVar[3];
for (int j = 0; j < 3; j++) {
if (Clauses[i,j] >= n) clause[j] = NotLit[Clauses[i,j]-n];
else clause[j] = Lit[Clauses[i,j]];
}
model.AddGenConstrOr(Cla[i], clause, string.Format("CNSTR_Clause{0}", i));
}
// Save problem
model.Write("genconstr_cs.mps");
model.Write("genconstr_cs.lp");
// Optimize
model.Optimize();
// Status checking
status = model.Status;
if (status == GRB.Status.INF_OR_UNBD ||
status == GRB.Status.INFEASIBLE ||
status == GRB.Status.UNBOUNDED ) {
Console.WriteLine("The model cannot be solved " +
"because it is infeasible or unbounded");
return;
}
if (status != GRB.Status.OPTIMAL) {
Console.WriteLine("Optimization was stopped with status {0}", status);
return;
}
// Print result
double objval = model.ObjVal;
358
Console.WriteLine("Logical expression is satisfiable");
else if (objval > 0.9)
Console.WriteLine("At least four clauses can be satisfied");
else
Console.WriteLine("Not even three clauses can be satisfied");
} catch (GRBException e) {
Console.WriteLine("Error code: {0}. {1}", e.ErrorCode, e.Message);
}
}
}
359
lp_cs.cs
/* Copyright 2016, Gurobi Optimization, Inc. */
using System;
using Gurobi;
class lp_cs
{
static void Main(string[] args)
{
if (args.Length < 1) {
Console.Out.WriteLine("Usage: lp_cs filename");
return;
}
try {
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env, args[0]);
model.Optimize();
if (optimstatus == GRB.Status.INF_OR_UNBD) {
model.Parameters.Presolve = 0;
model.Optimize();
optimstatus = model.Status;
}
if (optimstatus == GRB.Status.OPTIMAL) {
double objval = model.ObjVal;
Console.WriteLine("Optimal objective: " + objval);
} else if (optimstatus == GRB.Status.INFEASIBLE) {
Console.WriteLine("Model is infeasible");
model.ComputeIIS();
model.Write("model.ilp");
360
} else if (optimstatus == GRB.Status.UNBOUNDED) {
Console.WriteLine("Model is unbounded");
} else {
Console.WriteLine("Optimization was stopped with status = "
+ optimstatus);
}
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
}
}
}
361
lpmethod_cs.cs
/* Copyright 2016, Gurobi Optimization, Inc. */
using System;
using Gurobi;
class lpmethod_cs
{
static void Main(string[] args)
{
if (args.Length < 1) {
Console.Out.WriteLine("Usage: lpmethod_cs filename");
return;
}
try {
// Read model
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env, args[0]);
362
Console.WriteLine("Solved in " + bestTime
+ " seconds with Method: " + bestMethod);
}
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
}
}
}
363
lpmod_cs.cs
/* Copyright 2016, Gurobi Optimization, Inc. */
using System;
using Gurobi;
class lpmod_cs
{
static void Main(string[] args)
{
if (args.Length < 1) {
Console.Out.WriteLine("Usage: lpmod_cs filename");
return;
}
try {
// Read model and determine whether it is an LP
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env, args[0]);
if (model.IsMIP != 0) {
Console.WriteLine("The model is not a linear program");
Environment.Exit(1);
}
model.Optimize();
if ((status == GRB.Status.INF_OR_UNBD) ||
(status == GRB.Status.INFEASIBLE) ||
(status == GRB.Status.UNBOUNDED)) {
Console.WriteLine("The model cannot be solved because it is "
+ "infeasible or unbounded");
Environment.Exit(1);
}
if (status != GRB.Status.OPTIMAL) {
Console.WriteLine("Optimization was stopped with status " + status);
Environment.Exit(0);
364
}
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode + ". " +
365
e.Message);
}
}
}
366
mip1_cs.cs
/* Copyright 2016, Gurobi Optimization, Inc. */
/* This example formulates and solves the following simple MIP model:
maximize x + y + 2 z
subject to x + 2 y + 3 z <= 4
x + y >= 1
x, y, z binary
*/
using System;
using Gurobi;
class mip1_cs
{
static void Main()
{
try {
GRBEnv env = new GRBEnv("mip1.log");
GRBModel model = new GRBModel(env);
// Create variables
model.SetObjective(x + y + 2 * z, GRB.MAXIMIZE);
// Optimize model
model.Optimize();
367
Console.WriteLine(y.VarName + " " + y.X);
Console.WriteLine(z.VarName + " " + z.X);
model.Dispose();
env.Dispose();
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
}
}
}
368
mip2_cs.cs
/* Copyright 2016, Gurobi Optimization, Inc. */
using System;
using Gurobi;
class mip2_cs
{
static void Main(string[] args)
{
if (args.Length < 1) {
Console.Out.WriteLine("Usage: mip2_cs filename");
return;
}
try {
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env, args[0]);
if (model.IsMIP == 0) {
Console.WriteLine("Model is not a MIP");
return;
}
model.Optimize();
369
Console.WriteLine("Optimization was stopped with status = "
+ optimstatus);
return;
}
Console.WriteLine();
for (int k = 0; k < model.SolCount; ++k) {
model.Parameters.SolutionNumber = k;
double objn = 0.0;
fixedmodel.Parameters.Presolve = 0;
fixedmodel.Optimize();
if (foptimstatus != GRB.Status.OPTIMAL) {
Console.WriteLine("Error: fixed model isn't optimal");
return;
}
370
GRBVar[] fvars = fixedmodel.GetVars();
double[] x = fixedmodel.Get(GRB.DoubleAttr.X, fvars);
string[] vnames = fixedmodel.Get(GRB.StringAttr.VarName, fvars);
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
}
}
}
371
multiobj_cs.cs
/* Copyright 2016, Gurobi Optimization, Inc. */
using System;
using Gurobi;
class multiobj_cs {
static void Main() {
try {
// Sample data
int groundSetSize = 20;
int nSubsets = 4;
int Budget = 12;
double[,] Set = new double[,]
{ { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1 },
{ 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0 },
{ 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0 } };
int[] SetObjPriority = new int[] {3, 2, 2, 1};
double[] SetObjWeight = new double[] {1.0, 0.25, 1.25, 1.0};
int e, i, status, nSolutions;
// Create environment
GRBEnv env = new GRBEnv("multiobj_cs.log");
372
for (e = 0; e < groundSetSize; e++) {
lhs.AddTerm(1.0, Elem[e]);
}
model.AddConstr(lhs, GRB.LESS_EQUAL, Budget, "Budget");
// Save problem
model.Write("multiobj_cs.lp");
// Optimize
model.Optimize();
// Status checking
status = model.Status;
if (status == GRB.Status.INF_OR_UNBD ||
status == GRB.Status.INFEASIBLE ||
status == GRB.Status.UNBOUNDED ) {
Console.WriteLine("The model cannot be solved " +
"because it is infeasible or unbounded");
return;
}
if (status != GRB.Status.OPTIMAL) {
373
Console.WriteLine("Optimization was stopped with status {0}", status);
return;
}
Console.Write("\tSet" + i);
for (e = 0; e < nSolutions; e++) {
model.Parameters.SolutionNumber = e;
Console.Write("{0,8}", model.ObjNVal);
}
Console.WriteLine();
}
model.Dispose();
env.Dispose();
} catch (GRBException e) {
Console.WriteLine("Error code = {0}", e);
Console.WriteLine(e.Message);
}
}
}
374
params_cs.cs
/* Copyright 2016, Gurobi Optimization, Inc. */
using System;
using Gurobi;
class params_cs
{
static void Main(string[] args)
{
if (args.Length < 1) {
Console.Out.WriteLine("Usage: params_cs filename");
return;
}
try {
// Read model and verify that it is a MIP
GRBEnv env = new GRBEnv();
GRBModel m = new GRBModel(env, args[0]);
if (m.IsMIP == 0) {
Console.WriteLine("The model is not an integer program");
Environment.Exit(1);
}
375
}
}
// Finally, delete the extra model, reset the time limit and
// continue to solve the best model to optimality
m.Dispose();
bestModel.Parameters.TimeLimit = GRB.INFINITY;
bestModel.Optimize();
Console.WriteLine("Solved with MIPFocus: " +
bestModel.Parameters.MIPFocus);
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode + ". " +
e.Message);
}
}
}
376
piecewise_cs.cs
/* Copyright 2016, Gurobi Optimization, Inc. */
using System;
using Gurobi;
class piecewise_cs
{
// Create environment
// Create variables
377
// Set objective for y
model.SetObjective(-y);
// Optimize model as an LP
model.Optimize();
Console.WriteLine();
378
for (int i = 0; i < npts; i++) {
ptf[i] = -ptf[i];
}
model.Optimize();
model.Dispose();
env.Dispose();
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
}
}
}
379
poolsearch_cs.cs
/* Copyright 2016, Gurobi Optimization, Inc. */
using System;
using Gurobi;
class poolsearch_cs {
try{
// Sample data
int groundSetSize = 10;
double[] objCoef = new double[] {32, 32, 15, 15, 6, 6, 1, 1, 1, 1};
double[] knapsackCoef = new double[] {16, 16, 8, 8, 4, 4, 2, 2, 1, 1};
double Budget = 33;
int e, status, nSolutions;
// Create environment
GRBEnv env = new GRBEnv("poolsearch_cs.log");
380
// set global sense for ALL objectives
model.ModelSense = GRB.MAXIMIZE;
// Limit the search space by setting a gap for the worst possible solution that will be ac
model.Parameters.PoolGap = 0.10;
// save problem
model.Write("poolsearch_cs.lp");
// Optimize
model.Optimize();
// Status checking
status = model.Status;
if (status == GRB.Status.INF_OR_UNBD ||
status == GRB.Status.INFEASIBLE ||
status == GRB.Status.UNBOUNDED ) {
Console.WriteLine("The model cannot be solved " +
"because it is infeasible or unbounded");
return;
}
if (status != GRB.Status.OPTIMAL) {
Console.WriteLine("Optimization was stopped with status {0}", status);
return;
}
381
// Print objective values of solutions
for (e = 0; e < nSolutions; e++) {
model.Parameters.SolutionNumber = e;
Console.Write("{0} ", model.PoolObjVal);
if (e%15 == 14) Console.WriteLine();
}
Console.WriteLine();
model.Dispose();
env.Dispose();
} catch (GRBException e) {
Console.WriteLine("Error code: {0}. {1}", e.ErrorCode, e.Message);
}
}
382
qcp_cs.cs
/* Copyright 2016, Gurobi Optimization, Inc. */
/* This example formulates and solves the following simple QCP model:
maximize x
subject to x + y + z = 1
x^2 + y^2 <= z^2 (second-order cone)
x^2 <= yz (rotated second-order cone)
*/
using System;
using Gurobi;
class qcp_cs
{
static void Main()
{
try {
GRBEnv env = new GRBEnv("qcp.log");
GRBModel model = new GRBModel(env);
// Create variables
// Set objective
GRBLinExpr obj = x;
model.SetObjective(obj, GRB.MAXIMIZE);
383
// Optimize model
model.Optimize();
model.Dispose();
env.Dispose();
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
}
}
}
384
qp_cs.cs
/* Copyright 2016, Gurobi Optimization, Inc. */
using System;
using Gurobi;
class qp_cs
{
static void Main()
{
try {
GRBEnv env = new GRBEnv("qp.log");
GRBModel model = new GRBModel(env);
// Create variables
// Set objective
// Optimize model
model.Optimize();
385
Console.WriteLine(x.VarName + " " + x.X);
Console.WriteLine(y.VarName + " " + y.X);
Console.WriteLine(z.VarName + " " + z.X);
x.VType = GRB.INTEGER;
y.VType = GRB.INTEGER;
z.VType = GRB.INTEGER;
// Optimize model
model.Optimize();
model.Dispose();
env.Dispose();
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
}
}
}
386
sensitivity_cs.cs
/* Copyright 2016, Gurobi Optimization, Inc. */
using System;
using Gurobi;
class sensitivity_cs
{
static void Main(string[] args)
{
if (args.Length < 1) {
Console.Out.WriteLine("Usage: sensitivity_cs filename");
return;
}
try {
// Create environment
if (model.IsMIP == 0) {
Console.WriteLine("Model is not a MIP");
return;
}
model.Optimize();
if (model.Status != GRB.Status.OPTIMAL) {
Console.WriteLine("Optimization ended with status " + model.Status);
return;
}
387
double origObjVal = model.ObjVal;
GRBVar[] vars = model.GetVars();
double[] origX = model.Get(GRB.DoubleAttr.X, vars);
model.Parameters.OutputFlag = 0;
model.Optimize();
if (model.Status == GRB.Status.OPTIMAL) {
Console.WriteLine("Objective sensitivity for variable "
+ v.VarName + " is " + (model.ObjVal - origObjVal));
} else {
Console.WriteLine("Objective sensitivity for variable "
+ v.VarName + " is infinite");
388
}
v.LB = 0.0;
v.UB = 1.0;
}
}
model.Dispose();
env.Dispose();
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode);
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
}
}
}
389
sos_cs.cs
/* Copyright 2016, Gurobi Optimization, Inc. */
/* This example creates a very simple Special Ordered Set (SOS) model.
The model consists of 3 continuous variables, no linear constraints,
and a pair of SOS constraints of type 1. */
using System;
using Gurobi;
class sos_cs
{
static void Main()
{
try {
GRBEnv env = new GRBEnv();
// Create variables
// Optimize model
model.Optimize();
390
for (int i = 0; i < 3; i++)
Console.WriteLine(x[i].VarName + " " + x[i].X);
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
}
}
}
391
sudoku_cs.cs
/* Copyright 2016, Gurobi Optimization, Inc. */
/*
Sudoku example.
The Sudoku board is a 9x9 grid, which is further divided into a 3x3 grid
of 3x3 grids. Each cell in the grid must take a value from 0 to 9.
No two grid cells in the same row, column, or 3x3 subgrid may take the
same value.
using System;
using System.IO;
using Gurobi;
class sudoku_cs
{
static void Main(string[] args)
{
int n = 9;
int s = 3;
if (args.Length < 1) {
Console.Out.WriteLine("Usage: sudoku_cs filename");
return;
}
try {
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env);
392
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int v = 0; v < n; v++) {
string st = "G_" + i.ToString() + "_" + j.ToString()
+ "_" + v.ToString();
vars[i,j,v] = model.AddVar(0.0, 1.0, 0.0, GRB.BINARY, st);
}
}
}
// Add constraints
GRBLinExpr expr;
393
string st = "C_" + j.ToString() + "_" + v.ToString();
model.AddConstr(expr == 1.0, st);
}
}
StreamReader sr = File.OpenText(args[0]);
if (val >= 0)
vars[i,j,val].LB = 1.0;
}
}
// Optimize model
model.Optimize();
394
Console.WriteLine();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int v = 0; v < n; v++) {
if (x[i,j,v] > 0.5) {
Console.Write(v+1);
}
}
}
Console.WriteLine();
}
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
}
}
}
395
tsp_cs.cs
/* Copyright 2016, Gurobi Optimization, Inc. */
using System;
using Gurobi;
int n = vars.GetLength(0);
int[] tour = findsubtour(GetSolution(vars));
if (tour.Length < n) {
// Add subtour elimination constraint
GRBLinExpr expr = 0;
for (int i = 0; i < tour.Length; i++)
for (int j = i+1; j < tour.Length; j++)
expr.AddTerm(1.0, vars[tour[i], tour[j]]);
AddLazy(expr <= tour.Length-1);
}
}
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
Console.WriteLine(e.StackTrace);
}
396
}
start = 0;
bestlen = n+1;
bestind = -1;
node = 0;
while (start < n) {
for (node = 0; node < n; node++)
if (!seen[node])
break;
if (node == n)
break;
for (len = 0; len < n; len++) {
tour[start+len] = node;
seen[node] = true;
for (i = 0; i < n; i++) {
if (sol[node, i] > 0.5 && !seen[i]) {
node = i;
break;
}
}
if (i == n) {
len++;
if (len < bestlen) {
bestlen = len;
bestind = start;
}
start += len;
break;
}
}
397
}
return tour;
}
if (args.Length < 1) {
Console.WriteLine("Usage: tsp_cs nnodes");
return;
}
int n = Convert.ToInt32(args[0]);
try {
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env);
model.Parameters.LazyConstraints = 1;
398
// Create variables
// Degree-2 constraints
model.SetCallback(new tsp_cs(vars));
model.Optimize();
if (model.SolCount > 0) {
int[] tour = findsubtour(model.Get(GRB.DoubleAttr.X, vars));
Console.Write("Tour: ");
for (int i = 0; i < tour.Length; i++)
Console.Write(tour[i] + " ");
Console.WriteLine();
}
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
399
Console.WriteLine(e.StackTrace);
}
}
}
400
tune_cs.cs
/* Copyright 2016, Gurobi Optimization, Inc. */
using System;
using Gurobi;
class tune_cs
{
static void Main(string[] args)
{
if (args.Length < 1) {
Console.Out.WriteLine("Usage: tune_cs filename");
return;
}
try {
GRBEnv env = new GRBEnv();
if (resultcount > 0) {
401
// Dispose of model and environment
model.Dispose();
env.Dispose();
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
}
}
}
402
workforce1_cs.cs
/* Copyright 2016, Gurobi Optimization, Inc. */
using System;
using Gurobi;
class workforce1_cs
{
static void Main()
{
try {
// Sample data
// Sets of days and workers
string[] Shifts =
new string[] { "Mon1", "Tue2", "Wed3", "Thu4", "Fri5", "Sat6",
"Sun7", "Mon8", "Tue9", "Wed10", "Thu11", "Fri12", "Sat13",
"Sun14" };
string[] Workers =
new string[] { "Amy", "Bob", "Cathy", "Dan", "Ed", "Fred", "Gu" };
403
// Model
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env);
model.ModelName = "assignment";
// Optimize
model.Optimize();
int status = model.Status;
if (status == GRB.Status.UNBOUNDED) {
Console.WriteLine("The model cannot be solved "
+ "because it is unbounded");
return;
}
if (status == GRB.Status.OPTIMAL) {
Console.WriteLine("The optimal objective is " + model.ObjVal);
return;
}
if ((status != GRB.Status.INF_OR_UNBD) &&
(status != GRB.Status.INFEASIBLE)) {
404
Console.WriteLine("Optimization was stopped with status " + status);
return;
}
// Do IIS
Console.WriteLine("The model is infeasible; computing IIS");
model.ComputeIIS();
Console.WriteLine("\nThe following constraint(s) "
+ "cannot be satisfied:");
foreach (GRBConstr c in model.GetConstrs()) {
if (c.IISConstr == 1) {
Console.WriteLine(c.ConstrName);
}
}
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode + ". " +
e.Message);
}
}
}
405
workforce2_cs.cs
/* Copyright 2016, Gurobi Optimization, Inc. */
using System;
using System.Collections.Generic;
using Gurobi;
class workforce2_cs
{
static void Main()
{
try {
// Sample data
// Sets of days and workers
string[] Shifts =
new string[] { "Mon1", "Tue2", "Wed3", "Thu4", "Fri5", "Sat6",
"Sun7", "Mon8", "Tue9", "Wed10", "Thu11", "Fri12", "Sat13",
"Sun14" };
string[] Workers =
new string[] { "Amy", "Bob", "Cathy", "Dan", "Ed", "Fred", "Gu" };
406
// Model
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env);
model.ModelName = "assignment";
// Optimize
model.Optimize();
int status = model.Status;
if (status == GRB.Status.UNBOUNDED) {
Console.WriteLine("The model cannot be solved "
+ "because it is unbounded");
return;
}
if (status == GRB.Status.OPTIMAL) {
Console.WriteLine("The optimal objective is " + model.ObjVal);
return;
}
if ((status != GRB.Status.INF_OR_UNBD) &&
(status != GRB.Status.INFEASIBLE)) {
407
Console.WriteLine("Optimization was stopped with status " + status);
return;
}
// Do IIS
Console.WriteLine("The model is infeasible; computing IIS");
LinkedList<string> removed = new LinkedList<string>();
Console.WriteLine();
model.Optimize();
status = model.Status;
if (status == GRB.Status.UNBOUNDED) {
Console.WriteLine("The model cannot be solved "
+ "because it is unbounded");
return;
}
if (status == GRB.Status.OPTIMAL) {
break;
}
if ((status != GRB.Status.INF_OR_UNBD) &&
(status != GRB.Status.INFEASIBLE)) {
Console.WriteLine("Optimization was stopped with status " +
status);
return;
}
}
408
Console.Write(s + " ");
}
Console.WriteLine();
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode + ". " +
e.Message);
}
}
}
409
workforce3_cs.cs
/* Copyright 2016, Gurobi Optimization, Inc. */
using System;
using Gurobi;
class workforce3_cs
{
static void Main()
{
try {
// Sample data
// Sets of days and workers
string[] Shifts =
new string[] { "Mon1", "Tue2", "Wed3", "Thu4", "Fri5", "Sat6",
"Sun7", "Mon8", "Tue9", "Wed10", "Thu11", "Fri12", "Sat13",
"Sun14" };
string[] Workers =
new string[] { "Amy", "Bob", "Cathy", "Dan", "Ed", "Fred", "Gu" };
410
// Model
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env);
model.ModelName = "assignment";
// Optimize
model.Optimize();
int status = model.Status;
if (status == GRB.Status.UNBOUNDED) {
Console.WriteLine("The model cannot be solved "
+ "because it is unbounded");
return;
}
if (status == GRB.Status.OPTIMAL) {
Console.WriteLine("The optimal objective is " + model.ObjVal);
return;
}
if ((status != GRB.Status.INF_OR_UNBD) &&
411
(status != GRB.Status.INFEASIBLE)) {
Console.WriteLine("Optimization was stopped with status " + status);
return;
}
Console.WriteLine("\nSlack values:");
GRBVar[] vars = model.GetVars();
for (int i = orignumvars; i < model.NumVars; ++i) {
GRBVar sv = vars[i];
if (sv.X > 1e-6) {
Console.WriteLine(sv.VarName + " = " + sv.X);
}
}
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode + ". " +
e.Message);
}
}
}
412
workforce4_cs.cs
/* Copyright 2016, Gurobi Optimization, Inc. */
using System;
using Gurobi;
class workforce4_cs
{
static void Main()
{
try {
// Sample data
// Sets of days and workers
string[] Shifts =
new string[] { "Mon1", "Tue2", "Wed3", "Thu4", "Fri5", "Sat6",
"Sun7", "Mon8", "Tue9", "Wed10", "Thu11", "Fri12", "Sat13",
"Sun14" };
string[] Workers =
new string[] { "Amy", "Bob", "Cathy", "Dan", "Ed", "Fred", "Gu" };
// Model
413
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env);
model.ModelName = "assignment";
// Slack variables for each shift constraint so that the shifts can
// be satisfied
GRBVar[] slacks = new GRBVar[nShifts];
for (int s = 0; s < nShifts; ++s) {
slacks[s] =
model.AddVar(0, GRB.INFINITY, 0, GRB.CONTINUOUS,
Shifts[s] + "Slack");
}
GRBLinExpr lhs;
414
lhs.AddTerm(1.0, x[w, s]);
}
model.AddConstr(lhs == shiftRequirements[s], Shifts[s]);
}
// Optimize
int status = solveAndPrint(model, totSlack, nWorkers, Workers, totShifts);
if (status != GRB.Status.OPTIMAL) {
return;
}
415
// Constraint: compute the average number of shifts worked
lhs = new GRBLinExpr();
for (int w = 0; w < nWorkers; ++w) {
lhs.AddTerm(1.0, totShifts[w]);
}
model.AddConstr(lhs == nWorkers * avgShifts, "avgShifts");
// Objective: minimize the sum of the square of the difference from the
// average number of shifts worked
GRBQuadExpr qobj = new GRBQuadExpr();
for (int w = 0; w < nWorkers; ++w) {
qobj.AddTerm(1.0, diffShifts[w], diffShifts[w]);
}
model.SetObjective(qobj);
// Optimize
status = solveAndPrint(model, totSlack, nWorkers, Workers, totShifts);
if (status != GRB.Status.OPTIMAL) {
return;
}
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode + ". " +
e.Message);
}
}
416
(status == GRB.Status.INFEASIBLE) ||
(status == GRB.Status.UNBOUNDED)) {
Console.WriteLine("The model cannot be solved "
+ "because it is infeasible or unbounded");
return status;
}
if (status != GRB.Status.OPTIMAL) {
Console.WriteLine("Optimization was stopped with status " + status);
return status;
}
// Print total slack and the number of shifts worked for each worker
Console.WriteLine("\nTotal slack required: " + totSlack.X);
for (int w = 0; w < nWorkers; ++w) {
Console.WriteLine(Workers[w] + " worked " +
totShifts[w].X + " shifts");
}
Console.WriteLine("\n");
return status;
}
}
417
workforce5_cs.cs
/* Copyright 2016, Gurobi Optimization, Inc. */
using System;
using Gurobi;
class workforce5_cs
{
static void Main()
{
try {
// Sample data
// Sets of days and workers
string[] Shifts =
new string[] { "Mon1", "Tue2", "Wed3", "Thu4", "Fri5", "Sat6",
"Sun7", "Mon8", "Tue9", "Wed10", "Thu11", "Fri12", "Sat13",
"Sun14" };
string[] Workers =
new string[] { "Amy", "Bob", "Cathy", "Dan", "Ed", "Fred", "Gu", "Tobi" };
418
{ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } };
// Create environment
GRBEnv env = new GRBEnv();
// Slack variables for each shift constraint so that the shifts can
// be satisfied
GRBVar[] slacks = new GRBVar[nShifts];
for (int s = 0; s < nShifts; ++s) {
slacks[s] =
model.AddVar(0, GRB.INFINITY, 0, GRB.CONTINUOUS,
string.Format("{0}Slack", Shifts[s]));
}
GRBLinExpr lhs;
419
// to each shift s, plus the slack
for (int s = 0; s < nShifts; ++s) {
lhs = new GRBLinExpr();
lhs.AddTerm(1.0, slacks[s]);
for (int w = 0; w < nWorkers; ++w) {
lhs.AddTerm(1.0, x[w,s]);
}
model.AddConstr(lhs, GRB.EQUAL, shiftRequirements[s], Shifts[s]);
}
420
model.ObjNPriority = 2;
model.ObjNWeight = 1.0;
model.ObjNName = "TotalSlack";
model.ObjNRelTol = 0.1;
model.ObjNAbsTol = 2.0;
totSlack.ObjN = 1.0;
// Save problem
model.Write("workforce5_cs.lp");
// Optimize
int status = solveAndPrint(model, totSlack, nWorkers, Workers, totShifts);
if (status != GRB.Status.OPTIMAL)
return;
} catch (GRBException e) {
Console.WriteLine("Error code: {0}. {1}", e.ErrorCode, e.Message);
}
}
model.Optimize();
int status = model.Status;
if (status == GRB.Status.INF_OR_UNBD ||
status == GRB.Status.INFEASIBLE ||
status == GRB.Status.UNBOUNDED ) {
Console.WriteLine("The model cannot be solved "
+ "because it is infeasible or unbounded");
421
return status;
}
if (status != GRB.Status.OPTIMAL ) {
Console.WriteLine("Optimization was stopped with status {0}", status);
return status;
}
// Print total slack and the number of shifts worked for each worker
Console.WriteLine("\nTotal slack required: {0}", totSlack.X);
for (int w = 0; w < nWorkers; ++w) {
Console.WriteLine("{0} worked {1} shifts", Workers[w], totShifts[w].X);
}
Console.WriteLine("\n");
return status;
}
422
3.5 Visual Basic Examples
This section includes source code for all of the Gurobi Visual Basic examples. The same source
code can be found in the examples/vb directory of the Gurobi distribution.
callback_vb.vb
' Copyright 2016, Gurobi Optimization, Inc.
' This example reads a model from a file, sets up a callback that
' monitors optimization progress and implements a custom
' termination strategy, and outputs progress information to the
' screen and to a log file.
'
' The termination strategy implemented in this callback stops the
' optimization of a MIP model once at least one of the following two
' conditions have been satisfied:
' 1) The optimality gap is less than 10%
' 2) At least 10000 nodes have been explored, and an integer feasible
' solution has been found.
' Note that termination is normally handled through Gurobi parameters
' (MIPGap, NodeLimit, etc.). You should only use a callback for
' termination if the available parameters don't capture your desired
' termination criterion.
Imports System
Imports Gurobi
Class callback_vb
Inherits GRBCallback
Private vars As GRBVar()
Private lastnode As Double
Private lastiter As Double
423
ElseIf where = GRB.Callback.SIMPLEX Then
' Simplex callback
Dim itcnt As Double = GetDoubleInfo(GRB.Callback.SPX_ITRCNT)
If itcnt Mod - lastiter >= 100 Then
lastiter = itcnt
Dim obj As Double = GetDoubleInfo(GRB.Callback.SPX_OBJVAL)
Dim pinf As Double = GetDoubleInfo(GRB.Callback.SPX_PRIMINF)
Dim dinf As Double = GetDoubleInfo(GRB.Callback.SPX_DUALINF)
Dim ispert As Integer = GetIntInfo(GRB.Callback.SPX_ISPERT)
Dim ch As Char
If ispert = 0 Then
ch = " "c
ElseIf ispert = 1 Then
ch = "S"c
Else
ch = "P"c
End If
Console.WriteLine(itcnt & " " & obj & ch & " " & pinf & " " & dinf)
End If
ElseIf where = GRB.Callback.MIP Then
' General MIP callback
Dim nodecnt As Double = GetDoubleInfo(GRB.Callback.MIP_NODCNT)
If nodecnt - lastnode >= 100 Then
lastnode = nodecnt
Dim objbst As Double = GetDoubleInfo(GRB.Callback.MIP_OBJBST)
Dim objbnd As Double = GetDoubleInfo(GRB.Callback.MIP_OBJBND)
If Math.Abs(objbst - objbnd) < 0.1 * (1.0R + Math.Abs(objbst)) Then
Abort()
End If
Dim actnodes As Integer = CInt(GetDoubleInfo(GRB.Callback.MIP_NODLFT))
Dim itcnt As Integer = CInt(GetDoubleInfo(GRB.Callback.MIP_ITRCNT))
Dim solcnt As Integer = GetIntInfo(GRB.Callback.MIP_SOLCNT)
Dim cutcnt As Integer = GetIntInfo(GRB.Callback.MIP_CUTCNT)
Console.WriteLine(nodecnt & " " & actnodes & " " & itcnt & " " & _
objbst & " " & objbnd & " " & solcnt & " " & cutcnt)
End If
ElseIf where = GRB.Callback.MIPSOL Then
' MIP solution callback
Dim obj As Double = GetDoubleInfo(GRB.Callback.MIPSOL_OBJ)
Dim nodecnt As Integer = CInt(GetDoubleInfo(GRB.Callback.MIPSOL_NODCNT))
Dim x As Double() = GetSolution(vars)
Console.WriteLine("**** New solution at node " & nodecnt & ", obj " & _
obj & ", x(0) = " & x(0) & "****")
End If
Catch e As GRBException
424
Console.WriteLine("Error code: " & e.ErrorCode & ". " & e.Message)
Console.WriteLine(e.StackTrace)
End Try
End Sub
Try
Dim env As New GRBEnv()
Dim model As New GRBModel(env, args(0))
Catch e As GRBException
Console.WriteLine("Error code: " & e.ErrorCode & ". " & e.Message)
Console.WriteLine(e.StackTrace)
End Try
End Sub
End Class
425
dense_vb.vb
' Copyright 2016, Gurobi Optimization, Inc.
'
' This example formulates and solves the following simple QP model:
'
' minimize x + y + x^2 + x*y + y^2 + y*z + z^2
' subject to x + 2 y + 3 z >= 4
' x + y >= 1
'
' The example illustrates the use of dense matrices to store A and Q
' (and dense vectors for the other relevant data). We don't recommend
' that you use dense matrices, but this example may be helpful if you
' already have your data in this format.
Imports Gurobi
Class dense_vb
Try
Dim model As New GRBModel(env)
426
For j As Integer = 0 To cols - 1
If A(i, j) <> 0 Then
expr.AddTerm(A(i, j), vars(j))
End If
Next
model.AddConstr(expr, sense(i), rhs(i), "")
Next
model.Optimize()
model.Dispose()
Catch e As GRBException
Console.WriteLine("Error code: " & e.ErrorCode & ". " & e.Message)
427
End Try
Return success
End Function
If success Then
Console.WriteLine("x: " & sol(0) & ", y: " & sol(1) & ", z: " & sol(2))
End If
env.Dispose()
Catch e As GRBException
Console.WriteLine("Error code: " & e.ErrorCode & ". " & e.Message)
End Try
End Sub
End Class
428
diet_vb.vb
' Copyright 2016, Gurobi Optimization, Inc.
' Solve the classic diet model, showing how to add constraints
' to an existing model.
Imports System
Imports Gurobi
Class diet_vb
Shared Sub Main()
Try
429
{320, 15, 12, 820}, _
{320, 31, 12, 1230}, _
{100, 8, 2.5, 125}, _
{330, 8, 10, 180}}
' Model
Dim env As New GRBEnv()
Dim model As New GRBModel(env)
model.ModelName = "diet"
' Solve
model.Optimize()
PrintSolution(model, buy, nutrition)
430
' Solve
model.Optimize()
Catch e As GRBException
Console.WriteLine("Error code: " & e.ErrorCode & ". " & e.Message)
End Try
End Sub
431
facility_vb.vb
' Copyright 2016, Gurobi Optimization, Inc.
'
' Facility location: a company currently ships its product from 5 plants
' to 4 warehouses. It is considering closing some plants to reduce
' costs. What plant(s) should the company close, in order to minimize
' transportation and fixed costs?
'
' Based on an example from Frontline Systems:
' http://www.solver.com/disfacility.htm
' Used with permission.
Imports System
Imports Gurobi
Class facility_vb
Shared Sub Main()
Try
' Model
Dim env As New GRBEnv()
Dim model As New GRBModel(env)
model.ModelName = "facility"
432
' Plant open decision variables: open(p) == 1 if plant p is open.
Dim open As GRBVar() = New GRBVar(nPlants - 1) {}
For p As Integer = 0 To nPlants - 1
open(p) = model.AddVar(0, 1, FixedCosts(p), GRB.BINARY, "Open" & p)
Next
' The objective is to minimize the total fixed and variable costs
model.ModelSense = GRB.MINIMIZE
' Guess at the starting point: close the plant with the highest
' fixed costs; open all others
433
open(p).Start = 1.0
Next
' Now close the plant with the highest fixed cost
Console.WriteLine("Initial guess:")
Dim maxFixed As Double = -GRB.INFINITY
For p As Integer = 0 To nPlants - 1
If FixedCosts(p) > maxFixed Then
maxFixed = FixedCosts(p)
End If
Next
For p As Integer = 0 To nPlants - 1
If FixedCosts(p) = maxFixed Then
open(p).Start = 0.0
Console.WriteLine("Closing plant " & p & vbLf)
Exit For
End If
Next
' Solve
model.Optimize()
Next
434
model.Dispose()
env.Dispose()
Catch e As GRBException
Console.WriteLine("Error code: " & e.ErrorCode & ". " & e.Message)
End Try
End Sub
End Class
435
feasopt_vb.vb
' Copyright 2016, Gurobi Optimization, Inc.
'
' This example reads a MIP model from a file, adds artificial
' variables to each constraint, and then minimizes the sum of the
' artificial variables. A solution with objective zero corresponds
' to a feasible solution to the input model.
' We can also use FeasRelax feature to do it. In this example, we
' use minrelax=1, i.e. optimizing the returned model finds a solution
' that minimizes the original objective, but only from among those
' solutions that minimize the sum of the artificial variables.
Imports Gurobi
Imports System
Class feasopt_vb
Shared Sub Main(ByVal args As String())
Try
Dim env As New GRBEnv()
Dim feasmodel As New GRBModel(env, args(0))
436
Dim constrs As GRBConstr() = New GRBConstr() {c(i)}
Dim coeffs As Double() = New Double() {1}
feasmodel.AddVar(0.0, GRB.INFINITY, 1.0, GRB.CONTINUOUS, _
constrs, coeffs, _
"ArtP_" & c(i).ConstrName)
End If
Next
Catch e As GRBException
Console.WriteLine("Error code: " & e.ErrorCode & ". " & e.Message)
End Try
End Sub
End Class
437
xanddive_vb.vb
' Copyright 2016, Gurobi Optimization, Inc.
'
' Implement a simple MIP heuristic. Relax the model,
' sort variables based on fractionality, and fix the 25% of
' the fractional variables that are closest to integer variables.
' Repeat until either the relaxation is integer feasible or
' linearly infeasible.
Imports System
Imports System.Collections.Generic
Imports Gurobi
Class fixanddive_vb
' Comparison class used to sort variable list based on relaxation
' fractionality
438
Try
' Read model
Dim env As New GRBEnv()
Dim model As New GRBModel(env, args(0))
model.Parameters.OutputFlag = 0
model.Optimize()
If fractional.Count = 0 Then
Console.WriteLine("Found feasible solution - objective " & _
model.ObjVal)
Exit For
End If
439
' Fix the first quartile to the nearest integer value
fractional.Sort(New FractionalCompare())
Dim nfix As Integer = Math.Max(fractional.Count / 4, 1)
For i As Integer = 0 To nfix - 1
Dim v As GRBVar = fractional(i)
Dim fixval As Double = Math.Floor(v.X + 0.5)
v.LB = fixval
v.UB = fixval
Console.WriteLine(" Fix " & v.VarName & " to " & fixval & _
" ( rel " & v.X & " )")
Next
model.Optimize()
Catch e As GRBException
Console.WriteLine("Error code: " & e.ErrorCode & ". " + e.Message)
End Try
End Sub
End Class
440
genconstr_vb.vb
' In this example we show the use of general constraints for modeling
' some common expressions. We use as an example a SAT-problem where we
' want to see if it is possible to satisfy at least four (or all) clauses
' of the logical for
'
' L = (x0 or ~x1 or x2) and (x1 or ~x2 or x3) and
' (x2 or ~x3 or x0) and (x3 or ~x0 or x1) and
' (~x0 or ~x1 or x2) and (~x1 or ~x2 or x3) and
' (~x2 or ~x3 or x0) and (~x3 or ~x0 or x1)
'
' We do this by introducing two variables for each literal (itself and its
' negated value), a variable for each clause, and then two
' variables for indicating if we can satisfy four, and another to identify
' the minimum of the clauses (so if it one, we can satisfy all clauses)
' and put these two variables in the objective.
' i.e. the Objective function will be
'
' maximize Obj0 + Obj1
'
' Obj0 = MIN(Clause1, ... , Clause8)
' Obj1 = 1 -> Clause1 + ... + Clause8 >= 4
'
' thus, the objective value will be two if and only if we can satisfy all
' clauses; one if and only of at least four clauses can be satisfied, and
' zero otherwise.
'
Imports Gurobi
Class genconstr_vb
Try
441
' e.g. {0, n+1, 2} means clause (x0 or ~x1 or x2)
Dim Clauses As Integer(,) = New Integer(,) { _
{ 0, n + 1, 2}, { 1, n + 2, 3}, _
{ 2, n + 3, 0}, { 3, n + 0, 1}, _
{n + 0, n + 1, 2}, {n + 1, n + 2, 3}, _
{n + 2, n + 3, 0}, {n + 3, n + 0, 1}}
442
Dim clause As GRBVar() = New GRBVar(2) {}
For j As Integer = 0 To 2
If Clauses(i, j) >= n Then
clause(j) = NotLit(Clauses(i, j) - n)
Else
clause(j) = Lit(Clauses(i, j))
End If
Next
model.AddGenConstrOr(Cla(i), clause, String.Format("CNSTR_Clause{0}", i))
Next
' Optimize
model.Optimize()
443
' Print result
Dim objval As Double = model.ObjVal
Catch e As GRBException
Console.WriteLine("Error code: {0}. {1}", e.ErrorCode, e.Message)
End Try
End Sub
End Class
444
lp_vb.vb
' Copyright 2016, Gurobi Optimization, Inc.
'
' This example reads an LP model from a file and solves it.
' If the model is infeasible or unbounded, the example turns off
' presolve and solves the model again. If the model is infeasible,
' the example computes an Irreducible Inconsistent Subsystem (IIS),
' and writes it to a file.
Imports System
Imports Gurobi
Class lp_vb
Shared Sub Main(ByVal args As String())
Try
Dim env As GRBEnv = New GRBEnv("lp1.log")
Dim model As GRBModel = New GRBModel(env, args(0))
model.Optimize()
445
optimstatus)
End If
Catch e As GRBException
Console.WriteLine("Error code: " & e.ErrorCode & ". " & e.Message)
End Try
End Sub
End Class
446
lpmethod_vb.vb
' Copyright 2016, Gurobi Optimization, Inc.
'
' Solve a model with different values of the Method parameter;
' show which value gives the shortest solve time.
Imports System
Imports Gurobi
Class lpmethod_vb
Try
' Read model and verify that it is a MIP
Dim env As New GRBEnv()
Dim model As New GRBModel(env, args(0))
447
End If
Catch e As GRBException
Console.WriteLine("Error code: " & e.ErrorCode & ". " & e.Message)
End Try
End Sub
End Class
448
lpmod_vb.vb
' Copyright 2016, Gurobi Optimization, Inc.
'
' This example reads an LP model from a file and solves it.
' If the model can be solved, then it finds the smallest positive variable,
' sets its upper bound to zero, and resolves the model two ways:
' first with an advanced start, then without an advanced start
' (i.e. from scratch).
Imports System
Imports Gurobi
Class lpmod_vb
Shared Sub Main(ByVal args As String())
Try
' Read model and determine whether it is an LP
Dim env As New GRBEnv()
Dim model As New GRBModel(env, args(0))
If model.IsMIP <> 0 Then
Console.WriteLine("The model is not a linear program")
Environment.Exit(1)
End If
model.Optimize()
449
' Find the smallest variable value
Dim minVal As Double = GRB.INFINITY
Dim minVar As GRBVar = Nothing
For Each v As GRBVar In model.GetVars()
Dim sol As Double = v.X
If (sol > 0.0001) AndAlso _
(sol < minVal) AndAlso _
(v.LB = 0.0) Then
minVal = sol
minVar = v
End If
Next
Console.WriteLine("*** Cold start: " & coldCount & " iterations, " & _
coldTime & " seconds")
Catch e As GRBException
450
Console.WriteLine("Error code: " & e.ErrorCode & ". " & e.Message)
End Try
End Sub
End Class
451
mip1_vb.vb
' Copyright 2016, Gurobi Optimization, Inc.
'
' This example formulates and solves the following simple MIP model:
'
' maximize x + y + 2 z
' subject to x + 2 y + 3 z <= 4
' x + y >= 1
' x, y, z binary
Imports System
Imports Gurobi
Class mip1_vb
Shared Sub Main()
Try
Dim env As GRBEnv = New GRBEnv("mip1.log")
Dim model As GRBModel = New GRBModel(env)
model.SetObjective(x + y + 2 * z, GRB.MAXIMIZE)
model.Optimize()
452
Console.WriteLine("Obj: " & model.ObjVal)
model.Dispose()
env.Dispose()
Catch e As GRBException
Console.WriteLine("Error code: " & e.ErrorCode & ". " & e.Message)
End Try
End Sub
End Class
453
mip2_vb.vb
' Copyright 2016, Gurobi Optimization, Inc.
'
' This example reads a MIP model from a file, solves it and
' prints the objective values from all feasible solutions
' generated while solving the MIP. Then it creates the fixed
' model and solves that model.
Imports System
Imports Gurobi
Class mip2_vb
Shared Sub Main(ByVal args As String())
Try
Dim env As GRBEnv = New GRBEnv("lp1.log")
Dim model As GRBModel = New GRBModel(env, args(0))
If model.IsMIP = 0 Then
Console.WriteLine("Model is not a MIP")
Return
End If
model.Optimize()
454
Console.WriteLine("Model is infeasible")
model.ComputeIIS()
model.Write("model.ilp")
Return
ElseIf optimstatus = GRB.Status.UNBOUNDED Then
Console.WriteLine("Model is unbounded")
Return
Else
Console.WriteLine("Optimization was stopped with status = " & _
optimstatus)
Return
End If
Console.WriteLine()
For k As Integer = 0 To model.SolCount - 1
model.Parameters.SolutionNumber = k
Dim objn As Double = 0.0
Console.WriteLine("Solution " & k & " has objective: " & objn)
Next
Console.WriteLine()
model.Parameters.OutputFlag = 1
455
End If
Catch e As GRBException
Console.WriteLine("Error code: " & e.ErrorCode & ". " & e.Message)
End Try
End Sub
End Class
456
multiobj_vb.vb
' Want to cover three different sets but subject to a common budget of
' elements allowed to be used. However, the sets have different priorities to
' be covered; and we tackle this by using multi-objective optimization.
Imports Gurobi
Class multiobj_vb
Try
' Sample data
Dim groundSetSize As Integer = 20
Dim nSubsets As Integer = 4
Dim Budget As Integer = 12
457
' Constraint: limit total number of elements to be picked to be at most
' Budget
Dim lhs As New GRBLinExpr()
For e = 0 To groundSetSize - 1
lhs.AddTerm(1.0, Elem(e))
Next
model.AddConstr(lhs, GRB.LESS_EQUAL, Budget, "Budget")
' Optimize
model.Optimize()
458
"because it is infeasible or unbounded")
Return
End If
If status <> GRB.Status.OPTIMAL Then
Console.WriteLine("Optimization was stopped with status {0}", status)
Return
End If
model.Dispose()
env.Dispose()
Catch e As GRBException
Console.WriteLine("Error code = {0}", e)
Console.WriteLine(e.Message)
459
End Try
End Sub
End Class
460
params_vb.vb
' Copyright 2016, Gurobi Optimization, Inc. */
Imports System
Imports Gurobi
Class params_vb
Shared Sub Main(args As String())
If args.Length < 1 Then
Console.Out.WriteLine("Usage: params_vb filename")
Return
End If
Try
' Read model and verify that it is a MIP
Dim env As New GRBEnv()
Dim m As New GRBModel(env, args(0))
If m.IsMIP = 0 Then
Console.WriteLine("The model is not an integer program")
Environment.Exit(1)
End If
461
' Finally, delete the extra model, reset the time limit and
' continue to solve the best model to optimality
m.Dispose()
bestModel.Parameters.TimeLimit = GRB.INFINITY
bestModel.Optimize()
462
piecewise_vb.vb
' Copyright 2016, Gurobi Optimization, Inc.
Imports System
Imports Gurobi
Class piecewise_vb
Shared Function f(u As Double) As Double
Return Math.Exp(-u)
End Function
Shared Function g(u As Double) As Double
Return 2 * u * u - 4 * u
End Function
463
' Set objective for y
model.SetObjective(-y)
model.Optimize()
Console.WriteLine()
464
ptf(i) = -ptf(i)
Next
model.Optimize()
model.Dispose()
env.Dispose()
Catch e As GRBException
Console.WriteLine("Error code: " + e.ErrorCode & ". " + e.Message)
End Try
End Sub
End Class
465
poolsearch_vb.vb
Imports Gurobi
Class poolsearch_vb
Try
'Sample data
Dim groundSetSize As Integer = 10
For e = 0 To groundSetSize - 1
Elem(e).VarName = String.Format("El{0}", e)
Next
466
For e = 0 To groundSetSize - 1
lhs.AddTerm(knapsackCoef(e), Elem(e))
Next
model.AddConstr(lhs, GRB.LESS_EQUAL, Budget, "Budget")
' Optimize
model.Optimize()
467
Next
Console.WriteLine()
model.Dispose()
env.Dispose()
Catch e As GRBException
Console.WriteLine("Error code: {0}. {1}", e.ErrorCode, e.Message)
End Try
End Sub
End Class
468
qcp_vb.vb
' Copyright 2016, Gurobi Optimization, Inc.
' This example formulates and solves the following simple QCP model:
'
' maximize x
' subject to x + y + z = 1
' x^2 + y^2 <= z^2 (second-order cone)
' x^2 <= yz (rotated second-order cone)
Imports Gurobi
Class qcp_vb
Shared Sub Main()
Try
Dim env As New GRBEnv("qcp.log")
Dim model As New GRBModel(env)
model.Optimize()
469
Console.WriteLine(x.VarName & " " & x.X)
Console.WriteLine(y.VarName & " " & y.X)
Console.WriteLine(z.VarName & " " & z.X)
model.Dispose()
env.Dispose()
Catch e As GRBException
Console.WriteLine("Error code: " & e.ErrorCode & ". " & e.Message)
End Try
End Sub
End Class
470
qp_vb.vb
' Copyright 2016, Gurobi Optimization, Inc.
' This example formulates and solves the following simple QP model:
'
' minimize x^2 + x*y + y^2 + y*z + z^2 + 2 x
' subject to x + 2 y + 3 z >= 4
' x + y >= 1
'
' It solves it once as a continuous model, and once as an integer model.
'
Imports Gurobi
Class qp_vb
Shared Sub Main()
Try
Dim env As New GRBEnv("qp.log")
Dim model As New GRBModel(env)
model.Optimize()
471
Console.WriteLine(y.VarName & " " & y.X)
Console.WriteLine(z.VarName & " " & z.X)
x.VType = GRB.INTEGER
y.VType = GRB.INTEGER
z.VType = GRB.INTEGER
model.Optimize()
model.Dispose()
env.Dispose()
Catch e As GRBException
Console.WriteLine("Error code: " & e.ErrorCode & ". " & e.Message)
End Try
End Sub
End Class
472
sensitivity_vb.vb
' Copyright 2016, Gurobi Optimization, Inc.
Imports System
Imports Gurobi
Class sensitivity_vb
Shared Sub Main(args As String())
If args.Length < 1 Then
Console.Out.WriteLine("Usage: sensitivity_vb filename")
Return
End If
Try
If model.IsMIP = 0 Then
Console.WriteLine("Model is not a MIP")
Return
End If
model.Optimize()
473
Dim origX As Double() = model.Get(GRB.DoubleAttr.X, vars)
model.Parameters.OutputFlag = 0
If v.LB = 0 AndAlso _
v.UB = 1 AndAlso _
(vType = GRB.BINARY OrElse vType = GRB.INTEGER) Then
model.Optimize()
474
' Restore the original variable bounds
v.LB = 0.0
v.UB = 1.0
End If
Next
model.Dispose()
env.Dispose()
Catch e As GRBException
Console.WriteLine("Error code: " + e.ErrorCode)
Console.WriteLine(e.Message)
Console.WriteLine(e.StackTrace)
End Try
End Sub
End Class
475
sos_vb.vb
' Copyright 2016, Gurobi Optimization, Inc.
'
' This example creates a very simple Special Ordered Set (SOS) model.
' The model consists of 3 continuous variables, no linear constraints,
' and a pair of SOS constraints of type 1.
Imports System
Imports Gurobi
Class sos_vb
Shared Sub Main()
Try
Dim env As New GRBEnv()
Dim model As New GRBModel(env)
model.Optimize()
For i As Integer = 0 To 2
Console.WriteLine(x(i).VarName & " " & x(i).X)
Next
476
' Dispose of model and env
model.Dispose()
env.Dispose()
Catch e As GRBException
Console.WriteLine("Error code: " & e.ErrorCode & ". " & e.Message)
End Try
End Sub
End Class
477
sudoku_vb.vb
' Copyright 2016, Gurobi Optimization, Inc.
'
' Sudoku example.
'
' The Sudoku board is a 9x9 grid, which is further divided into a 3x3 grid
' of 3x3 grids. Each cell in the grid must take a value from 0 to 9.
' No two grid cells in the same row, column, or 3x3 subgrid may take the
' same value.
Imports System
Imports System.IO
Imports Gurobi
Class sudoku_vb
Shared Sub Main(ByVal args as String())
Dim n As Integer = 9
Dim s As Integer = 3
Try
Dim env As New GRBEnv()
Dim model As New GRBModel(env)
For i As Integer = 0 To n - 1
For j As Integer = 0 To n - 1
For v As Integer = 0 To n - 1
Dim st As String = "G_" & i & "_" & j & "_" & v
478
vars(i, j, v) = model.AddVar(0.0, 1.0, 0.0, GRB.BINARY, st)
Next
Next
Next
For i As Integer = 0 To n - 1
For j As Integer = 0 To n - 1
expr = 0
For v As Integer = 0 To n - 1
expr.AddTerm(1.0, vars(i, j, v))
Next
Dim st As String = "V_" & i & "_" & j
model.AddConstr(expr = 1, st)
Next
Next
For i As Integer = 0 To n - 1
For v As Integer = 0 To n - 1
expr = 0
For j As Integer = 0 To n - 1
expr.AddTerm(1.0, vars(i, j, v))
Next
Dim st As String = "R_" & i & "_" & v
model.AddConstr(expr = 1, st)
Next
Next
For j As Integer = 0 To n - 1
For v As Integer = 0 To n - 1
expr = 0
For i As Integer = 0 To n - 1
expr.AddTerm(1.0, vars(i, j, v))
Next
Dim st As String = "C_" & j & "_" & v
model.AddConstr(expr = 1, st)
479
Next
Next
For v As Integer = 0 To n - 1
For i0 As Integer = 0 To s - 1
For j0 As Integer = 0 To s - 1
expr = 0
For i1 As Integer = 0 To s - 1
For j1 As Integer = 0 To s - 1
expr.AddTerm(1.0, vars(i0 * s + i1, j0 * s + j1, v))
Next
Next
Dim st As String = "Sub_" & v & "_" & i0 & "_" & j0
model.AddConstr(expr = 1, st)
Next
Next
Next
For i As Integer = 0 To n - 1
Dim input As String = sr.ReadLine()
For j As Integer = 0 To n - 1
Dim val As Integer = Microsoft.VisualBasic.Asc(input(j)) - 48 - 1
' 0-based
If val >= 0 Then
vars(i, j, val).LB = 1.0
End If
Next
Next
model.Optimize()
Console.WriteLine()
480
For i As Integer = 0 To n - 1
For j As Integer = 0 To n - 1
For v As Integer = 0 To n - 1
If x(i, j, v) > 0.5 Then
Console.Write(v + 1)
End If
Next
Next
Console.WriteLine()
Next
Catch e As GRBException
Console.WriteLine("Error code: " & e.ErrorCode & ". " & e.Message)
End Try
End Sub
End Class
481
tsp_vb.vb
' Copyright 2016, Gurobi Optimization, Inc.
'
' Solve a traveling salesman problem on a randomly generated set of
' points using lazy constraints. The base MIP model only includes
' 'degree-2' constraints, requiring each node to have exactly
' two incident edges. Solutions to this model may contain subtours -
' tours that don't visit every node. The lazy constraint callback
' adds new constraints to cut them off.
Imports Gurobi
Class tsp_vb
Inherits GRBCallback
Private vars As GRBVar(,)
482
Console.WriteLine(e.StackTrace)
End Try
End Sub
For i = 0 To n - 1
seen(i) = False
Next
start = 0
bestlen = n+1
bestind = -1
node = 0
While start < n
For node = 0 To n - 1
if Not seen(node)
Exit For
End if
Next
if node = n
Exit While
End if
For len = 0 To n - 1
tour(start+len) = node
seen(node) = true
For i = 0 To n - 1
if sol(node, i) > 0.5 AndAlso Not seen(i)
node = i
Exit For
End If
Next
If i = n
len = len + 1
If len < bestlen
bestlen = len
bestind = start
483
End If
start = start + len
Exit For
End If
Next
End While
For i = 0 To bestlen - 1
tour(i) = tour(bestind+i)
Next
System.Array.Resize(tour, bestlen)
Return tour
End Function
Try
Dim env As New GRBEnv()
Dim model As New GRBModel(env)
model.Parameters.LazyConstraints = 1
484
For i As Integer = 0 To n - 1
x(i) = r.NextDouble()
y(i) = r.NextDouble()
Next
For i As Integer = 0 To n - 1
For j As Integer = 0 To i
vars(i, j) = model.AddVar(0.0, 1.0, distance(x, y, i, j), _
GRB.BINARY, "x" & i & "_" & j)
vars(j, i) = vars(i, j)
Next
Next
For i As Integer = 0 To n - 1
Dim expr As GRBLinExpr = 0
For j As Integer = 0 To n - 1
expr.AddTerm(1.0, vars(i, j))
Next
model.AddConstr(expr = 2.0, "deg2_" & i)
Next
For i As Integer = 0 To n - 1
vars(i, i).UB = 0.0
Next
model.SetCallback(New tsp_vb(vars))
model.Optimize()
Console.Write("Tour: ")
For i As Integer = 0 To tour.Length - 1
Console.Write(tour(i) & " ")
Next
Console.WriteLine()
End If
485
' Dispose of model and environment
model.Dispose()
env.Dispose()
Catch e As GRBException
Console.WriteLine("Error code: " & e.ErrorCode & ". " & e.Message)
Console.WriteLine(e.StackTrace)
End Try
End Sub
End Class
486
tune_vb.vb
' Copyright 2016, Gurobi Optimization, Inc. */
'
' This example reads a model from a file and tunes it.
' It then writes the best parameter settings to a file
' and solves the model using these parameters.
Imports System
Imports Gurobi
Class tune_vb
Shared Sub Main(ByVal args As String())
Try
Dim env As New GRBEnv()
487
' Dispose of model and environment
model.Dispose()
env.Dispose()
Catch e As GRBException
Console.WriteLine("Error code: " & e.ErrorCode & ". " & e.Message)
End Try
End Sub
End Class
488
workforce1_vb.vb
' Copyright 2016, Gurobi Optimization, Inc.
'
' Assign workers to shifts; each worker may or may not be available on a
' particular day. If the problem cannot be solved, use IIS to find a set of
' conflicting constraints. Note that there may be additional conflicts
' besides what is reported via IIS.
Imports System
Imports Gurobi
Class workforce1_vb
Shared Sub Main()
Try
489
' Model
Dim env As New GRBEnv()
Dim model As New GRBModel(env)
model.ModelName = "assignment"
' Optimize
model.Optimize()
Dim status As Integer = model.Status
If status = GRB.Status.UNBOUNDED Then
Console.WriteLine("The model cannot be solved " & _
"because it is unbounded")
Exit Sub
End If
If status = GRB.Status.OPTIMAL Then
Console.WriteLine("The optimal objective is " & model.ObjVal)
Exit Sub
End If
If (status <> GRB.Status.INF_OR_UNBD) AndAlso _
(status <> GRB.Status.INFEASIBLE) Then
490
Console.WriteLine("Optimization was stopped with status " & status)
Exit Sub
End If
' Do IIS
Console.WriteLine("The model is infeasible; computing IIS")
model.ComputeIIS()
Console.WriteLine(vbLf & "The following constraint(s) " & _
"cannot be satisfied:")
For Each c As GRBConstr In model.GetConstrs()
If c.IISConstr = 1 Then
Console.WriteLine(c.ConstrName)
End If
Next
Catch e As GRBException
Console.WriteLine("Error code: " & e.ErrorCode & ". " & e.Message)
End Try
End Sub
End Class
491
workforce2_vb.vb
' Copyright 2016, Gurobi Optimization, Inc.
'
' Assign workers to shifts; each worker may or may not be available on a
' particular day. If the problem cannot be solved, use IIS iteratively to
' find all conflicting constraints.
Imports System
Imports System.Collections.Generic
Imports Gurobi
Class workforce2_vb
Shared Sub Main()
Try
492
' Model
Dim env As New GRBEnv()
Dim model As New GRBModel(env)
model.ModelName = "assignment"
' Optimize
model.Optimize()
Dim status As Integer = model.Status
If status = GRB.Status.UNBOUNDED Then
Console.WriteLine("The model cannot be solved " & _
"because it is unbounded")
Exit Sub
End If
If status = GRB.Status.OPTIMAL Then
Console.WriteLine("The optimal objective is " & model.ObjVal)
Exit Sub
End If
If (status <> GRB.Status.INF_OR_UNBD) AndAlso _
(status <> GRB.Status.INFEASIBLE) Then
493
Console.WriteLine("Optimization was stopped with status " & status)
Exit Sub
End If
' Do IIS
Console.WriteLine("The model is infeasible; computing IIS")
Dim removed As LinkedList(Of String) = New LinkedList(Of String)()
Console.WriteLine()
model.Optimize()
status = model.Status
494
Console.Write(s & " ")
Next
Console.WriteLine()
Catch e As GRBException
Console.WriteLine("Error code: " & e.ErrorCode & ". " & e.Message)
End Try
End Sub
End Class
495
workforce3_vb.vb
' Copyright 2016, Gurobi Optimization, Inc.
' Assign workers to shifts; each worker may or may not be available on a
' particular day. If the problem cannot be solved, relax the model
' to determine which constraints cannot be satisfied, and how much
' they need to be relaxed.
Imports System
Imports Gurobi
Class workforce3_vb
Shared Sub Main()
Try
496
' Model
Dim env As New GRBEnv()
Dim model As New GRBModel(env)
model.ModelName = "assignment"
' Optimize
model.Optimize()
Dim status As Integer = model.Status
If status = GRB.Status.UNBOUNDED Then
Console.WriteLine("The model cannot be solved " & _
"because it is unbounded")
Return
End If
If status = GRB.Status.OPTIMAL Then
Console.WriteLine("The optimal objective is " & model.ObjVal)
Return
End If
If (status <> GRB.Status.INF_OR_UNBD) AndAlso _
(status <> GRB.Status.INFEASIBLE) Then
497
Console.WriteLine("Optimization was stopped with status " & _
status)
Return
End If
env.Dispose()
Catch e As GRBException
Console.WriteLine("Error code: " + e.ErrorCode & ". " + e.Message)
End Try
End Sub
End Class
498
workforce4_vb.vb
' Copyright 2016, Gurobi Optimization, Inc.
'
' Assign workers to shifts; each worker may or may not be available on a
' particular day. We use Pareto optimization to solve the model:
' first, we minimize the linear sum of the slacks. Then, we constrain
' the sum of the slacks, and we minimize a quadratic objective that
' tries to balance the workload among the workers.
Imports System
Imports Gurobi
Class workforce4_vb
Shared Sub Main()
Try
' Model
Dim env As New GRBEnv()
499
Dim model As New GRBModel(env)
model.ModelName = "assignment"
' Add a new slack variable to each shift constraint so that the
' shifts can be satisfied
Dim slacks As GRBVar() = New GRBVar(nShifts - 1) {}
For s As Integer = 0 To nShifts - 1
slacks(s) = _
model.AddVar(0, GRB.INFINITY, 0, GRB.CONTINUOUS, _
Shifts(s) & "Slack")
Next
500
lhs.AddTerm(1.0, x(w, s))
Next
model.AddConstr(lhs = shiftRequirements(s), Shifts(s))
Next
' Constraint: compute the total number of shifts for each worker
For w As Integer = 0 To nWorkers - 1
lhs = 0
For s As Integer = 0 To nShifts - 1
lhs.AddTerm(1.0, x(w, s))
Next
model.AddConstr(lhs = totShifts(w), "totShifts" & Workers(w))
Next
' Optimize
Dim status As Integer = _
solveAndPrint(model, totSlack, nWorkers, Workers, totShifts)
If status <> GRB.Status.OPTIMAL Then
Exit Sub
End If
' Constrain the slack by setting its upper and lower bounds
totSlack.UB = totSlack.X
totSlack.LB = totSlack.X
' Variables to count the difference from average for each worker;
' note that these variables can take negative values.
Dim diffShifts As GRBVar() = New GRBVar(nWorkers - 1) {}
For w As Integer = 0 To nWorkers - 1
diffShifts(w) = _
model.AddVar(-GRB.INFINITY, GRB.INFINITY, 0, _
501
GRB.CONTINUOUS, Workers(w) & "Diff")
Next
' Constraint: compute the difference from the average number of shifts
For w As Integer = 0 To nWorkers - 1
model.AddConstr(totShifts(w) - avgShifts = diffShifts(w), _
Workers(w) & "Diff")
Next
' Optimize
status = solveAndPrint(model, totSlack, nWorkers, Workers, totShifts)
If status <> GRB.Status.OPTIMAL Then
Exit Sub
End If
Catch e As GRBException
Console.WriteLine("Error code: " & e.ErrorCode & ". " & e.Message)
End Try
End Sub
502
Dim status As Integer = model.Status
solveAndPrint = status
If (status = GRB.Status.INF_OR_UNBD) OrElse _
(status = GRB.Status.INFEASIBLE) OrElse _
(status = GRB.Status.UNBOUNDED) Then
Console.WriteLine("The model cannot be solved because " & _
"it is infeasible or unbounded")
Exit Function
End If
If status <> GRB.Status.OPTIMAL Then
Console.WriteLine("Optimization was stopped with status " _
& status)
Exit Function
End If
' Print total slack and the number of shifts worked for each worker
Console.WriteLine(vbLf & "Total slack required: " & totSlack.X)
For w As Integer = 0 To nWorkers - 1
Console.WriteLine(Workers(w) & " worked " & _
totShifts(w).X & " shifts")
Next
Console.WriteLine(vbLf)
End Function
End Class
503
workforce5_vb.vb
Imports System
Imports Gurobi
Class workforce5_vb
Shared Sub Main()
Try
504
{1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}
' Slack variables for each shift constraint so that the shifts can
' be satisfied
Dim slacks As GRBVar() = New GRBVar(nShifts - 1) {}
For s As Integer = 0 To nShifts - 1
slacks(s) = model.AddVar(0, GRB.INFINITY, 0, GRB.CONTINUOUS, _
String.Format("{0}Slack", Shifts(s)))
Next
505
lhs.AddTerm(1.0, slacks(s))
For w As Integer = 0 To nWorkers - 1
lhs.AddTerm(1.0, x(w, s))
Next
model.AddConstr(lhs, GRB.EQUAL, shiftRequirements(s), Shifts(s))
Next
' Constraint: compute the total number of shifts for each worker
For w As Integer = 0 To nWorkers - 1
lhs = New GRBLinExpr()
lhs.AddTerm(-1.0, totShifts(w))
For s As Integer = 0 To nShifts - 1
lhs.AddTerm(1.0, x(w, s))
Next
model.AddConstr(lhs, GRB.EQUAL, 0, String.Format("totShifts{0}", Workers(w)))
Next
506
totSlack.ObjN = 1.0
' Optimize
Dim status As Integer = _
solveAndPrint(model, totSlack, nWorkers, Workers, totShifts)
env.Dispose()
Catch e As GRBException
Console.WriteLine("Error code: {0}. {1}", e.ErrorCode, e.Message)
End Try
End Sub
model.Optimize()
Dim status As Integer = model.Status
If status = GRB.Status.INF_OR_UNBD OrElse _
status = GRB.Status.INFEASIBLE OrElse _
status = GRB.Status.UNBOUNDED Then
Console.WriteLine("The model cannot be solved " & _
"because it is infeasible or unbounded")
Return status
End If
507
If status <> GRB.Status.OPTIMAL Then
Console.WriteLine("Optimization was stopped with status {0}", status)
Return status
End If
' Print total slack and the number of shifts worked for each worker
Console.WriteLine(vbLf & "Total slack required: {0}", totSlack.X)
For w As Integer = 0 To nWorkers - 1
Console.WriteLine("{0} worked {1} shifts", Workers(w), totShifts(w).X)
Next
Console.WriteLine(vbLf)
Return status
End Function
End Class
508
3.6 Python Examples
This section includes source code for all of the Gurobi Python examples. The same source code can
be found in the examples/python directory of the Gurobi distribution.
callback.py
#!/usr/bin/python
import sys
from gurobipy import *
509
model._lastiter = itcnt
obj = model.cbGet(GRB.Callback.SPX_OBJVAL)
ispert = model.cbGet(GRB.Callback.SPX_ISPERT)
pinf = model.cbGet(GRB.Callback.SPX_PRIMINF)
dinf = model.cbGet(GRB.Callback.SPX_DUALINF)
if ispert == 0:
ch = ' '
elif ispert == 1:
ch = 'S'
else:
ch = 'P'
print('%d %g%s %g %g' % (int(itcnt), obj, ch, pinf, dinf))
elif where == GRB.Callback.MIP:
# General MIP callback
nodecnt = model.cbGet(GRB.Callback.MIP_NODCNT)
objbst = model.cbGet(GRB.Callback.MIP_OBJBST)
objbnd = model.cbGet(GRB.Callback.MIP_OBJBND)
solcnt = model.cbGet(GRB.Callback.MIP_SOLCNT)
if nodecnt - model._lastnode >= 100:
model._lastnode = nodecnt
actnodes = model.cbGet(GRB.Callback.MIP_NODLFT)
itcnt = model.cbGet(GRB.Callback.MIP_ITRCNT)
cutcnt = model.cbGet(GRB.Callback.MIP_CUTCNT)
print('%d %d %d %g %g %d %d' % (nodecnt, actnodes, \
itcnt, objbst, objbnd, solcnt, cutcnt))
if abs(objbst - objbnd) < 0.1 * (1.0 + abs(objbst)):
print('Stop early - 10% gap achieved')
model.terminate()
if nodecnt >= 10000 and solcnt:
print('Stop early - 10000 nodes explored')
model.terminate()
elif where == GRB.Callback.MIPSOL:
# MIP solution callback
nodecnt = model.cbGet(GRB.Callback.MIPSOL_NODCNT)
obj = model.cbGet(GRB.Callback.MIPSOL_OBJ)
solcnt = model.cbGet(GRB.Callback.MIPSOL_SOLCNT)
x = model.cbGetSolution(model.getVars())
print('**** New solution at node %d, obj %g, sol %d, ' \
'x[0] = %g ****' % (nodecnt, obj, solcnt, x[0]))
elif where == GRB.Callback.MIPNODE:
# MIP node callback
print('**** New node ****')
if model.cbGet(GRB.Callback.MIPNODE_STATUS) == GRB.Status.OPTIMAL:
x = model.cbGetNodeRel(model.getVars())
model.cbSetSolution(model.getVars(), x)
510
elif where == GRB.Callback.BARRIER:
# Barrier callback
itcnt = model.cbGet(GRB.Callback.BARRIER_ITRCNT)
primobj = model.cbGet(GRB.Callback.BARRIER_PRIMOBJ)
dualobj = model.cbGet(GRB.Callback.BARRIER_DUALOBJ)
priminf = model.cbGet(GRB.Callback.BARRIER_PRIMINF)
dualinf = model.cbGet(GRB.Callback.BARRIER_DUALINF)
cmpl = model.cbGet(GRB.Callback.BARRIER_COMPL)
print('%d %g %g %g %g %g' % (itcnt, primobj, dualobj, \
priminf, dualinf, cmpl))
elif where == GRB.Callback.MESSAGE:
# Message callback
msg = model.cbGet(GRB.Callback.MSG_STRING)
model._logfile.write(msg)
if len(sys.argv) < 2:
print('Usage: callback.py filename')
quit()
setParam('OutputFlag', 0)
setParam('Heuristics', 0)
model = read(sys.argv[1])
model._lastiter = -GRB.INFINITY
model._lastnode = -GRB.INFINITY
model._logfile = logfile
model.optimize(mycallback)
print('')
print('Optimization complete')
511
if model.SolCount == 0:
print('No solution found, optimization status = %d' % model.Status)
else:
print('Solution found, objective = %g' % model.ObjVal)
for v in model.getVars():
if v.X != 0.0:
print('%s %g' % (v.VarName, v.X))
logfile.close()
512
custom.py
#
# Copyright 2016, Gurobi Optimization, Inc.
#
# Interactive shell customization example
#
# Define a set of customizations for the Gurobi shell.
# Type 'from custom import *' to import them into your shell.
#
def myread(name):
return read('/home/jones/models/' + name)
def myopt(model):
model.optimize(mycallback)
513
dense.py
#!/usr/bin/python
import sys
from gurobipy import *
model = Model()
# Populate A matrix
for i in range(rows):
expr = LinExpr()
for j in range(cols):
if A[i][j] != 0:
expr += A[i][j]*vars[j]
model.addConstr(expr, sense[i], rhs[i])
# Populate objective
obj = QuadExpr()
for i in range(cols):
for j in range(cols):
if Q[i][j] != 0:
obj += Q[i][j]*vars[i]*vars[j]
for j in range(cols):
if c[j] != 0:
514
obj += c[j]*vars[j]
model.setObjective(obj)
# Solve
model.optimize()
if model.status == GRB.Status.OPTIMAL:
x = model.getAttr('x', vars)
for i in range(cols):
solution[i] = x[i]
return True
else:
return False
c = [1, 1, 0]
Q = [[1, 1, 0], [0, 1, 1], [0, 0, 1]]
A = [[1, 2, 3], [1, 1, 0]]
sense = [GRB.GREATER_EQUAL, GRB.GREATER_EQUAL]
rhs = [4, 1]
lb = [0, 0, 0]
ub = [GRB.INFINITY, GRB.INFINITY, GRB.INFINITY]
vtype = [GRB.CONTINUOUS, GRB.CONTINUOUS, GRB.CONTINUOUS]
sol = [0]*3
# Optimize
if success:
print('x: %g, y: %g, z: %g' % (sol[0], sol[1], sol[2]))
515
diet.py
#!/usr/bin/python
516
('fries', 'calories'): 380,
('fries', 'protein'): 4,
('fries', 'fat'): 19,
('fries', 'sodium'): 270,
('macaroni', 'calories'): 320,
('macaroni', 'protein'): 12,
('macaroni', 'fat'): 10,
('macaroni', 'sodium'): 930,
('pizza', 'calories'): 320,
('pizza', 'protein'): 15,
('pizza', 'fat'): 12,
('pizza', 'sodium'): 820,
('salad', 'calories'): 320,
('salad', 'protein'): 31,
('salad', 'fat'): 12,
('salad', 'sodium'): 1230,
('milk', 'calories'): 100,
('milk', 'protein'): 8,
('milk', 'fat'): 2.5,
('milk', 'sodium'): 125,
('ice cream', 'calories'): 330,
('ice cream', 'protein'): 8,
('ice cream', 'fat'): 10,
('ice cream', 'sodium'): 180 }
# Model
m = Model("diet")
517
# buy[f] = m.addVar(name=f)
# Nutrition constraints
m.addConstrs(
(quicksum(nutritionValues[f,c] * buy[f] for f in foods) == nutrition[c]
for c in categories), "_")
def printSolution():
if m.status == GRB.Status.OPTIMAL:
print('\nCost: %g' % m.objVal)
print('\nBuy:')
buyx = m.getAttr('x', buy)
nutritionx = m.getAttr('x', nutrition)
for f in foods:
if buy[f].x > 0.0001:
print('%s %g' % (f, buyx[f]))
print('\nNutrition:')
for c in categories:
print('%s %g' % (c, nutritionx[c]))
else:
print('No solution')
# Solve
m.optimize()
printSolution()
# Solve
m.optimize()
printSolution()
518
diet2.py
#!/usr/bin/python
519
('fries', 'calories'): 380,
('fries', 'protein'): 4,
('fries', 'fat'): 19,
('fries', 'sodium'): 270,
('macaroni', 'calories'): 320,
('macaroni', 'protein'): 12,
('macaroni', 'fat'): 10,
('macaroni', 'sodium'): 930,
('pizza', 'calories'): 320,
('pizza', 'protein'): 15,
('pizza', 'fat'): 12,
('pizza', 'sodium'): 820,
('salad', 'calories'): 320,
('salad', 'protein'): 31,
('salad', 'fat'): 12,
('salad', 'sodium'): 1230,
('milk', 'calories'): 100,
('milk', 'protein'): 8,
('milk', 'fat'): 2.5,
('milk', 'sodium'): 125,
('ice cream', 'calories'): 330,
('ice cream', 'protein'): 8,
('ice cream', 'fat'): 10,
('ice cream', 'sodium'): 180 }
import dietmodel
dietmodel.solve(categories, minNutrition, maxNutrition,
foods, cost, nutritionValues)
520
diet3.py
#!/usr/bin/python
# Use a SQLite database with the diet model (dietmodel.py). The database
# (diet.db) can be recreated using the included SQL script (diet.sql).
#
# Note that this example reads an external data file (..\data\diet.db).
# As a result, it must be run from the Gurobi examples/python directory.
import os
import sqlite3
from gurobipy import *
con.close()
import dietmodel
dietmodel.solve(categories, minNutrition, maxNutrition,
foods, cost, nutritionValues)
521
diet4.py
#!/usr/bin/python
import os
import xlrd
sh = book.sheet_by_name("Categories")
categories = []
minNutrition = {}
maxNutrition = {}
i = 1
while True:
try:
c = sh.cell_value(i, 0)
categories.append(c)
minNutrition[c] = sh.cell_value(i,1)
maxNutrition[c] = sh.cell_value(i,2)
i = i + 1
except IndexError:
break
sh = book.sheet_by_name("Foods")
foods = []
cost = {}
i = 1
while True:
try:
f = sh.cell_value(i, 0)
foods.append(f)
cost[f] = sh.cell_value(i,1)
i = i + 1
522
except IndexError:
break
sh = book.sheet_by_name("Nutrition")
nutritionValues = {}
i = 1
for food in foods:
j = 1
for cat in categories:
nutritionValues[food,cat] = sh.cell_value(i,j)
j += 1
i += 1
import dietmodel
dietmodel.solve(categories, minNutrition, maxNutrition,
foods, cost, nutritionValues)
523
dietmodel.py
#!/usr/bin/python
# Nutrition constraints
m.addConstrs(
(quicksum(nutritionValues[f,c] * buy[f] for f in foods) == nutrition[c]
for c in categories), "_")
def printSolution():
if m.status == GRB.Status.OPTIMAL:
print('\nCost: %g' % m.objVal)
print('\nBuy:')
buyx = m.getAttr('x', buy)
nutritionx = m.getAttr('x', nutrition)
for f in foods:
if buy[f].x > 0.0001:
print('%s %g' % (f, buyx[f]))
print('\nNutrition:')
524
for c in categories:
print('%s %g' % (c, nutritionx[c]))
else:
print('No solution')
# Solve
m.optimize()
printSolution()
# Solve
m.optimize()
printSolution()
525
facility.py
#!/usr/bin/python
# Model
m = Model("facility")
526
name="open")
# Production constraints
# Note that the right-hand limit sets the production to zero if the plant
# is closed
m.addConstrs(
(transport.sum('*',p) <= capacity[p]*open[p] for p in plants),
"Capacity")
# Demand constraints
m.addConstrs(
(transport.sum(w) == demand[w] for w in warehouses),
"Demand")
# Guess at the starting point: close the plant with the highest fixed costs;
# open all others
527
# First, open all plants
for p in plants:
open[p].start = 1.0
# Solve
m.optimize()
# Print solution
print('\nTOTAL COSTS: %g' % m.objVal)
print('SOLUTION:')
for p in plants:
if open[p].x > 0.99:
print('Plant %s open' % p)
for w in warehouses:
if transport[w,p].x > 0:
print(' Transport %g units to warehouse %s' % \
(transport[w,p].x, w))
else:
print('Plant %s closed!' % p)
528
feasopt.py
#!/usr/bin/python
import sys
from gurobipy import *
if len(sys.argv) < 2:
print('Usage: feasopt.py filename')
quit()
feasmodel = gurobi.read(sys.argv[1])
feasmodel1 = feasmodel.copy()
# clear objective
feasmodel.setObjective(0.0)
for c in feasmodel.getConstrs():
sense = c.sense
if sense != '>':
feasmodel.addVar(obj=1.0, name="ArtN_" + c.constrName,
column=Column([-1], [c]))
if sense != '<':
feasmodel.addVar(obj=1.0, name="ArtP_" + c.constrName,
column=Column([1], [c]))
529
feasmodel.optimize()
feasmodel.write('feasopt.lp')
feasmodel1.write("feasopt1.lp");
feasmodel1.optimize();
530
xanddive.py
#!/usr/bin/python
import sys
from gurobipy import *
def sortkey(v1):
sol = v1.x
return abs(sol-int(sol+0.5))
if len(sys.argv) < 2:
print('Usage: fixanddive.py filename')
quit()
# Read model
model = gurobi.read(sys.argv[1])
model.Params.outputFlag = 0
model.optimize()
531
for iter in range(1000):
fractional = []
for v in intvars:
sol = v.x
if abs(sol - int(sol+0.5)) > 1e-5:
fractional += [v]
fractional.sort(key=sortkey)
if len(fractional) == 0:
print('Found feasible solution - objective %g' % model.objVal)
break
model.optimize()
if model.status != GRB.Status.OPTIMAL:
print('Relaxation is infeasible')
break
532
genconstr.py
#!/usr/bin/python
try:
NLITERALS = 4
n = NLITERALS
# Example data:
# e.g. {0, n+1, 2} means clause (x0 or ~x1 or x2)
Clauses = [[ 0, n+1, 2],
[ 1, n+2, 3],
[ 2, n+3, 0],
[ 3, n+0, 1],
[n+0, n+1, 2],
533
[n+1, n+2, 3],
[n+2, n+3, 0],
[n+3, n+0, 1]]
# Save problem
model.write("genconstr.mps")
model.write("genconstr.lp")
# Optimize
model.optimize()
# Status checking
534
status = model.getAttr(GRB.Attr.Status)
if status == GRB.INF_OR_UNBD or \
status == GRB.INFEASIBLE or \
status == GRB.UNBOUNDED:
print("The model cannot be solved because it is infeasible or unbounded")
sys.exit(1)
if status != GRB.OPTIMAL:
print("Optimization was stopped with status ", status)
sys.exit(1)
# Print result
objval = model.getAttr(GRB.Attr.ObjVal)
except GurobiError as e:
print('Error code ' + str(e.errno) + ": " + str(e))
except AttributeError:
print('Encountered an attribute error')
535
lp.py
#!/usr/bin/python
import sys
from gurobipy import *
if len(sys.argv) < 2:
print('Usage: lp.py filename')
quit()
model = read(sys.argv[1])
model.optimize()
if model.status == GRB.Status.INF_OR_UNBD:
# Turn presolve off to determine whether model is infeasible
# or unbounded
model.setParam(GRB.Param.Presolve, 0)
model.optimize()
if model.status == GRB.Status.OPTIMAL:
print('Optimal objective: %g' % model.objVal)
model.write('model.sol')
exit(0)
elif model.status != GRB.Status.INFEASIBLE:
print('Optimization was stopped with status %d' % model.status)
exit(0)
print('')
print('Model is infeasible')
model.computeIIS()
model.write("model.ilp")
print("IIS written to file 'model.ilp'")
536
lpmethod.py
#!/usr/bin/python
import sys
from gurobipy import *
if len(sys.argv) < 2:
print('Usage: lpmethod.py filename')
quit()
# Read model
m = read(sys.argv[1])
537
lpmod.py
#!/usr/bin/python
import sys
from gurobipy import *
if len(sys.argv) < 2:
print('Usage: lpmod.py filename')
quit()
model = read(sys.argv[1])
if model.isMIP == 1:
print('The model is not a linear program')
exit(1)
model.optimize()
status = model.status
if status != GRB.Status.OPTIMAL:
print('Optimization was stopped with status %d' % status)
exit(0)
538
print('\n*** Setting %s from %g to zero ***\n' % (minVar.varName, minVal))
minVar.ub = 0.0
coldCount = model.IterCount
coldTime = model.Runtime
print('')
print('*** Warm start: %g iterations, %g seconds' % (warmCount, warmTime))
print('*** Cold start: %g iterations, %g seconds' % (coldCount, coldTime))
539
mip1.py
#!/usr/bin/python
# This example formulates and solves the following simple MIP model:
# maximize
# x + y + 2 z
# subject to
# x + 2 y + 3 z <= 4
# x + y >= 1
# x, y, z binary
try:
# Create variables
x = m.addVar(vtype=GRB.BINARY, name="x")
y = m.addVar(vtype=GRB.BINARY, name="y")
z = m.addVar(vtype=GRB.BINARY, name="z")
# Set objective
m.setObjective(x + y + 2 * z, GRB.MAXIMIZE)
m.optimize()
for v in m.getVars():
print('%s %g' % (v.varName, v.x))
except GurobiError as e:
print('Error code ' + str(e.errno) + ": " + str(e))
540
except AttributeError:
print('Encountered an attribute error')
541
mip2.py
#!/usr/bin/python
# This example reads a MIP model from a file, solves it and prints
# the objective values from all feasible solutions generated while
# solving the MIP. Then it creates the associated fixed model and
# solves that model.
import sys
from gurobipy import *
if len(sys.argv) < 2:
print('Usage: mip2.py filename')
quit()
model = read(sys.argv[1])
if model.isMIP == 0:
print('Model is not a MIP')
exit(0)
model.optimize()
if model.status == GRB.Status.OPTIMAL:
print('Optimal objective: %g' % model.objVal)
elif model.status == GRB.Status.INF_OR_UNBD:
print('Model is infeasible or unbounded')
exit(0)
elif model.status == GRB.Status.INFEASIBLE:
print('Model is infeasible')
exit(0)
elif model.status == GRB.Status.UNBOUNDED:
print('Model is unbounded')
exit(0)
else:
print('Optimization ended with status %d' % model.status)
exit(0)
542
for k in range(model.solCount):
model.Params.solutionNumber = k
objn = 0
for v in model.getVars():
objn += v.obj * v.xn
print('Solution %d has objective %g' % (k, objn))
print('')
model.Params.outputFlag = 1
fixed = model.fixed()
fixed.Params.presolve = 0
fixed.optimize()
if fixed.status != GRB.Status.OPTIMAL:
print("Error: fixed model isn't optimal")
exit(1)
543
multiobj.py
#!/usr/bin/python
try:
# Sample data
Groundset = range(20)
Subsets = range(4)
Budget = 12;
Set = [ [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1 ],
[ 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0 ],
[ 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0 ] ]
SetObjPriority = [ 3, 2, 2, 1]
SetObjWeight = [1.0, 0.25, 1.25, 1.0]
544
for i in Subsets:
model.setParam(GRB.Param.ObjNumber, i)
model.ObjNPriority = SetObjPriority[i]
model.ObjNWeight = SetObjWeight[i]
# Save problem
model.write('multiobj.lp')
# Optimize
model.optimize()
model.setParam(GRB.Param.OutputFlag, 0)
# Status checking
status = model.Status
if status == GRB.Status.INF_OR_UNBD or \
status == GRB.Status.INFEASIBLE or \
status == GRB.Status.UNBOUNDED:
print('The model cannot be solved because it is infeasible or unbounded')
sys.exit(1)
if status != GRB.Status.OPTIMAL:
print('Optimization was stopped with status ' + str(status))
sys.exit(1)
545
for i in Subsets:
model.setParam(GRB.Param.ObjNumber, i)
print('\tSet%d' % i, end='')
for e in range(nSolutions):
model.setParam(GRB.Param.SolutionNumber, e)
print(' %6g' % model.ObjNVal, end='')
print('')
except GurobiError as e:
print('Error code ' + str(e.errno) + ": " + str(e))
except AttributeError as e:
print('Encountered an attribute error: ' + str(e))
546
netow.py
#!/usr/bin/python
# Model data
cost = {
('Pencils', 'Detroit', 'Boston'): 10,
('Pencils', 'Detroit', 'New York'): 20,
('Pencils', 'Detroit', 'Seattle'): 60,
('Pencils', 'Denver', 'Boston'): 40,
('Pencils', 'Denver', 'New York'): 40,
('Pencils', 'Denver', 'Seattle'): 30,
('Pens', 'Detroit', 'Boston'): 20,
('Pens', 'Detroit', 'New York'): 20,
('Pens', 'Detroit', 'Seattle'): 80,
('Pens', 'Denver', 'Boston'): 60,
('Pens', 'Denver', 'New York'): 70,
('Pens', 'Denver', 'Seattle'): 30 }
inflow = {
('Pencils', 'Detroit'): 50,
547
('Pencils', 'Denver'): 60,
('Pencils', 'Boston'): -50,
('Pencils', 'New York'): -50,
('Pencils', 'Seattle'): -10,
('Pens', 'Detroit'): 60,
('Pens', 'Denver'): 40,
('Pens', 'Boston'): -40,
('Pens', 'New York'): -30,
('Pens', 'Seattle'): -30 }
# Create variables
flow = m.addVars(commodities, arcs, obj=cost, name="flow")
# Print solution
if m.status == GRB.Status.OPTIMAL:
solution = m.getAttr('x', flow)
for h in commodities:
print('\nOptimal flows for %s:' % h)
for i,j in arcs:
548
if solution[h,i,j] > 0:
print('%s -> %s: %g' % (i, j, solution[h,i,j]))
549
params.py
#!/usr/bin/python
import sys
from gurobipy import *
if len(sys.argv) < 2:
print('Usage: params.py filename')
quit()
# Finally, delete the extra model, reset the time limit and
# continue to solve the best model to optimality
del m
bestModel.Params.timeLimit = "default"
bestModel.optimize()
print('Solved with MIPFocus: %d' % bestModel.Params.MIPFocus)
550
piecewise.py
#!/usr/bin/python
def f(u):
return exp(-u)
def g(u):
return 2 * u * u - 4 * u
try:
m = Model()
# Create variables
lb = 0.0
ub = 1.0
m.setObjective(-y)
551
# Add piecewise-linear objective functions for x and z
npts = 101
ptu = []
ptf = []
ptg = []
for i in range(npts):
ptu.append(lb + (ub - lb) * i / (npts - 1))
ptf.append(f(ptu[i]))
ptg.append(g(ptu[i]))
# Optimize model as an LP
m.optimize()
for i in range(npts):
ptf[i] = -ptf[i]
m.optimize()
552
print('IsMIP: %d' % m.IsMIP)
for v in m.getVars():
print('%s %g' % (v.VarName, v.X))
print('Obj: %g' % m.ObjVal)
except GurobiError as e:
print('Error code ' + str(e.errno) + ": " + str(e))
except AttributeError:
print('Encountered an attribute error')
553
poolsearch.py
#!/usr/bin/python
try:
# Sample data
Groundset = range(10)
objCoef = [32, 32, 15, 15, 6, 6, 1, 1, 1, 1]
knapsackCoef = [16, 16, 8, 8, 4, 4, 2, 2, 1, 1]
Budget = 33
# save problem
554
model.write('poolsearch.lp')
# Optimize
model.optimize()
model.setParam(GRB.Param.OutputFlag, 0)
# Status checking
status = model.Status
if status == GRB.Status.INF_OR_UNBD or \
status == GRB.Status.INFEASIBLE or \
status == GRB.Status.UNBOUNDED:
print('The model cannot be solved because it is infeasible or unbounded')
sys.exit(1)
if status != GRB.Status.OPTIMAL:
print('Optimization was stopped with status ' + str(status))
sys.exit(1)
555
for e in Groundset:
if Elem[e].Xn > .9:
print(' El%d' % e, end='')
print('')
except GurobiError as e:
print('Gurobi error ' + str(e.errno) + ": " + str(e.message))
except AttributeError as e:
print('Encountered an attribute error: ' + str(e))
556
portfolio.py
#!/usr/bin/python
# Portfolio selection: given a sum of money to invest, one must decide how to
# spend it amongst a portfolio of financial securities. Our approach is due
# to Markowitz (1959) and looks to minimize the risk associated with the
# investment while realizing a target expected return. By varying the target,
# one can compute an 'efficient frontier', which defines the optimal portfolio
# for a given expected return.
#
# Note that this example reads historical return data from a comma-separated
# file (../data/portfolio.csv). As a result, it must be run from the Gurobi
# examples/python directory.
#
# This example requires the pandas, NumPy, and Matplotlib Python packages,
# which are part of the SciPy ecosystem for mathematics, science, and
# engineering (http://scipy.org). These packages aren't included in all
# Python distributions, but are included by default with Anaconda Python.
557
m.setObjective(portfolio_risk, GRB.MINIMIZE)
558
frontier.plot(color='DarkGreen', label='Efficient Frontier', ax=ax)
559
qcp.py
#!/usr/bin/python
# This example formulates and solves the following simple QCP model:
# maximize x
# subject to x + y + z = 1
# x^2 + y^2 <= z^2 (second-order cone)
# x^2 <= yz (rotated second-order cone)
# Create variables
x = m.addVar(name="x")
y = m.addVar(name="y")
z = m.addVar(name="z")
# Set objective: x
obj = 1.0*x
m.setObjective(obj, GRB.MAXIMIZE)
# Add constraint: x + y + z = 1
m.addConstr(x + y + z == 1, "c0")
m.optimize()
for v in m.getVars():
print('%s %g' % (v.varName, v.x))
560
qp.py
#!/usr/bin/python
# Create variables
x = m.addVar(ub=1.0, name="x")
y = m.addVar(ub=1.0, name="y")
z = m.addVar(ub=1.0, name="z")
m.optimize()
for v in m.getVars():
print('%s %g' % (v.varName, v.x))
x.vType = GRB.INTEGER
y.vType = GRB.INTEGER
z.vType = GRB.INTEGER
561
m.optimize()
for v in m.getVars():
print('%s %g' % (v.varName, v.x))
562
sensitivity.py
#!/usr/bin/python
import sys
from gurobipy import *
if len(sys.argv) < 2:
print('Usage: sensitivity.py filename')
quit()
model = read(sys.argv[1])
if model.IsMIP == 0:
print('Model is not a MIP')
exit(0)
model.optimize()
if model.status != GRB.Status.OPTIMAL:
print('Optimization ended with status %d' % model.status)
exit(0)
origObjVal = model.ObjVal
for v in model.getVars():
v._origX = v.X
model.Params.outputFlag = 0
for v in model.getVars():
if (v.LB == 0 and v.UB == 1 \
563
and (v.VType == GRB.BINARY or v.VType == GRB.INTEGER)):
for vv in model.getVars():
if not vv.sameAs(v):
vv.Start = vv._origX
model.optimize()
if model.status == GRB.Status.OPTIMAL:
print('Objective sensitivity for variable %s is %g' % \
(v.VarName, model.ObjVal - origObjVal))
else:
print('Objective sensitivity for variable %s is infinite' % \
v.VarName)
v.LB = 0
v.UB = 1
564
sos.py
#!/usr/bin/python
# This example creates a very simple Special Ordered Set (SOS) model.
# The model consists of 3 continuous variables, no linear constraints,
# and a pair of SOS constraints of type 1.
try:
model = Model("sos")
# Create variables
x0 = model.addVar(ub=1.0, name="x0")
x1 = model.addVar(ub=1.0, name="x1")
x2 = model.addVar(ub=2.0, name="x2")
# Set objective
model.setObjective(2 * x0 + x1 + x2, GRB.MAXIMIZE)
model.optimize()
for v in model.getVars():
print('%s %g' % (v.varName, v.x))
except GurobiError as e:
print('Error code ' + str(e.errno) + ": " + str(e))
except AttributeError:
print('Encountered an attribute error')
565
sudoku.py
#!/usr/bin/python
# Sudoku example.
# The Sudoku board is a 9x9 grid, which is further divided into a 3x3 grid
# of 3x3 grids. Each cell in the grid must take a value from 0 to 9.
# No two grid cells in the same row, column, or 3x3 subgrid may take the
# same value.
#
# In the MIP formulation, binary variables x[i,j,v] indicate whether
# cell <i,j> takes value 'v'. The constraints are as follows:
# 1. Each cell must take exactly one value (sum_v x[i,j,v] = 1)
# 2. Each value is used exactly once per row (sum_i x[i,j,v] = 1)
# 3. Each value is used exactly once per column (sum_j x[i,j,v] = 1)
# 4. Each value is used exactly once per 3x3 subgrid (sum_grid x[i,j,v] = 1)
#
# Input datasets for this example can be found in examples/data/sudoku*.
import sys
import math
from gurobipy import *
if len(sys.argv) < 2:
print('Usage: sudoku.py filename')
quit()
f = open(sys.argv[1])
grid = f.read().split()
n = len(grid[0])
s = int(math.sqrt(n))
model = Model('sudoku')
566
for i in range(n):
for j in range(n):
if grid[i][j] != '.':
v = int(grid[i][j]) - 1
vars[i,j,v].LB = 1
model.addConstrs((vars.sum(i,j,'*') == 1
for i in range(n)
for j in range(n)), name='V')
model.addConstrs((vars.sum(i,'*',v) == 1
for i in range(n)
for v in range(n)), name='R')
model.addConstrs((vars.sum('*',j,v) == 1
for j in range(n)
for v in range(n)), name='C')
model.addConstrs((
quicksum(vars[i,j,v] for i in range(i0*s, (i0+1)*s)
for j in range(j0*s, (j0+1)*s)) == 1
for v in range(n)
for i0 in range(s)
for j0 in range(s)), name='Sub')
model.optimize()
model.write('sudoku.lp')
print('')
print('Solution:')
print('')
567
solution = model.getAttr('X', vars)
for i in range(n):
sol = ''
for j in range(n):
for v in range(n):
if solution[i,j,v] > 0.5:
sol += str(v+1)
print(sol)
568
tsp.py
#!/usr/bin/python
import sys
import math
import random
import itertools
from gurobipy import *
def subtour(edges):
unvisited = list(range(n))
cycle = range(n+1) # initial length has 1 more city
while unvisited: # true if list is non-empty
thiscycle = []
neighbors = unvisited
while neighbors:
current = neighbors[0]
thiscycle.append(current)
569
unvisited.remove(current)
neighbors = [j for i,j in edges.select(current,'*') if j in unvisited]
if len(cycle) > len(thiscycle):
cycle = thiscycle
return cycle
# Parse argument
if len(sys.argv) < 2:
print('Usage: tsp.py npoints')
exit(1)
n = int(sys.argv[1])
random.seed(1)
points = [(random.randint(0,100),random.randint(0,100)) for i in range(n)]
dist = {(i,j) :
math.sqrt(sum((points[i][k]-points[j][k])**2 for k in range(2)))
for i in range(n) for j in range(i)}
m = Model()
# Create variables
570
m.addConstrs(vars.sum(i,'*') == 2 for i in range(n))
# Optimize model
m._vars = vars
m.Params.lazyConstraints = 1
m.optimize(subtourelim)
tour = subtour(selected)
assert len(tour) == n
print('')
print('Optimal tour: %s' % str(tour))
print('Optimal cost: %g' % m.objVal)
print('')
571
tune.py
#!/usr/bin/python
import sys
from gurobipy import *
if len(sys.argv) < 2:
print('Usage: tune.py filename')
quit()
if model.tuneResultCount > 0:
572
workforce1.py
#!/usr/bin/python
# Worker availability
availability = tuplelist([
('Amy', 'Tue2'), ('Amy', 'Wed3'), ('Amy', 'Fri5'), ('Amy', 'Sun7'),
('Amy', 'Tue9'), ('Amy', 'Wed10'), ('Amy', 'Thu11'), ('Amy', 'Fri12'),
('Amy', 'Sat13'), ('Amy', 'Sun14'), ('Bob', 'Mon1'), ('Bob', 'Tue2'),
('Bob', 'Fri5'), ('Bob', 'Sat6'), ('Bob', 'Mon8'), ('Bob', 'Thu11'),
573
('Bob', 'Sat13'), ('Cathy', 'Wed3'), ('Cathy', 'Thu4'), ('Cathy', 'Fri5'),
('Cathy', 'Sun7'), ('Cathy', 'Mon8'), ('Cathy', 'Tue9'), ('Cathy', 'Wed10'),
('Cathy', 'Thu11'), ('Cathy', 'Fri12'), ('Cathy', 'Sat13'),
('Cathy', 'Sun14'), ('Dan', 'Tue2'), ('Dan', 'Wed3'), ('Dan', 'Fri5'),
('Dan', 'Sat6'), ('Dan', 'Mon8'), ('Dan', 'Tue9'), ('Dan', 'Wed10'),
('Dan', 'Thu11'), ('Dan', 'Fri12'), ('Dan', 'Sat13'), ('Dan', 'Sun14'),
('Ed', 'Mon1'), ('Ed', 'Tue2'), ('Ed', 'Wed3'), ('Ed', 'Thu4'),
('Ed', 'Fri5'), ('Ed', 'Sun7'), ('Ed', 'Mon8'), ('Ed', 'Tue9'),
('Ed', 'Thu11'), ('Ed', 'Sat13'), ('Ed', 'Sun14'), ('Fred', 'Mon1'),
('Fred', 'Tue2'), ('Fred', 'Wed3'), ('Fred', 'Sat6'), ('Fred', 'Mon8'),
('Fred', 'Tue9'), ('Fred', 'Fri12'), ('Fred', 'Sat13'), ('Fred', 'Sun14'),
('Gu', 'Mon1'), ('Gu', 'Tue2'), ('Gu', 'Wed3'), ('Gu', 'Fri5'),
('Gu', 'Sat6'), ('Gu', 'Sun7'), ('Gu', 'Mon8'), ('Gu', 'Tue9'),
('Gu', 'Wed10'), ('Gu', 'Thu11'), ('Gu', 'Fri12'), ('Gu', 'Sat13'),
('Gu', 'Sun14')
])
# Model
m = Model("assignment")
# Optimize
m.optimize()
status = m.status
if status == GRB.Status.UNBOUNDED:
print('The model cannot be solved because it is unbounded')
574
exit(0)
if status == GRB.Status.OPTIMAL:
print('The optimal objective is %g' % m.objVal)
exit(0)
if status != GRB.Status.INF_OR_UNBD and status != GRB.Status.INFEASIBLE:
print('Optimization was stopped with status %d' % status)
exit(0)
# do IIS
print('The model is infeasible; computing IIS')
m.computeIIS()
print('\nThe following constraint(s) cannot be satisfied:')
for c in m.getConstrs():
if c.IISConstr:
print('%s' % c.constrName)
575
workforce2.py
#!/usr/bin/python
# Worker availability
availability = tuplelist([
('Amy', 'Tue2'), ('Amy', 'Wed3'), ('Amy', 'Fri5'), ('Amy', 'Sun7'),
('Amy', 'Tue9'), ('Amy', 'Wed10'), ('Amy', 'Thu11'), ('Amy', 'Fri12'),
('Amy', 'Sat13'), ('Amy', 'Sun14'), ('Bob', 'Mon1'), ('Bob', 'Tue2'),
('Bob', 'Fri5'), ('Bob', 'Sat6'), ('Bob', 'Mon8'), ('Bob', 'Thu11'),
('Bob', 'Sat13'), ('Cathy', 'Wed3'), ('Cathy', 'Thu4'), ('Cathy', 'Fri5'),
576
('Cathy', 'Sun7'), ('Cathy', 'Mon8'), ('Cathy', 'Tue9'), ('Cathy', 'Wed10'),
('Cathy', 'Thu11'), ('Cathy', 'Fri12'), ('Cathy', 'Sat13'),
('Cathy', 'Sun14'), ('Dan', 'Tue2'), ('Dan', 'Wed3'), ('Dan', 'Fri5'),
('Dan', 'Sat6'), ('Dan', 'Mon8'), ('Dan', 'Tue9'), ('Dan', 'Wed10'),
('Dan', 'Thu11'), ('Dan', 'Fri12'), ('Dan', 'Sat13'), ('Dan', 'Sun14'),
('Ed', 'Mon1'), ('Ed', 'Tue2'), ('Ed', 'Wed3'), ('Ed', 'Thu4'),
('Ed', 'Fri5'), ('Ed', 'Sun7'), ('Ed', 'Mon8'), ('Ed', 'Tue9'),
('Ed', 'Thu11'), ('Ed', 'Sat13'), ('Ed', 'Sun14'), ('Fred', 'Mon1'),
('Fred', 'Tue2'), ('Fred', 'Wed3'), ('Fred', 'Sat6'), ('Fred', 'Mon8'),
('Fred', 'Tue9'), ('Fred', 'Fri12'), ('Fred', 'Sat13'), ('Fred', 'Sun14'),
('Gu', 'Mon1'), ('Gu', 'Tue2'), ('Gu', 'Wed3'), ('Gu', 'Fri5'),
('Gu', 'Sat6'), ('Gu', 'Sun7'), ('Gu', 'Mon8'), ('Gu', 'Tue9'),
('Gu', 'Wed10'), ('Gu', 'Thu11'), ('Gu', 'Fri12'), ('Gu', 'Sat13'),
('Gu', 'Sun14')
])
# Model
m = Model("assignment")
# Optimize
m.optimize()
status = m.status
if status == GRB.Status.UNBOUNDED:
print('The model cannot be solved because it is unbounded')
exit(0)
if status == GRB.Status.OPTIMAL:
print('The optimal objective is %g' % m.objVal)
exit(0)
if status != GRB.Status.INF_OR_UNBD and status != GRB.Status.INFEASIBLE:
print('Optimization was stopped with status %d' % status)
exit(0)
# do IIS
577
print('The model is infeasible; computing IIS')
removed = []
m.computeIIS()
print('\nThe following constraint cannot be satisfied:')
for c in m.getConstrs():
if c.IISConstr:
print('%s' % c.constrName)
# Remove a single constraint from the model
removed.append(str(c.constrName))
m.remove(c)
break
print('')
m.optimize()
status = m.status
if status == GRB.Status.UNBOUNDED:
print('The model cannot be solved because it is unbounded')
exit(0)
if status == GRB.Status.OPTIMAL:
break
if status != GRB.Status.INF_OR_UNBD and status != GRB.Status.INFEASIBLE:
print('Optimization was stopped with status %d' % status)
exit(0)
578
workforce3.py
#!/usr/bin/python
# Worker availability
availability = tuplelist([
('Amy', 'Tue2'), ('Amy', 'Wed3'), ('Amy', 'Fri5'), ('Amy', 'Sun7'),
('Amy', 'Tue9'), ('Amy', 'Wed10'), ('Amy', 'Thu11'), ('Amy', 'Fri12'),
('Amy', 'Sat13'), ('Amy', 'Sun14'), ('Bob', 'Mon1'), ('Bob', 'Tue2'),
('Bob', 'Fri5'), ('Bob', 'Sat6'), ('Bob', 'Mon8'), ('Bob', 'Thu11'),
579
('Bob', 'Sat13'), ('Cathy', 'Wed3'), ('Cathy', 'Thu4'), ('Cathy', 'Fri5'),
('Cathy', 'Sun7'), ('Cathy', 'Mon8'), ('Cathy', 'Tue9'), ('Cathy', 'Wed10'),
('Cathy', 'Thu11'), ('Cathy', 'Fri12'), ('Cathy', 'Sat13'),
('Cathy', 'Sun14'), ('Dan', 'Tue2'), ('Dan', 'Wed3'), ('Dan', 'Fri5'),
('Dan', 'Sat6'), ('Dan', 'Mon8'), ('Dan', 'Tue9'), ('Dan', 'Wed10'),
('Dan', 'Thu11'), ('Dan', 'Fri12'), ('Dan', 'Sat13'), ('Dan', 'Sun14'),
('Ed', 'Mon1'), ('Ed', 'Tue2'), ('Ed', 'Wed3'), ('Ed', 'Thu4'),
('Ed', 'Fri5'), ('Ed', 'Sun7'), ('Ed', 'Mon8'), ('Ed', 'Tue9'),
('Ed', 'Thu11'), ('Ed', 'Sat13'), ('Ed', 'Sun14'), ('Fred', 'Mon1'),
('Fred', 'Tue2'), ('Fred', 'Wed3'), ('Fred', 'Sat6'), ('Fred', 'Mon8'),
('Fred', 'Tue9'), ('Fred', 'Fri12'), ('Fred', 'Sat13'), ('Fred', 'Sun14'),
('Gu', 'Mon1'), ('Gu', 'Tue2'), ('Gu', 'Wed3'), ('Gu', 'Fri5'),
('Gu', 'Sat6'), ('Gu', 'Sun7'), ('Gu', 'Mon8'), ('Gu', 'Tue9'),
('Gu', 'Wed10'), ('Gu', 'Thu11'), ('Gu', 'Fri12'), ('Gu', 'Sat13'),
('Gu', 'Sun14')
])
# Model
m = Model("assignment")
# Optimize
m.optimize()
status = m.status
if status == GRB.Status.UNBOUNDED:
print('The model cannot be solved because it is unbounded')
exit(0)
if status == GRB.Status.OPTIMAL:
print('The optimal objective is %g' % m.objVal)
exit(0)
if status != GRB.Status.INF_OR_UNBD and status != GRB.Status.INFEASIBLE:
print('Optimization was stopped with status %d' % status)
exit(0)
580
# Relax the constraints to make the model feasible
print('The model is infeasible; relaxing the constraints')
orignumvars = m.NumVars
m.feasRelaxS(0, False, False, True)
m.optimize()
status = m.status
if status in (GRB.Status.INF_OR_UNBD, GRB.Status.INFEASIBLE, GRB.Status.UNBOUNDED):
print('The relaxed model cannot be solved \
because it is infeasible or unbounded')
exit(1)
if status != GRB.Status.OPTIMAL:
print('Optimization was stopped with status %d' % status)
exit(1)
print('\nSlack values:')
slacks = m.getVars()[orignumvars:]
for sv in slacks:
if sv.X > 1e-6:
print('%s = %g' % (sv.VarName, sv.X))
581
workforce4.py
#!/usr/bin/python
# Worker availability
availability = tuplelist([
('Amy', 'Tue2'), ('Amy', 'Wed3'), ('Amy', 'Fri5'), ('Amy', 'Sun7'),
('Amy', 'Tue9'), ('Amy', 'Wed10'), ('Amy', 'Thu11'), ('Amy', 'Fri12'),
('Amy', 'Sat13'), ('Amy', 'Sun14'), ('Bob', 'Mon1'), ('Bob', 'Tue2'),
582
('Bob', 'Fri5'), ('Bob', 'Sat6'), ('Bob', 'Mon8'), ('Bob', 'Thu11'),
('Bob', 'Sat13'), ('Cathy', 'Wed3'), ('Cathy', 'Thu4'), ('Cathy', 'Fri5'),
('Cathy', 'Sun7'), ('Cathy', 'Mon8'), ('Cathy', 'Tue9'), ('Cathy', 'Wed10'),
('Cathy', 'Thu11'), ('Cathy', 'Fri12'), ('Cathy', 'Sat13'),
('Cathy', 'Sun14'), ('Dan', 'Tue2'), ('Dan', 'Wed3'), ('Dan', 'Fri5'),
('Dan', 'Sat6'), ('Dan', 'Mon8'), ('Dan', 'Tue9'), ('Dan', 'Wed10'),
('Dan', 'Thu11'), ('Dan', 'Fri12'), ('Dan', 'Sat13'), ('Dan', 'Sun14'),
('Ed', 'Mon1'), ('Ed', 'Tue2'), ('Ed', 'Wed3'), ('Ed', 'Thu4'),
('Ed', 'Fri5'), ('Ed', 'Sun7'), ('Ed', 'Mon8'), ('Ed', 'Tue9'),
('Ed', 'Thu11'), ('Ed', 'Sat13'), ('Ed', 'Sun14'), ('Fred', 'Mon1'),
('Fred', 'Tue2'), ('Fred', 'Wed3'), ('Fred', 'Sat6'), ('Fred', 'Mon8'),
('Fred', 'Tue9'), ('Fred', 'Fri12'), ('Fred', 'Sat13'), ('Fred', 'Sun14'),
('Gu', 'Mon1'), ('Gu', 'Tue2'), ('Gu', 'Wed3'), ('Gu', 'Fri5'),
('Gu', 'Sat6'), ('Gu', 'Sun7'), ('Gu', 'Mon8'), ('Gu', 'Tue9'),
('Gu', 'Wed10'), ('Gu', 'Thu11'), ('Gu', 'Fri12'), ('Gu', 'Sat13'),
('Gu', 'Sun14')
])
# Model
m = Model("assignment")
# Slack variables for each shift constraint so that the shifts can
# be satisfied
slacks = m.addVars(shifts, name="Slack")
583
# Objective: minimize the total slack
# Note that this replaces the previous 'pay' objective coefficients
m.setObjective(totSlack)
# Optimize
def solveAndPrint():
m.optimize()
status = m.status
if status == GRB.Status.INF_OR_UNBD or status == GRB.Status.INFEASIBLE \
or status == GRB.Status.UNBOUNDED:
print('The model cannot be solved because it is infeasible or \
unbounded')
exit(1)
if status != GRB.Status.OPTIMAL:
print('Optimization was stopped with status %d' % status)
exit(0)
# Print total slack and the number of shifts worked for each worker
print('')
print('Total slack required: %g' % totSlack.x)
for w in workers:
print('%s worked %g shifts' % (w, totShifts[w].x))
print('')
solveAndPrint()
584
"Diff")
# Objective: minimize the sum of the square of the difference from the
# average number of shifts worked
m.setObjective(quicksum(diffShifts[w]*diffShifts[w] for w in workers))
# Optimize
solveAndPrint()
585
workforce5.py
#!/usr/bin/python
try:
# Sample data
# Sets of days and workers
Shifts = [ "Mon1", "Tue2", "Wed3", "Thu4", "Fri5", "Sat6",
"Sun7", "Mon8", "Tue9", "Wed10", "Thu11", "Fri12", "Sat13",
"Sun14" ]
Workers = [ "Amy", "Bob", "Cathy", "Dan", "Ed", "Fred", "Gu", "Tobi" ]
586
# use binary variables.
x = model.addVars(availability.keys(), ub=availability, vtype=GRB.BINARY,
name='x')
# Slack variables for each shift constraint so that the shifts can
# be satisfied
slacks = model.addVars(Shifts, name='Slack')
587
model.ObjNAbsTol = 2.0
totSlack.ObjN = 1.0
# Save problem
model.write('workforce5.lp')
# Optimize
model.optimize()
status = model.Status
if status == GRB.Status.INF_OR_UNBD or \
status == GRB.Status.INFEASIBLE or \
status == GRB.Status.UNBOUNDED:
print('The model cannot be solved because it is infeasible or unbounded')
sys.exit(0)
if status != GRB.Status.OPTIMAL:
print('Optimization was stopped with status ' + str(status))
sys.exit(0)
# Print total slack and the number of shifts worked for each worker
print('')
print('Total slack required: ' + str(totSlack.X))
for w in Workers:
print(w + ' worked ' + str(totShifts[w].X) + ' shifts')
print('')
except GurobiError as e:
print('Error code ' + str(e.errno) + ": " + str(e))
except AttributeError as e:
print('Encountered an attribute error: ' + str(e))
588
3.7 MATLAB Examples
This section includes source code for all of the Gurobi MATLAB examples. The same source code
can be found in the examples/matlab directory of the Gurobi distribution.
diet.m
function diet()
% diet Solve the classic diet model
ncategories = 4;
categories = {'calories'; 'protein'; 'fat'; 'sodium'};
% minNutrition maxNutrition
categorynutrition = [ 1800 2200; % calories
91 inf; % protein
0 65; % fat
0 1779]; % sodium
nfoods = 9;
foods = {'hamburger';
'chicken';
'hot dog';
'fries';
'macaroni';
'pizza';
'salad';
'milk';
'ice cream'};
589
% calories protein fat sodium
nutritionValues = [ 410 24 26 730; % hamburger
420 32 10 1190; % chicken
560 20 32 1800; % hot dog
380 4 19 270; % fries
320 12 10 930; % macaroni
320 15 12 820; % pizza
320 31 12 1230; % salad
100 8 2.5 125; % milk
330 8 10 180]; % ice cream
nutritionValues = sparse(nutritionValues);
model.modelName = 'diet';
function printSolution(result)
if strcmp(result.status, 'OPTIMAL')
buy = result.x(1:nfoods);
nutrition = result.x(nfoods+1:nfoods+ncategories);
fprintf('\nCost: %f\n', result.objval);
fprintf('\nBuy:\n')
for f=1:nfoods
if buy(f) > 0.0001
fprintf('%10s %g\n', foods{f}, buy(f));
end
end
fprintf('\nNutrition:\n')
for c=1:ncategories
fprintf('%10s %g\n', categories{c}, nutrition(c));
end
else
fprintf('No solution\n');
end
end
% Solve
results = gurobi(model);
printSolution(results);
590
fprintf('\nAdding constraint at most 6 servings of dairy\n')
milk = find(strcmp('milk', foods));
icecream = find(strcmp('ice cream', foods));
model.A(end+1,:) = sparse([1; 1], [milk; icecream], 1, ...
1, nfoods + ncategories);
model.rhs(end+1) = 6;
model.sense(end+1) = '<';
% Solve
results = gurobi(model);
printSolution(results)
end
591
intlinprog.m
function [x, fval, exitflag] = intlinprog(f, intcon, A, b, Aeq, beq, lb, ub)
%INTLINPROG A mixed integer linear programming example using the
% Gurobi MATLAB interface
%
% This example is based on the intlinprog interface defined in the
% MATLAB Optimization Toolbox. The Optimization Toolbox
% is a registered trademark of The MathWorks, Inc.
%
% x = INTLINPROG(f,intcon,A,b) solves the problem:
%
% minimize f'*x
% subject to A*x <= b
% x(j) integer, when j is in the vector
% intcon of integer constraints
%
% x = INTLINPROG(f,intcon,A,b,Aeq,beq) solves the problem:
%
% minimize f'*x
% subject to A*x <= b,
% Aeq*x == beq
% x(j) integer, where j is in the vector
% intcon of integer constraints
%
% x = INTLINPROG(f,intcon,A,b,Aeq,beq,lb,ub) solves the problem:
%
% minimize f'*x
% subject to A*x <= b,
% Aeq*x == beq,
% lb <= x <= ub.
% x(j) integer, where j is in the vector
% intcon of integer constraints
%
% You can set lb(j) = -inf, if x(j) has no lower bound,
% and ub(j) = inf, if x(j) has no upper bound.
%
% [x, fval] = INTLINPROG(f, intcon, A, b) returns the objective value
% at the solution. That is, fval = f'*x.
%
% [x, fval, exitflag] = INTLINPROG(f, intcon, A, b) returns an exitflag
% containing the status of the optimization. The values for
% exitflag and corresponding status codes are:
% 2 - Solver stopped prematurely. Integer feasible point found.
% 1 - Optimal solution found.
% 0 - Solver stopped prematurely. No integer feasible point found.
592
% -2 - No feasible point found.
% -3 - Problem is unbounded.
if nargin < 4
error('intlinprog(f, intcon, A, b)')
end
if nargin > 8
error('intlinprog(f, intcon, A, b, Aeq, beq, lb, ub)');
end
if ~isempty(A)
n = size(A, 2);
elseif nargin > 5 && ~isempty(Aeq)
n = size(Aeq, 2);
else
error('No linear constraints specified')
end
if ~issparse(A)
A = sparse(A);
end
model.obj = f;
model.vtype = repmat('C', n, 1);
model.vtype(intcon) = 'I';
if nargin < 5
model.A = A;
model.rhs = b;
model.sense = '<';
else
model.A = [A; Aeq];
model.rhs = [b; beq];
model.sense = [repmat('<', size(A,1), 1); repmat('=', size(Aeq,1), 1)];
end
if nargin < 7
model.lb = -inf(n,1);
else
model.lb = lb;
593
end
if nargin == 8
model.ub = ub;
end
params.outputflag = 1;
result = gurobi(model, params);
if strcmp(result.status, 'OPTIMAL')
exitflag = 1;
elseif strcmp(result.status, 'INTERRUPTED')
if isfield(result, 'x')
exitflag = 2;
else
exitflag = 0;
end
elseif strcmp(result.status, 'INF_OR_UNBD')
params.dualreductions = 0;
result = gurobi(model, params);
if strcmp(result.status, 'INFEASIBLE')
exitflag = -2;
elseif strcmp(result.status, 'UNBOUNDED')
exitflag = -3;
else
exitflag = nan;
end
else
exitflag = nan;
end
if isfield(result, 'x')
x = result.x;
else
x = nan(n,1);
end
if isfield(result, 'objval')
fval = result.objval;
else
fval = nan;
end
594
595
linprog.m
function [x, fval, exitflag] = linprog(f, A, b, Aeq, beq, lb, ub)
%LINPROG A linear programming example using the Gurobi MATLAB interface
%
% This example is based on the linprog interface defined in the
% MATLAB Optimization Toolbox. The Optimization Toolbox
% is a registered trademark of The MathWorks, Inc.
%
% x = LINPROG(f,A,b) solves the linear programming problem:
%
% minimize f'*x
% subject to A*x <= b
%
%
% x = LINPROG(f,A,b,Aeq,beq) solves the problem:
%
% minimize f'*x
% subject to A*x <= b,
% Aeq*x == beq.
%
% x = LINPROG(f,A,b,Aeq,beq,lb,ub) solves the problem:
%
% minimize f'*x
% subject to A*x <= b,
% Aeq*x == beq,
% lb <= x <= ub.
%
% You can set lb(j) = -inf, if x(j) has no lower bound,
% and ub(j) = inf, if x(j) has no upper bound.
%
% [x, fval] = LINPROG(f, A, b) returns the objective value
% at the solution. That is, fval = f'*x.
%
% [x, fval, exitflag] = LINPROG(f, A, b) returns an exitflag
% containing the status of the optimization. The values for
% exitflag and corresponding status codes are:
% 1 - OPTIMAL,
% 0 - ITERATION_LIMIT,
% -2 - INFEASIBLE,
% -3 - UNBOUNDED.
%
if nargin < 3
error('linprog(f, A, b)')
end
596
if nargin > 7
error('linprog(f, A, b, Aeq, beq, lb, ub)');
end
if ~isempty(A)
n = size(A, 2);
elseif nargin > 4 && ~isempty(Aeq)
n = size(Aeq, 2);
else
error('No linear constraints specified')
end
if ~issparse(A)
A = sparse(A);
end
model.obj = f;
if nargin < 4
model.A = A;
model.rhs = b;
model.sense = '<';
else
model.A = [A; Aeq];
model.rhs = [b; beq];
model.sense = [repmat('<', size(A,1), 1); repmat('=', size(Aeq,1), 1)];
end
if nargin < 6
model.lb = -inf(n,1);
else
model.lb = lb;
end
if nargin == 7
model.ub = ub;
end
params.outputflag = 0;
597
result = gurobi(model, params);
if strcmp(result.status, 'OPTIMAL')
exitflag = 1;
elseif strcmp(result.status, 'ITERATION_LIMIT')
exitflag = 0;
elseif strcmp(result.status, 'INF_OR_UNBD')
params.dualreductions = 0;
result = gurobi(model, params);
if strcmp(result.status, 'INFEASIBLE')
exitflag = -2;
elseif strcmp(result.status, 'UNBOUNDED')
exitflag = -3;
else
exitflag = nan;
end
elseif strcmp(result.status, 'INFEASIBLE')
exitflag = -2;
elseif strcmp(result.status, 'UNBOUNDED')
exitflag = -3;
else
exitflag = nan;
end
if isfield(result, 'x')
x = result.x;
else
x = nan(n,1);
end
if isfield(result, 'objval')
fval = result.objval;
else
fval = nan;
end
598
lp.m
% Copyright 2016, Gurobi Optimization, Inc.
%
% This example formulates and solves the following simple LP model:
% maximize
% x + 2 y + 3 z
% subject to
% x + y <= 1
% y + z <= 1
%
clear model;
model.A = sparse([1 1 0; 0 1 1]);
model.obj = [1 2 3];
model.modelsense = 'Max';
model.rhs = [1 1];
model.sense = [ '<' '<'];
result = gurobi(model)
disp(result.objval);
disp(result.x);
clear params;
params.method = 2;
params.timelimit = 100;
disp(result.objval);
disp(result.x)
599
lp2.m
% Copyright 2016, Gurobi Optimization, Inc.
%
% Formulate a simple linear program, solve it, and then solve it
% again using the optimal basis.
clear model;
model.A = sparse([1 3 4; 8 2 3]);
model.obj = [1 2 3];
model.rhs = [4 7];
model.sense = ['>' '>'];
model.vbasis = result.vbasis;
model.cbasis = result.cbasis;
result = gurobi(model)
600
mip1.m
% Copyright 2016, Gurobi Optimization, Inc.
% This example formulates and solves the following simple MIP model:
% maximize
% x + y + 2 z
% subject to
% x + 2 y + 3 z <= 4
% x + y >= 1
% x, y, z binary
try
clear model;
model.A = sparse([1 2 3; 1 1 0]);
model.obj = [1 1 2];
model.rhs = [4; 1];
model.sense = '<>';
model.vtype = 'B';
model.modelsense = 'max';
model.varnames = names;
gurobi_write(model, 'mip1.lp');
clear params;
params.outputflag = 0;
disp(result)
for v=1:length(names)
fprintf('%s %d\n', names{v}, result.x(v));
end
catch gurobiError
fprintf('Error reported\n');
end
601
piecewise.m
% Copyright 2016, Gurobi Optimization, Inc.
try
clear model;
model.A = sparse([1 2 3; 1 1 0]);
model.obj = [0; -1; 0];
model.rhs = [4; 1];
model.sense = '<>';
model.vtype = 'C';
model.lb = [0; 0; 0];
model.ub = [1; 1; 1];
model.varnames = names;
% Optimize model as LP
602
result = gurobi(model);
disp(result);
for v=1:length(names)
fprintf('%s %d\n', names{v}, result.x(v));
end
gurobi_write(model, 'pwl.lp')
disp(result);
for v=1:length(names)
fprintf('%s %d\n', names{v}, result.x(v));
end
catch gurobiError
fprintf('Error reported\n');
end
603
qcp.m
% Copyright 2016, Gurobi Optimization, Inc.
% This example formulates and solves the following simple QCP model:
% maximize
% x
% subject to
% x + y + z = 1
% x^2 + y^2 <= z^2 (second-order cone)
% x^2 <= yz (rotated second-order cone)
clear model
names = {'x', 'y', 'z'};
model.varnames = names;
% Set objective: x
model.obj = [ 1 0 0 ];
model.modelsense = 'max';
% Add constraint: x + y + z = 1
model.A = sparse([1 1 1]);
model.rhs = 1;
model.sense = '=';
gurobi_write(model, 'qcp.lp');
result = gurobi(model);
for j=1:3
fprintf('%s %e\n', names{j}, result.x(j))
end
604
fprintf('Obj: %e\n', result.objval);
605
qp.m
% Copyright 2016, Gurobi Optimization, Inc.
clear model;
names = {'x', 'y', 'z'};
model.varnames = names;
model.Q = sparse([1 0.5 0; 0.5 1 0.5; 0 0.5 1]);
model.A = sparse([1 2 3; 1 1 0]);
model.obj = [2 0 0];
model.rhs = [4 1];
model.sense = '>';
gurobi_write(model, 'qp.lp');
results = gurobi(model);
for v=1:length(names)
fprintf('%s %e\n', names{v}, results.x(v));
end
model.vtype = 'B';
results = gurobi(model);
for v=1:length(names)
fprintf('%s %e\n', names{v}, results.x(v));
end
606
sos.m
% Copyright 2016, Gurobi Optimization, Inc.
try
clear model;
model.ub = [1 1 2];
model.obj = [2 1 1];
model.modelsense = 'Max';
model.A = sparse(1,3);
model.rhs = 0;
model.sense = '=';
result = gurobi(model);
for i=1:3
fprintf('x%d %e\n', i, result.x(i))
end
catch gurobiError
fprintf('Encountered an error\n')
end
607
3.8 R Examples
This section includes source code for all of the Gurobi R examples. The same source code can be
found in the examples/R directory of the Gurobi distribution.
lp.R
# Copyright 2016, Gurobi Optimization, Inc.
#
# This example formulates and solves the following simple LP model:
# maximize
# x + 2 y + 3 z
# subject to
# x + y <= 1
# y + z <= 1
library("Matrix")
library("gurobi")
print(result$objval)
print(result$x)
print(result$objval)
print(result$x)
# Third option for A - as a sparse triplet matrix (using the slam package)...
608
params <- list(Method=2, TimeLimit=100)
print(result$objval)
print(result$x)
609
lp2.R
# Copyright 2016, Gurobi Optimization, Inc.
#
# Formulate a simple linear program, solve it, and then solve it
# again using the optimal basis.
library("gurobi")
610
mip.R
# Copyright 2016, Gurobi Optimization, Inc.
#
# This example formulates and solves the following simple MIP model:
# maximize
# x + y + 2 z
# subject to
# x + 2 y + 3 z <= 4
# x + y >= 1
# x, y, z binary
library("gurobi")
print('Solution:')
print(result$objval)
print(result$x)
611
piecewise.R
# Copyright 2016, Gurobi Optimization, Inc.
#
# This example considers the following separable, convex problem:
#
# minimize
# f(x) - y + g(z)
# subject to
# x + 2 y + 3 z <= 4
# x + y >= 1
# x, y, z <= 1
#
# where f(u) = exp(-u) and g(u) = 2 u^2 - 4u, for all real u. It
# formulates and solves a simpler LP model by approximating f and
# g with piecewise-linear functions. Then it transforms the model
# into a MIP by negating the approximation for f, which gives
# a non-convex piecewise-linear function, and solves it again.
library("gurobi")
612
result <- gurobi(model)
print(result$objval)
print(result$x)
print(result$objval)
print(result$x)
613
qcp.R
# Copyright 2016, Gurobi Optimization, Inc.
#
# This example formulates and solves the following simple QCP model:
# maximize
# x
# subject to
# x + y + z = 1
# x^2 + y^2 <= z^2 (second-order cone)
# x^2 <= yz (rotated second-order cone)
library("gurobi")
library("Matrix")
print(result$objval)
print(result$x)
614
qp.R
# Copyright 2016, Gurobi Optimization, Inc.
#
# This example formulates and solves the following simple QP model:
# minimize
# x^2 + x*y + y^2 + y*z + z^2 + 2 x
# subject to
# x + 2 y + 3z >= 4
# x + y >= 1
library("gurobi")
print(result$objval)
print(result$x)
615
sos.R
# Copyright 2016, Gurobi Optimization, Inc.
#
# This example formulates and solves the following simple SOS model:
# maximize
# 2 x + y + z
# subject to
# x1 = 0 or x2 = 0 (SOS1 constraint)
# x1 = 0 or x3 = 0 (SOS1 constraint)
# x1 <= 1, x2 <= 1, x3 <= 2
library("gurobi")
# First SOS: x1 = 0 or x2 = 0
sos1 <- list()
sos1$type <- 1
sos1$index <- c(1, 2)
sos1$weight <- c(1, 2)
# Second SOS: x1 = 0 or x3 = 0
sos2 <- list()
sos2$type <- 1
sos2$index <- c(1, 3)
sos2$weight <- c(1, 2)
print(result$objval)
print(result$x)
616