1

我正在使用NetworkX来解决具有多个源和接收器的最大流量问题。我发现了一个在 NetworkX 中运行良好的函数,max_cost_flow但我遇到的问题是它要求净需求为零,换句话说,任何接收器都不应低于它的需要,否则会引发错误。

我可以使用什么(或如何修改此算法)来允许它计算最佳可能流量,而不一定满足所有条件?

根据 kraskevich 的建议:

import networkx as nx

def convert(graph):

    allNodes = graph.nodes()

    newSource = len(allNodes) + 1
    newSink = len(allNodes) + 2

    graph.add_node(newSource)
    graph.add_node(newSink)


    for currentNode in allNodes:

        demand = graph.node[currentNode]['demand']

        if demand < 0 :
            graph.add_edge(newSource, currentNode, weight=0, capacity=demand)


        if demand > 0:
            graph.add_edge(newSink, currentNode, weight=0, capacity=demand)

    return graph



g = nx.DiGraph()

g.add_node(1, demand = 1)
g.add_node(2, demand = -2)
g.add_node(3, demand = 2)
g.add_node(4, demand = -4)

g.add_edge(1, 2, weight=4, capacity=100)
g.add_edge(1, 4, weight=3, capacity=100)
g.add_edge(3, 2, weight=5, capacity=100)
g.add_edge(3, 4, weight=2, capacity=100)
g.add_edge(3, 1, weight=1)
newGraph = convert(g)
print(nx.max_flow_min_cost(g, newGraph.nodes()[-2],newGraph.nodes()[-1]))
4

1 回答 1

2
  1. 您可以通过创建一个新的源顶点并将零成本的边和来自它的旧需求值的边添加到所有旧源,将多源流问题转换为单源问题。

  2. 您可以对所有水槽做同样的事情(但边缘应该从旧水槽到新水槽)。

  3. 之后,您可以使用max_flow_min_cost函数找到具有最小成本的最大流量(它不需要满足所有需求)。

更新:您的代码中有一些错误。这是一个工作示例(我稍微更改了图表,使流量不为零):

import networkx as nx

def convert(graph):
    allNodes = graph.nodes()
    newSource = len(allNodes) + 1
    newSink = len(allNodes) + 2

    graph.add_node(newSource)
    graph.add_node(newSink)

    for currentNode in allNodes:
        demand = graph.node[currentNode]['demand']
        # Direction matters
        # It goes FROM the new source and TO the new sink
        if demand < 0:
            graph.add_edge(newSource, currentNode, weight=0, capacity=-demand)
        if demand > 0:
            graph.add_edge(currentNode, newSink, weight=0, capacity=demand)
        # We also need to zero out all demands
        graph.node[currentNode]['demand'] = 0
    return graph



g = nx.DiGraph()

g.add_node(1, demand = 1)
g.add_node(2, demand = -2)
g.add_node(3, demand = 2)
g.add_node(4, demand = -4)

g.add_edge(1, 2, weight=4, capacity=100)
g.add_edge(1, 4, weight=3, capacity=100)
g.add_edge(2, 3, weight=5, capacity=100)
g.add_edge(4, 3, weight=2, capacity=100)
g.add_edge(1, 3, weight=1)
newGraph = convert(g)
# The order of s and t matters here, too
print(nx.max_flow_min_cost(g, g.nodes()[-2], g.nodes()[-1]))
于 2017-03-26T17:04:00.650 回答