diff --git a/src/constraints.jl b/src/constraints.jl index fcb5b403101..ad06807785d 100644 --- a/src/constraints.jl +++ b/src/constraints.jl @@ -588,6 +588,17 @@ function value(con_ref::ConstraintRef{Model, <:_MOICON}; result::Int = 1) return reshape_vector(_constraint_primal(con_ref, result), con_ref.shape) end +""" + value(con_ref::ConstraintRef, var_value::Function) + +Evaluate the primal value of the constraint `con_ref` using `var_value(v)` +as the value for each variable `v`. +""" +function value(con_ref::ConstraintRef{Model, <:_MOICON}, var_value::Function) + f = jump_function(constraint_object(con_ref)) + return reshape_vector(value.(f, var_value), con_ref.shape) +end + # Returns the value of MOI.ConstraintPrimal in a type-stable way function _constraint_primal( con_ref::ConstraintRef{ diff --git a/src/variables.jl b/src/variables.jl index 613f65a341f..63976018dc2 100644 --- a/src/variables.jl +++ b/src/variables.jl @@ -767,6 +767,15 @@ function value(v::VariableRef; result::Int = 1)::Float64 return MOI.get(owner_model(v), MOI.VariablePrimal(result), v) end +""" + value(v::VariableRef, var_value::Function) + +Evaluate the value of the variable `v` as `var_value(v)`. +""" +function value(v::VariableRef, var_value::Function) + return var_value(v) +end + """ has_values(model::Model; result::Int = 1) diff --git a/test/constraint.jl b/test/constraint.jl index 8c0739e8933..6011b748930 100644 --- a/test/constraint.jl +++ b/test/constraint.jl @@ -663,6 +663,21 @@ function test_Model_add_to_function_constant_vector(::Any, ::Any) @test JuMP.moi_set(con) == MOI.Nonnegatives(2) end +function test_Model_value_constraint_var(ModelType, ::Any) + model = ModelType() + @variable(model, x[1:2]) + @constraint(model, c1, x[1] + x[2] <= 3.0) + @constraint(model, c2, x[1]^2 + x[2]^2 <= 3.0) + @constraint(model, c3, [1.0, x[1], x[2]] in SecondOrderCone()) + + vals = Dict(x[1] => 1.0, x[2] => 2.0) + f = vidx -> vals[vidx] + + @test value(c1, f) === 3.0 # Affine expression + @test value(c2, f) === 5.0 # Quadratic expression + @test value(c3, f) == [1.0, 1.0, 2.0] # Vector expression +end + function _test_shadow_price_util(model_string, constraint_dual, constraint_shadow) model = Model() MOIU.loadfromstring!(backend(model), model_string) diff --git a/test/variable.jl b/test/variable.jl index 04a3684be62..38db2e7b76b 100644 --- a/test/variable.jl +++ b/test/variable.jl @@ -713,6 +713,17 @@ function test_Model_value(::Any, ::Any) @test value(JuMP._MA.Zero()) === 0.0 end +function test_Model_value_var(ModelType, ::Any) + model = ModelType() + @variable(model, x[1:2]) + + vals = Dict(x[1] => 1.0, x[2] => 2.0) + f = vidx -> vals[vidx] + + @test value(x[1], f) === 1.0 + @test value(x[2], f) === 2.0 +end + function test_Model_relax_integrality(::Any, ::Any) model = Model() @variable(model, x, Bin)