Skip to main content

How to extract solution values to separate matrices/dataframes in Python?

Answered

Comments

2 comments

  • Official comment
    Simranjit Kaur
    • Gurobi Staff
    This post is more than two years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum, or try Gurobot, our chatbot interface offering instant, expert-level support.
  • Riley Clement
    • Gurobi Staff

    Hi Aleksandrs,

    You can use numpy.reshape and Model.getAttr to do this concisely.  For example:

    # setup
    import gurobipy as gp
    import numpy as np

    m = gp.Model()
    x = m.addVars(range(5), range(3), vtype="B", obj=np.random.random(size=(5,3)), name="v")
    m.addConstr(gp.quicksum(x.values())==7)
    m.optimize()

    # print variable names in numpy matrix to verify the result of reshape
    print(np.reshape(m.getAttr("VarName", m.getVars()), (5,3)))

    # print variable values in solution in numpy matrix
    print(np.reshape(m.getAttr("X", m.getVars()), (5,3)))

    The print statements give

    array([['v[0,0]', 'v[0,1]', 'v[0,2]'],
           ['v[1,0]', 'v[1,1]', 'v[1,2]'],
           ['v[2,0]', 'v[2,1]', 'v[2,2]'],
           ['v[3,0]', 'v[3,1]', 'v[3,2]'],
           ['v[4,0]', 'v[4,1]', 'v[4,2]']], dtype='<U6')

    and

    array([[1., 0., 1.],
           [0., 0., 0.],
           [1., 0., 0.],
           [0., 0., 1.],
           [1., 1., 1.]])

    respectively.

    - Riley

     

    2

Post is closed for comments.