Skip to main content

[HELP] Translation of Algebraic Mathematical Model to using python gurobi api




  • Richard Oberdieck
    Gurobi Staff Gurobi Staff

    Hi Evans,


    here is an implementation of your problem in Python using Gurobi:

    First, we define a few basics. Since I don't know anything about your problem‚ I just generated some random data.

    import gurobipy as gp
    import numpy as np

    # The nodes
    nodes = 10
    V = range(nodes)
    n = np.random.rand(nodes) # max capacity of node i

    # The arcs
    A = [(i,j) for i in V for j in V] # The set of arcs. This may have to be adjusted for your problem
    c = np.random.rand(nodes, nodes) # max capacity of arc ij


    Next, we formulate and solve the problem:

    solution_found = False
    tau = 2

    while not solution_found:
    T = range(tau)
    m = gp.Model()

    # Add the variables
    y = m.addVars(nodes,tau)
    x = m.addVars(A, tau, lb=-gp.GRB.INFINITY)

    # This picks the last element from y and maximizes that
    m.setObjective(y[nodes-1,tau-1], sense=gp.GRB.MAXIMIZE)

    # The constraints
    for t in T:
    for j in V:
    if t > 0:
    m.addConstr(y[j,t] - y[j,t-1] - x.sum('*',j,t-1) + x.sum(j,'*',t-1) == 0)

    m.addConstr(y[j,t] <= n[j])

    for i,j in A:
    m.addConstr(x[i,j,t] + x[j,i,t] >= 0)
    m.addConstr(x[i,j,t] + x[j,i,t] <= c[i,j])


    if m.Status == gp.GRB.OPTIMAL:
    solution_found = True

    tau += 1

    Note that Python indexes at 0, which leads to the "-1" in a few places. Also, note that I assume that the super sink is the last node for convenience.


    Good luck

  • Evans Etrue Howard
    First Comment
    First Question

    Thanks very much Richard for the solution. You are a life saver. 

    Honestly I have 5 more constraints. Please help me out if am not asking for too much.  Attached is a picture of the other constraints.

  • Richard Oberdieck
    Gurobi Staff Gurobi Staff

    Hi Evans,

    I think you should give it shot yourself based on the code that I sent. You can see that the gurobipy interface is quite easy to use, so it should be possible for you to add the additional constraints.

    Best regards


  • Evans Etrue Howard
    First Comment
    First Question

    Thanks. I have been able to implement it. Thanks very much. Your code was very intuitive and and straightforward. 

    You are need very helpful


Please sign in to leave a comment.