Skip to content

Commit fd8a036

Browse files
committed
fix inefficient variable check; refactor all_variables
1 parent 0245f2f commit fd8a036

File tree

3 files changed

+23
-4
lines changed

3 files changed

+23
-4
lines changed

src/backends/moi_backend.jl

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,15 @@ function MOI.get(backend::GraphMOIBackend, attr::MOI.NumberOfVariables, node::Op
235235
return length(backend.node_variables[node])
236236
end
237237

238+
function MOI.get(backend::GraphMOIBackend, attr::MOI.ListOfVariableIndices, node::OptiNode)
239+
graph_indices = backend.node_variables[node]
240+
var_indices = MOI.VariableIndex[]
241+
for graph_index in graph_indices
242+
push!(var_indices, backend.graph_to_element_map[graph_index].index)
243+
end
244+
return var_indices
245+
end
246+
238247
function MOI.get(
239248
backend::GraphMOIBackend, attr::MOI.ListOfConstraintTypesPresent, element::OptiElement
240249
)

src/optinode.jl

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -117,9 +117,8 @@ function JuMP.num_variables(node::OptiNode)
117117
end
118118

119119
function JuMP.all_variables(node::OptiNode)
120-
gb = graph_backend(node)
121-
graph_indices = gb.node_variables[node]
122-
return getindex.(Ref(gb.graph_to_element_map), graph_indices)
120+
var_inds = MOI.get(node, MOI.ListOfVariableIndices(), node)
121+
return NodeVariableRef.(Ref(node), var_inds)
123122
end
124123

125124
function JuMP.delete(node::OptiNode, cref::ConstraintRef)
@@ -211,7 +210,13 @@ function _check_node_variables(
211210
NodeVariableRef,JuMP.GenericAffExpr,JuMP.GenericQuadExpr,JuMP.GenericNonlinearExpr
212211
},
213212
)
214-
return isempty(setdiff(_extract_variables(jump_func), JuMP.all_variables(node)))
213+
extract_vars = _extract_variables(jump_func)
214+
for var in extract_vars
215+
if var.node != node
216+
error("Variable $var does not belong to node $node")
217+
end
218+
end
219+
return nothing
215220
end
216221

217222
### Objective

test/test_optigraph.jl

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,11 @@ function test_variable_constraints()
293293
set_start_value(n2[:x], 3.0)
294294
@test start_value(n2[:x]) == 3.0
295295

296+
# variable not owned
297+
@test_throws ErrorException("Variable $(n1[:x]) does not belong to node $n2") @constraint(
298+
n2, n1[:x] >= 0
299+
)
300+
296301
# bounds
297302
@test has_lower_bound(n1[:x]) == true
298303
@test has_upper_bound(n1[:x]) == false

0 commit comments

Comments
 (0)