forked from jump-dev/JuMP.jl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse_nlp.jl
638 lines (609 loc) · 21.2 KB
/
parse_nlp.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
# 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 https://mozilla.org/MPL/2.0/.
# Returns the block expression inside a :let that holds the code to be run.
# The other block (not returned) is for declaring variables in the scope of the
# let.
function _let_code_block(ex::Expr)
@assert isexpr(ex, :let)
return ex.args[2]
end
function _error_curly(x)
return Base.error(
"The curly syntax (sum{},prod{},norm2{}) is no longer supported. Expression: $x.",
)
end
function _warn_auto_register(opname, N)
@warn("""Function $(opname) automatically registered with $N arguments.
Calling the function with a different number of arguments will result in an
error.
While you can safely ignore this warning, we recommend that you manually
register the function as follows:
```Julia
model = Model()
register(model, :$opname, $N, $opname; autodiff = true)
```""")
return
end
# generates code which converts an expression into a NodeData array (tape)
# parent is the index of the parent expression
# values is the name of the list of constants which appear in the expression
function _parse_NL_expr(m, x, tapevar, parent, values)
if isexpr(x, :block)
error(
"`begin...end` blocks are not supported in nonlinear macros. The " *
"nonlinear expression must be a single statement.",
)
end
if isexpr(x, :call) &&
length(x.args) >= 2 &&
(isexpr(x.args[2], :generator) || isexpr(x.args[2], :flatten))
header = x.args[1]
if _is_sum(header)
operatorid = operator_to_id[:+]
elseif _is_prod(header)
operatorid = operator_to_id[:*]
else
error("Unrecognized expression $header(...)")
end
codeblock = :(
let
end
)
block = _let_code_block(codeblock)
push!(
block.args,
:(push!($tapevar, NodeData(CALL, $operatorid, $parent))),
)
parentvar = gensym()
push!(block.args, :($parentvar = length($tapevar)))
code = _MA.rewrite_generator(
x.args[2],
t -> _parse_NL_expr(m, t, tapevar, parentvar, values),
)
push!(block.args, code)
return codeblock
end
if isexpr(x, :call)
if isexpr(x.args[1], :.)
# Functions like foo.bar cannot possibly be registered, because you
# can register only with a symbol name.
errorstring =
"Unexpected function $(x.args[1]). See the " *
"documentation on how to register a function."
return :(error($errorstring))
end
if _is_sum(x.args[1]) || _is_prod(x.args[1])
opname = x.args[1]
errorstring =
"$opname() can appear in nonlinear expressions " *
" only if the argument is a generator statement, for example, " *
"$opname(x[i] for i in 1:N)."
return :(error($errorstring))
end
if length(x.args) == 2 && !isexpr(x.args[2], :...) # univariate
code = :(
let
end
)
block = _let_code_block(code)
@assert isexpr(block, :block)
if haskey(univariate_operator_to_id, x.args[1])
operatorid = univariate_operator_to_id[x.args[1]]
push!(
block.args,
:(push!(
$tapevar,
NodeData(CALLUNIVAR, $operatorid, $parent),
)),
)
else
opname = quot(x.args[1])
f = x.args[1]
errorstring = """
Unrecognized function \"$(f)\" used in nonlinear expression.
If the function exists, but is not within the scope of this call,
you should register it as a user-defined function before building
the model. For example:
```julia
model = Model()
register(model, :$(f), 1, $(f), autodiff=true)
# ... variables and constraints ...
```
"""
errorstring2 = "Incorrect number of arguments for \"$(x.args[1])\" in nonlinear expression."
lookupcode = quote
if $(esc(m)).nlp_data === nothing
try
register(
$(esc(m)),
$opname,
1,
$(esc(x.args[1]));
autodiff = true,
)
_warn_auto_register($opname, 1)
catch
error($errorstring)
end
end
if !haskey(
$(esc(
m,
)).nlp_data.user_operators.univariate_operator_to_id,
$opname,
)
if haskey(
$(esc(
m,
)).nlp_data.user_operators.multivariate_operator_to_id,
$opname,
)
error($errorstring2)
else
try
register(
$(esc(m)),
$opname,
1,
$(esc(x.args[1]));
autodiff = true,
)
_warn_auto_register($opname, 1)
catch
error($errorstring)
end
end
end
operatorid =
$(esc(
m,
)).nlp_data.user_operators.univariate_operator_to_id[$opname] +
_Derivatives.USER_UNIVAR_OPERATOR_ID_START - 1
end
push!(
block.args,
:(
$lookupcode;
push!(
$tapevar,
NodeData(CALLUNIVAR, operatorid, $parent),
)
),
)
end
parentvar = gensym()
push!(block.args, :($parentvar = length($tapevar)))
push!(
block.args,
_parse_NL_expr(m, x.args[2], tapevar, parentvar, values),
)
return code
else
code = :(
let
end
)
block = _let_code_block(code)
@assert isexpr(block, :block)
if haskey(operator_to_id, x.args[1]) # fast compile-time lookup
operatorid = operator_to_id[x.args[1]]
push!(
block.args,
:(push!($tapevar, NodeData(CALL, $operatorid, $parent))),
)
elseif haskey(comparison_operator_to_id, x.args[1])
operatorid = comparison_operator_to_id[x.args[1]]
push!(
block.args,
:(push!(
$tapevar,
NodeData(COMPARISON, $operatorid, $parent),
)),
)
else # could be user defined
opname = quot(x.args[1])
N = length(x.args) - 1
f = x.args[1]
errorstring = """
Unrecognized function \"$(f)\" used in nonlinear expression.
If the function exists, but is not within the scope of this call,
you should register it as a user-defined function before building
the model. For example:
```julia
model = Model()
register(model, :$(f), $(N), $(f), autodiff=true)
# ... variables and constraints ...
```
"""
errorstring2 = "Incorrect number of arguments for \"$(x.args[1])\" in nonlinear expression."
lookupcode = quote
if $(esc(m)).nlp_data === nothing
try
register(
$(esc(m)),
$opname,
$N,
$(esc(x.args[1]));
autodiff = true,
)
_warn_auto_register($opname, $N)
catch
error($errorstring)
end
end
if !haskey(
$(esc(
m,
)).nlp_data.user_operators.multivariate_operator_to_id,
$opname,
)
if haskey(
$(esc(
m,
)).nlp_data.user_operators.univariate_operator_to_id,
$opname,
)
error($errorstring2)
else
try
register(
$(esc(m)),
$opname,
$N,
$(esc(x.args[1]));
autodiff = true,
)
_warn_auto_register($opname, $N)
catch
error($errorstring)
end
end
end
operatorid =
$(esc(
m,
)).nlp_data.user_operators.multivariate_operator_to_id[$opname] +
_Derivatives.USER_OPERATOR_ID_START - 1
end
push!(
block.args,
:($lookupcode;
push!($tapevar, NodeData(CALL, operatorid, $parent))),
)
end
parentvar = gensym()
push!(block.args, :($parentvar = length($tapevar)))
for i in 1:length(x.args)-1
arg = x.args[i+1]
if isexpr(arg, :...)
if !isa(arg.args[1], Symbol)
error(
"Unexpected expression in $x. JuMP supports " *
"splatting only symbols. For example, x... is " *
"ok, but (x + 1)..., [x; y]... and g(f(y)...) " *
"are not.",
)
end
push!(
block.args,
quote
for val in $(esc(arg.args[1]))
_parse_NL_expr_runtime(
$(esc(m)),
val,
$tapevar,
$parentvar,
$values,
)
end
end,
)
else
push!(
block.args,
_parse_NL_expr(m, arg, tapevar, parentvar, values),
)
end
end
return code
end
end
if isexpr(x, :comparison)
code = :(
let
end
)
block = _let_code_block(code)
op = x.args[2]
operatorid = comparison_operator_to_id[op]
for k in 2:2:length(x.args)-1
@assert x.args[k] == op # don't handle a <= b >= c
end
parentvar = gensym()
push!(
block.args,
:(push!($tapevar, NodeData(COMPARISON, $operatorid, $parent))),
)
push!(block.args, :($parentvar = length($tapevar)))
for k in 1:2:length(x.args)
push!(
block.args,
_parse_NL_expr(m, x.args[k], tapevar, parentvar, values),
)
end
return code
end
if isexpr(x, :&&) || isexpr(x, :||)
code = :(
let
end
)
block = _let_code_block(code)
op = x.head
operatorid = logic_operator_to_id[op]
parentvar = gensym()
push!(
block.args,
:(push!($tapevar, NodeData(LOGIC, $operatorid, $parent))),
)
push!(block.args, :($parentvar = length($tapevar)))
push!(
block.args,
_parse_NL_expr(m, x.args[1], tapevar, parentvar, values),
)
push!(
block.args,
_parse_NL_expr(m, x.args[2], tapevar, parentvar, values),
)
return code
end
if isexpr(x, :curly)
_error_curly(x)
end
if isexpr(x, :...)
error("Unexpected splatting expression $x.")
end
# at the lowest level?
return :(_parse_NL_expr_runtime(
$(esc(m)),
$(esc(x)),
$tapevar,
$parent,
$values,
))
end
function _parse_NL_expr_runtime(m::Model, x::Real, tape, parent, values)
push!(values, x)
push!(tape, NodeData(VALUE, length(values), parent))
return nothing
end
function _parse_NL_expr_runtime(m::Model, x::VariableRef, tape, parent, values)
if owner_model(x) !== m
error(
"Variable in nonlinear expression does not belong to the " *
"corresponding model",
)
end
push!(tape, NodeData(MOIVARIABLE, x.index.value, parent))
return nothing
end
function _parse_NL_expr_runtime(
m::Model,
x::NonlinearExpression,
tape,
parent,
values,
)
push!(tape, NodeData(SUBEXPRESSION, x.index, parent))
return nothing
end
function _parse_NL_expr_runtime(
m::Model,
x::NonlinearParameter,
tape,
parent,
values,
)
push!(tape, NodeData(PARAMETER, x.index, parent))
return nothing
end
function _parse_NL_expr_runtime(
m::Model,
x::AbstractArray,
tape,
parent,
values,
)
return error(
"Unexpected array $x in nonlinear expression. Nonlinear expressions may contain only scalar expressions.",
)
end
function _parse_NL_expr_runtime(
m::Model,
x::GenericQuadExpr,
tape,
parent,
values,
)
push!(tape, NodeData(CALL, operator_to_id[:+], parent))
sum_parent = length(tape)
_parse_NL_expr_runtime(m, x.aff, tape, sum_parent, values)
for (xy, c) in x.terms
push!(tape, NodeData(CALL, operator_to_id[:*], sum_parent))
mult_parent = length(tape)
_parse_NL_expr_runtime(m, xy.a, tape, mult_parent, values)
_parse_NL_expr_runtime(m, xy.b, tape, mult_parent, values)
if !isone(c) # Optimization: no need for * node.
_parse_NL_expr_runtime(m, c, tape, mult_parent, values)
end
end
return
end
function _parse_NL_expr_runtime(
m::Model,
x::GenericAffExpr,
tape,
parent,
values,
)
push!(tape, NodeData(CALL, operator_to_id[:+], parent))
sum_parent = length(tape)
if !iszero(x.constant)
_parse_NL_expr_runtime(m, x.constant, tape, sum_parent, values)
end
for (v, c) in x.terms
if isone(c) # Optimization: no need for * node.
_parse_NL_expr_runtime(m, v, tape, sum_parent, values)
else
push!(tape, NodeData(CALL, operator_to_id[:*], sum_parent))
mult_parent = length(tape)
_parse_NL_expr_runtime(m, c, tape, mult_parent, values)
_parse_NL_expr_runtime(m, v, tape, mult_parent, values)
end
end
return
end
function _parse_NL_expr_runtime(m::Model, x, tape, parent, values)
return error(
"Unexpected object $x (of type $(typeof(x)) in nonlinear expression.",
)
end
function _parse_NL_expr_runtime(m, x, tape, parent, values)
return error(
"Encountered an error parsing nonlinear expression: we don't support " *
"models of type $(typeof(m)). In general, JuMP's nonlinear features " *
"don't work with JuMP-extensions.",
)
end
function _expression_complexity(ex::Expr)
return isempty(ex.args) ? 1 : sum(_expression_complexity, ex.args)
end
_expression_complexity(other) = 1
# This is separated from the macro version to make it available for other @NL*
# macros.
function _process_NL_expr(model, ex)
# This is an arbitrary cutoff. See issue #1355.
if _expression_complexity(ex) > 5000
@warn "Processing a very large nonlinear expression with " *
"@NLexpression/@NLconstraint/@NLobjective. This may be very " *
"slow. Consider using setNLobjective() and addNLconstraint() " *
"instead of the macros or reformulating the expressions using " *
"sum() and prod() to make them more compact. The macros are " *
"designed to process smaller, human-readable expressions."
end
parsed = _parse_NL_expr(model, ex, :tape, -1, :values)
return quote
tape = NodeData[]
values = Float64[]
$parsed
_NonlinearExprData(tape, values)
end
end
macro _process_NL_expr(model, ex)
return _process_NL_expr(model, ex)
end
function _Derivatives.expr_to_nodedata(
ex::VariableRef,
nd::Vector{NodeData},
values::Vector{Float64},
parentid,
r::_Derivatives.UserOperatorRegistry,
)
push!(nd, NodeData(MOIVARIABLE, ex.index.value, parentid))
return nothing
end
function _Derivatives.expr_to_nodedata(
ex::NonlinearExpression,
nd::Vector{NodeData},
values::Vector{Float64},
parentid,
r::_Derivatives.UserOperatorRegistry,
)
push!(nd, NodeData(SUBEXPRESSION, ex.index, parentid))
return nothing
end
function _Derivatives.expr_to_nodedata(
ex::NonlinearParameter,
nd::Vector{NodeData},
values::Vector{Float64},
parentid,
r::_Derivatives.UserOperatorRegistry,
)
push!(nd, NodeData(PARAMETER, ex.index, parentid))
return nothing
end
function _Derivatives.expr_to_nodedata(
ex::GenericAffExpr,
nd::Vector{NodeData},
values::Vector{Float64},
parentid,
r::_Derivatives.UserOperatorRegistry,
)
push!(nd, NodeData(CALL, operator_to_id[:+], parentid))
sum_parent = length(nd)
if !iszero(ex.constant)
_Derivatives.expr_to_nodedata(ex.constant, nd, values, sum_parent, r)
end
for (v, c) in ex.terms
if isone(c) # Optimization: no need for * node.
_Derivatives.expr_to_nodedata(v, nd, values, sum_parent, r)
else
push!(nd, NodeData(CALL, operator_to_id[:*], sum_parent))
mult_parent = length(nd)
_Derivatives.expr_to_nodedata(c, nd, values, mult_parent, r)
_Derivatives.expr_to_nodedata(v, nd, values, mult_parent, r)
end
end
return
end
function _Derivatives.expr_to_nodedata(
ex::GenericQuadExpr,
nd::Vector{NodeData},
values::Vector{Float64},
parentid,
r::_Derivatives.UserOperatorRegistry,
)
push!(nd, NodeData(CALL, operator_to_id[:+], parentid))
sum_parent = length(nd)
_Derivatives.expr_to_nodedata(ex.aff, nd, values, sum_parent, r)
for (xy, c) in ex.terms
push!(nd, NodeData(CALL, operator_to_id[:*], sum_parent))
mult_parent = length(nd)
_Derivatives.expr_to_nodedata(xy.a, nd, values, mult_parent, r)
_Derivatives.expr_to_nodedata(xy.b, nd, values, mult_parent, r)
if !isone(c) # Optimization: no need for * node.
_Derivatives.expr_to_nodedata(c, nd, values, mult_parent, r)
end
end
return
end
# Construct a _NonlinearExprData from a Julia expression.
# VariableRef objects should be spliced into the expression.
function _NonlinearExprData(m::Model, ex::Expr)
_init_NLP(m)
_check_expr(m, ex)
nd, values = _Derivatives.expr_to_nodedata(ex, m.nlp_data.user_operators)
return _NonlinearExprData(nd, values)
end
_NonlinearExprData(m::Model, ex) = _NonlinearExprData(m, :($ex + 0))
# Error if:
# 1) Unexpected expression
# 2) VariableRef doesn't match the model
function _check_expr(m::Model, ex::Expr)
if ex.head == :ref # if we have x[1] already in there, something is wrong
error(
"Unrecognized expression $ex. JuMP variable objects and input coefficients should be spliced directly into expressions.",
)
end
for e in ex.args
_check_expr(m, e)
end
return
end
function _check_expr(m::Model, v::VariableRef)
owner_model(v) === m || error("Variable $v does not belong to this model.")
return
end
_check_expr(m::Model, ex) = nothing