Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add write_to_file #531

Merged
merged 2 commits into from
Jan 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
14 changes: 14 additions & 0 deletions test/test_utilities.jl
Original file line number Diff line number Diff line change
Expand Up @@ -922,6 +922,20 @@ function test_ProbabilityVectors()
return
end

function test_write_to_file()
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)
return
end

end # TestUtilities

TestUtilities.runtests()
Loading