Skip to main content

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

Answered

Comments

1 comment

  • Riley Clement
    • Gurobi Staff 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

Please sign in to leave a comment.