Skip to content

Commit

Permalink
Simplify div of monomial and variable
Browse files Browse the repository at this point in the history
  • Loading branch information
odow committed Mar 17, 2024
1 parent faf3389 commit bb90b58
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 8 deletions.
22 changes: 14 additions & 8 deletions src/nl_to_polynomial.jl
Original file line number Diff line number Diff line change
Expand Up @@ -94,21 +94,27 @@ function _to_polynomial!(
return a^b
elseif _is_operator(expr, :/) && length(operands) == 2
a, b = _to_polynomial!.(Ref(d), T, operands)
return a / b
# TODO(odow): see PR#113
# divisor, remainder = Base.divrem(a, b)
# if iszero(remainder)
# return divisor
# else
# return a / b
# end
return _checked_div(a, b)
elseif _is_variable(expr)
return _to_polynomial!(d, T, operands[1])
else
throw(InvalidNLExpression("Cannot convert `$(expr)` into a polynomial"))
end
end

_checked_div(a, b) = a / b

function _checked_div(
a::DynamicPolynomials.Monomial,
b::DynamicPolynomials.Variable,
)
divisor, remainder = Base.divrem(a, b)
if iszero(remainder)
return divisor
end
return a / b

Check warning on line 115 in src/nl_to_polynomial.jl

View check run for this annotation

Codecov / codecov/patch

src/nl_to_polynomial.jl#L115

Added line #L115 was not covered by tests
end

function _to_polynomial(expr, ::Type{T}) where {T}
d = Dict{MOI.VariableIndex,VarType}()
poly = _to_polynomial!(d, T, expr)
Expand Down
32 changes: 32 additions & 0 deletions test/qcqp.jl
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,38 @@ function test_scalar_nonlinear_function(x, y, T)
return
end

function test_scalar_nonlinear_function_div_rem_zero(x, y, T)
inner = Model{T}()
model = PolyJuMP.JuMP.GenericModel{T}() do
return PolyJuMP.QCQP.Optimizer{T}(MOI.Utilities.MockOptimizer(inner))
end
PolyJuMP.@variable(model, x)
PolyJuMP.@objective(model, Min, x^3 / x)
PolyJuMP.optimize!(model)
@test MOI.get(inner, MOI.NumberOfVariables()) == 1
@test isempty(MOI.get(inner, MOI.ListOfConstraintTypesPresent()))
@test PolyJuMP.objective_function(model) isa PolyJuMP.GenericNonlinearExpr
F = MOI.get(inner, MOI.ObjectiveFunctionType())
@test F <: MOI.ScalarQuadraticFunction{T}
return
end

test_scalar_nonlinear_function_div_rem_one(x, y, ::Type{Int}) = nothing

function test_scalar_nonlinear_function_div_rem_one(x, y, T)
inner = Model{T}()
model = PolyJuMP.JuMP.GenericModel{T}() do
return PolyJuMP.QCQP.Optimizer{T}(MOI.Utilities.MockOptimizer(inner))
end
PolyJuMP.@variable(model, x)
PolyJuMP.@objective(model, Min, x^3 / 2)
PolyJuMP.optimize!(model)
@test MOI.get(inner, MOI.NumberOfVariables()) == 2
F, S = MOI.ScalarQuadraticFunction{T}, MOI.EqualTo{T}
@test (F, S) in MOI.get(inner, MOI.ListOfConstraintTypesPresent())
return
end

function test_variable_primal(x, y, T)
inner = Model{T}()
optimizer = MOI.Utilities.MockOptimizer(inner)
Expand Down

0 comments on commit bb90b58

Please sign in to comment.