Return Tuple from JuMP

I have few questions on JuMP. Can we return JuMP results as a named tuple of termination status and variable values? See MWE below. Variables will not always contain values, eg. if model is infeasible, so I don’t know how to create a tuple in that case.

How can I capture the log of the solver (one of the open source ones Clp, Cbc, glpk) and write to a file?


using JuMP
function solve()
c = rand(10)
d = rand(10)
model = Model(Cbc.Optimizer)
@variable(model, x[1:10] >= 0)
@constraint(model,sum(x[i]*c[i] for i=1:10) >=sum(d))
optimize!(model)
status = termination_status(model) 
if status == MOI.INFEASIBLE
   solution = Nothing
   objective = Nothing
elseif status == MOI.OPTIMAL
    solution = value.(x)
    objective = objective_value(model)
elseif status == MOI.TIME_LIMIT && has_values(model)
    solution = value.(x)
    objective = objective_value(model)
else
    error("The model was not solved correctly.")
end
result = (status, solution, objective)
end

When I check result is a tuple, but not a named tuple. so I cannot query, result.solution to get values of x

You can dump out result as a dictionary
result = Dict("status"=>status, "solution" => solution, "obj_value"=>JuMP.objective_value(model))

and access each key by typing

result["status"]
result["solution"]
result["obj_value"]

NamedTuples aren’t specific to JuMP. Here’s the Julia documentation: Essentials · The Julia Language

You want something like:

function solve()
    c = rand(10)
    d = rand(10)
    model = Model(Cbc.Optimizer)
    @variable(model, x[1:10] >= 0)
    @constraint(model, sum(x[i] * c[i] for i in 1:10) >= sum(d))
    optimize!(model)
    status = termination_status(model) 
    if status == MOI.INFEASIBLE
        return (
            status = status,
            solution = fill(NaN, 10),
            objective = NaN,
        )
    elseif status == MOI.OPTIMAL || (status == MOI.TIME_LIMIT && has_values(model))
        return (
            status = status, 
            solution = value.(x), 
            objective = objective_value(model),
        )
    else
        error("The model was not solved correctly.")
    end
end

Thank you. Is there a function to save the cbc solver output / log and write to a file? I have checked JuMP documentation but it doesn’t not state anything about it