From 23ccb2cb1bbffef35b679696afa5eb248ae25933 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20Legat?= Date: Thu, 8 Aug 2024 12:59:32 +0200 Subject: [PATCH] Allow changing coefficient type in read_from_file (#3801) * 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 --- src/file_formats.jl | 15 ++++++++++----- test/test_file_formats.jl | 14 ++++++++++++++ 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/src/file_formats.jl b/src/file_formats.jl index 8dd0367bb0a..09931ea614c 100644 --- a/src/file_formats.jl +++ b/src/file_formats.jl @@ -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; @@ -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 diff --git a/test/test_file_formats.jl b/test/test_file_formats.jl index 6f3f12b78fd..5569c868d46 100644 --- a/test/test_file_formats.jl +++ b/test/test_file_formats.jl @@ -8,6 +8,8 @@ module TestFileFormats using JuMP using Test +import LinearAlgebra + function test_mof_file() model = Model() @variable(model, x) @@ -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