Skip to content

Commit

Permalink
Fix type instability in set_objective_coefficient (#3590)
Browse files Browse the repository at this point in the history
  • Loading branch information
joaquimg authored Nov 29, 2023
1 parent 814f490 commit 3cbb874
Showing 1 changed file with 34 additions and 22 deletions.
56 changes: 34 additions & 22 deletions src/objective.jl
Original file line number Diff line number Diff line change
Expand Up @@ -261,29 +261,41 @@ function set_objective_coefficient(
if _nlp_objective_function(model) !== nothing
error("A nonlinear objective is already set in the model")
end
coeff = convert(T, coeff)::T
obj_fct_type = objective_function_type(model)
if obj_fct_type == GenericVariableRef{T}
# Promote the objective function to be an affine expression.
current_obj = objective_function(model)
if index(current_obj) == index(variable)
set_objective_function(model, coeff * variable)
else
set_objective_function(
model,
add_to_expression!(coeff * variable, current_obj),
)
end
elseif obj_fct_type == GenericAffExpr{T,GenericVariableRef{T}} ||
obj_fct_type == GenericQuadExpr{T,GenericVariableRef{T}}
MOI.modify(
backend(model),
MOI.ObjectiveFunction{moi_function_type(obj_fct_type)}(),
MOI.ScalarCoefficientChange(index(variable), coeff),
)
coeff_t = convert(T, coeff)::T
F = objective_function_type(model)
_set_objective_coefficient(model, variable, coeff_t, F)
model.is_model_dirty = true
return
end

function _set_objective_coefficient(
model::GenericModel{T},
variable::GenericVariableRef{T},
coeff::T,
::Type{GenericVariableRef{T}},
) where {T}
current_obj = objective_function(model)
if index(current_obj) == index(variable)
set_objective_function(model, coeff * variable)
else
error("Objective function type not supported: $(obj_fct_type)")
set_objective_function(
model,
add_to_expression!(coeff * variable, current_obj),
)
end
model.is_model_dirty = true
return
end

function _set_objective_coefficient(
model::GenericModel{T},
variable::GenericVariableRef{T},
coeff::T,
::Type{F},
) where {T,F}
MOI.modify(
backend(model),
MOI.ObjectiveFunction{moi_function_type(F)}(),
MOI.ScalarCoefficientChange(index(variable), coeff),
)
return
end

0 comments on commit 3cbb874

Please sign in to comment.