Skip to content

Commit d8e9515

Browse files
committed
Cache subexpressions when building MOI.ScalarNonlinearExpression
1 parent b19c3e7 commit d8e9515

File tree

2 files changed

+13
-0
lines changed

2 files changed

+13
-0
lines changed

src/JuMP.jl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,8 @@ mutable struct GenericModel{T<:Real} <: AbstractModel
138138
# A dictionary to store timing information from the JuMP macros.
139139
enable_macro_timing::Bool
140140
macro_times::Dict{Tuple{LineNumberNode,String},Float64}
141+
# We use `Any` as key because we haven't defined `GenericNonlinearExpr` yet
142+
subexpressions::Dict{Any,MOI.ScalarNonlinearFunction}
141143
end
142144

143145
value_type(::Type{GenericModel{T}}) where {T} = T
@@ -251,6 +253,7 @@ function direct_generic_model(
251253
Dict{Any,MOI.ConstraintIndex}(),
252254
false,
253255
Dict{Tuple{LineNumberNode,String},Float64}(),
256+
Dict{Any,MOI.ScalarNonlinearFunction}(),
254257
)
255258
end
256259

src/nlp_expr.jl

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -553,6 +553,10 @@ end
553553
moi_function(x::Number) = x
554554

555555
function moi_function(f::GenericNonlinearExpr{V}) where {V}
556+
model = owner_model(f)
557+
if haskey(model.subexpressions, f)
558+
return model.subexpressions[f]
559+
end
556560
ret = MOI.ScalarNonlinearFunction(f.head, similar(f.args))
557561
stack = Tuple{MOI.ScalarNonlinearFunction,Int,GenericNonlinearExpr{V}}[]
558562
for i in length(f.args):-1:1
@@ -564,6 +568,10 @@ function moi_function(f::GenericNonlinearExpr{V}) where {V}
564568
end
565569
while !isempty(stack)
566570
parent, i, arg = pop!(stack)
571+
if haskey(model.subexpressions, arg)
572+
parent.args[i] = model.subexpressions[arg]
573+
continue
574+
end
567575
child = MOI.ScalarNonlinearFunction(arg.head, similar(arg.args))
568576
parent.args[i] = child
569577
for j in length(arg.args):-1:1
@@ -573,7 +581,9 @@ function moi_function(f::GenericNonlinearExpr{V}) where {V}
573581
child.args[j] = moi_function(arg.args[j])
574582
end
575583
end
584+
model.subexpressions[arg] = child
576585
end
586+
model.subexpressions[f] = ret
577587
return ret
578588
end
579589

0 commit comments

Comments
 (0)