Statistics
| Branch: | Revision:

iof-tools / networkxMiCe / networkx-master / networkx / algorithms / approximation / tests / test_vertex_cover.py @ 5cef0f13

History | View | Annotate | Download (1.68 KB)

1
from nose.tools import assert_equals
2
from nose.tools import ok_
3
import networkx as nx
4
from networkx.algorithms.approximation import min_weighted_vertex_cover
5

    
6

    
7
def is_cover(G, node_cover):
8
    return all({u, v} & node_cover for u, v in G.edges())
9

    
10

    
11
class TestMWVC(object):
12
    """Unit tests for the approximate minimum weighted vertex cover
13
    function,
14
    :func:`~networkx.algorithms.approximation.vertex_cover.min_weighted_vertex_cover`.
15

16
    """
17

    
18
    def test_unweighted_directed(self):
19
        # Create a star graph in which half the nodes are directed in
20
        # and half are directed out.
21
        G = nx.DiGraph()
22
        G.add_edges_from((0, v) for v in range(1, 26))
23
        G.add_edges_from((v, 0) for v in range(26, 51))
24
        cover = min_weighted_vertex_cover(G)
25
        assert_equals(2, len(cover))
26
        ok_(is_cover(G, cover))
27

    
28
    def test_unweighted_undirected(self):
29
        # create a simple star graph
30
        size = 50
31
        sg = nx.star_graph(size)
32
        cover = min_weighted_vertex_cover(sg)
33
        assert_equals(2, len(cover))
34
        ok_(is_cover(sg, cover))
35

    
36
    def test_weighted(self):
37
        wg = nx.Graph()
38
        wg.add_node(0, weight=10)
39
        wg.add_node(1, weight=1)
40
        wg.add_node(2, weight=1)
41
        wg.add_node(3, weight=1)
42
        wg.add_node(4, weight=1)
43

    
44
        wg.add_edge(0, 1)
45
        wg.add_edge(0, 2)
46
        wg.add_edge(0, 3)
47
        wg.add_edge(0, 4)
48

    
49
        wg.add_edge(1, 2)
50
        wg.add_edge(2, 3)
51
        wg.add_edge(3, 4)
52
        wg.add_edge(4, 1)
53

    
54
        cover = min_weighted_vertex_cover(wg, weight="weight")
55
        csum = sum(wg.nodes[node]["weight"] for node in cover)
56
        assert_equals(4, csum)
57
        ok_(is_cover(wg, cover))