-
Notifications
You must be signed in to change notification settings - Fork 22
/
conic_algorithm.jl
2463 lines (2120 loc) · 93.1 KB
/
conic_algorithm.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2017, Chris Coey and Miles Lubin
# Copyright 2016, Los Alamos National Laboratory, LANS LLC.
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, you can obtain one at http://mozilla.org/MPL/2.0/.
#=========================================================
This mixed-integer conic programming algorithm is described in:
Lubin, Yamangil, Bent, Vielma (2016), Extended formulations
in Mixed-Integer Convex Programming, IPCO 2016, Liege, Belgium
(available online at http://arxiv.org/abs/1511.06710)
Model MICP with JuMP.jl conic format or Convex.jl DCP format
http://mathprogbasejl.readthedocs.org/en/latest/conic.html
=========================================================#
using JuMP
using ConicBenchmarkUtilities
#=========================================================
Constants
=========================================================#
const sqrt2 = sqrt(2)
const sqrt2inv = 1/sqrt2
const infeas_ray_tol = 1e-10 # For checking if conic subproblem infeasible ray is sufficiently negative
const feas_factor = 100. # For checking if solution is considered feasible from its maximum conic violation
const unstable_soc_disagg_tol = 1e-5 # For checking if a disaggregated SOC cut is numerically unstable
#=========================================================
Conic model object
=========================================================#
type PajaritoConicModel <: MathProgBase.AbstractConicModel
# Solver parameters
log_level::Int # Verbosity flag: 0 for quiet, 1 for basic solve info, 2 for iteration info, 3 for detailed timing and cuts and solution feasibility info
timeout::Float64 # Time limit for algorithm (in seconds)
rel_gap::Float64 # Relative optimality gap termination condition
mip_solver_drives::Bool # Let MIP solver manage convergence ("branch and cut")
mip_solver::MathProgBase.AbstractMathProgSolver # MIP solver (MILP or MISOCP)
mip_subopt_solver::MathProgBase.AbstractMathProgSolver # MIP solver for suboptimal solves (with appropriate options already passed)
mip_subopt_count::Int # Number of times to use `mip_subopt_solver` between `mip_solver` solves
round_mip_sols::Bool # Round integer variable values before solving subproblems
use_mip_starts::Bool # Use conic subproblem feasible solutions as MIP warm-starts or heuristic solutions
cont_solver::MathProgBase.AbstractMathProgSolver # Continuous conic solver
solve_relax::Bool # Solve the continuous conic relaxation to add initial subproblem cuts
solve_subp::Bool # Solve the continuous conic subproblems to add subproblem cuts
dualize_relax::Bool # Solve the conic dual of the continuous conic relaxation
dualize_subp::Bool # Solve the conic duals of the continuous conic subproblems
all_disagg::Bool # Disaggregate cuts on the nonpolyhedral cones
soc_disagg::Bool # Disaggregate SOC using extended formulation
soc_abslift::Bool # Use SOC absolute value lifting
soc_in_mip::Bool # Use SOC cones in the MIP model (if `mip_solver` supports MISOCP)
sdp_eig::Bool # Use PSD cone eigenvector cuts
sdp_soc::Bool # Use PSD cone eigenvector SOC cuts (if `mip_solver` supports MISOCP)
init_soc_one::Bool # Use SOC initial L_1 cuts
init_soc_inf::Bool # Use SOC initial L_inf cuts
init_exp::Bool # Use Exp initial cuts
init_sdp_lin::Bool # Use PSD cone initial linear cuts
init_sdp_soc::Bool # Use PSD cone initial SOC cuts (if `mip_solver` supports MISOCP)
scale_subp_cuts::Bool # Use scaling for subproblem cuts
scale_subp_factor::Float64 # Fixed multiplicative factor for scaled subproblem cuts
scale_subp_up::Bool # Scale up any scaled subproblem cuts that are smaller than the equivalent separation cut
viol_cuts_only::Bool # Only add cuts violated by current MIP solution
sep_cuts_only::Bool # Add primal cuts, do not add subproblem cuts
sep_cuts_always::Bool # Add primal cuts and subproblem cuts
sep_cuts_assist::Bool # Add subproblem cuts, and add primal cuts only subproblem cuts cannot be added
cut_zero_tol::Float64 # Zero tolerance for cut coefficients
mip_feas_tol::Float64 # Absolute feasibility tolerance used for primal cuts (set equal to feasibility tolerance of `mip_solver`)
dump_subproblems::Bool # Save each conic subproblem in conic benchmark format (CBF) at a specified location
dump_basename::String # Basename of conic subproblem CBF files: "/path/to/foo" creates files "/path/to/foo_NN.cbf" where "NN" is a counter
# Initial data
num_var_orig::Int # Initial number of variables
num_con_orig::Int # Initial number of constraints
c_orig # Initial objective coefficients vector
A_orig # Initial affine constraint matrix (sparse representation)
b_orig # Initial constraint right hand side
cone_con_orig # Initial constraint cones vector (cone, index)
cone_var_orig # Initial variable cones vector (cone, index)
var_types::Vector{Symbol} # Variable types vector on original variables (only :Bin, :Cont, :Int)
# var_start::Vector{Float64} # Variable warm start vector on original variables
# Conic subproblem data
cone_con_sub::Vector{Tuple{Symbol,Vector{Int}}} # Constraint cones data in conic subproblem
cone_var_sub::Vector{Tuple{Symbol,Vector{Int}}} # Variable cones data in conic subproblem
A_sub_cont::SparseMatrixCSC{Float64,Int64} # Submatrix of A containing full rows and continuous variable columns
A_sub_int::SparseMatrixCSC{Float64,Int64} # Submatrix of A containing full rows and integer variable columns
b_sub::Vector{Float64} # Subvector of b containing full rows
c_sub_cont::Vector{Float64} # Subvector of c for continuous variables
c_sub_int::Vector{Float64} # Subvector of c for integer variables
# MIP data
model_mip::JuMP.Model # JuMP MIP (outer approximation) model
x_int::Vector{JuMP.Variable} # JuMP (sub)vector of integer variables
x_cont::Vector{JuMP.Variable} # JuMP (sub)vector of continuous variables
num_cones::Int # Number of cones in the MIP (linear and non-linear)
# SOC data
num_soc::Int # Number of SOCs
r_idx_soc_subp::Vector{Int} # Row index of r variable in SOCs in subproblems
t_idx_soc_subp::Vector{Vector{Int}} # Row indices of t variables in SOCs in subproblem
r_soc::Vector{JuMP.AffExpr} # r variable (epigraph) in SOCs
t_soc::Vector{Vector{JuMP.AffExpr}} # t variables in SOCs
pi_soc::Vector{Vector{JuMP.Variable}} # pi variables (disaggregated) in SOCs
rho_soc::Vector{Vector{JuMP.Variable}} # rho variables (absolute values) in SOCs
# ExpPrimal data
num_exp::Int # Number of ExpPrimal cones
r_idx_exp_subp::Vector{Int} # Row index of r variable in ExpPrimals in subproblems
s_idx_exp_subp::Vector{Int} # Row index of s variable in ExpPrimals in subproblems
t_idx_exp_subp::Vector{Int} # Row index of t variable in ExpPrimals in subproblems
r_exp::Vector{JuMP.AffExpr} # r variable in ExpPrimals
s_exp::Vector{JuMP.AffExpr} # s variable in ExpPrimals
t_exp::Vector{JuMP.AffExpr} # t variable in ExpPrimals
# SDP data
num_sdp::Int # Number of SDP cones
t_idx_sdp_subp::Vector{Vector{Int}} # Row indices of svec v variables in SDPs in subproblem
smat_sdp::Vector{Symmetric{Float64,Array{Float64,2}}} # Preallocated array for smat space values
T_sdp::Vector{Array{JuMP.AffExpr,2}} # smat space T variables in SDPs
# Miscellaneous for algorithms
inf_subp_scale::Float64 # Calculated infeasible subproblem cuts scaling factor
opt_subp_scale::Float64 # Calculated optimal subproblem cuts scaling factor
update_conicsub::Bool # Indicates whether to use setbvec! to update an existing conic subproblem model
model_conic::MathProgBase.AbstractConicModel # Conic subproblem model: persists when the conic solver implements MathProgBase.setbvec!
oa_started::Bool # Indicator for Iterative or MIP-solver-driven algorithms started
cache_dual::Dict{Vector{Float64},Vector{Float64}} # Set of integer solution subvectors already seen
new_incumb::Bool # Indicates whether a new incumbent solution from the conic solver is waiting to be added as warm-start or heuristic
cb_heur # Heuristic callback reference (MIP-driven only)
cb_lazy # Lazy callback reference (MIP-driven only)
aggregate_cut::JuMP.AffExpr # If not disaggregating cuts on nonpolyhedral cones, build up single cut expression here before adding
# Solution and bound information
is_best_conic::Bool # Indicates best feasible came from conic solver solution, otherwise MIP solver solution
best_bound::Float64 # Best lower bound from MIP
best_obj::Float64 # Best feasible objective value
best_int::Vector{Float64} # Best feasible integer solution
best_cont::Vector{Float64} # Best feasible continuous solution
gap_rel_opt::Float64 # Relative optimality gap = |best_bound - best_obj|/|best_obj|
final_soln::Vector{Float64} # Final solution on original variables
# Logging information and status
logs::Dict{Symbol,Any} # Logging information
status::Symbol # Current Pajarito status
# Model constructor
function PajaritoConicModel(log_level, timeout, rel_gap, mip_solver_drives, mip_solver, mip_subopt_solver, mip_subopt_count, round_mip_sols, use_mip_starts, cont_solver, solve_relax, solve_subp, dualize_relax, dualize_subp, all_disagg, soc_disagg, soc_abslift, soc_in_mip, sdp_eig, sdp_soc, init_soc_one, init_soc_inf, init_exp, init_sdp_lin, init_sdp_soc, scale_subp_cuts, scale_subp_factor, scale_subp_up, viol_cuts_only, sep_cuts_only, sep_cuts_always, sep_cuts_assist, cut_zero_tol, mip_feas_tol, dump_subproblems, dump_basename)
m = new()
m.log_level = log_level
m.mip_solver_drives = mip_solver_drives
m.solve_relax = solve_relax
m.solve_subp = solve_subp
m.dualize_relax = dualize_relax
m.dualize_subp = dualize_subp
m.use_mip_starts = use_mip_starts
m.round_mip_sols = round_mip_sols
m.mip_subopt_count = mip_subopt_count
m.mip_subopt_solver = mip_subopt_solver
m.soc_in_mip = soc_in_mip
m.all_disagg = all_disagg
m.soc_disagg = soc_disagg
m.soc_abslift = soc_abslift
m.init_soc_one = init_soc_one
m.init_soc_inf = init_soc_inf
m.init_exp = init_exp
m.scale_subp_cuts = scale_subp_cuts
m.scale_subp_factor = scale_subp_factor
m.scale_subp_up = scale_subp_up
m.viol_cuts_only = viol_cuts_only
m.mip_solver = mip_solver
m.cont_solver = cont_solver
m.timeout = timeout
m.rel_gap = rel_gap
m.cut_zero_tol = cut_zero_tol
m.sep_cuts_only = sep_cuts_only
m.sep_cuts_always = sep_cuts_always
m.sep_cuts_assist = sep_cuts_assist
m.mip_feas_tol = mip_feas_tol
m.init_sdp_lin = init_sdp_lin
m.init_sdp_soc = init_sdp_soc
m.sdp_eig = sdp_eig
m.sdp_soc = sdp_soc
m.dump_subproblems = dump_subproblems
m.dump_basename = dump_basename
m.var_types = Symbol[]
# m.var_start = Float64[]
m.num_var_orig = 0
m.num_con_orig = 0
m.oa_started = false
m.best_obj = Inf
m.best_bound = -Inf
m.gap_rel_opt = NaN
m.status = :NotLoaded
create_logs!(m)
return m
end
end
#=========================================================
MathProgBase functions
=========================================================#
# Verify initial conic data and convert appropriate types and store in Pajarito model
function MathProgBase.loadproblem!(m::PajaritoConicModel, c, A, b, cone_con, cone_var)
# Check dimensions of conic problem
num_con_orig = length(b)
num_var_orig = length(c)
if size(A) != (num_con_orig, num_var_orig)
error("Dimension mismatch between A matrix $(size(A)), b vector ($(length(b))), and c vector ($(length(c)))\n")
end
if isempty(cone_con) || isempty(cone_var)
error("Variable or constraint cones are missing\n")
end
A_sp = sparse(A)
dropzeros!(A_sp)
if m.log_level > 1
@printf "\nProblem dimensions:\n"
@printf "%16s | %7d\n" "variables" num_var_orig
@printf "%16s | %7d\n" "constraints" num_con_orig
@printf "%16s | %7d\n" "nonzeros in A" nnz(A_sp)
end
# Check constraint cones
inds_con = zeros(Int, num_con_orig)
for (spec, inds) in cone_con
if spec == :Free
error("A cone $spec should not be in the constraint cones\n")
end
if any(inds .> num_con_orig)
error("Some indices in a constraint cone do not correspond to indices of vector b\n")
end
inds_con[inds] += 1
end
if any(inds_con .== 0)
error("Some indices in vector b do not correspond to indices of a constraint cone\n")
end
if any(inds_con .> 1)
error("Some indices in vector b appear in multiple constraint cones\n")
end
# Check variable cones
inds_var = zeros(Int, num_var_orig)
for (spec, inds) in cone_var
if any(inds .> num_var_orig)
error("Some indices in a variable cone do not correspond to indices of vector c\n")
end
inds_var[inds] += 1
end
if any(inds_var .== 0)
error("Some indices in vector c do not correspond to indices of a variable cone\n")
end
if any(inds_var .> 1)
error("Some indices in vector c appear in multiple variable cones\n")
end
num_soc = 0
min_soc = 0
max_soc = 0
num_rot = 0
min_rot = 0
max_rot = 0
num_exp = 0
num_sdp = 0
min_sdp = 0
max_sdp = 0
# Verify consistency of cone indices and summarize cone info
for (spec, inds) in vcat(cone_con, cone_var)
if isempty(inds)
error("A cone $spec has no associated indices\n")
end
if spec == :SOC
if length(inds) < 2
error("A cone $spec has fewer than 2 indices ($(length(inds)))\n")
end
num_soc += 1
if max_soc < length(inds)
max_soc = length(inds)
end
if (min_soc == 0) || (min_soc > length(inds))
min_soc = length(inds)
end
elseif spec == :SOCRotated
if length(inds) < 3
error("A cone $spec has fewer than 3 indices ($(length(inds)))\n")
end
num_rot += 1
if max_rot < length(inds)
max_rot = length(inds)
end
if (min_rot == 0) || (min_rot > length(inds))
min_rot = length(inds)
end
elseif spec == :SDP
if length(inds) < 3
error("A cone $spec has fewer than 3 indices ($(length(inds)))\n")
else
if floor(sqrt(8 * length(inds) + 1)) != sqrt(8 * length(inds) + 1)
error("A cone $spec (in SD svec form) does not have a valid (triangular) number of indices ($(length(inds)))\n")
end
end
num_sdp += 1
if max_sdp < length(inds)
max_sdp = length(inds)
end
if (min_sdp == 0) || (min_sdp > length(inds))
min_sdp = length(inds)
end
elseif spec == :ExpPrimal
if length(inds) != 3
error("A cone $spec does not have exactly 3 indices ($(length(inds)))\n")
end
num_exp += 1
end
end
m.num_soc = num_soc + num_rot
m.num_exp = num_exp
m.num_sdp = num_sdp
if m.log_level > 1
@printf "\nCones summary:"
@printf "\n%-16s | %-7s | %-9s | %-9s\n" "Cone" "Count" "Min dim." "Max dim."
if num_soc > 0
@printf "%16s | %7d | %9d | %9d\n" "Second order" num_soc min_soc max_soc
end
if num_rot > 0
@printf "%16s | %7d | %9d | %9d\n" "Rotated S.O." num_rot min_rot max_rot
end
if num_exp > 0
@printf "%16s | %7d | %9d | %9d\n" "Primal expon." num_exp 3 3
end
if num_sdp > 0
min_side = round(Int, sqrt(1/4+2*min_sdp)-1/2)
max_side = round(Int, sqrt(1/4+2*max_sdp)-1/2)
@printf "%16s | %7d | %7s^2 | %7s^2\n" "Pos. semidef." num_sdp min_side max_side
end
end
if m.solve_relax || m.solve_subp
# Verify cone compatibility with conic solver
conic_spec = MathProgBase.supportedcones(m.cont_solver)
# Pajarito converts rotated SOCs to standard SOCs
if :SOC in conic_spec
push!(conic_spec, :SOCRotated)
end
# Error if a cone in data is not supported
for (spec, _) in vcat(cone_con, cone_var)
if !(spec in conic_spec)
error("Cones $spec are not supported by the specified conic solver (only $conic_spec)\n")
end
end
end
# Save original data
m.num_con_orig = length(b)
m.num_var_orig = length(c)
m.c_orig = c
m.A_orig = A_sp
m.b_orig = b
m.cone_con_orig = cone_con
m.cone_var_orig = cone_var
m.final_soln = fill(NaN, m.num_var_orig)
m.status = :Loaded
flush(STDOUT)
flush(STDERR)
end
# Store warm-start vector on original variables in Pajarito model
function MathProgBase.setwarmstart!(m::PajaritoConicModel, var_start::Vector{Real})
error("Warm-starts are not currently implemented in Pajarito (submit an issue)\n")
# # Check if vector can be loaded
# if m.status != :Loaded
# error("Must specify warm start right after loading problem\n")
# end
# if length(var_start) != m.num_var_orig
# error("Warm start vector length ($(length(var_start))) does not match number of variables ($(m.num_var_orig))\n")
# end
#
# m.var_start = var_start
end
# Store variable type vector on original variables in Pajarito model
function MathProgBase.setvartype!(m::PajaritoConicModel, var_types::Vector{Symbol})
if m.status != :Loaded
error("Must call setvartype! immediately after loadproblem!\n")
end
if length(var_types) != m.num_var_orig
error("Variable types vector length ($(length(var_types))) does not match number of variables ($(m.num_var_orig))\n")
end
num_cont = 0
num_bin = 0
num_int = 0
for vtype in var_types
if vtype == :Cont
num_cont += 1
elseif vtype == :Bin
num_bin += 1
elseif vtype == :Int
num_int += 1
else
error("A variable type ($vtype) is invalid; variable types must be :Bin, :Int, or :Cont\n")
end
end
if (num_bin + num_int) == 0
error("No variable types are :Bin or :Int; use the continuous conic solver directly if your problem is continuous\n")
end
if m.log_level > 1
@printf "\nVariable types:\n"
if num_cont > 0
@printf "%16s | %7d\n" "continuous" num_cont
end
if num_bin > 0
@printf "%16s | %7d\n" "binary" num_bin
end
if num_int > 0
@printf "%16s | %7d\n" "integer" num_int
end
end
m.var_types = var_types
flush(STDOUT)
flush(STDERR)
end
# Solve, given the initial conic model data and the variable types vector and possibly a warm-start vector
function MathProgBase.optimize!(m::PajaritoConicModel)
if m.status != :Loaded
error("Must call optimize! function after setvartype! and loadproblem!\n")
end
if isempty(m.var_types)
error("Variable types were not specified (use setvartype! function)\n")
end
m.logs[:total] = time()
# Transform data
if m.log_level > 1
@printf "\n%-33s" "Transforming data..."
end
tic()
(c_new, A_new, b_new, cone_con_new, cone_var_new, keep_cols, var_types_new, cols_cont, cols_int) = transform_data(copy(m.c_orig), copy(m.A_orig), copy(m.b_orig), deepcopy(m.cone_con_orig), deepcopy(m.cone_var_orig), copy(m.var_types), m.solve_relax)
m.logs[:data_trans] += toq()
if m.log_level > 1
@printf "%6.2fs\n" m.logs[:data_trans]
end
if m.solve_subp
# Create conic subproblem
if m.log_level > 1
@printf "\n%-33s" "Creating conic subproblem..."
end
tic()
map_rows_subp = create_conicsub_data!(m, c_new, A_new, b_new, cone_con_new, cone_var_new, var_types_new, cols_cont, cols_int)
if m.dualize_subp
solver_conicsub = ConicDualWrapper(conicsolver=m.cont_solver)
else
solver_conicsub = m.cont_solver
end
m.model_conic = MathProgBase.ConicModel(solver_conicsub)
if method_exists(MathProgBase.setbvec!, (typeof(m.model_conic), Vector{Float64}))
# Can use setbvec! on the conic subproblem model: load it
m.update_conicsub = true
MathProgBase.loadproblem!(m.model_conic, m.c_sub_cont, m.A_sub_cont, m.b_sub, m.cone_con_sub, m.cone_var_sub)
else
m.update_conicsub = false
end
m.logs[:data_conic] += toq()
if m.log_level > 1
@printf "%6.2fs\n" m.logs[:data_conic]
end
else
map_rows_subp = zeros(Int, length(b_new))
m.c_sub_cont = c_new[cols_cont]
m.c_sub_int = c_new[cols_int]
end
# Create MIP model
if m.log_level > 1
@printf "\n%-33s" "Building MIP model..."
end
tic()
(r_idx_soc_relx, t_idx_soc_relx, r_idx_exp_relx, s_idx_exp_relx, t_idx_exp_relx, t_idx_sdp_relx) = create_mip_data!(m, c_new, A_new, b_new, cone_con_new, cone_var_new, var_types_new, map_rows_subp, cols_cont, cols_int)
m.logs[:data_mip] += toq()
if m.log_level > 1
@printf "%6.2fs\n" m.logs[:data_mip]
end
flush(STDOUT)
flush(STDERR)
# Calculate infeasible and optimal subproblem K* cuts scaling factors
m.inf_subp_scale = m.mip_feas_tol*m.scale_subp_factor
m.opt_subp_scale = m.mip_feas_tol/m.rel_gap*m.scale_subp_factor
if m.all_disagg
m.inf_subp_scale *= m.num_cones
m.opt_subp_scale *= m.num_cones
end
if m.solve_relax
# Solve relaxed conic problem, proceed with algorithm if optimal or suboptimal, else finish
if m.log_level > 1
@printf "\n%-33s" "Solving conic relaxation..."
end
tic()
if m.dualize_relax
solver_relax = ConicDualWrapper(conicsolver=m.cont_solver)
else
solver_relax = m.cont_solver
end
model_relax = MathProgBase.ConicModel(solver_relax)
MathProgBase.loadproblem!(model_relax, c_new, A_new, b_new, cone_con_new, cone_var_new)
MathProgBase.optimize!(model_relax)
m.logs[:relax_solve] += toq()
if m.log_level > 1
@printf "%6.2fs\n" m.logs[:relax_solve]
end
status_relax = MathProgBase.status(model_relax)
if status_relax == :Infeasible
if m.log_level > 0
println("Initial conic relaxation status was $status_relax\n")
end
m.status = :Infeasible
elseif status_relax == :Unbounded
warn("Initial conic relaxation status was $status_relax\n")
m.status = :UnboundedRelax
else
# if status_relax in (:Optimal, :Suboptimal, :PDFeas, :DualFeas)
if m.log_level > 2
@printf " - Relaxation status = %14s\n" status_relax
end
dual_conic = Float64[]
try
dual_conic = MathProgBase.getdual(model_relax)
if any(isnan, dual_conic)
dual_conic = Float64[]
end
end
if !isempty(dual_conic) && !any(isnan, dual_conic)
m.status = :SolvedRelax
dual_obj = -dot(b_new, dual_conic)
m.best_bound = dual_obj
if m.log_level > 2
@printf " - Relaxation bound = %14.6f\n" dual_obj
end
# Optionally scale dual
if m.scale_subp_cuts
# Rescale by number of cones / absval of full conic objective
scale!(dual_conic, m.opt_subp_scale/(abs(dual_obj) + 1e-5))
end
# Add relaxation cut(s)
tic()
m.aggregate_cut = JuMP.AffExpr(0)
for n in 1:m.num_soc
u_val = dual_conic[r_idx_soc_relx[n]]
w_val = dual_conic[t_idx_soc_relx[n]]
add_subp_cut_soc!(m, m.r_soc[n], m.t_soc[n], m.pi_soc[n], m.rho_soc[n], u_val, w_val)
end
for n in 1:m.num_exp
u_val = dual_conic[r_idx_exp_relx[n]]
v_val = dual_conic[s_idx_exp_relx[n]]
w_val = dual_conic[t_idx_exp_relx[n]]
add_subp_cut_exp!(m, m.r_exp[n], m.s_exp[n], m.t_exp[n], u_val, v_val, w_val)
end
for n in 1:m.num_sdp
# Get smat space dual
W_val = make_smat!(m.smat_sdp[n], dual_conic[t_idx_sdp_relx[n]])
add_subp_cut_sdp!(m, m.T_sdp[n], W_val)
end
if !m.all_disagg
@constraint(m.model_mip, m.aggregate_cut >= 0)
end
m.logs[:relax_cuts] += toq()
else
m.status = :FailedRelax
end
end
# Free the conic model
if applicable(MathProgBase.freemodel!, model_relax)
MathProgBase.freemodel!(model_relax)
end
end
flush(STDOUT)
flush(STDERR)
# Finish if exceeded timeout option, else proceed to MIP solves if not infeasible
if (time() - m.logs[:total]) > m.timeout
m.status = :UserLimit
elseif m.status != :Infeasible
# Initialize and begin iterative or MIP-solver-driven algorithm
m.oa_started = true
m.new_incumb = false
m.cache_dual = Dict{Vector{Float64},Vector{Float64}}()
if m.log_level >= 1
@printf "\nStarting %s algorithm\n" (m.mip_solver_drives ? "MIP-solver-driven" : "iterative")
end
status_oa = m.mip_solver_drives ? solve_mip_driven!(m) : solve_iterative!(m)
if status_oa == :Infeasible
m.status = :Infeasible
elseif status_oa == :Unbounded
if !m.solve_relax
warn("MIP solver returned status $status_oa; try using the conic relaxation cuts (set solve_relax = true)\n")
elseif m.status == :SolvedRelax
warn("MIP solver returned status $status_oa but the conic relaxation solve succeeded; try tightening the conic solver tolerances (or submit an issue)\n")
else
warn("MIP solver returned status $status_oa and the conic relaxation solve failed; use a conic solver that succeeds on the relaxation (or submit an issue)\n")
end
m.status = :UnboundedOA
elseif (status_oa == :UserLimit) || (status_oa == :Optimal) || (status_oa == :Suboptimal) || (status_oa == :FailedOA)
if (status_oa == :Suboptimal) || (status_oa == :FailedOA)
warn("Pajarito failed to converge to the desired relative gap; try turning off the MIP solver's presolve functionality\n")
end
if isfinite(m.best_obj)
# Have a best feasible solution, update final solution on original variables
soln_new = zeros(length(c_new))
soln_new[cols_int] = m.best_int
soln_new[cols_cont] = m.best_cont
m.final_soln = zeros(m.num_var_orig)
m.final_soln[keep_cols] = soln_new
end
m.status = status_oa
else
warn("MIP solver returned status $status_oa, which Pajarito does not handle\n")
m.status = :FailedMIP
end
end
flush(STDOUT)
flush(STDERR)
# Finish timer and print summary
m.logs[:total] = time() - m.logs[:total]
print_finish(m)
flush(STDOUT)
flush(STDERR)
end
MathProgBase.numconstr(m::PajaritoConicModel) = m.num_con_orig
MathProgBase.numvar(m::PajaritoConicModel) = m.num_var_orig
MathProgBase.status(m::PajaritoConicModel) = m.status
MathProgBase.getsolvetime(m::PajaritoConicModel) = m.logs[:total]
MathProgBase.getobjval(m::PajaritoConicModel) = m.best_obj
MathProgBase.getobjbound(m::PajaritoConicModel) = m.best_bound
MathProgBase.getsolution(m::PajaritoConicModel) = m.final_soln
function MathProgBase.getnodecount(m::PajaritoConicModel)
if !m.mip_solver_drives
error("Node count not defined when using iterative algorithm\n")
else
return MathProgBase.getnodecount(m.model_mip)
end
end
#=========================================================
Data and model functions
=========================================================#
# Transform/preprocess data
function transform_data(c_orig, A_orig, b_orig, cone_con_orig, cone_var_orig, var_types, solve_relax)
(A_I, A_J, A_V) = findnz(A_orig)
num_con_new = length(b_orig)
b_new = b_orig
cone_con_new = Tuple{Symbol,Vector{Int}}[(spec, vec(collect(inds))) for (spec, inds) in cone_con_orig]
num_var_new = 0
cone_var_new = Tuple{Symbol,Vector{Int}}[]
old_new_col = zeros(Int, length(c_orig))
vars_nonneg = Int[]
vars_nonpos = Int[]
vars_free = Int[]
for (spec, cols) in cone_var_orig
# Ignore zero variable cones
if spec != :Zero
vars_nonneg = Int[]
vars_nonpos = Int[]
vars_free = Int[]
for j in cols
if var_types[j] == :Bin
# Put binary vars in NonNeg var cone, unless the original var cone was NonPos in which case the binary vars are fixed at zero
if spec != :NonPos
num_var_new += 1
old_new_col[j] = num_var_new
push!(vars_nonneg, j)
end
else
# Put non-binary vars in NonNeg or NonPos or Free var cone
num_var_new += 1
old_new_col[j] = num_var_new
if spec == :NonNeg
push!(vars_nonneg, j)
elseif spec == :NonPos
push!(vars_nonpos, j)
else
push!(vars_free, j)
end
end
end
if !isempty(vars_nonneg)
push!(cone_var_new, (:NonNeg, vars_nonneg))
end
if !isempty(vars_nonpos)
push!(cone_var_new, (:NonPos, vars_nonpos))
end
if !isempty(vars_free)
push!(cone_var_new, (:Free, vars_free))
end
if (spec != :Free) && (spec != :NonNeg) && (spec != :NonPos)
# Convert nonlinear var cone to constraint cone
push!(cone_con_new, (spec, collect((num_con_new + 1):(num_con_new + length(cols)))))
for j in cols
num_con_new += 1
push!(A_I, num_con_new)
push!(A_J, j)
push!(A_V, -1.)
push!(b_new, 0.)
end
end
end
end
keep_cols = find(old_new_col)
c_new = c_orig[keep_cols]
var_types_new = var_types[keep_cols]
A_full = sparse(A_I, A_J, A_V, num_con_new, length(c_orig))
A_keep = A_full[:, keep_cols]
dropzeros!(A_keep)
(A_I, A_J, A_V) = findnz(A_keep)
# Convert SOCRotated cones to SOC cones (MathProgBase definitions)
has_rsoc = false
socr_rows = Vector{Int}[]
for n_cone in 1:length(cone_con_new)
(spec, rows) = cone_con_new[n_cone]
if spec == :SOCRotated
cone_con_new[n_cone] = (:SOC, rows)
push!(socr_rows, rows)
has_rsoc = true
end
end
if has_rsoc
row_to_nzind = map(t -> Int[], 1:num_con_new)
for (ind, i) in enumerate(A_I)
push!(row_to_nzind[i], ind)
end
for rows in socr_rows
inds_1 = row_to_nzind[rows[1]]
inds_2 = row_to_nzind[rows[2]]
# Use old constraint cone SOCRotated for (sqrt2inv*(p1+p2),sqrt2inv*(-p1+p2),q) in SOC
for ind in inds_1
A_V[ind] *= sqrt2inv
end
for ind in inds_2
A_V[ind] *= sqrt2inv
end
append!(A_I, fill(rows[1], length(inds_2)))
append!(A_J, A_J[inds_2])
append!(A_V, A_V[inds_2])
append!(A_I, fill(rows[2], length(inds_1)))
append!(A_J, A_J[inds_1])
append!(A_V, -A_V[inds_1])
b1 = b_new[rows[1]]
b2 = b_new[rows[2]]
b_new[rows[1]] = sqrt2inv*(b1 + b2)
b_new[rows[2]] = sqrt2inv*(-b1 + b2)
end
end
if solve_relax
# Preprocess to tighten bounds on binary and integer variables in conic relaxation
# Detect isolated row nonzeros with nonzero b
row_slck_count = zeros(Int, num_con_new)
for (ind, i) in enumerate(A_I)
if (A_V[ind] != 0.) && (b_new[i] != 0.)
if row_slck_count[i] == 0
row_slck_count[i] = ind
elseif row_slck_count[i] > 0
row_slck_count[i] = -1
end
end
end
bin_set_upper = falses(length(var_types_new))
# For each bound-type constraint, tighten by rounding
for (spec, rows) in cone_con_new
if (spec != :NonNeg) && (spec != :NonPos)
continue
end
for i in rows
if row_slck_count[i] > 0
# Isolated variable x_j with b_i - a_ij*x_j in spec, b_i & a_ij nonzero
j = A_J[row_slck_count[i]]
type_j = var_types_new[j]
bound_j = b_new[i] / A_V[row_slck_count[i]]
if (spec == :NonNeg) && (A_V[row_slck_count[i]] > 0) || (spec == :NonPos) && (A_V[row_slck_count[i]] < 0)
# Upper bound: b_i/a_ij >= x_j
if type_j == :Bin
# Tighten binary upper bound to 1
if spec == :NonNeg
# 1 >= x_j
b_new[i] = 1.
A_V[row_slck_count[i]] = 1.
else
# -1 <= -x_j
b_new[i] = -1.
A_V[row_slck_count[i]] = -1.
end
bin_set_upper[j] = true
elseif type_j == :Int
# Tighten binary or integer upper bound by rounding down
if spec == :NonNeg
# floor >= x_j
b_new[i] = floor(bound_j)
A_V[row_slck_count[i]] = 1.
else
# -floor <= -x_j
b_new[i] = -floor(bound_j)
A_V[row_slck_count[i]] = -1.
end
end
else
# Lower bound: b_i/a_ij <= x_j
if type_j != :Cont
# Tighten binary or integer lower bound by rounding up
if spec == :NonPos
# ceil <= x_j
b_new[i] = ceil(bound_j)
A_V[row_slck_count[i]] = 1.
else
# -ceil >= -x_j
b_new[i] = -ceil(bound_j)
A_V[row_slck_count[i]] = -1.
end
end
end
end
end
end
# For any binary variables without upper bound set, add 1 >= x_j to constraint cones
num_con_prev = num_con_new
for (j, j_type) in enumerate(var_types_new)
if (j_type == :Bin) && !bin_set_upper[j]
num_con_new += 1
push!(A_I, num_con_new)
push!(A_J, j)
push!(A_V, 1.)
push!(b_new, 1.)
end
end
if num_con_new > num_con_prev
push!(cone_con_new, (:NonNeg, collect((num_con_prev + 1):num_con_new)))
end
end
A_new = sparse(A_I, A_J, A_V, num_con_new, num_var_new)
dropzeros!(A_new)
# Collect indices of continuous and integer variables
cols_cont = find(vt -> (vt == :Cont), var_types_new)
cols_int = find(vt -> (vt != :Cont), var_types_new)
return (c_new, A_new, b_new, cone_con_new, cone_var_new, keep_cols, var_types_new, cols_cont, cols_int)
end
# Create conic subproblem data
function create_conicsub_data!(m, c_new::Vector{Float64}, A_new::SparseMatrixCSC{Float64,Int}, b_new::Vector{Float64}, cone_con_new::Vector{Tuple{Symbol,Vector{Int}}}, cone_var_new::Vector{Tuple{Symbol,Vector{Int}}}, var_types_new::Vector{Symbol}, cols_cont::Vector{Int}, cols_int::Vector{Int})
# Build new subproblem variable cones by removing integer variables
num_cont = 0
cone_var_sub = Tuple{Symbol,Vector{Int}}[]
for (spec, cols) in cone_var_new
cols_cont_new = Int[]
for j in cols
if var_types_new[j] == :Cont
num_cont += 1
push!(cols_cont_new, num_cont)
end
end
if !isempty(cols_cont_new)
push!(cone_var_sub, (spec, cols_cont_new))
end
end
# Determine "empty" rows with no nonzero coefficients on continuous variables
(A_cont_I, _, A_cont_V) = findnz(A_new[:, cols_cont])
num_con_new = size(A_new, 1)
rows_nz = falses(num_con_new)
for (i, v) in zip(A_cont_I, A_cont_V)
if !rows_nz[i] && (v != 0)
rows_nz[i] = true
end
end
# Build new subproblem constraint cones by removing empty rows
num_full = 0
rows_full = Int[]
cone_con_sub = Tuple{Symbol,Vector{Int}}[]
map_rows_subp = Vector{Int}(num_con_new)
for (spec, rows) in cone_con_new
if (spec == :Zero) || (spec == :NonNeg) || (spec == :NonPos)
rows_full_new = Int[]
for i in rows
if rows_nz[i]
push!(rows_full, i)
num_full += 1
push!(rows_full_new, num_full)
end
end
if !isempty(rows_full_new)
push!(cone_con_sub, (spec, rows_full_new))
end
else
map_rows_subp[rows] = collect((num_full + 1):(num_full + length(rows)))
push!(cone_con_sub, (spec, collect((num_full + 1):(num_full + length(rows)))))
append!(rows_full, rows)
num_full += length(rows)
end
end
# Store conic data