2

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!

Feng
  • 105
  • 5

1 Answers1

4
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
Przemyslaw Szufel
  • 40,002
  • 3
  • 32
  • 62
  • Hi Przemyslaw, Thanks for your help. This works. For my second question, how we can parse the constraint expression? For example, there are 100 variables x1...x100. I would like to know which variables are in this constraint and what are their coefficients. – Feng Jul 08 '20 at 03:02
  • 1
    `all_constraints` returns objects and you can find that info within them. – Przemyslaw Szufel Jul 08 '20 at 07:31
  • Hi Przemyslaw, I was not clear. What I meant was that, when I have a constraint (e.g., all_constraints(m)[1] ), I would like to parse this constraint, e.g., figure out which variables appear in the constraint, and what are their coefficients. Then I will save variable names and coefficients in separate columns of an excel file for further analysis. Do you think if this is possible? – Feng Jul 08 '20 at 15:53
  • 1
    Hi @Feng, I think my answer on this question might provide some insight for you: https://stackoverflow.com/questions/62800012/how-to-extract-optimization-problem-matrices-a-b-c-using-jump-in-julia – miga89 Jul 10 '20 at 08:45
  • I found one function that can do this: constraint_object. The return has a property .func.terms, which is a dictionary with pairs of VariableRef and coefficients. Hi @miga89, Thanks for pointing me to your post. That is exactly what I was looking for. – Feng Jul 10 '20 at 21:08