[Python] Python Gurobi - Write dual problem to file

Discussão em 'Python' iniciado por Stack, Agosto 26, 2025.

  1. Stack

    Stack Membro Participativo

    Using gurobipy, I am able to write my primal problem using model.write(). I also know I am able to calculate the duals with m.getAttr("Pi", m.getConstrs()). Now I am curious if, instead of writing out the dual model manually in the code, if it is possible to easily generate the dual of an LP and write it to a file just like we write the primal problem to a .lp file. Here is some toy code I am attempting to do this with, feel free to test it at your leisure:

    import gurobipy as gp
    import os
    from gurobipy import GRB

    def write_to_file(model, filestring):
    directory = os.getcwd()
    filename = directory+filestring
    model.write(filename)


    nodes = ['s', 'a', 'b', 'c', 'd', 'e','t']
    orig = 's'
    dest = 't'

    arcs, capacity = gp.multidict({
    ('s', 'a') : 1,
    ('a', 'b') : 3,
    ('b', 'a') : 2,
    ('c', 'e') : 4,
    ('s', 'b') : 4,
    ('a', 'd') : 4,
    ('b', 'd') : 3,
    ('d', 't') : 9,
    ('s', 'c') : 6,
    ('b', 'e') : 1,
    ('e', 't') : 4
    })

    m = gp.Model("Rec4")

    # add our variables
    flow = m.addVars(arcs, name = "flow")

    # cannot go over capacity
    m.addConstrs(
    (flow.sum(i,j) <= capacity[i,j] for i,j in arcs), "cap")

    # flow conservation
    m.addConstrs(
    (flow.sum(i,'*') - flow.sum('*',i) == 0 for i in nodes if i != orig and i != dest), "conservation")

    # maximize flow
    obj = (flow.sum('*', dest) - flow.sum(dest, '*'))
    m.setObjective(obj, GRB.MAXIMIZE)

    m.optimize()

    # print solutions
    if m.status == GRB.OPTIMAL:
    solution = m.getAttr('x', flow)
    for i, j in arcs:
    if solution[i, j] > 0:
    print('%s -> %s: %g' % (i, j, solution[i, j]))

    write_to_file(m, "//test.lp")

    ########################################################################
    # Dual problem
    duals = m.getAttr("Pi", m.getConstrs())
    print(duals)

    Continue reading...

Compartilhe esta Página