diff --git a/Project.toml b/Project.toml index d3bf1d1d41..5bcde02789 100644 --- a/Project.toml +++ b/Project.toml @@ -31,7 +31,7 @@ CliqueTrees = "1.17.1" CodecBzip2 = "0.6, 0.7, 0.8" CodecZlib = "0.6, 0.7" ForwardDiff = "1" -JSON = "0.21, 1" +JSON = "1" JSONSchema = "1.1" JuliaC = "0.3" LinearAlgebra = "1" diff --git a/src/FileFormats/MOF/write.jl b/src/FileFormats/MOF/write.jl index b07b9f8639..0c53f4e615 100644 --- a/src/FileFormats/MOF/write.jl +++ b/src/FileFormats/MOF/write.jl @@ -4,6 +4,29 @@ # Use of this source code is governed by an MIT-style license that can be found # in the LICENSE.md file or at https://opensource.org/licenses/MIT. +# The objects of the MathOptFormat document. Their values have any type so that +# JSON writes all of them with the same methods, whatever their fields. +const _Object = JSON.Object{String,Any} + +# Create a `JSON.Object{String,Any}` with the `key => value` pairs. +# +# Julia compiles a function taking a variable number of arguments, such as this +# one, without specializing on the type of each argument, so the type of `value` +# is unknown below. Because the keys are declared as `String`, `object[key] = +# value` still matches only one method of `setindex!`, so the call is resolved +# at compile time and the same compiled code inserts values of any type. With +# keys of unknown type, as in `JSON.Object(pairs...)`, the methods for `String` +# and `Symbol` keys would both match and the method would be selected at run +# time: this is slower and, in an executable compiled with `juliac --trim`, it +# fails for the types of values whose method was not compiled. +function _object(pairs::Pair{String}...) + object = _Object() + for (key, value) in pairs + object[key] = value + end + return object +end + """ Base.write(io::IO, model::FileFormats.MOF.Model) @@ -27,7 +50,7 @@ function Base.write(io::IO, model::MOI.ModelLike, options::Options) else FileFormats.create_unique_names(model; warn = options.warn) end - variables, constraints = NamedTuple[], NamedTuple[] + variables, constraints = _Object[], _Object[] name_map = _write_variables(variables, model) objective = _write_nlpblock(constraints, model, name_map) has_scalar_nonlinear = false @@ -35,29 +58,27 @@ function Base.write(io::IO, model::MOI.ModelLike, options::Options) objective, has_scalar_nonlinear = _write_objective(model, name_map) end has_scalar_nonlinear |= _write_constraints(constraints, model, name_map) - object = (; - name = "MathOptFormat Model", - version = ( - major = Int(_SUPPORTED_VERSIONS[1].major), - minor = Int(_SUPPORTED_VERSIONS[1].minor), - ), - variables = variables, - objective = objective, - constraints = constraints, - ) + object = _Object() if has_scalar_nonlinear - object = (; has_scalar_nonlinear = true, object...) + object["has_scalar_nonlinear"] = true end + object["name"] = "MathOptFormat Model" + object["version"] = _object( + "major" => Int(_SUPPORTED_VERSIONS[1].major), + "minor" => Int(_SUPPORTED_VERSIONS[1].minor), + ) + object["variables"] = variables + object["objective"] = objective + object["constraints"] = constraints Base.write(io, JSON.json(object)) return end -function _write_variables(variables::Vector{NamedTuple}, model::MOI.ModelLike) +function _write_variables(variables::Vector{_Object}, model::MOI.ModelLike) name_map = Dict{MOI.VariableIndex,String}() for index in MOI.get(model, MOI.ListOfVariableIndices()) - variable = moi_to_object(index, model) - name_map[index] = variable[:name] - push!(variables, variable) + push!(variables, moi_to_object(index, model)) + name_map[index] = MOI.get(model, MOI.VariableName(), index) end return name_map end @@ -101,7 +122,7 @@ function extract_function_and_set(expr::Expr) end function _write_nlpblock( - constraints::Vector{NamedTuple}, + constraints::Vector{_Object}, model::MOI.ModelLike, name_map::Dict{MOI.VariableIndex,String}, ) @@ -120,9 +141,9 @@ function _write_nlpblock( func = _lift_variable_indices(func) push!( constraints, - (; - :function => moi_to_object(Nonlinear(func), name_map), - :set => moi_to_object(set, name_map), + _object( + "function" => moi_to_object(Nonlinear(func), name_map), + "set" => moi_to_object(set, name_map), ), ) end @@ -130,9 +151,9 @@ function _write_nlpblock( objective = MOI.objective_expr(nlp_block.evaluator) objective = _lift_variable_indices(objective) sense = MOI.get(model, MOI.ObjectiveSense()) - return (; - :sense => moi_to_object(sense), - :function => moi_to_object(Nonlinear(objective), name_map), + return _object( + "sense" => moi_to_object(sense), + "function" => moi_to_object(Nonlinear(objective), name_map), ) end return @@ -144,19 +165,19 @@ function _write_objective( ) sense = MOI.get(model, MOI.ObjectiveSense()) if sense == MOI.FEASIBILITY_SENSE - return (; :sense => moi_to_object(sense)), false + return _object("sense" => moi_to_object(sense)), false end F = MOI.get(model, MOI.ObjectiveFunctionType()) objective_function = MOI.get(model, MOI.ObjectiveFunction{F}()) - object = (; - :sense => moi_to_object(sense), - :function => moi_to_object(objective_function, name_map), + object = _object( + "sense" => moi_to_object(sense), + "function" => moi_to_object(objective_function, name_map), ) return object, (F == MOI.ScalarNonlinearFunction) end function _write_constraints( - constraints::Vector{NamedTuple}, + constraints::Vector{_Object}, model::MOI.ModelLike, name_map::Dict{MOI.VariableIndex,String}, ) @@ -173,7 +194,7 @@ end """ moi_to_object(x, model::MOI.ModelLike) -Convert `x` into a NamedTuple representation. +Convert `x` into a `JSON.Object{String,Any}`. """ function moi_to_object end @@ -190,11 +211,12 @@ function moi_to_object(index::MOI.VariableIndex, model::MOI.ModelLike) primal_start = _start(model, MOI.VariablePrimalStart(), index) if name == "" error("Variable name for $(index) cannot be blank in an MOF file.") - elseif isnothing(primal_start) - return (name = name,) - else - return (name = name, primal_start = primal_start) end + object = _object("name" => name) + if !isnothing(primal_start) + object["primal_start"] = primal_start + end + return object end function moi_to_object( @@ -206,22 +228,22 @@ function moi_to_object( set = MOI.get(model, MOI.ConstraintSet(), index) dual_start = _start(model, MOI.ConstraintDualStart(), index) primal_start = _start(model, MOI.ConstraintPrimalStart(), index) - pairs = Pair{Symbol,Any}[] + object = _Object() if F != MOI.VariableIndex name = MOI.get(model, MOI.ConstraintName(), index) if name != "" - push!(pairs, :name => name) + object["name"] = name end end - push!(pairs, :function => moi_to_object(func, name_map)) - push!(pairs, :set => moi_to_object(set, name_map)) + object["function"] = moi_to_object(func, name_map) + object["set"] = moi_to_object(set, name_map) if !isnothing(dual_start) - push!(pairs, :dual_start => dual_start) + object["dual_start"] = dual_start end if !isnothing(primal_start) - push!(pairs, :primal_start => primal_start) + object["primal_start"] = primal_start end - return NamedTuple(pairs) + return object end function moi_to_object(sense::MOI.OptimizationSense) @@ -241,7 +263,7 @@ function moi_to_object( foo::MOI.VariableIndex, name_map::Dict{MOI.VariableIndex,String}, ) - return (type = "Variable", name = name_map[foo]) + return _object("type" => "Variable", "name" => name_map[foo]) end function _convert_nonlinear_to_mof( @@ -252,15 +274,16 @@ function _convert_nonlinear_to_mof( if expr.head != :call error("Expected an expression that was a function. Got $(expr).") end - node = (type = string(expr.args[1]), args = Any[]) + args = Any[] for i in 2:length(expr.args) push!( - node[:args], + args, _convert_nonlinear_to_mof(expr.args[i], node_list, name_map), ) end + node = _object("type" => string(expr.args[1]), "args" => args) push!(node_list, node) - return (type = "node", index = length(node_list)) + return _object("type" => "node", "index" => length(node_list)) end function _convert_nonlinear_to_mof( @@ -268,12 +291,13 @@ function _convert_nonlinear_to_mof( node_list::Vector{Any}, name_map::Dict{MOI.VariableIndex,String}, ) - node = (type = string(f.head), args = Any[]) + args = Any[] for arg in f.args - push!(node[:args], _convert_nonlinear_to_mof(arg, node_list, name_map)) + push!(args, _convert_nonlinear_to_mof(arg, node_list, name_map)) end + node = _object("type" => string(f.head), "args" => args) push!(node_list, node) - return (type = "node", index = length(node_list)) + return _object("type" => "node", "index" => length(node_list)) end function _convert_nonlinear_to_mof( @@ -309,16 +333,20 @@ function _convert_nonlinear_to_mof( ::Vector{Any}, ::Dict{MOI.VariableIndex,String}, ) - return (type = "complex", real = real(value), imag = imag(value)) + return _object( + "type" => "complex", + "real" => real(value), + "imag" => imag(value), + ) end function moi_to_object(foo::Nonlinear, name_map::Dict{MOI.VariableIndex,String}) node_list = Any[] root = _convert_nonlinear_to_mof(foo.expr, node_list, name_map) - return ( - type = "ScalarNonlinearFunction", - root = root, - node_list = node_list, + return _object( + "type" => "ScalarNonlinearFunction", + "root" => root, + "node_list" => node_list, ) end @@ -328,10 +356,10 @@ function moi_to_object( ) node_list = Any[] root = _convert_nonlinear_to_mof(foo, node_list, name_map) - return ( - type = "ScalarNonlinearFunction", - root = root, - node_list = node_list, + return _object( + "type" => "ScalarNonlinearFunction", + "root" => root, + "node_list" => node_list, ) end @@ -341,17 +369,20 @@ function moi_to_object( foo::MOI.ScalarAffineTerm, name_map::Dict{MOI.VariableIndex,String}, ) - return (coefficient = foo.coefficient, variable = name_map[foo.variable]) + return _object( + "coefficient" => foo.coefficient, + "variable" => name_map[foo.variable], + ) end function moi_to_object( foo::MOI.ScalarAffineFunction, name_map::Dict{MOI.VariableIndex,String}, ) - return ( - type = "ScalarAffineFunction", - terms = moi_to_object.(foo.terms, Ref(name_map)), - constant = foo.constant, + return _object( + "type" => "ScalarAffineFunction", + "terms" => moi_to_object.(foo.terms, Ref(name_map)), + "constant" => foo.constant, ) end @@ -359,10 +390,10 @@ function moi_to_object( foo::MOI.ScalarQuadraticTerm, name_map::Dict{MOI.VariableIndex,String}, ) - return ( - coefficient = foo.coefficient, - variable_1 = name_map[foo.variable_1], - variable_2 = name_map[foo.variable_2], + return _object( + "coefficient" => foo.coefficient, + "variable_1" => name_map[foo.variable_1], + "variable_2" => name_map[foo.variable_2], ) end @@ -370,11 +401,11 @@ function moi_to_object( foo::MOI.ScalarQuadraticFunction, name_map::Dict{MOI.VariableIndex,String}, ) - return ( - type = "ScalarQuadraticFunction", - affine_terms = moi_to_object.(foo.affine_terms, Ref(name_map)), - quadratic_terms = moi_to_object.(foo.quadratic_terms, Ref(name_map)), - constant = foo.constant, + return _object( + "type" => "ScalarQuadraticFunction", + "affine_terms" => moi_to_object.(foo.affine_terms, Ref(name_map)), + "quadratic_terms" => moi_to_object.(foo.quadratic_terms, Ref(name_map)), + "constant" => foo.constant, ) end @@ -384,9 +415,9 @@ function moi_to_object( foo::MOI.VectorOfVariables, name_map::Dict{MOI.VariableIndex,String}, ) - return ( - type = "VectorOfVariables", - variables = [name_map[variable] for variable in foo.variables], + return _object( + "type" => "VectorOfVariables", + "variables" => [name_map[variable] for variable in foo.variables], ) end @@ -398,10 +429,10 @@ function moi_to_object( rows = map(foo.rows) do f return _convert_nonlinear_to_mof(f, node_list, name_map) end - return ( - type = "VectorNonlinearFunction", - rows = rows, - node_list = node_list, + return _object( + "type" => "VectorNonlinearFunction", + "rows" => rows, + "node_list" => node_list, ) end @@ -411,9 +442,9 @@ function moi_to_object( foo::MOI.VectorAffineTerm, name_map::Dict{MOI.VariableIndex,String}, ) - return ( - output_index = foo.output_index, - scalar_term = moi_to_object(foo.scalar_term, name_map), + return _object( + "output_index" => foo.output_index, + "scalar_term" => moi_to_object(foo.scalar_term, name_map), ) end @@ -421,10 +452,10 @@ function moi_to_object( foo::MOI.VectorAffineFunction, name_map::Dict{MOI.VariableIndex,String}, ) - return ( - type = "VectorAffineFunction", - terms = moi_to_object.(foo.terms, Ref(name_map)), - constants = foo.constants, + return _object( + "type" => "VectorAffineFunction", + "terms" => moi_to_object.(foo.terms, Ref(name_map)), + "constants" => foo.constants, ) end @@ -432,9 +463,9 @@ function moi_to_object( foo::MOI.VectorQuadraticTerm, name_map::Dict{MOI.VariableIndex,String}, ) - return ( - output_index = foo.output_index, - scalar_term = moi_to_object(foo.scalar_term, name_map), + return _object( + "output_index" => foo.output_index, + "scalar_term" => moi_to_object(foo.scalar_term, name_map), ) end @@ -442,11 +473,11 @@ function moi_to_object( foo::MOI.VectorQuadraticFunction, name_map::Dict{MOI.VariableIndex,String}, ) - return ( - type = "VectorQuadraticFunction", - affine_terms = moi_to_object.(foo.affine_terms, Ref(name_map)), - quadratic_terms = moi_to_object.(foo.quadratic_terms, Ref(name_map)), - constants = foo.constants, + return _object( + "type" => "VectorQuadraticFunction", + "affine_terms" => moi_to_object.(foo.affine_terms, Ref(name_map)), + "quadratic_terms" => moi_to_object.(foo.quadratic_terms, Ref(name_map)), + "constants" => foo.constants, ) end @@ -466,11 +497,11 @@ function moi_to_object( set::SetType, ::Dict{MOI.VariableIndex,String}, ) where {SetType} - pairs = Pair{Symbol,Any}[:type=>head_name(SetType)] + object = _object("type" => head_name(SetType)) for key in fieldnames(SetType) - push!(pairs, Symbol(string(key)) => getfield(set, key)) + object[string(key)] = getfield(set, key) end - return NamedTuple(pairs) + return object end # ========== Non-typed scalar sets ========== @@ -542,10 +573,10 @@ function moi_to_object( name_map::Dict{MOI.VariableIndex,String}, ) where {I,S} @assert I == MOI.ACTIVATE_ON_ONE || I == MOI.ACTIVATE_ON_ZERO - return ( - type = "Indicator", - set = moi_to_object(set.set, name_map), - activate_on = (I == MOI.ACTIVATE_ON_ONE) ? "one" : "zero", + return _object( + "type" => "Indicator", + "set" => moi_to_object(set.set, name_map), + "activate_on" => (I == MOI.ACTIVATE_ON_ONE) ? "one" : "zero", ) end @@ -553,16 +584,19 @@ function moi_to_object( set::MOI.Reified, name_map::Dict{MOI.VariableIndex,String}, ) - return (type = "Reified", set = moi_to_object(set.set, name_map)) + return _object( + "type" => "Reified", + "set" => moi_to_object(set.set, name_map), + ) end function moi_to_object( set::MOI.Table{T}, ::Dict{MOI.VariableIndex,String}, ) where {T} - return ( - type = "Table", - table = [set.table[i, :] for i in 1:size(set.table, 1)], + return _object( + "type" => "Table", + "table" => [set.table[i, :] for i in 1:size(set.table, 1)], ) end @@ -570,5 +604,8 @@ function moi_to_object( set::MOI.Scaled, name_map::Dict{MOI.VariableIndex,String}, ) - return (type = "Scaled", set = moi_to_object(set.set, name_map)) + return _object( + "type" => "Scaled", + "set" => moi_to_object(set.set, name_map), + ) end diff --git a/test/FileFormats/MOF/test_MOF.jl b/test/FileFormats/MOF/test_MOF.jl index 4303e0f6cc..485a9e04f7 100644 --- a/test/FileFormats/MOF/test_MOF.jl +++ b/test/FileFormats/MOF/test_MOF.jl @@ -224,22 +224,22 @@ function _convert_mof_to_expr( node_list::Vector{T}, name_map::Dict{String,MOI.VariableIndex}, ) where {T} - head = haskey(node, :type) ? node[:type] : node[:head] + head = haskey(node, "type") ? node["type"] : node["head"] if head == "real" - return node[:value] + return node["value"] elseif head == "complex" - return Complex(node[:real], node[:imag]) + return Complex(node["real"], node["imag"]) elseif head == "variable" - return name_map[node[:name]] + return name_map[node["name"]] elseif head == "node" return _convert_mof_to_expr( - node_list[node[:index]], + node_list[node["index"]], node_list, name_map, ) else expr = Expr(:call, Symbol(head)) - for arg in node[:args] + for arg in node["args"] push!(expr.args, _convert_mof_to_expr(arg, node_list, name_map)) end return expr @@ -358,7 +358,8 @@ function test_Blank_variable_name() variable = MOI.add_variable(model) @test_throws Exception MOF.moi_to_object(variable, model) MOI.FileFormats.create_unique_names(model, warn = true) - @test MOF.moi_to_object(variable, model) == (name = "x1",) + @test JSON.json(MOF.moi_to_object(variable, model)) == + JSON.json((name = "x1",)) end function test_Duplicate_variable_name() @@ -367,11 +368,11 @@ function test_Duplicate_variable_name() MOI.set(model, MOI.VariableName(), x, "x") y = MOI.add_variable(model) MOI.set(model, MOI.VariableName(), y, "x") - @test MOF.moi_to_object(x, model) == (name = "x",) - @test MOF.moi_to_object(y, model) == (name = "x",) + @test JSON.json(MOF.moi_to_object(x, model)) == JSON.json((name = "x",)) + @test JSON.json(MOF.moi_to_object(y, model)) == JSON.json((name = "x",)) MOI.FileFormats.create_unique_names(model, warn = true) - @test MOF.moi_to_object(x, model) == (name = "x",) - @test MOF.moi_to_object(y, model) == (name = "x_1",) + @test JSON.json(MOF.moi_to_object(x, model)) == JSON.json((name = "x",)) + @test JSON.json(MOF.moi_to_object(y, model)) == JSON.json((name = "x_1",)) end function test_Blank_constraint_name() @@ -382,7 +383,7 @@ function test_Blank_constraint_name() c = MOI.add_constraint(model, f, MOI.ZeroOne()) name_map = Dict(x => "x") MOI.FileFormats.create_unique_names(model, warn = true) - @test MOF.moi_to_object(c, model, name_map)[:name] == "c1" + @test MOF.moi_to_object(c, model, name_map)["name"] == "c1" end function test_Duplicate_constraint_name() @@ -395,11 +396,11 @@ function test_Duplicate_constraint_name() MOI.set(model, MOI.ConstraintName(), c1, "c") MOI.set(model, MOI.ConstraintName(), c2, "c") name_map = Dict(x => "x") - @test MOF.moi_to_object(c1, model, name_map)[:name] == "c" - @test MOF.moi_to_object(c2, model, name_map)[:name] == "c" + @test MOF.moi_to_object(c1, model, name_map)["name"] == "c" + @test MOF.moi_to_object(c2, model, name_map)["name"] == "c" MOI.FileFormats.create_unique_names(model, warn = true) - @test MOF.moi_to_object(c1, model, name_map)[:name] == "c_1" - @test MOF.moi_to_object(c2, model, name_map)[:name] == "c" + @test MOF.moi_to_object(c1, model, name_map)["name"] == "c_1" + @test MOF.moi_to_object(c2, model, name_map)["name"] == "c" end function test_empty_model() @@ -1444,7 +1445,7 @@ function test_integer_coefficients() x = MOI.VariableIndex(1) names = Dict(x => "x") f = 2 * x * x + 3 * x + 4 - @test MOF.moi_to_object(f, names) == ( + @test JSON.json(MOF.moi_to_object(f, names)) == JSON.json(( type = "ScalarQuadraticFunction", affine_terms = [(coefficient = 3, variable = "x")], quadratic_terms = [( @@ -1453,7 +1454,7 @@ function test_integer_coefficients() variable_2 = "x", ),], constant = 4, - ) + )) return end @@ -1524,7 +1525,7 @@ function test_mof_scalaraffinefunction() (type = "log", args = Any[(type = "node", index = 2)]), ], ) - @test object == object_dest + @test JSON.json(object) == JSON.json(object_dest) return end @@ -1543,7 +1544,7 @@ function test_mof_scalarquadraticfunction() (type = "log", args = Any[(type = "node", index = 2)]), ], ) - @test object == object_dest + @test JSON.json(object) == JSON.json(object_dest) return end diff --git a/test/JuliaC/MyApp/src/MyApp.jl b/test/JuliaC/MyApp/src/MyApp.jl index 177a6b9a90..c79c06d929 100644 --- a/test/JuliaC/MyApp/src/MyApp.jl +++ b/test/JuliaC/MyApp/src/MyApp.jl @@ -21,6 +21,12 @@ function @main(args::Vector{String})::Cint end # The following commands are not traced by `test_juliac.jl`: the compiled # binary must run them with the methods resolved at compile time. + if head == "--starts" + return run_starts(args) + end + if head == "--linear" + return run_linear(args) + end if head == "--names" return run_names(args) end @@ -57,6 +63,32 @@ function run_mathoptformat(args::Vector{String})::Cint return _write(model, args) end +# A starting value for `x`, so the object of the variable in the document has a +# `primal_start` field, which the traced model does not have. When the objects +# were `NamedTuple`s, JSON needed methods for each combination of fields, so +# this failed without a trace, see +# https://github.com/jump-dev/MathOptInterface.jl/pull/3151. +function run_starts(args::Vector{String})::Cint + model, x = _model() + MOI.set(model, MOI.VariablePrimalStart(), x, 1.0) + return _write(model, args) +end + +# The traced model without its nonlinear constraint, so the document has no +# `has_scalar_nonlinear` field: its top-level object has other fields than the +# one of the traced model, see +# https://github.com/jump-dev/MathOptInterface.jl/pull/3151. +function run_linear(args::Vector{String})::Cint + model = MOI.FileFormats.MOF.Model() + x = MOI.add_variable(model) + MOI.set(model, MOI.VariableName(), x, "x") + MOI.add_constraint(model, x, MOI.GreaterThan(0.0)) + objective = MOI.ScalarAffineFunction([MOI.ScalarAffineTerm(1.0, x)], 0.0) + MOI.set(model, MOI.ObjectiveSense(), MOI.MIN_SENSE) + MOI.set(model, MOI.ObjectiveFunction{typeof(objective)}(), objective) + return _write(model, args) +end + # A second variable named `x`, which is renamed. function run_names(args::Vector{String})::Cint model, _ = _model() diff --git a/test/JuliaC/test_juliac.jl b/test/JuliaC/test_juliac.jl index c6fb90f029..4045814a86 100644 --- a/test/JuliaC/test_juliac.jl +++ b/test/JuliaC/test_juliac.jl @@ -119,6 +119,23 @@ function test_mathoptformat(output_dir) return end +function test_starts(output_dir) + compiled, reference = _run(output_dir, "--starts") + @test compiled == reference + object = JSON.parse(compiled) + @test object["variables"] == [Dict("name" => "x", "primal_start" => 1.0)] + return +end + +function test_linear(output_dir) + compiled, reference = _run(output_dir, "--linear") + @test compiled == reference + object = JSON.parse(compiled) + @test !haskey(object, "has_scalar_nonlinear") + @test length(object["constraints"]) == 1 + return +end + function test_names(output_dir) compiled, reference = _run(output_dir, "--names") @test compiled == reference