How to write a JuMP constraint into a text file?

Viewed 264

I have searched but didn't find an answer. I have read a MPS file into a JuMP model. Now I would like to write a subset of constraints into a text file for further analysis. I know how to write a JuMP model into a LP or MPS file. But here I just want to write a subset of constraints into a text file. If I can parse the constraints, figuring out what are the coefficients and what are the variables, that would even be better. Thanks in advance!

1 Answers
println(file_stream, m)

println will nicely format a JuMP model and the output will be a text file.

Full code:

using JuMP
using GLPK
m = Model(optimizer_with_attributes(GLPK.Optimizer))
@variable(m, x1 >= 0)
@variable(m, x2 >= 0)
@constraint(m, x1 + x2 <= 10)
@objective(m, Max, 2x1 + x2)
open("model.txt", "w") do f
   println(f, m)
end

Let's see what is in the file:

$ more model.txt

Max 2 x1 + x2
Subject to
 x1 + x2 <= 10.0
 x1 >= 0.0
 x2 >= 0.0

If you want constraints only this code will do:

open("cons.txt","w") do f
    for c in vcat([all_constraints(m, t...) for t in list_of_constraint_types(m)]...)
       println(f , c)
    end
end
Related