Skip to content

Commit

Permalink
Add write_to_file
Browse files Browse the repository at this point in the history
  • Loading branch information
odow committed Jan 9, 2024
1 parent 905fc12 commit 1cd6d18
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/Convex.jl
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ export Positive, Negative, ComplexSign, NoSign

# Problems
export add_constraints!, maximize, minimize, Problem, satisfy, solve!
export write_to_file

# Module level globals

Expand Down
29 changes: 29 additions & 0 deletions src/problems.jl
Original file line number Diff line number Diff line change
Expand Up @@ -235,3 +235,32 @@ end
function add_constraint!(p::Problem, constraint::Constraint)
return add_constraints!(p, constraint)
end

"""
write_to_file(problem::Problem{Float64}, filename::String)
Write the current problem to the file at `filename`.
Requires solving the problem at least once using [`solve!`](@ref) to ensure that
the problem is loaded into a MathOptInterface model.
The file format is inferred from the filename extension. Supported file
types depend on the model type.
Currently, `Float64` is the only supported coefficient type. This may be
relaxed in future if file formats support other types.
"""
function write_to_file(p::Problem{T}, filename::String) where {T<:Float64}
if isnothing(p.model)
msg = """
Problem has not been loaded into a MathOptInterface model;
call `solve!(problem, optimizer)` before writing problem to file.
"""
throw(ArgumentError(msg))
end
dest = MOI.FileFormats.Model(; filename)
model = MOI.Bridges.full_bridge_optimizer(dest, T)
MOI.copy_to(model, p.model)
MOI.write_to_file(dest, filename)
return
end
13 changes: 13 additions & 0 deletions test/test_utilities.jl
Original file line number Diff line number Diff line change
Expand Up @@ -771,6 +771,19 @@ mutable struct DictVector{T} <: Convex.AbstractVariable
)
return this
end

@testset "test_write_to_file" begin
x = Variable(3)
p = minimize(logsumexp(x))
dir = mktempdir()
filename = joinpath(dir, "test.mof.json")
@test_throws ArgumentError write_to_file(p, filename)
solve!(p, SCS.Optimizer; silent_solver = true)
write_to_file(p, filename)
@test occursin("ExponentialCone", read(filename, String))
p_int = minimize(logsumexp(x); numeric_type = Int)
@test_throws MethodError write_to_file(p_int, filename)
end
end

Convex.evaluate(x::DictVector) = global_cache[x.id_hash][:value]
Expand Down

0 comments on commit 1cd6d18

Please sign in to comment.