Skip to main content

How to use model.get(A) function?




  • Jaromił Najman
    Gurobi Staff Gurobi Staff

    You can see a simple example of the getA method in the respective documentation. Once, you have the A matrix, you can then automatically convert the sparse matrix format to a dense one and write it to a CSV file. You could use the todense method of the scipy module.

    import gurobipy as gp
    import scipy as sp
    import pandas as pd

    m = gp.Model("mip1")
    x = m.addVar(ub=2, name="x")
    y = m.addVar(ub=2, name="y")
    z = m.addVar(ub=1, name="z")

    m.setObjective(x + y - z, GRB.MINIMIZE)
    m.addConstr(x + 2 * y + 3 * z <= 4, "c0")
    m.addConstr(x + y >= 1, "c1")

    A = m.getA()
    denseMatrix = pd.DataFrame(data=sp.sparse.csr_matrix.todense(A))
    denseMatrix.to_csv("Amatrix.csv", index=False)

    Best regards, 

  • Prachi Agrawal
    First Comment
    First Question

    Thank you so much for your reply. 

    It really helps me a lot. 

  • Prachi Agrawal
    First Comment
    First Question

    Is it possible to use model.get A function with pyomo optimization?

    How can we use this function?


    Could you please give an example of this?

  • Eli Towle
    Gurobi Staff Gurobi Staff

    Pyomo doesn't support all of the features available in the native Gurobi Python API. However, if you're using the "persistent" Gurobi interface, you can access the underlying \(\texttt{gurobipy}\) Model object using the \(\texttt{_solver_model}\) attribute of your GurobiPersistent object. You can use this object to call \(\texttt{gurobipy}\) methods like Model.getA(). For example:

    model = ConcreteModel()
    model.y = Var([1, 2], domain=NonNegativeReals)
    model.my_constraint1 = Constraint(expr=3 * model.y[1] + 4 * model.y[2] <= 12)
    model.my_constraint2 = Constraint(expr=5 * model.y[1] + model.y[2] <= 11)

    solver = SolverFactory("gurobi_persistent", model=model)
    A = solver._solver_model.getA()


  • Prachi Agrawal
    First Comment
    First Question

    I am using GUROBI OPTIMIZATION to solve an LPP with an MPS file format. I am modifying matrix A and I can get matrix A using getA function. Can I extract the cost vector (objective function coefficients) and the RHS vector (the b vector) from an MPS file? I want to solve the LPP by modifying A, the vector b, and the cost coefficient c.

    Is it possible to get the b and c vectors from the MPS file?


Please sign in to leave a comment.