# Ticket #7593: trac_7593.patch

File trac_7593.patch, 2.8 KB (added by ncohen, 11 years ago)
• ## sage/graphs/graph.py

# HG changeset patch
# User Nathann Cohen <nathann.cohen@gmail.com>
# Date 1260813556 -3600
# Node ID cf964062f80b2e2ae11115502e40fdfe869baa9e
# Parent  964c2f4ce74db0417a771de0b0cfc951b1fab73c
Matching for graph

diff -r 964c2f4ce74d -r cf964062f80b sage/graphs/graph.py
 a v = pv return B, C def matching(self,value_only=False, use_edge_labels=True): r""" Returns a maximum weighted matching of the graph ( cf. http://en.wikipedia.org/wiki/Matching ) represented by the list of its edges. Given a graph G such that each edge e has a weight w_e, a maximum matching is a subset S of the edges of G of maximum weight such that no two edges of S are incident with each other. As an optimization problem, it can be expressed as : .. math:: \mbox{Maximize : }&\sum_{e\in G.edges()} w_e b_e\\ \mbox{Such that : }&\forall v \in G, \sum_{(u,v)\in G.edges()} b_{(u,v)}\leq 1\\ &\forall x\in G, b_x\mbox{ is a binary variable} INPUT: - value_only (boolean) - When set to True, only the cardinal ( or the weight ) of the the matching is returned - use_edge_labels (boolean) - When set to True, computes a weighted matching where each edge is weighted by its label. ( if an edge has no label, 1 is assumed ) when set to False, each edge has weight 1 EXAMPLE:: sage: g=graphs.PappusGraph() sage: g.matching(value_only=True) # optional - requires Glpk or COIN-OR/CBC 9.0 """ from sage.numerical.mip import MixedIntegerLinearProgram g=self # returns the weight of an edge considering it may not be # weighted ... weight=lambda x: 1 if x==None else x p=MixedIntegerLinearProgram(maximization=True) b=p.new_variable(dim=2) [p.set_objective(sum([weight(w)*b[min(u,v)][max(u,v)] for (u,v,w) in g.edges()]))] # for any vertex v, there is at most one edge incident to v in the maximum matching [p.add_constraint(sum([b[min(u,v)][max(u,v)] for u in g.neighbors(v)]),max=1) for v in g.vertices()] p.set_binary(b) if value_only: return p.solve(objective_only=True) else: p.solve() b=p.get_values(b) return [(u,v,w) for (u,v,w) in g.edges() if b[min(u,v)][max(u,v)] == 1] ### Vertex handlers def add_vertex(self, name=None):