求解最大权重二分 b 匹配

Sin*_*ina 5 python graph bipartite networkx pulp

我的问题是关于最大权重 B 匹配问题。

二部匹配问题将二部图中的两组顶点配对。甲最大加权匹配二部(MWM)被定义为一个匹配,其中在匹配的边的值的总和有最大值。一个著名的 MWM 多项式时间算法是匈牙利算法。

我感兴趣的是一个特定的最大加权二分匹配,称为权重二分 B 匹配问题。权重二分 B 匹配问题 (WBM) 寻求匹配顶点,以便每个顶点与不超过其容量b允许的顶点匹配。

在此处输入图片说明

此图(来自Chen 等人)显示了 WBM 问题。输入图的得分为 2.2,即所有边权重的总和。解决方案 H 的蓝色边缘在满足红色度约束的所有子图中产生最高分,1.6。

尽管最近有一些工作解决了 WBM 问题(thisthis),但我找不到该算法的任何实现。有谁知道 WBM 问题是否已经存在于像 networkX 这样的任何库中?

Ram*_*han 3

让我们尝试逐步执行此操作,编写我们自己的函数来解决问题中指定的 WBM 问题。

pulp当我们给定两组节点(u 和 v、边权重和顶点容量)时,使用它来制定和解决加权二分匹配 (WBM) 并不太困难。

在下面的步骤 2 中,您将找到一个(希望很容易理解)函数,用于将 WBM 表述为 ILP,并使用pulp.Go 来解决它,看看它是否有帮助。(你需要pip install pulp

步骤 1:设置二分图容量和边权重

import networkx as nx
from pulp import *
import matplotlib.pyplot as plt

from_nodes = [1, 2, 3]
to_nodes = [1, 2, 3, 4]
ucap = {1: 1, 2: 2, 3: 2} #u node capacities
vcap = {1: 1, 2: 1, 3: 1, 4: 1} #v node capacities

wts = {(1, 1): 0.5, (1, 3): 0.3,
       (2, 1): 0.4, (2, 4): 0.1,
       (3, 2): 0.7, (3, 4): 0.2}

#just a convenience function to generate a dict of dicts
def create_wt_doubledict(from_nodes, to_nodes):

    wt = {}
    for u in from_nodes:
        wt[u] = {}
        for v in to_nodes:
            wt[u][v] = 0

    for k,val in wts.items():
        u,v = k[0], k[1]
        wt[u][v] = val
    return(wt)
Run Code Online (Sandbox Code Playgroud)

步骤 2:求解 WBM(用整数规划表示)

为了使后面的代码更容易理解,这里有一些描述:

  • WBM 是分配问题的变体。
  • 我们将右侧的节点“匹配”到左侧的节点。
  • 边缘有权重
  • 目标是最大化所选边的权重总和。
  • 附加约束集:对于每个节点,所选边的数量必须小于指定的“容量”。
  • PuLP 文档(如果您不熟悉)puLP

def solve_wbm(from_nodes, to_nodes, wt):
''' A wrapper function that uses pulp to formulate and solve a WBM'''

    prob = LpProblem("WBM Problem", LpMaximize)

    # Create The Decision variables
    choices = LpVariable.dicts("e",(from_nodes, to_nodes), 0, 1, LpInteger)

    # Add the objective function 
    prob += lpSum([wt[u][v] * choices[u][v] 
                   for u in from_nodes
                   for v in to_nodes]), "Total weights of selected edges"


    # Constraint set ensuring that the total from/to each node 
    # is less than its capacity
    for u in from_nodes:
        for v in to_nodes:
            prob += lpSum([choices[u][v] for v in to_nodes]) <= ucap[u], ""
            prob += lpSum([choices[u][v] for u in from_nodes]) <= vcap[v], ""


    # The problem data is written to an .lp file
    prob.writeLP("WBM.lp")

    # The problem is solved using PuLP's choice of Solver
    prob.solve()

    # The status of the solution is printed to the screen
    print( "Status:", LpStatus[prob.status])
    return(prob)


def print_solution(prob):
    # Each of the variables is printed with it's resolved optimum value
    for v in prob.variables():
        if v.varValue > 1e-3:
            print(f'{v.name} = {v.varValue}')
    print(f"Sum of wts of selected edges = {round(value(prob.objective), 4)}")


def get_selected_edges(prob):

    selected_from = [v.name.split("_")[1] for v in prob.variables() if v.value() > 1e-3]
    selected_to   = [v.name.split("_")[2] for v in prob.variables() if v.value() > 1e-3]

    selected_edges = []
    for su, sv in list(zip(selected_from, selected_to)):
        selected_edges.append((su, sv))
    return(selected_edges)        
Run Code Online (Sandbox Code Playgroud)

步骤 3:指定图形并调用 WBM 求解器

wt = create_wt_doubledict(from_nodes, to_nodes)
p = solve_wbm(from_nodes, to_nodes, wt)
print_solution(p)
Run Code Online (Sandbox Code Playgroud)

这给出:

Status: Optimal
e_1_3 = 1.0
e_2_1 = 1.0
e_3_2 = 1.0
e_3_4 = 1.0
Sum of wts of selected edges = 1.6
Run Code Online (Sandbox Code Playgroud)

步骤 4:(可选)使用 Networkx 绘制图表

selected_edges = get_selected_edges(p)


#Create a Networkx graph. Use colors from the WBM solution above (selected_edges)
graph = nx.Graph()
colors = []
for u in from_nodes:
    for v in to_nodes:
        edgecolor = 'blue' if (str(u), str(v)) in selected_edges else 'gray'
        if wt[u][v] > 0:
            graph.add_edge('u_'+ str(u), 'v_' + str(v))
            colors.append(edgecolor)


def get_bipartite_positions(graph):
    pos = {}
    for i, n in enumerate(graph.nodes()):
        x = 0 if 'u' in n else 1 #u:0, v:1
        pos[n] = (x,i)
    return(pos)

pos = get_bipartite_positions(graph)


nx.draw_networkx(graph, pos, with_labels=True, edge_color=colors,
       font_size=20, alpha=0.5, width=3)

plt.axis('off')
plt.show() 

print("done")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

蓝色边缘是为 WBM 选择的边缘。希望这可以帮助您前进。