Skip to content

Commit

Permalink
Allow changing coefficient type in read_from_file (#3801)
Browse files Browse the repository at this point in the history
* Allow changing coefficient type in read_from_file

* New approach

* Mention MOF

* Fix

* Add test

* Update test_file_formats.jl

---------

Co-authored-by: Oscar Dowson <[email protected]>
  • Loading branch information
blegat and odow authored Aug 8, 2024
1 parent 629181a commit 23ccb2c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
15 changes: 10 additions & 5 deletions src/file_formats.jl
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,14 @@ function Base.write(
return
end

_value_type(::MOI.Utilities.AbstractModelLike{T}) where {T} = T

# This fallback may not get the correct value type. However, since
# all models defined in `MOI.FileFormats` return a
# `MOI.Utilities.GenericModel` except `NL` and `MOF` which only supports
# `Float64`, this does the job for now.
_value_type(::MOI.ModelLike) = Float64

"""
read_from_file(
filename::String;
Expand All @@ -107,12 +115,9 @@ function read_from_file(
format::MOI.FileFormats.FileFormat = MOI.FileFormats.FORMAT_AUTOMATIC,
kwargs...,
)
src =
MOI.FileFormats.Model(; format = format, filename = filename, kwargs...)
src = MOI.FileFormats.Model(; format, filename, kwargs...)
MOI.read_from_file(src, filename)
# TODO(odow): what number type to choose? Are there any non-Float64 file
# formats?
model = GenericModel{Float64}()
model = GenericModel{_value_type(src)}()
MOI.copy_to(model, src)
return model
end
Expand Down
14 changes: 14 additions & 0 deletions test/test_file_formats.jl
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ module TestFileFormats
using JuMP
using Test

import LinearAlgebra

function test_mof_file()
model = Model()
@variable(model, x)
Expand Down Expand Up @@ -138,4 +140,16 @@ function test_nl_round_trip()
return
end

function test_sdpa_bigfloat()
model = Model()
@variable(model, x)
@constraint(model, LinearAlgebra.Symmetric([1 x; x 1]) in PSDCone())
@objective(model, Max, 2x)
write_to_file(model, "model.dat-s")
model_2 = read_from_file("model.dat-s"; number_type = BigFloat)
@test model_2 isa GenericModel{BigFloat}
rm("model.dat-s")
return
end

end

0 comments on commit 23ccb2c

Please sign in to comment.