-
-
Notifications
You must be signed in to change notification settings - Fork 400
/
Copy pathmacros.jl
1684 lines (1459 loc) · 63.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
_is_sum(s::Symbol) = (s == :sum) || (s == :∑) || (s == :Σ)
_is_prod(s::Symbol) = (s == :prod) || (s == :∏)
function _error_curly(x)
Base.error("The curly syntax (sum{},prod{},norm2{}) is no longer supported. Expression: $x.")
end
include("parse_expr.jl")
function _build_ref_sets(expr::Expr, cname)
c = copy(expr)
idxvars = Any[]
idxsets = Any[]
# Creating an indexed set of refs
refcall = Expr(:ref, cname)
# On 0.7, :(t[i;j]) is a :ref, while t[i,j;j] is a :typed_vcat.
# In both cases :t is the first arg.
if isexpr(c, :typed_vcat) || isexpr(c, :ref)
popfirst!(c.args)
end
condition = :()
if isexpr(c, :vcat) || isexpr(c, :typed_vcat)
# Parameters appear as plain args at the end.
if length(c.args) > 2
error("Unsupported syntax $c.")
elseif length(c.args) == 2
condition = pop!(c.args)
end # else no condition.
elseif isexpr(c, :ref) || isexpr(c, :vect)
# Parameters appear at the front.
if isexpr(c.args[1], :parameters)
if length(c.args[1].args) != 1
error("Invalid syntax: $c. Multiple semicolons are not " *
"supported.")
end
condition = popfirst!(c.args).args[1]
end
end
if isexpr(c, :vcat) || isexpr(c, :typed_vcat) || isexpr(c, :ref)
if isexpr(c.args[1], :parameters)
@assert length(c.args[1].args) == 1
condition = popfirst!(c.args).args[1]
end # else no condition.
end
for s in c.args
parse_done = false
if isa(s, Expr)
parse_done, idxvar, _idxset = _try_parse_idx_set(s::Expr)
if parse_done
idxset = esc(_idxset)
end
end
if !parse_done # No index variable specified
idxvar = gensym()
idxset = esc(s)
end
push!(idxvars, idxvar)
push!(idxsets, idxset)
push!(refcall.args, esc(idxvar))
end
return refcall, idxvars, idxsets, condition
end
_build_ref_sets(c, cname) = (cname, Any[], Any[], :())
"""
JuMP._build_ref_sets(expr::Expr)
Helper function for macros to construct container objects. Takes an `Expr` that specifies the container, e.g. `:(x[i=1:3,[:red,:blue]],k=S; i+k <= 6)`, and returns:
1. `refcall`: Expr to reference a particular element in the container, e.g. `:(x[i,red,s])`
2. `idxvars`: Names for the index variables, e.g. `[:i, gensym(), :k]`
3. `idxsets`: Sets used for indexing, e.g. `[1:3, [:red,:blue], S]`
4. `condition`: Expr containing any conditional imposed on indexing, or `:()` if none is present
"""
_build_ref_sets(c) = _build_ref_sets(c, _get_name(c))
"""
JuMP._get_looped_code(varname, code, condition, idxvars, idxsets, sym, requestedcontainer::Symbol; lowertri=false)
Helper function for macros to transform expression objects containing kernel code, index sets, conditionals, etc. to an expression that performs the desired loops that iterate over the kernel code. Arguments to the function are:
1. `varname`: name and appropriate indexing sets (if any) for container that is assigned to in the kernel code, e.g. `:myvar` or `:(x[i=1:3,[:red,:blue]])`
2. `code`: `Expr` containing kernel code
3. `condition`: `Expr` that is evaluated immediately before kernel code in each iteration. If none, pass `:()`.
4. `idxvars`: Names for the index variables for each loop, e.g. `[:i, gensym(), :k]`
5. `idxsets`: Sets used to define iteration for each loop, e.g. `[1:3, [:red,:blue], S]`
6. `sym`: A `Symbol`/`Expr` containing the element type of the container that is being iterated over, e.g. `:AffExpr` or `:VariableRef`
7. `requestedcontainer`: Argument that is passed through to `generate_container`. Either `:Auto`, `:Array`, `:DenseAxisArray`, or `:SparseAxisArray`.
8. `lowertri`: `Bool` keyword argument that is `true` if the iteration is over a cartesian array and should only iterate over the lower triangular entries, filling upper triangular entries with copies, e.g. `x[1,3] === x[3,1]`, and `false` otherwise.
"""
function _get_looped_code(varname, code, condition, idxvars, idxsets, sym, requestedcontainer::Symbol; lowertri=false)
# if we don't have indexing, just return to avoid allocating stuff
if isempty(idxsets)
return code
end
hascond = (condition != :())
if !(requestedcontainer in [:Auto, :Array, :DenseAxisArray, :SparseAxisArray])
# We do this two-step interpolation, first into the string, and then
# into the expression because interpolating into a string inside an
# expression has scoping issues.
error_message = "Invalid container type $requestedcontainer. Must be " *
"Auto, Array, DenseAxisArray, or SparseAxisArray."
return :(error($error_message))
end
if hascond
if requestedcontainer == :Auto
requestedcontainer = :SparseAxisArray
elseif requestedcontainer == :Array || requestedcontainer == :DenseAxisArray
return :(error("Requested container type is incompatible with ",
"conditional indexing. Use :SparseAxisArray or ",
":Auto instead."))
end
end
containercode, autoduplicatecheck = Containers.generate_container(sym,
idxvars, idxsets, requestedcontainer)
if lowertri
@assert !hascond
@assert length(idxvars) == 2
@assert !Containers.has_dependent_sets(idxvars, idxsets)
i, j = esc(idxvars[1]), esc(idxvars[2])
expr = copy(code)
vname = expr.args[1].args[1]
tmp = gensym()
expr.args[1] = tmp
code = quote
for $i in $(idxsets[1]), $j in $(idxsets[2])
$i <= $j || continue
$expr
$vname[$i,$j] = $tmp
$vname[$j,$i] = $tmp
end
end
else
if !autoduplicatecheck # we need to check for duplicate keys in the index set
if length(idxvars) > 1
keytuple = Expr(:tuple, esc.(idxvars)...)
else
keytuple = esc(idxvars[1])
end
code = quote
if haskey($varname, $keytuple)
error(string("Repeated index ", $keytuple,". Index sets must have unique elements."))
end
$code
end
end
if hascond
code = quote
$(esc(condition)) || continue
$code
end
end
for (idxvar, idxset) in zip(reverse(idxvars),reverse(idxsets))
code = quote
for $(esc(idxvar)) in $idxset
$code
end
end
end
end
return quote
$varname = $containercode
$code
nothing
end
end
"""
_extract_kw_args(args)
Process the arguments to a macro, separating out the keyword arguments.
Return a tuple of (flat_arguments, keyword arguments, and requestedcontainer),
where `requestedcontainer` is a symbol to be passed to `_get_looped_code`.
"""
function _extract_kw_args(args)
kw_args = filter(x -> isexpr(x, :(=)) && x.args[1] != :container , collect(args))
flat_args = filter(x->!isexpr(x, :(=)), collect(args))
requestedcontainer = :Auto
for kw in args
if isexpr(kw, :(=)) && kw.args[1] == :container
requestedcontainer = kw.args[2]
end
end
return flat_args, kw_args, requestedcontainer
end
"""
_add_kw_args(call, kw_args)
Add the keyword arguments `kw_args` to the function call expression `call`,
escaping the expressions. The elements of `kw_args` should be expressions of the
form `:(key = value)`. The `kw_args` vector can be extracted from the arguments
of a macro with [`_extract_kw_args`](@ref).
## Examples
```jldoctest; setup = :(using JuMP)
julia> call = :(f(1, a=2))
:(f(1, a=2))
julia> JuMP._add_kw_args(call, [:(b=3), :(c=4)])
julia> call
:(f(1, a=2, $(Expr(:escape, :(b=3))), $(Expr(:escape, :(c=4)))))
```
"""
function _add_kw_args(call, kw_args)
for kw in kw_args
@assert isexpr(kw, :(=))
push!(call.args, esc(Expr(:kw, kw.args...)))
end
end
_get_name(c::Symbol) = c
_get_name(c::Nothing) = ()
_get_name(c::AbstractString) = c
function _get_name(c::Expr)
if c.head == :string
return c
else
return c.args[1]
end
end
_valid_model(m::AbstractModel, name) = nothing
_valid_model(m, name) = error("Expected $name to be a JuMP model, but it has type ", typeof(m))
function _assert_valid_model(m, macrocode)
# assumes m is already escaped
quote
_valid_model($m, $(quot(m.args[1])))
$macrocode
end
end
"""
_macro_return(model, code, variable)
Return a block of code that
1. runs the code block `code` in a local scope and
2. returns the value of a local variable named `variable`. `variable` must
reference a variable defined by `code`.
"""
function _macro_return(code, variable)
return quote
let
# The let block ensures that all variables created behave like
# local variables, see
# https://github.com/JuliaOpt/JuMP.jl/issues/1496.
# To make $variable accessible from outside we need to return it at
# the end of the block.
$code
$variable
end
end
end
function _error_if_cannot_register(model::AbstractModel, name::Symbol)
obj_dict = object_dictionary(model)
if haskey(obj_dict, name)
error("An object of name $name is already attached to this model. " *
"If this is intended, consider using the anonymous construction" *
" syntax, e.g., x = @variable(model, [1:N], ...) where the " *
"name of the object does not appear inside the macro.")
end
return
end
function _error_if_cannot_register(model::AbstractModel, name)
error("Invalid name $name.")
end
"""
_macro_assign_and_return(code, variable, name;
final_variable=variable,
model_for_registering=nothing)
Return runs `code` in a local scope which returns the value of `variable`
and then assign `final_variable` to `name`.
If `model_for_registering` is given, the generated code assigns the resulting
object to the model dictionary.
"""
function _macro_assign_and_return(code, variable, name;
final_variable=variable,
model_for_registering=nothing)
macro_code = _macro_return(code, variable)
return quote
$(if model_for_registering !== nothing
:(_error_if_cannot_register($model_for_registering,
$(quot(name))))
end)
$variable = $macro_code
$(if model_for_registering !== nothing
:(object_dictionary($model_for_registering)[$(quot(name))] =
$final_variable)
end)
# This assignment should be in the scope calling the macro
$(esc(name)) = $final_variable
end
end
function _check_vectorized(sense::Symbol)
sense_str = string(sense)
if sense_str[1] == '.'
Symbol(sense_str[2:end]), true
else
sense, false
end
end
# two-argument build_constraint is used for one-sided constraints.
# Right-hand side is zero.
"""
sense_to_set(_error::Function, ::Val{sense_symbol})
Converts a sense symbol to a set `set` such that
`@constraint(model, func sense_symbol 0) is equivalent to
`@constraint(model, func in set)` for any `func::AbstractJuMPScalar`.
## Example
Once a custom set is defined you can directly create a JuMP constraint with it:
```jldoctest sense_to_set; setup = :(using JuMP)
julia> struct CustomSet{T} <: MOI.AbstractScalarSet
value::T
end
julia> model = Model();
julia> @variable(model, x)
x
julia> cref = @constraint(model, x in CustomSet(1.0))
x ∈ CustomSet{Float64}(1.0)
```
However, there might be an appropriate sign that could be used in order to
provide a more convenient syntax:
```jldoctest sense_to_set
julia> JuMP.sense_to_set(::Function, ::Val{:⊰}) = CustomSet(0.0)
julia> MOIU.shift_constant(set::CustomSet, value) = CustomSet(set.value + value)
julia> cref = @constraint(model, x ⊰ 1)
x ∈ CustomSet{Float64}(1.0)
```
Note that the whole function is first moved to the right-hand side, then the
sign is transformed into a set with zero constant and finally the constant is
moved to the set with `MOIU.shift_constant`.
"""
function sense_to_set end
sense_to_set(_error::Function, ::Union{Val{:(<=)}, Val{:(≤)}}) = MOI.LessThan(0.0)
sense_to_set(_error::Function, ::Union{Val{:(>=)}, Val{:(≥)}}) = MOI.GreaterThan(0.0)
sense_to_set(_error::Function, ::Val{:(==)}) = MOI.EqualTo(0.0)
sense_to_set(_error::Function, ::Val{S}) where S = _error("Unrecognized sense $S")
function parse_one_operator_constraint(_error::Function, vectorized::Bool,
::Union{Val{:in}, Val{:∈}}, aff, set)
newaff, parseaff = _parse_expr_toplevel(aff, :q)
parsecode = :(q = Val{false}(); $parseaff)
if vectorized
buildcall = :(build_constraint.($_error, $newaff, Ref($(esc(set)))))
else
buildcall = :(build_constraint($_error, $newaff, $(esc(set))))
end
parsecode, buildcall
end
function parse_one_operator_constraint(_error::Function, vectorized::Bool, sense::Val, lhs, rhs)
# Simple comparison - move everything to the LHS
aff = :($lhs - $rhs)
set = sense_to_set(_error, sense)
parse_one_operator_constraint(_error, vectorized, Val(:in), aff, set)
end
function parse_constraint(_error::Function, sense::Symbol, lhs, rhs)
(sense, vectorized) = _check_vectorized(sense)
vectorized, parse_one_operator_constraint(_error, vectorized, Val(sense), lhs, rhs)...
end
function parse_ternary_constraint(_error::Function, vectorized::Bool, lb, ::Union{Val{:(<=)}, Val{:(≤)}}, aff, rsign::Union{Val{:(<=)}, Val{:(≤)}}, ub)
newaff, parseaff = _parse_expr_toplevel(aff, :aff)
newlb, parselb = _parse_expr_toplevel(lb, :lb)
newub, parseub = _parse_expr_toplevel(ub, :ub)
if vectorized
buildcall = :(build_constraint.($_error, $newaff, $newlb, $newub))
else
buildcall = :(build_constraint($_error, $newaff, $newlb, $newub))
end
parseaff, parselb, parseub, buildcall
end
function parse_ternary_constraint(_error::Function, vectorized::Bool, ub, ::Union{Val{:(>=)}, Val{:(≥)}}, aff, rsign::Union{Val{:(>=)}, Val{:(≥)}}, lb)
parse_ternary_constraint(_error, vectorized, lb, Val(:(<=)), aff, Val(:(<=)), ub)
end
function parse_ternary_constraint(_error::Function, args...)
_error("Only two-sided rows of the form lb <= expr <= ub or ub >= expr >= lb are supported.")
end
function parse_constraint(_error::Function, lb, lsign::Symbol, aff, rsign::Symbol, ub)
(lsign, lvectorized) = _check_vectorized(lsign)
(rsign, rvectorized) = _check_vectorized(rsign)
((vectorized = lvectorized) == rvectorized) || _error("Signs are inconsistently vectorized")
parseaff, parselb, parseub, buildcall = parse_ternary_constraint(_error, vectorized, lb, Val(lsign), aff, Val(rsign), ub)
parsecode = quote
aff = Val{false}()
$parseaff
lb = 0.0
$parselb
ub = 0.0
$parseub
end
vectorized, parsecode, buildcall
end
function parse_constraint(_error::Function, args...)
# Unknown
_error("Constraints must be in one of the following forms:\n" *
" expr1 <= expr2\n" * " expr1 >= expr2\n" *
" expr1 == expr2\n" * " lb <= expr <= ub")
end
# Generic fallback.
function build_constraint(_error::Function, func,
set::Union{MOI.AbstractScalarSet, MOI.AbstractVectorSet})
return _error("unable to add the constraint because we don't recognize " *
"$(func) as a valid JuMP function.")
end
function build_constraint(_error::Function, v::AbstractJuMPScalar,
set::MOI.AbstractScalarSet)
return ScalarConstraint(v, set)
end
function build_constraint(_error::Function,
expr::Union{GenericAffExpr, GenericQuadExpr},
set::MOI.AbstractScalarSet)
offset = constant(expr)
add_to_expression!(expr, -offset)
return ScalarConstraint(expr, MOIU.shift_constant(set, -offset))
end
function build_constraint(_error::Function, α::Number,
set::MOI.AbstractScalarSet)
return build_constraint(_error, convert(AffExpr, α), set)
end
function build_constraint(_error::Function, x::Vector{<:AbstractJuMPScalar},
set::MOI.AbstractVectorSet)
return VectorConstraint(x, set)
end
function build_constraint(_error::Function, a::Vector{<:Number},
set::MOI.AbstractVectorSet)
return build_constraint(_error, convert(Vector{AffExpr}, a), set)
end
function build_constraint(_error::Function, x::AbstractArray,
set::MOI.AbstractScalarSet)
return _error("Unexpected vector in scalar constraint. Did you mean to use",
" the dot comparison operators like .==, .<=, and .>=",
" instead?")
end
function build_constraint(
_error::Function, x::Matrix, set::MOI.AbstractVectorSet)
return _error(
"unexpected matrix in vector constraint. Do you need to flatten the " *
"matrix into a vector using `vec()`?")
end
function build_constraint(_error::Function, ::Matrix, T::Union{
MOI.PositiveSemidefiniteConeSquare, MOI.PositiveSemidefiniteConeTriangle})
return _error("instead of `$(T)`, use `JuMP.PSDCone()`.")
end
# three-argument build_constraint is used for two-sided constraints.
function build_constraint(_error::Function, func::AbstractJuMPScalar,
lb::Real, ub::Real)
return build_constraint(_error, func, MOI.Interval(lb, ub))
end
# This method intercepts `@constraint(model, lb <= var <= ub)` and promotes
# `var` to an `AffExpr` to form a `ScalarAffineFunction-in-Interval` instead of
# `SingleVariable-in-Interval`. To create a
# `MOI.SingleVariable`-in-`MOI.Interval`, use
# `@constraint(model, var in MOI.Interval(lb, ub))`. We do this for consistency
# with how one-sided (in)equality constraints are parsed.
function build_constraint(_error::Function, func::AbstractVariableRef,
lb::Real, ub::Real)
return build_constraint(_error, 1.0func, lb, ub)
end
function build_constraint(_error::Function, expr, lb, ub)
lb isa Number || _error(string("Expected $lb to be a number."))
ub isa Number || _error(string("Expected $ub to be a number."))
if lb isa Number && ub isa Number
_error("Range constraint is not supported for $expr.")
end
end
function build_constraint(
::Function, x::Vector{<:AbstractJuMPScalar}, set::MOI.SOS1)
return VectorConstraint(x, MOI.SOS1{Float64}(set.weights))
end
function build_constraint(
::Function, x::Vector{<:AbstractJuMPScalar}, set::MOI.SOS2)
return VectorConstraint(x, MOI.SOS2{Float64}(set.weights))
end
# TODO: update 3-argument @constraint macro to pass through names like @variable
"""
_constraint_macro(args, macro_name::Symbol, parsefun::Function)
Returns the code for the macro `@constraint_like args...` of syntax
```julia
@constraint_like con # Single constraint
@constraint_like ref con # group of constraints
```
where `@constraint_like` is either `@constraint` or `@SDconstraint`.
The expression `con` is parsed by `parsefun` which returns a `build_constraint`
call code that, when executed, returns an `AbstractConstraint`. The macro
keyword arguments (except the `container` keyword argument which is used to
determine the container type) are added to the `build_constraint` call. The
returned value of this call is passed to `add_constraint` which returns a
constraint reference.
"""
function _constraint_macro(args, macro_name::Symbol, parsefun::Function)
_error(str...) = _macro_error(macro_name, args, str...)
args, kw_args, requestedcontainer = _extract_kw_args(args)
if length(args) < 2
if length(kw_args) > 0
_error("Not enough positional arguments")
else
_error("Not enough arguments")
end
end
m = args[1]
x = args[2]
extra = args[3:end]
m = esc(m)
# Two formats:
# - @constraint_like(m, a*x <= 5)
# - @constraint_like(m, myref[a=1:5], a*x <= 5)
length(extra) > 1 && _error("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()
name = _get_name(c)
base_name = anonvar ? "" : string(name)
# TODO: support the base_name keyword argument
if isa(x, Symbol)
_error("Incomplete constraint specification $x. Are you missing a comparison (<=, >=, or ==)?")
end
(x.head == :block) &&
_error("Code block passed as constraint. Perhaps you meant to use @constraints instead?")
# Strategy: build up the code for add_constraint, and if needed
# we will wrap in loops to assign to the ConstraintRefs
refcall, idxvars, idxsets, condition = _build_ref_sets(c, variable)
vectorized, parsecode, buildcall = parsefun(_error, x.args...)
_add_kw_args(buildcall, kw_args)
if vectorized
# TODO: Pass through names here.
constraintcall = :(add_constraint.($m, $buildcall))
else
constraintcall = :(add_constraint($m, $buildcall, $(_name_call(base_name, idxvars))))
end
code = quote
$parsecode
$(refcall) = $constraintcall
end
# Determine the return type of add_constraint. This is needed for JuMP extensions for which this is different than ConstraintRef
if vectorized
contype = :( AbstractArray{constraint_type($m)} ) # TODO use a concrete type instead of AbstractArray, see #525, #1310
else
contype = :( constraint_type($m) )
end
creationcode = _get_looped_code(variable, code, condition, idxvars, idxsets, contype, requestedcontainer)
if anonvar
# Anonymous constraint, no need to register it in the model-level
# dictionary nor to assign it to a variable in the user scope.
# We simply return the constraint reference
macro_code = _macro_return(creationcode, variable)
else
# We register the constraint reference to its name and
# we assign it to a variable in the local scope of this name
macro_code = _macro_assign_and_return(creationcode, variable, name,
model_for_registering = m)
end
return _assert_valid_model(m, macro_code)
end
# This function needs to be implemented by all `AbstractModel`s
constraint_type(m::Model) = ConstraintRef{typeof(m)}
"""
@constraint(m::Model, expr)
Add a constraint described by the expression `expr`.
@constraint(m::Model, ref[i=..., j=..., ...], expr)
Add a group of constraints described by the expression `expr` parametrized by
`i`, `j`, ...
The expression `expr` can either be
* of the form `func in set` constraining the function `func` to belong to the
set `set` which is either a [`MathOptInterface.AbstractSet`](http://www.juliaopt.org/MathOptInterface.jl/v0.6.2/apireference.html#Sets-1)
or one of the JuMP shortcuts [`SecondOrderCone`](@ref),
[`RotatedSecondOrderCone`](@ref) and [`PSDCone`](@ref), e.g.
`@constraint(model, [1, x-1, y-2] in SecondOrderCone())` constrains the norm
of `[x-1, y-2]` be less than 1;
* of the form `a sign b`, where `sign` is one of `==`, `≥`, `>=`, `≤` and
`<=` building the single constraint enforcing the comparison to hold for the
expression `a` and `b`, e.g. `@constraint(m, x^2 + y^2 == 1)` constrains `x`
and `y` to lie on the unit circle;
* of the form `a ≤ b ≤ c` or `a ≥ b ≥ c` (where `≤` and `<=` (resp. `≥` and
`>=`) can be used interchangeably) constraining the paired the expression
`b` to lie between `a` and `c`;
* of the forms `@constraint(m, a .sign b)` or
`@constraint(m, a .sign b .sign c)` which broadcast the constraint creation to
each element of the vectors.
## Note for extending the constraint macro
Each constraint will be created using
`add_constraint(m, build_constraint(_error, func, set))` where
* `_error` is an error function showing the constraint call in addition to the
error message given as argument,
* `func` is the expression that is constrained
* and `set` is the set in which it is constrained to belong.
For `expr` of the first type (i.e. `@constraint(m, func in set)`), `func` and
`set` are passed unchanged to `build_constraint` but for the other types, they
are determined from the expressions and signs. For instance,
`@constraint(m, x^2 + y^2 == 1)` is transformed into
`add_constraint(m, build_constraint(_error, x^2 + y^2, MOI.EqualTo(1.0)))`.
To extend JuMP to accept new constraints of this form, it is necessary to add
the corresponding methods to `build_constraint`. Note that this will likely mean
that either `func` or `set` will be some custom type, rather than e.g. a
`Symbol`, since we will likely want to dispatch on the type of the function or
set appearing in the constraint.
"""
macro constraint(args...)
_constraint_macro(args, :constraint, parse_constraint)
end
function parse_SD_constraint(_error::Function, sense::Symbol, lhs, rhs)
# Simple comparison - move everything to the LHS
aff = :()
if sense == :⪰ || sense == :(≥) || sense == :(>=)
aff = :($lhs - $rhs)
elseif sense == :⪯ || sense == :(≤) || sense == :(<=)
aff = :($rhs - $lhs)
else
_error("Invalid sense $sense in SDP constraint")
end
vectorized = false
parsecode, buildcall = parse_one_operator_constraint(_error, false, Val(:in), aff, :(JuMP.PSDCone()))
vectorized, parsecode, buildcall
end
function parse_SD_constraint(_error::Function, args...)
_error("Constraints must be in one of the following forms:\n" *
" expr1 <= expr2\n" *
" expr1 >= expr2")
end
"""
@SDconstraint(model::Model, expr)
Add a semidefinite constraint described by the expression `expr`.
@SDconstraint(model::Model, ref[i=..., j=..., ...], expr)
Add a group of semidefinite constraints described by the expression `expr`
parametrized by `i`, `j`, ...
The expression `expr` needs to be of the form `a sign b` where `sign` is `⪰`,
`≥`, `>=`, `⪯`, `≤` or `<=` and `a` and `b` are `square` matrices. It
constrains the matrix `x = a - b` (or `x = b - a` if the sign is `⪯`, `≤` or
`<=`) to be symmetric and positive semidefinite.
By default, we check numerical symmetry of the matrix `x`, and if symmetry is
violated by some arbitrary amount, we add explicit equality constraints.
You can use `Symmetric(x) in PSDCone()` with the [`@constraint`](@ref) macro to
skip these checks if you know the matrix must be symmetric; see
[`PSDCone`](@ref) for more information.
## Examples
The following constrains the matrix `[x-1 2x-2; -3 x-4]` to be symmetric and
positive semidefinite, that is, it constrains `2x-2` to be equal to `-3` and
constrains all eigenvalues of the matrix to be nonnegative.
```jldoctest; setup = :(using JuMP)
julia> model = Model();
julia> @variable(model, x)
x
julia> a = [x 2x
0 x];
julia> b = [1 2
3 4];
julia> cref = @SDconstraint(model, a ⪰ b)
[x - 1 2 x - 2;
-3 x - 4 ] ∈ PSDCone()
julia> jump_function(constraint_object(cref))
4-element Array{GenericAffExpr{Float64,VariableRef},1}:
x - 1
-3
2 x - 2
x - 4
julia> moi_set(constraint_object(cref))
MathOptInterface.PositiveSemidefiniteConeSquare(2)
```
In the set `PositiveSemidefiniteConeSquare(2)` in the last output, `Square`
means that the matrix is passed as a square matrix as the corresponding
off-diagonal entries need to be constrained to be equal. A similar set
`PositiveSemidefiniteConeTriangle` exists which only uses the upper triangular
part of the matrix assuming that it is symmetric, see [`PSDCone`](@ref) to see
how to use it.
"""
macro SDconstraint(args...)
_constraint_macro(args, :SDconstraint, parse_SD_constraint)
end
"""
@build_constraint(constraint_expr)
Constructs a `ScalarConstraint` or `VectorConstraint` using the same
machinery as [`@constraint`](@ref) but without adding the constraint to a model.
Constraints using broadcast operators like `x .<= 1` are also supported and will
create arrays of `ScalarConstraint` or `VectorConstraint`.
## Examples
```jldoctest; setup = :(using JuMP)
model = Model();
@variable(model, x);
@build_constraint(2x >= 1)
# output
ScalarConstraint{GenericAffExpr{Float64,VariableRef},MathOptInterface.GreaterThan{Float64}}(2 x, MathOptInterface.GreaterThan{Float64}(1.0))
```
"""
macro build_constraint(constraint_expr)
_error(str...) = _macro_error(:build_constraint, (constraint_expr,), str...)
if isa(constraint_expr, Symbol)
_error("Incomplete constraint specification $constraint_expr. " *
"Are you missing a comparison (<=, >=, or ==)?")
end
is_vectorized, parse_code, build_call = parse_constraint(
_error, constraint_expr.args...)
result_variable = gensym()
code = quote
$parse_code
$result_variable = $build_call
end
return _macro_return(code, result_variable)
end
_add_JuMP_prefix(s::Symbol) = Expr(:., JuMP, :($(QuoteNode(s))))
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)
if typeof(x) != Expr || x.head != :block
# We do a weird string interpolation here so that it gets
# interpolated at compile time, not run-time.
error("Invalid syntax for @" * $(string(mac)))
end
@assert isa(x.args[1], LineNumberNode)
lastline = x.args[1]
code = quote end
for it in x.args
if isa(it, LineNumberNode)
lastline = it
elseif isexpr(it, :tuple) # line with commas
args = []
# Keyword arguments have to appear like:
# x, (start = 10, lower_bound = 5)
# because of the precedence of "=".
for ex in it.args
if isexpr(ex, :tuple) # embedded tuple
append!(args, ex.args)
else
push!(args, ex)
end
end
mac = esc(Expr(:macrocall, $(_add_JuMP_prefix(sym)), lastline, m, args...))
push!(code.args, mac)
else # stand-alone symbol or expression
push!(code.args, esc(Expr(:macrocall, $(_add_JuMP_prefix(sym)), lastline, m, it)))
end
end
push!(code.args, :(nothing))
return code
end
end
end
# Doc strings for the auto-generated macro pluralizations
@doc """
@constraints(m, args...)
adds groups of constraints at once, in the same fashion as @constraint. The model must be the first argument, and multiple constraints can be added on multiple lines wrapped in a `begin ... end` block. For example:
@constraints(m, begin
x >= 1
y - w <= 2
sum_to_one[i=1:3], z[i] + y == 1
end)
""" :(@constraints)
"""
_moi_sense(_error::Function, sense)
Return an expression whose value is an `MOI.OptimizationSense` corresponding
to `sense`. Sense is either the symbol `:Min` or `:Max`, corresponding
respectively to `MOI.MIN_SENSE` and `MOI.MAX_SENSE` or it is another symbol,
which should be the name of a variable or expression whose value is an
`MOI.OptimizationSense`.
In the last case, the expression throws an error using the `_error`
function in case the value is not an `MOI.OptimizationSense`.
"""
function _moi_sense(_error::Function, sense)
if sense == :Min
expr = MOI.MIN_SENSE
elseif sense == :Max
expr = MOI.MAX_SENSE
else
# Refers to a variable that holds the sense.
# TODO: Better document this behavior
expr = esc(sense)
end
return :(_throw_error_for_invalid_sense($_error, $expr))
end
function _throw_error_for_invalid_sense(_error::Function, sense)
_error("Unexpected sense `$value`. The sense must be an",
" `MOI.OptimizatonSense`, `Min` or `Max`.")
end
function _throw_error_for_invalid_sense(
_error::Function, sense::MOI.OptimizationSense)
return sense
end
"""
@objective(model::Model, sense, func)
Set the objective sense to `sense` and objective function to `func`. The
objective sense can be either `Min`, `Max`, `MathOptInterface.MIN_SENSE`,
`MathOptInterface.MAX_SENSE` or `MathOptInterface.FEASIBILITY_SENSE`; see
[`MathOptInterface.ObjectiveSense`](http://www.juliaopt.org/MathOptInterface.jl/v0.8/apireference.html#MathOptInterface.ObjectiveSense).
In order to set the sense programatically, i.e., when `sense` is a Julia
variable whose value is the sense, one of the three
`MathOptInterface.ObjectiveSense` values should be used. The function `func` can
be a single JuMP variable, an affine expression of JuMP variables or a quadratic
expression of JuMP variables.
## Examples
To minimize the value of the variable `x`, do as follows:
```jldoctest @objective; setup = :(using JuMP)
julia> model = Model()
A JuMP Model
Feasibility problem with:
Variables: 0
Model mode: AUTOMATIC
CachingOptimizer state: NO_OPTIMIZER
Solver name: No optimizer attached.
julia> @variable(model, x)
x
julia> @objective(model, Min, x)
x
```
To maximize the value of the affine expression `2x - 1`, do as follows:
```jldoctest @objective
julia> @objective(model, Max, 2x - 1)
2 x - 1
```
To set a quadratic objective and set the objective sense programatically, do
as follows:
```jldoctest @objective
julia> sense = MOI.MIN_SENSE
MIN_SENSE::OptimizationSense = 0
julia> @objective(model, sense, x^2 - 2x + 1)
x² - 2 x + 1
```
"""
macro objective(model, args...)
_error(str...) = _macro_error(:objective, (model, args...), str...)
# We don't overwrite `model` as it is used in `_error`
esc_model = esc(model)
if length(args) != 2
# Either just an objective sense, or just an expression.
_error("needs three arguments: model, objective sense (Max or Min) and expression.")
end
sense, x = args
sense_expr = _moi_sense(_error, sense)
newaff, parsecode = _parse_expr_toplevel(x, :q)
code = quote
q = Val{false}()
$parsecode
set_objective($esc_model, $sense_expr, $newaff)
end
return _assert_valid_model(esc_model, _macro_return(code, newaff))
end
# Return a standalone, unnamed expression
# ex = @_build_expression(2x + 3y)
# Currently for internal use only.
macro _build_expression(x)
newaff, parsecode = _parse_expr_toplevel(x, :q)
code = quote
q = Val{false}()
$parsecode
end
return _macro_return(code, newaff)
end
"""
@expression(args...)
Efficiently builds a linear or quadratic expression but does not add to model
immediately. Instead, returns the expression which can then be inserted in other
constraints. For example:
```julia
@expression(m, shared, sum(i*x[i] for i=1:5))
@constraint(m, shared + y >= 5)
@constraint(m, shared + z <= 10)
```
The `ref` accepts index sets in the same way as `@variable`, and those indices
can be used in the construction of the expressions:
```julia
@expression(m, expr[i=1:3], i*sum(x[j] for j=1:3))
```
Anonymous syntax is also supported: