forked from jump-dev/JuMP.jl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
macros.jl
1288 lines (1192 loc) · 48.2 KB
/
macros.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, Iain Dunning, Joey Huchette, Miles Lubin, and contributors
# 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/.
using Base.Meta
issum(s::Symbol) = (s == :sum) || (s == :∑) || (s == :Σ)
isprod(s::Symbol) = (s == :prod) || (s == :∏)
function curly_to_generator(x)
# we have a filter condition
x = copy(x)
@assert isexpr(x,:curly)
if isexpr(x.args[2],:parameters)
cond = x.args[2].args[1]
body = x.args[3]
if length(x.args) == 3 # no iteration set!
push!(x.args,:(_ in 1))
end
for i in length(x.args):-1:4
if i == length(x.args)
body = Expr(:generator,body,Expr(:filter,cond,x.args[i]))
else
body = Expr(:generator,body,x.args[i])
end
end
else
cond = nothing
body = x.args[2]
if length(x.args) == 2 # no iteration set!
push!(x.args,:(_ in 1))
end
for i in length(x.args):-1:3
body = Expr(:generator,body,x.args[i])
end
end
if isexpr(body.args[1],:generator)
body = Expr(:flatten,body)
end
name = x.args[1]
if name == :norm2
return Expr(:call,:norm,body)
elseif name == :norm1
return Expr(:call,:norm,body,1)
elseif name == :norminf
return Expr(:call,:norm,body,Inf)
elseif name == :norm∞
return Expr(:call,:norm,body,Inf)
else
return Expr(:call,name,body)
end
end
function warn_curly(x)
genform = curly_to_generator(x)
if length(genform.args) == 2
# don't print extra parens
genstr = "$(genform.args[1])$(genform.args[2])"
else
genstr = "$genform"
end
Base.warn_once("The curly syntax (sum{},prod{},norm2{}) is deprecated in favor of the new generator syntax (sum(),prod(),norm()).")
Base.warn_once("Replace $x with $genstr.")
end
include("parseExpr_staged.jl")
###############################################################################
# buildrefsets
# Unexported. Takes as input an object representing a name, associated index
# sets, and conditions on those sets, for example
# buildrefsets(:(x[i=1:3,[:red,:blue]],k=S; i+k <= 6))
# Used internally in macros to build JuMPContainers and constraints. Returns
# refcall: Expr to reference a particular element, e.g. :(x[i,j,k])
# idxvars: Index names used in referencing, e.g.g {:i,:j,:k}
# idxsets: Index sets for indexing, e.g. {1:3, [:red,:blue], S}
# idxpairs: Vector of IndexPair
# condition: Expr containing any condition present for indexing
# Note in particular that it does not actually evaluate the condition, and so
# it returns just the cartesian product of possible indices.
function buildrefsets(expr::Expr, cname)
c = copy(expr)
idxvars = Any[]
idxsets = Any[]
idxpairs = IndexPair[]
# Creating an indexed set of refs
refcall = Expr(:ref, cname)
if isexpr(c, :typed_vcat) || isexpr(c, :ref)
shift!(c.args)
end
condition = :()
if isexpr(c, :vcat) || isexpr(c, :typed_vcat)
if isexpr(c.args[1], :parameters)
@assert length(c.args[1].args) == 1
condition = shift!(c.args).args[1]
else
condition = pop!(c.args)
end
end
for s in c.args
parse_done = false
if isa(s, Expr)
parse_done, idxvar, _idxset = tryParseIdxSet(s::Expr)
if parse_done
idxset = esc(_idxset)
push!(idxpairs, IndexPair(idxvar, _idxset))
end
end
if !parse_done # No index variable specified
idxvar = gensym()
idxset = esc(s)
push!(idxpairs, IndexPair(nothing,s))
end
push!(idxvars, idxvar)
push!(idxsets, idxset)
push!(refcall.args, esc(idxvar))
end
return refcall, idxvars, idxsets, idxpairs, condition
end
buildrefsets(c, cname) = (cname, Any[], Any[], IndexPair[], :())
buildrefsets(c) = buildrefsets(c, getname(c))
###############################################################################
# getloopedcode
# Unexported. Takes a bit of code and corresponding looping information and
# returns that code nested in corresponding loops, along with preceding code
# to construct an appropriate container. Input is:
# c: symbolic representation of name and appropriate indexing sets, if
# any. E.g. :(myvar) or :(x[i=1:3,[:red,:blue]])
# code: inner loop code kernel to be nested in the loops
# condition: a boolean expression to be evaluated before each kernel.
# If none, pass :().
# idxvars: As defined for buildrefsets
# idxsets: As defined for buildrefsets
# idxpairs: As defined for buildrefsets
# sym: A symbol or expression containing the element type of the
# resulting container, e.g. :AffExpr or :Variable
function getloopedcode(varname, code, condition, idxvars, idxsets, idxpairs, sym; lowertri=false)
# if we don't have indexing, just return to avoid allocating stuff
if isempty(idxsets)
return code
end
hascond = (condition != :())
if lowertri
@assert !hascond
@assert length(idxvars) == 2
@assert length(idxpairs) == 2
@assert !hasdependentsets(idxvars, idxsets)
i, j = esc(idxvars[1]), esc(idxvars[2])
expr = copy(code)
vname = expr.args[1].args[1]
expr.args[1] = :tmp
code = quote
let
$(localvar(i))
$(localvar(j))
for $i in $(idxsets[1]), $j in $(idxsets[2])
$i <= $j || continue
$expr
$vname[$i,$j] = tmp
$vname[$j,$i] = tmp
end
end
end
else
if hascond
code = quote
$(esc(condition)) || continue
$code
end
end
for (idxvar, idxset) in zip(reverse(idxvars),reverse(idxsets))
code = quote
let
$(localvar(esc(idxvar)))
for $(esc(idxvar)) in $idxset
$code
end
end
end
end
end
if hascond || hasdependentsets(idxvars,idxsets)
# force a JuMPDict
N = length(idxsets)
mac = :($varname = JuMPDict{$(sym),$N}())
else
mac = gendict(varname, sym, idxsets...)
end
return quote
$mac
$code
nothing
end
end
localvar(x::Symbol) = _localvar(x)
localvar(x::Expr) = Expr(:block, _localvar(x)...)
_localvar(x::Symbol) = :(local $(esc(x)))
function _localvar(x::Expr)
@assert x.head == :escape
args = Any[]
for t in x.args
if isa(t, Symbol)
push!(args, :(local $(esc(t))))
else
@assert isa(t, Expr)
if t.head == :tuple
append!(args, map(_localvar, t.args))
else
error("Internal error defining local variables in macros; please file an issue at https://github.com/JuliaOpt/JuMP.jl/issues/new")
end
end
end
args
end
function addkwargs!(call, kwargs)
kwsymbol = VERSION < v"0.6.0-dev.1934" ? :kw : :(=) # changed by julia PR #19868
for kw in kwargs
@assert isexpr(kw, kwsymbol)
push!(call.args, esc(Expr(:kw, kw.args...)))
end
end
getname(c::Symbol) = c
getname(c::Void) = ()
getname(c::AbstractString) = c
function getname(c::Expr)
if c.head == :string
return c
else
return c.args[1]
end
end
validmodel(m::AbstractModel, name) = nothing
validmodel(m::MathProgBase.MathProgCallbackData, name) = error("Expected $name to be a JuMP model, but it is a callback object. Use of this macro is not supported within callbacks.")
validmodel(m, name) = error("Expected $name to be a JuMP model, but it has type ", typeof(m))
function assert_validmodel(m, macrocode)
# assumes m is already escaped
quote
validmodel($m, $(quot(m.args[1])))
$macrocode
end
end
function _canonicalize_sense(sns::Symbol)
if sns == :(==)
return (:(==),false)
elseif sns == :(>=) || sns == :(≥)
return (:(>=),false)
elseif sns == :(<=) || sns == :(≤)
return (:(<=),false)
elseif sns == :(.==)
return (:(==),true)
elseif sns == :(.>=) || sns == :(.≥)
return (:(>=),true)
elseif sns == :(.<=) || sns == :(.≤)
return (:(<=),true)
else
error("Unrecognized sense $sns")
end
end
function _construct_constraint!(args...)
warn("_construct_constraint! is deprecated. Use constructconstraint! instead")
constructconstraint!(args...)
end
# two-argument constructconstraint! is used for one-sided constraints.
# Right-hand side is zero.
constructconstraint!(v::Variable, sense::Symbol) = constructconstraint!(convert(AffExpr,v), sense)
function constructconstraint!(aff::AffExpr, sense::Symbol)
offset = aff.constant
aff.constant = 0.0
if sense == :(<=) || sense == :≤
return LinearConstraint(aff, -Inf, -offset)
elseif sense == :(>=) || sense == :≥
return LinearConstraint(aff, -offset, Inf)
elseif sense == :(==)
return LinearConstraint(aff, -offset, -offset)
else
error("Cannot handle ranged constraint")
end
end
function constructconstraint!(aff::AffExpr, lb, ub)
offset = aff.constant
aff.constant = 0.0
LinearConstraint(aff, lb-offset, ub-offset)
end
constructconstraint!(quad::QuadExpr, sense::Symbol) = QuadConstraint(quad, sense)
function constructconstraint!(normexpr::SOCExpr, sense::Symbol)
# check that the constraint is SOC representable
if sense == :(<=)
SOCConstraint(normexpr)
elseif sense == :(>=)
SOCConstraint(-normexpr)
else
error("Invalid sense $sense in SOC constraint")
end
end
constructconstraint!(x::Array, sense::Symbol) = map(c->constructconstraint!(c,sense), x)
constructconstraint!(x::AbstractArray, sense::Symbol) = constructconstraint!([x[i] for i in eachindex(x)], sense)
_vectorize_like(x::Number, y::AbstractArray{AffExpr}) = (ret = similar(y, typeof(x)); fill!(ret, x))
function _vectorize_like{R<:Number}(x::AbstractArray{R}, y::AbstractArray{AffExpr})
for i in 1:max(ndims(x),ndims(y))
_size(x,i) == _size(y,i) || error("Unequal sizes for ranged constraint")
end
x
end
function constructconstraint!(x::AbstractArray{AffExpr}, lb, ub)
LB = _vectorize_like(lb,x)
UB = _vectorize_like(ub,x)
ret = similar(x, LinearConstraint)
map!(ret, eachindex(ret)) do i
constructconstraint!(x[i], LB[i], UB[i])
end
end
# three-argument constructconstraint! is used for two-sided constraints.
function constructconstraint!(aff::AffExpr, lb::Real, ub::Real)
offset = aff.constant
aff.constant = 0.0
LinearConstraint(aff,lb-offset,ub-offset)
end
constructconstraint!(aff::Variable, lb::Real, ub::Real) = constructconstraint!(convert(AffExpr,v),lb,ub)
constructconstraint!(q::QuadExpr, lb, ub) = error("Two-sided quadratic constraints not supported. (Try @NLconstraint instead.)")
constraint_error(args, str) = error("In @constraint($(join(args,","))): ", str)
macro constraint(args...)
# Pick out keyword arguments
if isexpr(args[1],:parameters) # these come if using a semicolon
kwargs = args[1]
args = args[2:end]
else
kwargs = Expr(:parameters)
end
kwsymbol = VERSION < v"0.6.0-dev.1934" ? :kw : :(=) # changed by julia PR #19868
append!(kwargs.args, filter(x -> isexpr(x, kwsymbol), collect(args))) # comma separated
args = filter(x->!isexpr(x, kwsymbol), collect(args))
if length(args) < 2
if length(kwargs.args) > 0
constraint_error(args, "Not enough positional arguments")
else
constraint_error(args, "Not enough arguments")
end
end
m = args[1]
x = args[2]
extra = args[3:end]
m = esc(m)
# Two formats:
# - @constraint(m, a*x <= 5)
# - @constraint(m, myref[a=1:5], a*x <= 5)
length(extra) > 1 && constraint_error(args, "Too many arguments.")
# Canonicalize the arguments
c = length(extra) == 1 ? x : gensym()
x = length(extra) == 1 ? extra[1] : x
anonvar = isexpr(c, :vect) || isexpr(c, :vcat) || length(extra) != 1
variable = gensym()
quotvarname = quot(getname(c))
escvarname = anonvar ? variable : esc(getname(c))
if isa(x, Symbol)
constraint_error(args, "Incomplete constraint specification $x. Are you missing a comparison (<=, >=, or ==)?")
end
(x.head == :block) &&
constraint_error(args, "Code block passed as constraint. Perhaps you meant to use @constraints instead?")
# Strategy: build up the code for non-macro addconstraint, and if needed
# we will wrap in loops to assign to the ConstraintRefs
refcall, idxvars, idxsets, idxpairs, condition = buildrefsets(c, variable)
# JuMP accepts constraint syntax of the form @constraint(m, foo in bar).
# This will be rewritten to a call to constructconstraint!(foo, bar). To
# extend JuMP to accept set-based constraints of this form, it is necessary
# to add the corresponding methods to constructconstraint!. Note that this
# will likely mean that bar will be some custom type, rather than e.g. a
# Symbol, since we will likely want to dispatch on the type of the set
# appearing in the constraint.
if isexpr(x, :call)
if x.args[1] == :in
@assert length(x.args) == 3
newaff, parsecode = parseExprToplevel(x.args[2], :q)
constraintcall = :(addconstraint($m, constructconstraint!($newaff,$(esc(x.args[3])))))
else
# Simple comparison - move everything to the LHS
@assert length(x.args) == 3
(sense,vectorized) = _canonicalize_sense(x.args[1])
lhs = :($(x.args[2]) - $(x.args[3]))
addconstr = (vectorized ? :addVectorizedConstraint : :addconstraint)
newaff, parsecode = parseExprToplevel(lhs, :q)
constraintcall = :($addconstr($m, constructconstraint!($newaff,$(quot(sense)))))
end
addkwargs!(constraintcall, kwargs.args)
code = quote
q = zero(AffExpr)
$parsecode
$(refcall) = $constraintcall
end
elseif isexpr(x, :comparison)
# Ranged row
(lsign,lvectorized) = _canonicalize_sense(x.args[2])
(rsign,rvectorized) = _canonicalize_sense(x.args[4])
if (lsign != :(<=)) || (rsign != :(<=))
constraint_error(args, "Only ranged rows of the form lb <= expr <= ub are supported.")
end
((vectorized = lvectorized) == rvectorized) || constraint_error("Signs are inconsistently vectorized")
addconstr = (lvectorized ? :addVectorizedConstraint : :addconstraint)
x_str = string(x)
lb_str = string(x.args[1])
ub_str = string(x.args[5])
newaff, parsecode = parseExprToplevel(x.args[3],:aff)
newlb, parselb = parseExprToplevel(x.args[1],:lb)
newub, parseub = parseExprToplevel(x.args[5],:ub)
constraintcall = :($addconstr($m, constructconstraint!($newaff,$newlb,$newub)))
addkwargs!(constraintcall, kwargs.args)
code = quote
aff = zero(AffExpr)
$parsecode
lb = 0.0
$parselb
ub = 0.0
$parseub
end
if vectorized
code = quote
$code
lbval, ubval = $newlb, $newub
end
else
code = quote
$code
CoefType = coeftype($newaff)
try
lbval = convert(CoefType, $newlb)
catch
constraint_error($args, string("Expected ",$lb_str," to be a ", CoefType, "."))
end
try
ubval = convert(CoefType, $newub)
catch
constraint_error($args, string("Expected ",$ub_str," to be a ", CoefType, "."))
end
end
end
code = quote
$code
$(refcall) = $constraintcall
end
else
# Unknown
constraint_error(args, string("Constraints must be in one of the following forms:\n" *
" expr1 <= expr2\n" * " expr1 >= expr2\n" *
" expr1 == expr2\n" * " lb <= expr <= ub"))
end
return assert_validmodel(m, quote
$(getloopedcode(variable, code, condition, idxvars, idxsets, idxpairs, :ConstraintRef))
$(if anonvar
variable
else
quote
registercon($m, $quotvarname, $variable)
$escvarname = $variable
end
end)
end)
end
macro SDconstraint(m, x)
m = esc(m)
if isa(x, Symbol)
error("in @SDconstraint: Incomplete constraint specification $x. Are you missing a comparison (<= or >=)?")
end
(x.head == :block) &&
error("Code block passed as constraint.")
isexpr(x,:call) && length(x.args) == 3 || error("in @SDconstraint ($(string(x))): constraints must be in one of the following forms:\n" *
" expr1 <= expr2\n" * " expr1 >= expr2")
# Build the constraint
# Simple comparison - move everything to the LHS
sense = x.args[1]
if sense == :⪰
sense = :(>=)
elseif sense == :⪯
sense = :(<=)
end
sense,_ = _canonicalize_sense(sense)
lhs = :()
if sense == :(>=)
lhs = :($(x.args[2]) - $(x.args[3]))
elseif sense == :(<=)
lhs = :($(x.args[3]) - $(x.args[2]))
else
error("Invalid sense $sense in SDP constraint")
end
newaff, parsecode = parseExprToplevel(lhs, :q)
assert_validmodel(m, quote
q = zero(AffExpr)
$parsecode
addconstraint($m, SDConstraint($newaff))
end)
end
macro LinearConstraint(x)
(x.head == :block) &&
error("Code block passed as constraint. Perhaps you meant to use @LinearConstraints instead?")
if isexpr(x, :call) && length(x.args) == 3
(sense,vectorized) = _canonicalize_sense(x.args[1])
# Simple comparison - move everything to the LHS
vectorized &&
error("in @LinearConstraint ($(string(x))): Cannot add vectorized constraints")
lhs = :($(x.args[2]) - $(x.args[3]))
return quote
newaff = @Expression($(esc(lhs)))
c = constructconstraint!(newaff,$(quot(sense)))
isa(c, LinearConstraint) ||
error("Constraint in @LinearConstraint is really a $(typeof(c))")
c
end
elseif isexpr(x, :comparison)
# Ranged row
(lsense,lvectorized) = _canonicalize_sense(x.args[2])
(rsense,rvectorized) = _canonicalize_sense(x.args[4])
if (lsense != :<=) || (rsense != :<=)
error("in @constraint ($(string(x))): only ranged rows of the form lb <= expr <= ub are supported.")
end
(lvectorized || rvectorized) &&
error("in @LinearConstraint ($(string(x))): Cannot add vectorized constraints")
lb = x.args[1]
ub = x.args[5]
return quote
if !isa($(esc(lb)),Number)
error(string("in @LinearConstraint (",$(string(x)),"): expected ",$(string(lb))," to be a number."))
elseif !isa($(esc(ub)),Number)
error(string("in @LinearConstraint (",$(string(x)),"): expected ",$(string(ub))," to be a number."))
end
newaff = @Expression($(esc(x.args[3])))
offset = newaff.constant
newaff.constant = 0.0
isa(newaff,AffExpr) || error("Ranged quadratic constraints are not allowed")
LinearConstraint(newaff,$(esc(lb))-offset,$(esc(ub))-offset)
end
else
# Unknown
error("in @LinearConstraint ($(string(x))): constraints must be in one of the following forms:\n" *
" expr1 <= expr2\n" * " expr1 >= expr2\n" *
" expr1 == expr2\n" * " lb <= expr <= ub")
end
end
macro QuadConstraint(x)
(x.head == :block) &&
error("Code block passed as constraint. Perhaps you meant to use @QuadConstraints instead?")
if isexpr(x, :call) && length(x.args) == 3
(sense,vectorized) = _canonicalize_sense(x.args[1])
# Simple comparison - move everything to the LHS
vectorized &&
error("in @QuadConstraint ($(string(x))): Cannot add vectorized constraints")
lhs = :($(x.args[2]) - $(x.args[3]))
return quote
newaff = @Expression($(esc(lhs)))
q = constructconstraint!(newaff,$(quot(sense)))
isa(q, QuadConstraint) || error("Constraint in @QuadConstraint is really a $(typeof(q))")
q
end
elseif isexpr(x, :comparison)
error("Ranged quadratic constraints are not allowed")
else
# Unknown
error("in @QuadConstraint ($(string(x))): constraints must be in one of the following forms:\n" *
" expr1 <= expr2\n" * " expr1 >= expr2\n" *
" expr1 == expr2")
end
end
macro SOCConstraint(x)
(x.head == :block) &&
error("Code block passed as constraint. Perhaps you meant to use @SOCConstraints instead?")
if isexpr(x, :call) && length(x.args) == 3
(sense,vectorized) = _canonicalize_sense(x.args[1])
# Simple comparison - move everything to the LHS
vectorized &&
error("in @SOCConstraint ($(string(x))): Cannot add vectorized constraints")
lhs = :($(x.args[2]) - $(x.args[3]))
return quote
newaff = @Expression($(esc(lhs)))
q = constructconstraint!(newaff,$(quot(sense)))
isa(q, SOCConstraint) || error("Constraint in @SOCConstraint is really a $(typeof(q))")
q
end
elseif isexpr(x, :comparison)
error("Ranged second-order cone constraints are not allowed")
else
# Unknown
error("in @SOCConstraint ($(string(x))): constraints must be in one of the following forms:\n" *
" expr1 <= expr2\n" * " expr1 >= expr2")
end
end
for (mac,sym) in [(:LinearConstraints, Symbol("@LinearConstraint")),
(:QuadConstraints, Symbol("@QuadConstraint")),
(:SOCConstraints, Symbol("@SOCConstraint"))]
@eval begin
macro $mac(x)
x.head == :block || error(string("Invalid syntax for ", $(quot(sym))))
@assert x.args[1].head == :line
code = Expr(:vect)
for it in x.args
if it.head == :line
# do nothing
elseif it.head == :comparison || (it.head == :call && it.args[1] in (:<=,:≤,:>=,:≥,:(==))) # regular constraint
push!(code.args, Expr(:macrocall, $sym, esc(it)))
elseif it.head == :tuple # constraint ref
if all([isexpr(arg,:comparison) for arg in it.args]...)
# the user probably had trailing commas at end of lines, e.g.
# @LinearConstraints(m, begin
# x <= 1,
# x >= 1
# end)
error(string("Invalid syntax in ", $(quot(sym)), ". Do you have commas at the end of a line specifying a constraint?"))
end
error(string($(quot(sym)), " does not currently support the two argument syntax for specifying groups of constraints in one line."))
else
error("Unexpected constraint expression $it")
end
end
return code
end
end
end
for (mac,sym) in [(:constraints, Symbol("@constraint")),
(:NLconstraints,Symbol("@NLconstraint")),
(:SDconstraints,Symbol("@SDconstraint")),
(:variables,Symbol("@variable")),
(:expressions, Symbol("@expression")),
(:NLexpressions, Symbol("@NLexpression"))]
@eval begin
macro $mac(m, x)
x.head == :block || error("Invalid syntax for @$mac")
@assert x.args[1].head == :line
code = quote end
for it in x.args
if isexpr(it, :line)
# do nothing
elseif isexpr(it, :tuple) # line with commas
args = []
for ex in it.args
if isexpr(ex, :tuple) # embedded tuple
append!(args, ex.args)
else
push!(args, ex)
end
end
args_esc = []
for ex in args
if isexpr(ex, :(=)) && VERSION < v"0.6.0-dev.1934"
push!(args_esc,Expr(:kw, ex.args[1], esc(ex.args[2])))
else
push!(args_esc, esc(ex))
end
end
mac = Expr(:macrocall,$(quot(sym)), esc(m), args_esc...)
push!(code.args, mac)
else # stand-alone symbol or expression
push!(code.args,Expr(:macrocall,$(quot(sym)), esc(m), esc(it)))
end
end
push!(code.args, :(nothing))
return code
end
end
end
macro objective(m, args...)
m = esc(m)
if length(args) != 2
# Either just an objective sene, or just an expression.
error("in @objective: needs three arguments: model, objective sense (Max or Min) and expression.")
end
sense, x = args
if sense == :Min || sense == :Max
sense = Expr(:quote,sense)
end
newaff, parsecode = parseExprToplevel(x, :q)
code = quote
q = zero(AffExpr)
$parsecode
setobjective($m, $(esc(sense)), $newaff)
end
return assert_validmodel(m, code)
end
# Return a standalone, unnamed expression
# ex = @Expression(2x + 3y)
# Currently for internal use only.
macro Expression(x)
newaff, parsecode = parseExprToplevel(x, :q)
return quote
q = 0.0
$parsecode
$newaff
end
end
macro expression(args...)
if length(args) == 3
m = esc(args[1])
c = args[2]
x = args[3]
elseif length(args) == 2
m = esc(args[1])
c = gensym()
x = args[2]
else
error("@expression: needs at least two arguments.")
end
anonvar = isexpr(c, :vect) || isexpr(c, :vcat)
variable = gensym()
escvarname = anonvar ? variable : esc(getname(c))
refcall, idxvars, idxsets, idxpairs, condition = buildrefsets(c, variable)
newaff, parsecode = parseExprToplevel(x, :q)
code = quote
q = 0.0
$parsecode
end
if isa(c,Expr)
code = quote
$code
(isa($newaff,AffExpr) || isa($newaff,Number) || isa($newaff,Variable)) || error("Collection of expressions with @expression must be linear. For quadratic expressions, use your own array.")
end
end
code = quote
$code
$(refcall) = $newaff
end
code = getloopedcode(variable, code, condition, idxvars, idxsets, idxpairs, :AffExpr)
if m === nothing # deprecated usage
return quote
$code
$(anonvar ? variable : :($escvarname = $variable))
end
else
# don't do anything with the model, but check that it's valid anyway
return assert_validmodel(m, quote
$code
$(anonvar ? variable : :($escvarname = $variable))
end)
end
end
function hasdependentsets(idxvars, idxsets)
# check if any index set depends on a previous index var
for i in 2:length(idxsets)
for v in idxvars[1:(i-1)]
if dependson(idxsets[i],v)
return true
end
end
end
return false
end
dependson(ex::Expr,s::Symbol) = any(a->dependson(a,s), ex.args)
dependson(ex::Symbol,s::Symbol) = (ex == s)
dependson(ex,s::Symbol) = false
function dependson(ex1,ex2)
@assert isa(ex2, Expr)
@assert ex2.head == :tuple
any(s->dependson(ex1,s), ex2.args)
end
function isdependent(idxvars,idxset,i)
for (it,idx) in enumerate(idxvars)
it == i && continue
dependson(idxset, idx) && return true
end
return false
end
esc_nonconstant(x::Number) = x
esc_nonconstant(x::Expr) = isexpr(x,:quote) ? x : esc(x)
esc_nonconstant(x) = esc(x)
# Returns the type of what `constructvariable!` would return with these starting positional arguments.
variabletype(m::Model) = Variable
# Returns a new variable belonging to the model `m`. Additional positional arguments can be used to dispatch the call to a different method.
# The return type should only depends on the positional arguments for `variabletype` to make sense.
function constructvariable!(m::Model, _error::Function, lowerbound::Number, upperbound::Number, category::Symbol, objective::Number, inconstraints::Vector, coefficients::Vector{Float64}, basename::AbstractString, start::Number; extra_kwargs...)
for (kwarg, _) in extra_kwargs
_error("Unrecognized keyword argument $kwarg")
end
Variable(m, lowerbound, upperbound, category == :Default ? :Cont : category, objective, inconstraints, coefficients, basename, start)
end
function constructvariable!(m::Model, _error::Function, lowerbound::Number, upperbound::Number, category::Symbol, basename::AbstractString, start::Number; extra_kwargs...)
for (kwarg, _) in extra_kwargs
_error("Unrecognized keyword argument $kwarg")
end
Variable(m, lowerbound, upperbound, category == :Default ? :Cont : category, basename, start)
end
const EMPTYSTRING = ""
variable_error(args, str) = error("In @variable($(join(args,","))): ", str)
# @variable(m, expr, extra...; kwargs...)
# where `extra` is a list of extra positional arguments and `kwargs` is a list of keyword arguments.
#
# It creates a new variable (resp. a container of new variables) belonging to the model `m` using `constructvariable!` to create the variable (resp. each variable of the container).
# The following modifications will be made to the arguments before they are passed to `constructvariable!`:
# * The `expr` argument will not be passed but the expression will be parsed to determine the kind of container needed (if one is needed) and
# additional information that will alter what is passed with the keywords `lowerbound`, `upperbound`, `basename` and `start`.
# * The `SDP` and `Symmetric` positional arguments in `extra` will not be passed to `constructvariable!`. Instead,
# * the `Symmetric` argument will check that the container is symmetric and only allocate one variable for each pair of non-diagonal entries.
# * the `SDP` argument will do the same as `Symmetric` but in addition it will specify that the variables created belongs to the SDP cone in the `varCones` field of the model.
# Moreover, if a Cont, Int, Bin, SemiCont or SemiInt is passed in `extra`, it will alter what is passed with the keyword `category`.
# * The keyword arguments start, objective, inconstraints, coefficients, basename, lowerbound, upperbound, category may not be passed as is to
# `constructvariable!` since they may be altered by the parsing of `expr` and we may need to pass it pointwise if it is a container since
# `constructvariable!` is called separately for each variable of the container. Moreover it will be passed as positional argument to `constructvariable!`.
# If `objective`, `inconstraints` and `coefficients` are not present, they won't be passed as positional argument but for the other five arguments,
# default values are passed when they are not present.
# * A custom error function is passed as positional argument to print the full @variable call before the error message.
#
# Examples (... is the custom error function):
# * `@variable(m, x >= 0)` is equivalent to `x = constructvariable!(m, msg -> error("In @variable(m, x >= 0): ", msg), 0, Inf, :Cont, "x", NaN)
# * `@variable(m, x[1:N,1:N], Symmetric, Poly(X))` is equivalent to
# ```
# x = Matrix{...}(N, N)
# for i in 1:N
# for j in 1:N
# x[i,j] = x[j,i] = constructvariable!(m, Poly(X), msg -> error("In @variable(m, x[1:N,1:N], Symmetric, Poly(X)): ", msg), -Inf, Inf, :Cont, "", NaN)
# end
# end
# ```
macro variable(args...)
_error(str) = variable_error(args, str)
m = esc(args[1])
extra = vcat(args[2:end]...)
# separate out keyword arguments
kwsymbol = VERSION < v"0.6.0-dev.1934" ? :kw : :(=)
kwargs = filter(ex->isexpr(ex,kwsymbol), extra)
extra = filter(ex->!isexpr(ex,kwsymbol), extra)
# if there is only a single non-keyword argument, this is an anonymous
# variable spec and the one non-kwarg is the model
if length(kwargs) == length(args)-1
x = gensym()
anon_singleton = true
else
x = shift!(extra)
if x in [:Cont,:Int,:Bin,:SemiCont,:SemiInt,:SDP]
_error("Ambiguous variable name $x detected. Use the \"category\" keyword argument to specify a category for an anonymous variable.")
end
anon_singleton = false
end
t = quot(:Default)
gottype = false
haslb = false
hasub = false
# Identify the variable bounds. Five (legal) possibilities are "x >= lb",
# "x <= ub", "lb <= x <= ub", "x == val", or just plain "x"
explicit_comparison = false
if isexpr(x,:comparison) # two-sided
explicit_comparison = true
haslb = true
hasub = true
if x.args[2] == :>= || x.args[2] == :≥
# ub >= x >= lb
x.args[4] == :>= || x.args[4] == :≥ || _error("Invalid variable bounds")
var = x.args[3]
lb = esc_nonconstant(x.args[5])
ub = esc_nonconstant(x.args[1])
elseif x.args[2] == :<= || x.args[2] == :≤
# lb <= x <= u
var = x.args[3]
(x.args[4] != :<= && x.args[4] != :≤) &&
_error("Expected <= operator after variable name.")
lb = esc_nonconstant(x.args[1])
ub = esc_nonconstant(x.args[5])
else
_error("Use the form lb <= ... <= ub.")
end
elseif isexpr(x,:call)
explicit_comparison = true
if x.args[1] == :>= || x.args[1] == :≥
# x >= lb
var = x.args[2]
@assert length(x.args) == 3
lb = esc_nonconstant(x.args[3])
haslb = true
ub = Inf
elseif x.args[1] == :<= || x.args[1] == :≤
# x <= ub
var = x.args[2]
# NB: May also be lb <= x, which we do not support
# We handle this later in the macro
@assert length(x.args) == 3
ub = esc_nonconstant(x.args[3])
hasub = true
lb = -Inf
elseif x.args[1] == :(==)
# fixed variable
var = x.args[2]
@assert length(x.args) == 3
lb = esc(x.args[3])
haslb = true
ub = esc(x.args[3])
hasub = true
gottype = true
t = quot(:Fixed)
else
# Its a comparsion, but not using <= ... <=
_error("Unexpected syntax $(string(x)).")
end
else
# No bounds provided - free variable
# If it isn't, e.g. something odd like f(x), we'll handle later
var = x
lb = -Inf
ub = Inf
end
anonvar = isexpr(var, :vect) || isexpr(var, :vcat) || anon_singleton
anonvar && explicit_comparison && error("Cannot use explicit bounds via >=, <= with an anonymous variable")
variable = gensym()
quotvarname = anonvar ? :(:__anon__) : quot(getname(var))
escvarname = anonvar ? variable : esc(getname(var))
if !isa(getname(var),Symbol) && !anonvar
Base.warn_once("Expression $(getname(var)) should not be used as a variable name. Use the \"anonymous\" syntax $(getname(var)) = @variable(m, ...) instead.")
end
# process keyword arguments
value = NaN
obj = nothing
inconstraints = nothing
coefficients = nothing
extra_kwargs = []
for ex in kwargs
kwarg = ex.args[1]
if kwarg == :start
value = esc(ex.args[2])
elseif kwarg == :objective
obj = esc(ex.args[2])
elseif kwarg == :inconstraints
inconstraints = esc(ex.args[2])
elseif kwarg == :coefficients
coefficients = esc(ex.args[2])
elseif kwarg == :basename
quotvarname = esc(ex.args[2])
elseif kwarg == :lowerbound
haslb && _error("Cannot specify variable lowerbound twice")
lb = esc_nonconstant(ex.args[2])
haslb = true
elseif kwarg == :upperbound
hasub && _error("Cannot specify variable upperbound twice")
ub = esc_nonconstant(ex.args[2])
hasub = true
elseif kwarg == :category
(t == quot(:Fixed)) && _error("Unexpected extra arguments when declaring a fixed variable")
t = esc_nonconstant(ex.args[2])
gottype = true
else
push!(extra_kwargs, ex)
end