Skip to content

Commit

Permalink
add dimension check
Browse files Browse the repository at this point in the history
  • Loading branch information
Joaquim Garcia committed Mar 22, 2024
1 parent 7be10cc commit eda33ac
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/objective.jl
Original file line number Diff line number Diff line change
Expand Up @@ -532,6 +532,13 @@ function set_objective_coefficients(
if _nlp_objective_function(model) !== nothing
error("A nonlinear objective is already set in the model")
end
if length(variables) != length(coeffs)
throw(
DimensionMismatch(
"The number of variables and coefficients must match",
),
)
end
coeffs_t = convert.(T, coeffs)::AbstractVector{T}
F = objective_function_type(model)
_set_objective_coefficients(model, variables, coeffs_t, F)
Expand Down Expand Up @@ -702,6 +709,13 @@ function set_objective_coefficients(
if _nlp_objective_function(model) !== nothing
error("A nonlinear objective is already set in the model")
end
if !(length(variables_1) == length(variables_2) == length(coeffs))
throw(
DimensionMismatch(
"The number of variables and coefficients must match",
),
)
end
coeffs_t = convert.(T, coeffs)::AbstractVector{<:T}
F = moi_function_type(objective_function_type(model))
_set_objective_coefficients(model, variables_1, variables_2, coeffs_t, F)
Expand Down
26 changes: 26 additions & 0 deletions test/test_objective.jl
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,19 @@ function test_objective_coef_update_linear_objective_batch_error()
return
end

function test_objective_coef_update_linear_objective_batch_dimension_error()
model = Model()
@variable(model, x[1:2])
@objective(model, Min, x[1] * x[2])
@test_throws(
DimensionMismatch(
"The number of variables and coefficients must match",
),
set_objective_coefficients(model, [x[1], x[2]], [2]),
)
return
end

function test_objective_coef_batch_update_linear_objective_changes()
model = Model()
@variable(model, x)
Expand Down Expand Up @@ -325,6 +338,19 @@ function test_set_objective_coefficient_quadratic_batch_error()
return
end

function test_set_objective_coefficient_quadratic_batch_dimension_error()
model = Model()
@variable(model, x[1:2])
@objective(model, Min, x[1] * x[2])
@test_throws(
DimensionMismatch(
"The number of variables and coefficients must match",
),
set_objective_coefficients(model, [x[1]], [x[1]], [2, 3]),
)
return
end

function test_set_objective_coefficient_quadratic_affine_original()
model = Model()
@variable(model, x[1:2])
Expand Down

0 comments on commit eda33ac

Please sign in to comment.