メインコンテンツへスキップ

Shortest Path Problem LP formulation

回答済み

コメント

3件のコメント

  • 正式なコメント
    Simranjit Kaur
    • Gurobi Staff
    This post is more than three 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.
  • Jonasz Staszek
    • Community Moderator
    • Gurobi-versary
    • Thought Leader
    • First Question

    Hi Elias,

    you could for example use NetworkX to construct your graph and then simply iterate over its nodes and their respective predecessors and successors to build your constraints. For your toy example, you could have:

    import networkx as nx
    import gurobipy as gp
    G = nx.DiGraph()

    # adding directed edges inferred from the example (NetworkX adds nodes automatically)
    G.add_edges_from([(0,1), (1,2), (1,3), (0,2), (2,3), (2,4), (2,5), (3,4), (3,5), (3,6), (4,5), (4,6), (4,7), (5,6), (5,7), (6,7)])

    # defining the model and variables
    m = gp.Model()
    x = gp.tupledict()
    for (v1, v2) in G.edges:
        x[v1, v2] = m.addVar(vtype="B", name=f"x_{v1}_{v2}")
        

    # adding flow conservation constraints
    for v in G.nodes:
        # we need to skip the source (0) and the sink (7)
        if v not in [0,7]:
            # we collect the predecessor variables
            expr1 = gp.quicksum(x[i,v] for i in G.predecessors(v))
            
            # we collect the successor variables 
            expr2 = gp.quicksum(x[v, j] for j in G.successors(v))
            
            # we add the constraint
            m.addLConstr(expr1 - expr2 == 0)

    Obviously, NetworkX does not require constructing the graph manually, as I did in the example above. You will find numerous ways to import a graph into NetworkX in the documentation. 

    Hope this helps.

    Best regards
    Jonasz

    1
  • Elias Ødegaard
    • Gurobi-versary
    • First Comment
    • First Question

    Thank you, Jonasz! 

    This was very helpful:)

    Elias

    1

投稿コメントは受け付けていません。