Skip to content

Commit

Permalink
Add convert and parse
Browse files Browse the repository at this point in the history
  • Loading branch information
odow committed Feb 1, 2023
1 parent c6133fe commit f5fdc67
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/Nonlinear/parse.jl
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,28 @@ function parse_expression(
return
end

function parse_expression(
data::Model,
expr::Expression,
x::MOI.ScalarAffineFunction{T},
parent::Int,
) where {T}
f = convert(MOI.ScalarNonlinearFunction{T}, x)
parse_expression(data, expr, f, parent)
return
end

function parse_expression(
data::Model,
expr::Expression,
x::MOI.ScalarQuadraticFunction{T},
parent::Int,
) where {T}
f = convert(MOI.ScalarNonlinearFunction{T}, x)
parse_expression(data, expr, f, parent)
return
end

function parse_expression(::Model, expr::Expression, x::Real, parent_index::Int)
push!(expr.values, convert(Float64, x)::Float64)
push!(expr.nodes, Node(NODE_VALUE, length(expr.values), parent_index))
Expand Down
46 changes: 46 additions & 0 deletions src/functions.jl
Original file line number Diff line number Diff line change
Expand Up @@ -773,3 +773,49 @@ function Base.convert(
[g.constant],
)
end

function Base.convert(
::Type{ScalarNonlinearFunction{T}},
term::ScalarAffineTerm{T},
) where {T}
return ScalarNonlinearFunction{T}(
:*,
Any[term.coefficient, term.variable],
)
end

function Base.convert(
F::Type{ScalarNonlinearFunction{T}},
f::ScalarAffineFunction{T},
) where {T}
args =
Any[convert(ScalarNonlinearFunction{T}, term) for term in f.terms]
if !iszero(f.constant)
push!(args, f.constant)
end
return ScalarNonlinearFunction{T}(:+, args)
end

function Base.convert(
::Type{ScalarNonlinearFunction{T}},
term::ScalarQuadraticTerm{T},
) where {T}
return ScalarNonlinearFunction{T}(
:*,
Any[term.coefficient, term.variable_1, term.variable_2],
)
end

function Base.convert(
F::Type{ScalarNonlinearFunction{T}},
f::ScalarQuadraticFunction{T},
) where {T}
args = Any[convert(F, term) for term in f.quadratic_terms]
for term in f.affine_terms
push!(args, convert(F, term))
end
if !iszero(f.constant)
push!(args, f.constant)
end
return ScalarNonlinearFunction{T}(:+, args)
end

0 comments on commit f5fdc67

Please sign in to comment.