/
MPS.jl
1757 lines (1630 loc) · 55.2 KB
/
MPS.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 (c) 2017: Miles Lubin and contributors
# Copyright (c) 2017: Google Inc.
#
# Use of this source code is governed by an MIT-style license that can be found
# in the LICENSE.md file or at https://opensource.org/licenses/MIT.
module MPS
import ..FileFormats
import MathOptInterface as MOI
# Julia 1.6 removes Grisu from Base. Previously, we went
# print_shortest(io, x) = Base.Grisu.print_shortest(io, x)
# To avoid adding Grisu as a dependency, use the following printing heuristic.
# TODO(odow): consider printing 1.0 as 1.0 instead of 1, i.e., without the
# rounding branch.
function print_shortest(io::IO, x::Real)
if isinteger(x) && (typemin(Int) <= x <= typemax(Int))
print(io, round(Int, x))
else
print(io, x)
end
return
end
const IndicatorLessThanTrue{T} =
MOI.Indicator{MOI.ACTIVATE_ON_ONE,MOI.LessThan{T}}
const IndicatorGreaterThanTrue{T} =
MOI.Indicator{MOI.ACTIVATE_ON_ONE,MOI.GreaterThan{T}}
const IndicatorEqualToTrue{T} =
MOI.Indicator{MOI.ACTIVATE_ON_ONE,MOI.EqualTo{T}}
const IndicatorLessThanFalse{T} =
MOI.Indicator{MOI.ACTIVATE_ON_ZERO,MOI.LessThan{T}}
const IndicatorGreaterThanFalse{T} =
MOI.Indicator{MOI.ACTIVATE_ON_ZERO,MOI.GreaterThan{T}}
const IndicatorEqualToFalse{T} =
MOI.Indicator{MOI.ACTIVATE_ON_ZERO,MOI.EqualTo{T}}
MOI.Utilities.@model(
Model,
(MOI.ZeroOne, MOI.Integer),
(MOI.EqualTo, MOI.GreaterThan, MOI.LessThan, MOI.Interval),
(),
(
MOI.SOS1,
MOI.SOS2,
IndicatorLessThanTrue,
IndicatorLessThanFalse,
IndicatorGreaterThanTrue,
IndicatorGreaterThanFalse,
IndicatorEqualToTrue,
IndicatorEqualToFalse,
),
(),
(MOI.ScalarAffineFunction, MOI.ScalarQuadraticFunction),
(MOI.VectorOfVariables,),
(MOI.VectorAffineFunction,)
)
function MOI.supports_constraint(
::Model{T},
::Type{MOI.VectorAffineFunction{T}},
::Type{<:Union{MOI.SOS1{T},MOI.SOS2{T}}},
) where {T}
return false
end
function MOI.supports_constraint(
::Model{T},
::Type{MOI.VectorOfVariables},
::Type{
<:Union{
IndicatorLessThanTrue{T},
IndicatorLessThanFalse{T},
IndicatorGreaterThanTrue{T},
IndicatorGreaterThanFalse{T},
IndicatorEqualToTrue{T},
IndicatorEqualToFalse{T},
},
},
) where {T}
return false
end
@enum(
QuadraticFormat,
kQuadraticFormatCPLEX,
kQuadraticFormatGurobi,
kQuadraticFormatMosek,
)
struct Options
warn::Bool
objsense::Bool
generic_names::Bool
quadratic_format::QuadraticFormat
end
function get_options(m::Model)
return get(
m.ext,
:MPS_OPTIONS,
Options(false, false, false, kQuadraticFormatGurobi),
)
end
"""
Model(; kwargs...)
Create an empty instance of FileFormats.MPS.Model.
Keyword arguments are:
- `warn::Bool=false`: print a warning when variables or constraints are renamed.
- `print_objsense::Bool=false`: print the OBJSENSE section when writing
- `generic_names::Bool=false`: strip all names in the model and replace them
with the generic names `C\$i` and `R\$i` for the i'th column and row
respectively.
- `quadratic_format::QuadraticFormat = kQuadraticFormatGurobi`: specify the
solver-specific extension used when writing the quadratic components of the
model. Options are `kQuadraticFormatGurobi`, `kQuadraticFormatCPLEX`, and
`kQuadraticFormatMosek`.
"""
function Model(;
warn::Bool = false,
print_objsense::Bool = false,
generic_names::Bool = false,
quadratic_format::QuadraticFormat = kQuadraticFormatGurobi,
)
model = Model{Float64}()
model.ext[:MPS_OPTIONS] =
Options(warn, print_objsense, generic_names, quadratic_format)
return model
end
function Base.show(io::IO, ::Model)
print(io, "A Mathematical Programming System (MPS) model")
return
end
@enum(VType, VTYPE_CONTINUOUS, VTYPE_INTEGER, VTYPE_BINARY)
# The card logic is as follows: where possible, try to fit within the strict MPS
# field limits. That means fields start at columns 2, 5, 15, 25, 40, and 50.
# However, since most readers default to loose MPS, make sure each field is
# separated by at least one space.
function pad_field(field, n)
return length(field) < n ? field : field * " "
end
struct Card
f1::String
f2::String
f3::String
f4::String
f5::String
f6::String
num_fields::Int
function Card(;
f1::String = "",
f2::String = "",
f3::String = "",
f4::String = "",
f5::String = "",
f6::String = "",
)
num_fields = isempty(f1) ? 0 : 1
num_fields = isempty(f2) ? num_fields : 2
num_fields = isempty(f3) ? num_fields : 3
num_fields = isempty(f4) ? num_fields : 4
num_fields = isempty(f5) ? num_fields : 5
num_fields = isempty(f6) ? num_fields : 6
return new(
pad_field(f1, 3),
pad_field(f2, 10),
pad_field(f3, 10),
pad_field(f4, 15),
pad_field(f5, 10),
pad_field(f6, Inf),
num_fields,
)
end
end
function Base.show(io::IO, card::Card)
# if card.num_fields == 0
# return
# elseif card.num_fields == 1
# print(io, " ", card.f1)
# return
# end
print(io, " ", rpad(card.f1, 3))
if card.num_fields == 2
print(io, card.f2)
return
end
print(io, rpad(card.f2, 10))
if card.num_fields == 3
print(io, card.f3)
return
end
print(io, rpad(card.f3, 10))
if card.num_fields == 4
print(io, card.f4)
return
end
print(io, rpad(card.f4, 15))
if card.num_fields == 5
print(io, card.f5)
return
end
print(io, rpad(card.f5, 10))
# if card.num_fields == 6
# print(io, card.f6)
# end
return
end
# ==============================================================================
#
# Base.write
#
# ==============================================================================
"""
Base.write(io::IO, model::FileFormats.MPS.Model)
Write `model` to `io` in the MPS file format.
"""
function Base.write(io::IO, model::Model)
options = get_options(model)
if options.generic_names
FileFormats.create_generic_names(model)
else
FileFormats.create_unique_names(
model;
warn = options.warn,
replacements = Function[s->replace(s, ' ' => '_')],
)
end
ordered_names = String[]
names = Dict{MOI.VariableIndex,String}()
var_to_column = Dict{MOI.VariableIndex,Int}()
for (i, x) in enumerate(MOI.get(model, MOI.ListOfVariableIndices()))
n = MOI.get(model, MOI.VariableName(), x)
push!(ordered_names, n)
names[x] = n
var_to_column[x] = i
end
write_model_name(io, model)
flip_obj = false
if options.objsense
if MOI.get(model, MOI.ObjectiveSense()) == MOI.MAX_SENSE
println(io, "OBJSENSE\n MAX")
else
println(io, "OBJSENSE\n MIN")
end
else
flip_obj = MOI.get(model, MOI.ObjectiveSense()) == MOI.MAX_SENSE
end
write_rows(io, model)
obj_const, indicators =
write_columns(io, model, flip_obj, ordered_names, names)
write_rhs(io, model, obj_const)
write_ranges(io, model)
write_bounds(io, model, ordered_names, names)
write_quadobj(io, model, ordered_names, var_to_column)
if options.quadratic_format != kQuadraticFormatCPLEX
# Gurobi needs qcons _after_ quadobj and _before_ SOS.
write_quadcons(io, model, ordered_names, var_to_column)
end
write_sos(io, model, names)
if options.quadratic_format == kQuadraticFormatCPLEX
# CPLEX needs qcons _after_ SOS.
write_quadcons(io, model, ordered_names, var_to_column)
end
write_indicators(io, indicators)
println(io, "ENDATA")
return
end
# ==============================================================================
# Model name
# ==============================================================================
function write_model_name(io::IO, model::Model)
model_name = MOI.get(model, MOI.Name())
println(io, rpad("NAME", 14), model_name)
return
end
# ==============================================================================
# ROWS
# ==============================================================================
const SET_TYPES = (
(MOI.LessThan{Float64}, "L"),
(MOI.GreaterThan{Float64}, "G"),
(MOI.EqualTo{Float64}, "E"),
(MOI.Interval{Float64}, "L"), # See the note in the RANGES section.
)
const FUNC_TYPES =
(MOI.ScalarAffineFunction{Float64}, MOI.ScalarQuadraticFunction{Float64})
function _write_rows(io, model, F, S, sense_char)
for index in MOI.get(model, MOI.ListOfConstraintIndices{F,S}())
row_name = MOI.get(model, MOI.ConstraintName(), index)
if row_name == ""
error("Row name is empty: $(index).")
end
println(io, Card(f1 = sense_char, f2 = row_name))
end
return
end
function _write_rows(io, model, F, S::Type{MOI.Interval{Float64}}, ::Any)
for index in MOI.get(model, MOI.ListOfConstraintIndices{F,S}())
row_name = MOI.get(model, MOI.ConstraintName(), index)
set = MOI.get(model, MOI.ConstraintSet(), index)
if set.lower == -Inf && set.upper == Inf
println(io, Card(f1 = "N", f2 = row_name))
elseif set.upper == Inf
println(io, Card(f1 = "G", f2 = row_name))
elseif set.lower == -Inf
println(io, Card(f1 = "L", f2 = row_name))
else
println(io, Card(f1 = "L", f2 = row_name))
end
end
return
end
function write_rows(io::IO, model::Model)
println(io, "ROWS")
println(io, Card(f1 = "N", f2 = "OBJ"))
for (set_type, sense_char) in SET_TYPES
for F in FUNC_TYPES
_write_rows(io, model, F, set_type, sense_char)
end
end
F = MOI.VectorAffineFunction{Float64}
_write_rows(io, model, F, IndicatorLessThanTrue{Float64}, "L")
_write_rows(io, model, F, IndicatorLessThanFalse{Float64}, "L")
_write_rows(io, model, F, IndicatorGreaterThanTrue{Float64}, "G")
_write_rows(io, model, F, IndicatorGreaterThanFalse{Float64}, "G")
_write_rows(io, model, F, IndicatorEqualToTrue{Float64}, "E")
_write_rows(io, model, F, IndicatorEqualToFalse{Float64}, "E")
return
end
# ==============================================================================
# COLUMNS
# ==============================================================================
function _list_of_integer_variables(model, names, integer_variables, S)
for index in
MOI.get(model, MOI.ListOfConstraintIndices{MOI.VariableIndex,S}())
v_index = MOI.get(model, MOI.ConstraintFunction(), index)
push!(integer_variables, names[v_index])
end
return
end
function list_of_integer_variables(model::Model, names)
integer_variables = Set{String}()
for S in (MOI.ZeroOne, MOI.Integer)
_list_of_integer_variables(model, names, integer_variables, S)
end
return integer_variables
end
function _extract_terms(
v_names::Dict{MOI.VariableIndex,String},
coefficients::Dict{String,Vector{Tuple{String,Float64}}},
row_name::String,
func::MOI.ScalarAffineFunction,
flip_sign::Bool = false,
)
for term in func.terms
variable_name = v_names[term.variable]
coef = flip_sign ? -term.coefficient : term.coefficient
push!(coefficients[variable_name], (row_name, coef))
end
return
end
function _extract_terms(
v_names::Dict{MOI.VariableIndex,String},
coefficients::Dict{String,Vector{Tuple{String,Float64}}},
row_name::String,
func::MOI.ScalarQuadraticFunction,
flip_sign::Bool = false,
)
for term in func.affine_terms
variable_name = v_names[term.variable]
coef = flip_sign ? -term.coefficient : term.coefficient
push!(coefficients[variable_name], (row_name, coef))
end
return
end
function _collect_coefficients(
model,
F,
S,
v_names::Dict{MOI.VariableIndex,String},
coefficients::Dict{String,Vector{Tuple{String,Float64}}},
)
for index in MOI.get(model, MOI.ListOfConstraintIndices{F,S}())
row_name = MOI.get(model, MOI.ConstraintName(), index)
func = MOI.get(model, MOI.ConstraintFunction(), index)
_extract_terms(v_names, coefficients, row_name, func)
end
return
end
_activation_condition(::Type{<:MOI.Indicator{A}}) where {A} = A
function _collect_indicator(model, S, names, coefficients, indicators)
F = MOI.VectorAffineFunction{Float64}
for index in MOI.get(model, MOI.ListOfConstraintIndices{F,S}())
row_name = MOI.get(model, MOI.ConstraintName(), index)
func = MOI.get(model, MOI.ConstraintFunction(), index)
funcs = MOI.Utilities.eachscalar(func)
z = convert(MOI.VariableIndex, funcs[1])
_extract_terms(names, coefficients, row_name, funcs[2])
condition = _activation_condition(S)
push!(
indicators,
(row_name, MOI.get(model, MOI.VariableName(), z), condition),
)
end
return
end
function _get_objective(model)
F = MOI.get(model, MOI.ObjectiveFunctionType())
f = MOI.get(model, MOI.ObjectiveFunction{F}())
if f isa MOI.VariableIndex
return convert(MOI.ScalarAffineFunction{Float64}, f)
end
return f
end
function write_columns(io::IO, model::Model, flip_obj, ordered_names, names)
indicators = Tuple{String,String,MOI.ActivationCondition}[]
coefficients = Dict{String,Vector{Tuple{String,Float64}}}(
n => Tuple{String,Float64}[] for n in ordered_names
)
# Build constraint coefficients
for (S, _) in SET_TYPES
for F in FUNC_TYPES
_collect_coefficients(model, F, S, names, coefficients)
end
end
for S in (
IndicatorLessThanTrue{Float64},
IndicatorLessThanFalse{Float64},
IndicatorGreaterThanTrue{Float64},
IndicatorGreaterThanFalse{Float64},
IndicatorEqualToTrue{Float64},
IndicatorEqualToFalse{Float64},
)
_collect_indicator(model, S, names, coefficients, indicators)
end
# Build objective
obj_func = _get_objective(model)
_extract_terms(names, coefficients, "OBJ", obj_func, flip_obj)
integer_variables = list_of_integer_variables(model, names)
println(io, "COLUMNS")
int_open = false
for variable in ordered_names
is_int = variable in integer_variables
if is_int && !int_open
println(io, Card(f2 = "MARKER", f3 = "'MARKER'", f5 = "'INTORG'"))
int_open = true
elseif !is_int && int_open
println(io, Card(f2 = "MARKER", f3 = "'MARKER'", f5 = "'INTEND'"))
int_open = false
end
if length(coefficients[variable]) == 0
# Every variable must appear in the COLUMNS section! Add a 0
# objective coefficient instead.
println(io, Card(f2 = variable, f3 = "OBJ", f4 = "0"))
end
for (constraint, coefficient) in coefficients[variable]
println(
io,
Card(
f2 = variable,
f3 = constraint,
f4 = sprint(print_shortest, coefficient),
),
)
end
end
return obj_func.constant, indicators
end
# ==============================================================================
# RHS
# ==============================================================================
_value(set::MOI.LessThan) = set.upper
_value(set::MOI.GreaterThan) = set.lower
_value(set::MOI.EqualTo) = set.value
_value(set::MOI.Indicator) = _value(set.set)
function _write_rhs(io, model, F, S)
for index in MOI.get(model, MOI.ListOfConstraintIndices{F,S}())
row_name = MOI.get(model, MOI.ConstraintName(), index)
set = MOI.get(model, MOI.ConstraintSet(), index)
println(
io,
Card(
f2 = "rhs",
f3 = row_name,
f4 = sprint(print_shortest, _value(set)),
),
)
end
return
end
function _write_rhs(io, model, F, S::Type{MOI.Interval{Float64}})
for index in MOI.get(model, MOI.ListOfConstraintIndices{F,S}())
row_name = MOI.get(model, MOI.ConstraintName(), index)
set = MOI.get(model, MOI.ConstraintSet(), index)
if set.lower == -Inf && set.upper == Inf
# No RHS. Free row
elseif set.upper == Inf
value = sprint(print_shortest, set.lower)
println(io, Card(f2 = "rhs", f3 = row_name, f4 = value))
elseif set.lower == -Inf
value = sprint(print_shortest, set.upper)
println(io, Card(f2 = "rhs", f3 = row_name, f4 = value))
else
value = sprint(print_shortest, set.upper)
println(io, Card(f2 = "rhs", f3 = row_name, f4 = value))
end
end
return
end
function write_rhs(io::IO, model::Model, obj_const)
println(io, "RHS")
for (set_type, _) in SET_TYPES
for F in FUNC_TYPES
_write_rhs(io, model, F, set_type)
end
end
F = MOI.VectorAffineFunction{Float64}
_write_rhs(io, model, F, IndicatorLessThanTrue{Float64})
_write_rhs(io, model, F, IndicatorLessThanFalse{Float64})
_write_rhs(io, model, F, IndicatorGreaterThanTrue{Float64})
_write_rhs(io, model, F, IndicatorGreaterThanFalse{Float64})
_write_rhs(io, model, F, IndicatorEqualToTrue{Float64})
_write_rhs(io, model, F, IndicatorEqualToFalse{Float64})
# Objective constants are added to the RHS as a negative offset.
# https://www.ibm.com/docs/en/icos/20.1.0?topic=standard-records-in-mps-format
if !iszero(obj_const)
println(
io,
Card(
f2 = "rhs",
f3 = "OBJ",
f4 = sprint(print_shortest, -obj_const),
),
)
end
return
end
# ==============================================================================
# RANGES
#
# Here is how RANGE information is encoded.
#
# Row type | Range value | lower bound | upper bound
# ------------------------------------------------------
# G | +/- | rhs | rhs + |range|
# L | +/- | rhs - |range| | rhs
# E | + | rhs | rhs + range
# E | - | rhs + range | rhs
#
# We elect to write out F-in-Interval constraints in terms of LessThan (L)
# constraints with a range shift. The RHS term is set to the upper bound, and
# the RANGE term to upper - lower.
# ==============================================================================
function _write_ranges(io::IO, model::Model, ::Type{F}) where {F}
cis = MOI.get(model, MOI.ListOfConstraintIndices{F,MOI.Interval{Float64}}())
for index in cis
set = MOI.get(model, MOI.ConstraintSet(), index)::MOI.Interval{Float64}
if isfinite(set.upper - set.lower)
# We only need to write the range if the bounds are both finite
row_name = MOI.get(model, MOI.ConstraintName(), index)
range = sprint(print_shortest, set.upper - set.lower)
println(io, Card(f2 = "rhs", f3 = row_name, f4 = range))
end
end
return
end
function write_ranges(io::IO, model::Model)
println(io, "RANGES")
for F in FUNC_TYPES
_write_ranges(io, model, F)
end
return
end
# ==============================================================================
# BOUNDS
# Variables default to [0, ∞).
# FR free variable -∞ < x < ∞
# FX fixed variable x == b
# MI lower bound -inf -∞ < x
# UP upper bound x <= b
# PL upper bound +inf x < ∞
# LO lower bound b <= x
# BV binary variable x = 0 or 1
#
# Not yet implemented:
# LI integer variable b <= x
# UI integer variable x <= b
# SC semi-cont variable x = 0 or l <= x <= b
# l is the lower bound on the variable. If none set then defaults to 1
# ==============================================================================
function write_single_bound(io::IO, var_name::String, lower, upper)
if lower == upper
println(
io,
Card(
f1 = "FX",
f2 = "bounds",
f3 = var_name,
f4 = sprint(print_shortest, lower),
),
)
elseif lower == -Inf && upper == Inf
println(io, Card(f1 = "FR", f2 = "bounds", f3 = var_name))
else
if lower == -Inf
println(io, Card(f1 = "MI", f2 = "bounds", f3 = var_name))
else
println(
io,
Card(
f1 = "LO",
f2 = "bounds",
f3 = var_name,
f4 = sprint(print_shortest, lower),
),
)
end
if upper == Inf
println(io, Card(f1 = "PL", f2 = "bounds", f3 = var_name))
else
println(
io,
Card(
f1 = "UP",
f2 = "bounds",
f3 = var_name,
f4 = sprint(print_shortest, upper),
),
)
end
end
return
end
function update_bounds(x::Tuple{Float64,Float64,VType}, set::MOI.GreaterThan)
return (max(x[1], set.lower), x[2], x[3])
end
function update_bounds(x::Tuple{Float64,Float64,VType}, set::MOI.LessThan)
return (x[1], min(x[2], set.upper), x[3])
end
function update_bounds(x::Tuple{Float64,Float64,VType}, set::MOI.Interval)
return (set.lower, set.upper, x[3])
end
function update_bounds(x::Tuple{Float64,Float64,VType}, set::MOI.EqualTo)
return (set.value, set.value, x[3])
end
function update_bounds(x::Tuple{Float64,Float64,VType}, set::MOI.ZeroOne)
return (x[1], x[2], VTYPE_BINARY)
end
function _collect_bounds(bounds, model, S, names)
for index in
MOI.get(model, MOI.ListOfConstraintIndices{MOI.VariableIndex,S}())
func = MOI.get(model, MOI.ConstraintFunction(), index)
set = MOI.get(model, MOI.ConstraintSet(), index)::S
name = names[func]
bounds[name] = update_bounds(bounds[name], set)
end
return
end
function write_bounds(io::IO, model::Model, ordered_names, names)
println(io, "BOUNDS")
bounds = Dict{String,Tuple{Float64,Float64,VType}}(
n => (-Inf, Inf, VTYPE_CONTINUOUS) for n in ordered_names
)
for S in (
MOI.LessThan{Float64},
MOI.GreaterThan{Float64},
MOI.EqualTo{Float64},
MOI.Interval{Float64},
MOI.ZeroOne,
)
_collect_bounds(bounds, model, S, names)
end
for var_name in ordered_names
lower, upper, vtype = bounds[var_name]
if vtype == VTYPE_BINARY
println(io, Card(f1 = "BV", f2 = "bounds", f3 = var_name))
# Only add bounds if they are tighter than the implicit bounds of a
# binary variable.
if lower > 0 || upper < 1
write_single_bound(io, var_name, lower, upper)
end
else
write_single_bound(io, var_name, lower, upper)
end
end
return
end
# ==============================================================================
# QUADRATIC OBJECTIVE
# ==============================================================================
function write_quadobj(io::IO, model::Model, ordered_names, var_to_column)
f = _get_objective(model)
if !(f isa MOI.ScalarQuadraticFunction{Float64})
return
end
options = get_options(model)
if options.quadratic_format == kQuadraticFormatGurobi
println(io, "QUADOBJ")
elseif options.quadratic_format == kQuadraticFormatCPLEX
println(io, "QMATRIX")
else
@assert options.quadratic_format == kQuadraticFormatMosek
println(io, "QSECTION OBJ")
end
_write_q_matrix(
io,
f,
ordered_names,
var_to_column;
duplicate_off_diagonal = options.quadratic_format ==
kQuadraticFormatCPLEX,
)
return
end
function _write_q_matrix(
io::IO,
f,
ordered_names,
var_to_column;
duplicate_off_diagonal::Bool,
)
# Convert the quadratic terms into matrix form. We don't need to scale
# because MOI uses the same Q/2 format as Gurobi, but we do need to ensure
# we collate off-diagonal terms in the lower-triangular.
terms = Dict{Tuple{Int,Int},Float64}()
for term in f.quadratic_terms
x, y = var_to_column[term.variable_1], var_to_column[term.variable_2]
if x > y
x, y = y, x
end
if haskey(terms, (x, y))
terms[(x, y)] += term.coefficient
else
terms[(x, y)] = term.coefficient
end
end
# Use sort for reproducibility, and so the Q matrix is given in order.
for (x, y) in sort!(collect(keys(terms)))
println(
io,
Card(
f2 = ordered_names[x],
f3 = ordered_names[y],
f4 = sprint(print_shortest, terms[(x, y)]),
),
)
if x != y && duplicate_off_diagonal
println(
io,
Card(
f2 = ordered_names[y],
f3 = ordered_names[x],
f4 = sprint(print_shortest, terms[(x, y)]),
),
)
end
end
return
end
# ==============================================================================
# QUADRATIC CONSTRAINTS
# ==============================================================================
function write_quadcons(io::IO, model::Model, ordered_names, var_to_column)
options = get_options(model)
F = MOI.ScalarQuadraticFunction{Float64}
for (S, _) in SET_TYPES
for ci in MOI.get(model, MOI.ListOfConstraintIndices{F,S}())
name = MOI.get(model, MOI.ConstraintName(), ci)
if options.quadratic_format == kQuadraticFormatMosek
println(io, "QSECTION $name")
else
println(io, "QCMATRIX $name")
end
f = MOI.get(model, MOI.ConstraintFunction(), ci)
_write_q_matrix(
io,
f,
ordered_names,
var_to_column;
duplicate_off_diagonal = options.quadratic_format !=
kQuadraticFormatMosek,
)
end
end
return
end
# ==============================================================================
# SOS
# ==============================================================================
function write_sos_constraint(io::IO, model::Model, index, names)
func = MOI.get(model, MOI.ConstraintFunction(), index)
set = MOI.get(model, MOI.ConstraintSet(), index)
for (variable, weight) in zip(func.variables, set.weights)
println(
io,
Card(f2 = names[variable], f3 = sprint(print_shortest, weight)),
)
end
end
function write_sos(io::IO, model::Model, names)
sos1_indices = MOI.get(
model,
MOI.ListOfConstraintIndices{MOI.VectorOfVariables,MOI.SOS1{Float64}}(),
)
sos2_indices = MOI.get(
model,
MOI.ListOfConstraintIndices{MOI.VectorOfVariables,MOI.SOS2{Float64}}(),
)
if length(sos1_indices) + length(sos2_indices) > 0
println(io, "SOS")
idx = 1
for (sos_type, indices) in enumerate([sos1_indices, sos2_indices])
for index in indices
println(io, Card(f1 = "S$(sos_type)", f2 = "SOS$(idx)"))
write_sos_constraint(io, model, index, names)
idx += 1
end
end
end
return
end
# ==============================================================================
# INDICATORS
# ==============================================================================
function write_indicators(io::IO, indicators)
if isempty(indicators)
return
end
println(io, "INDICATORS")
for (row, var, condition) in indicators
if condition == MOI.ACTIVATE_ON_ONE
println(io, Card(f1 = "IF", f2 = row, f3 = var, f4 = "1"))
else
println(io, Card(f1 = "IF", f2 = row, f3 = var, f4 = "0"))
end
end
return
end
# ==============================================================================
#
# Base.read!
#
# Here is a template for an MPS file, reproduced from
# http://lpsolve.sourceforge.net/5.5/mps-format.htm.
#
# Field: 1 2 3 4 5 6
# Columns: 2-3 5-12 15-22 25-36 40-47 50-61
# NAME problem name
# ROWS
# type name
# COLUMNS
# column row value row value
# name name name
# RHS
# rhs row value row value
# name name name
# RANGES
# range row value row value
# name name name
# BOUNDS
# type bound column value
# name name
# SOS
# type CaseName SOSName SOSpriority
# CaseName VarName1 VarWeight1
# CaseName VarName2 VarWeight2
# CaseName VarNameN VarWeightN
# ENDATA
# ==============================================================================
@enum(Sense, SENSE_N, SENSE_G, SENSE_L, SENSE_E, SENSE_UNKNOWN)
function Sense(s::String)
if s == "G"
return SENSE_G
elseif s == "L"
return SENSE_L
elseif s == "E"
return SENSE_E
elseif s == "N"
return SENSE_N
else
return SENSE_UNKNOWN
end
end
struct _SOSConstraint
type::Int
weights::Vector{Float64}
columns::Vector{String}
end
mutable struct TempMPSModel
name::String
is_minimization::Bool
obj_name::String
c::Vector{Float64}
obj_constant::Float64
col_lower::Vector{Float64}
col_upper::Vector{Float64}
row_lower::Vector{Float64}
row_upper::Vector{Float64}
sense::Vector{Sense}
A::Vector{Vector{Tuple{Int,Float64}}}
vtype::Vector{VType}
name_to_col::Dict{String,Int}
col_to_name::Vector{String}
name_to_row::Dict{String,Int}
row_to_name::Vector{String}
intorg_flag::Bool # A flag used to parse COLUMNS section.
sos_constraints::Vector{_SOSConstraint}
quad_obj::Vector{Tuple{String,String,Float64}}
qc_matrix::Dict{String,Vector{Tuple{String,String,Float64}}}
current_qc_matrix::String
indicators::Dict{String,Tuple{String,MOI.ActivationCondition}}
end
function TempMPSModel()
return TempMPSModel(
"",
true,
"",
Float64[], # c
0.0, # obj_constant
Float64[], # col_lower
Float64[], # col_upper
Float64[], # row_lower
Float64[], # row_upper
Sense[], # sense
Vector{Vector{Tuple{Int,Float64}}}[], # A
Bool[],
Dict{String,Int}(),
String[],