示例#1
0
    def test_digraphs(self):
        for dest, source in [(to_dict_of_dicts, from_dict_of_dicts),
                             (to_dict_of_lists, from_dict_of_lists)]:
            G = cycle_graph(10)

            # Dict of [dicts, lists]
            dod = dest(G)
            GG = source(dod)
            assert_equal(sorted(G.nodes()), sorted(GG.nodes()))
            assert_equal(sorted(G.edges()), sorted(GG.edges()))
            GW = from_whatever(dod)
            assert_equal(sorted(G.nodes()), sorted(GW.nodes()))
            assert_equal(sorted(G.edges()), sorted(GW.edges()))
            GI = Graph(dod)
            assert_equal(sorted(G.nodes()), sorted(GI.nodes()))
            assert_equal(sorted(G.edges()), sorted(GI.edges()))

            G = cycle_graph(10, create_using=DiGraph())
            dod = dest(G)
            GG = source(dod, create_using=DiGraph())
            assert_equal(sorted(G.nodes()), sorted(GG.nodes()))
            assert_equal(sorted(G.edges()), sorted(GG.edges()))
            GW = from_whatever(dod, create_using=DiGraph())
            assert_equal(sorted(G.nodes()), sorted(GW.nodes()))
            assert_equal(sorted(G.edges()), sorted(GW.edges()))
            GI = DiGraph(dod)
            assert_equal(sorted(G.nodes()), sorted(GI.nodes()))
            assert_equal(sorted(G.edges()), sorted(GI.edges()))
示例#2
0
    def test_digraphs(self):
        for dest, source in [(to_dict_of_dicts, from_dict_of_dicts),
                             (to_dict_of_lists, from_dict_of_lists)]:
            G = cycle_graph(10)

            # Dict of [dicts, lists]
            dod = dest(G)
            GG = source(dod)
            assert_nodes_equal(sorted(G.nodes()), sorted(GG.nodes()))
            assert_edges_equal(sorted(G.edges()), sorted(GG.edges()))
            GW = to_networkx_graph(dod)
            assert_nodes_equal(sorted(G.nodes()), sorted(GW.nodes()))
            assert_edges_equal(sorted(G.edges()), sorted(GW.edges()))
            GI = nx.Graph(dod)
            assert_nodes_equal(sorted(G.nodes()), sorted(GI.nodes()))
            assert_edges_equal(sorted(G.edges()), sorted(GI.edges()))

            G = cycle_graph(10, create_using=nx.DiGraph)
            dod = dest(G)
            GG = source(dod, create_using=nx.DiGraph)
            assert sorted(G.nodes()) == sorted(GG.nodes())
            assert sorted(G.edges()) == sorted(GG.edges())
            GW = to_networkx_graph(dod, create_using=nx.DiGraph)
            assert sorted(G.nodes()) == sorted(GW.nodes())
            assert sorted(G.edges()) == sorted(GW.edges())
            GI = nx.DiGraph(dod)
            assert sorted(G.nodes()) == sorted(GI.nodes())
            assert sorted(G.edges()) == sorted(GI.edges())
示例#3
0
    def test_digraphs(self):
        for dest, source in [(to_dict_of_dicts, from_dict_of_dicts),
                             (to_dict_of_lists, from_dict_of_lists)]:
            G = cycle_graph(10)

            # Dict of [dicts, lists]
            dod = dest(G)
            GG = source(dod)
            assert_nodes_equal(sorted(G.nodes()), sorted(GG.nodes()))
            assert_edges_equal(sorted(G.edges()), sorted(GG.edges()))
            GW = to_networkx_graph(dod)
            assert_nodes_equal(sorted(G.nodes()), sorted(GW.nodes()))
            assert_edges_equal(sorted(G.edges()), sorted(GW.edges()))
            GI = nx.Graph(dod)
            assert_nodes_equal(sorted(G.nodes()), sorted(GI.nodes()))
            assert_edges_equal(sorted(G.edges()), sorted(GI.edges()))

            G = cycle_graph(10, create_using=nx.DiGraph())
            dod = dest(G)
            GG = source(dod, create_using=nx.DiGraph())
            assert_equal(sorted(G.nodes()), sorted(GG.nodes()))
            assert_equal(sorted(G.edges()), sorted(GG.edges()))
            GW = to_networkx_graph(dod, create_using=nx.DiGraph())
            assert_equal(sorted(G.nodes()), sorted(GW.nodes()))
            assert_equal(sorted(G.edges()), sorted(GW.edges()))
            GI = nx.DiGraph(dod)
            assert_equal(sorted(G.nodes()), sorted(GI.nodes()))
            assert_equal(sorted(G.edges()), sorted(GI.edges()))
示例#4
0
 def test_graph_edit_distance_node_match(self):
     G1 = cycle_graph(5)
     G2 = cycle_graph(5)
     for n, attr in G1.nodes.items():
         attr['color'] = 'red' if n % 2 == 0 else 'blue'
     for n, attr in G2.nodes.items():
         attr['color'] = 'red' if n % 2 == 1 else 'blue'
     assert graph_edit_distance(G1, G2) == 0
     assert graph_edit_distance(G1, G2, node_match=lambda n1, n2: n1['color'] == n2['color']) == 1
示例#5
0
 def test_graph_edit_distance_node_match(self):
     G1 = cycle_graph(5)
     G2 = cycle_graph(5)
     for n, attr in G1.nodes.items():
         attr["color"] = "red" if n % 2 == 0 else "blue"
     for n, attr in G2.nodes.items():
         attr["color"] = "red" if n % 2 == 1 else "blue"
     assert graph_edit_distance(G1, G2) == 0
     assert (graph_edit_distance(
         G1, G2, node_match=lambda n1, n2: n1["color"] == n2["color"]) == 1)
    def test_graph(self):
        G=cycle_graph(10)
        e=G.edges()
        source=[u for u,v in e]
        dest=[v for u,v in e]
        ex=zip(source,dest,source)
        G=Graph()
        G.add_weighted_edges_from(ex)
        
        # Dict of dicts
        dod=to_dict_of_dicts(G)
        GG=from_dict_of_dicts(dod,create_using=Graph())
        assert_equal(sorted(G.nodes()), sorted(GG.nodes()))
        assert_equal(sorted(G.edges()), sorted(GG.edges()))
        GW=to_networkx_graph(dod,create_using=Graph())
        assert_equal(sorted(G.nodes()), sorted(GW.nodes()))
        assert_equal(sorted(G.edges()), sorted(GW.edges()))
        GI=Graph(dod)
        assert_equal(sorted(G.nodes()), sorted(GI.nodes()))
        assert_equal(sorted(G.edges()), sorted(GI.edges()))

        # Dict of lists
        dol=to_dict_of_lists(G)
        GG=from_dict_of_lists(dol,create_using=Graph())
        # dict of lists throws away edge data so set it to none
        enone=[(u,v,{}) for (u,v,d) in G.edges(data=True)]
        assert_equal(sorted(G.nodes()), sorted(GG.nodes()))
        assert_equal(enone, sorted(GG.edges(data=True)))
        GW=to_networkx_graph(dol,create_using=Graph())
        assert_equal(sorted(G.nodes()), sorted(GW.nodes()))
        assert_equal(enone, sorted(GW.edges(data=True)))
        GI=Graph(dol)
        assert_equal(sorted(G.nodes()), sorted(GI.nodes()))
        assert_equal(enone, sorted(GI.edges(data=True)))
示例#7
0
    def test_optimal_edit_paths(self):
        G1 = path_graph(3)
        G2 = cycle_graph(3)
        paths, cost = optimal_edit_paths(G1, G2)
        assert cost == 1
        assert len(paths) == 6

        def canonical(vertex_path, edge_path):
            return tuple(sorted(vertex_path)), tuple(
                sorted(edge_path, key=lambda x: (None in x, x)))

        expected_paths = [([(0, 0), (1, 1), (2, 2)], [((0, 1), (0, 1)),
                                                      ((1, 2), (1, 2)),
                                                      (None, (0, 2))]),
                          ([(0, 0), (1, 2), (2, 1)], [((0, 1), (0, 2)),
                                                      ((1, 2), (1, 2)),
                                                      (None, (0, 1))]),
                          ([(0, 1), (1, 0), (2, 2)], [((0, 1), (0, 1)),
                                                      ((1, 2), (0, 2)),
                                                      (None, (1, 2))]),
                          ([(0, 1), (1, 2), (2, 0)], [((0, 1), (1, 2)),
                                                      ((1, 2), (0, 2)),
                                                      (None, (0, 1))]),
                          ([(0, 2), (1, 0), (2, 1)], [((0, 1), (0, 2)),
                                                      ((1, 2), (0, 1)),
                                                      (None, (1, 2))]),
                          ([(0, 2), (1, 1), (2, 0)], [((0, 1), (1, 2)),
                                                      ((1, 2), (0, 1)),
                                                      (None, (0, 2))])]
        assert ({canonical(*p)
                 for p in paths} == {canonical(*p)
                                     for p in expected_paths})
示例#8
0
    def test_graph_edit_distance(self):
        G0 = nx.Graph()
        G1 = path_graph(6)
        G2 = cycle_graph(6)
        G3 = wheel_graph(7)

        assert graph_edit_distance(G0, G0) == 0
        assert graph_edit_distance(G0, G1) == 11
        assert graph_edit_distance(G1, G0) == 11
        assert graph_edit_distance(G0, G2) == 12
        assert graph_edit_distance(G2, G0) == 12
        assert graph_edit_distance(G0, G3) == 19
        assert graph_edit_distance(G3, G0) == 19

        assert graph_edit_distance(G1, G1) == 0
        assert graph_edit_distance(G1, G2) == 1
        assert graph_edit_distance(G2, G1) == 1
        assert graph_edit_distance(G1, G3) == 8
        assert graph_edit_distance(G3, G1) == 8

        assert graph_edit_distance(G2, G2) == 0
        assert graph_edit_distance(G2, G3) == 7
        assert graph_edit_distance(G3, G2) == 7

        assert graph_edit_distance(G3, G3) == 0
示例#9
0
    def test_graph(self):
        G=cycle_graph(10)
        e=G.edges()
        source=[u for u,v in e]
        dest=[v for u,v in e]
        ex=zip(source,dest,source)
        G=Graph()
        G.add_weighted_edges_from(ex)

        # Dict of dicts
        dod=to_dict_of_dicts(G)
        GG=from_dict_of_dicts(dod,create_using=Graph())
        assert_equal(sorted(G.nodes()), sorted(GG.nodes()))
        assert_equal(sorted(G.edges()), sorted(GG.edges()))
        GW=to_networkx_graph(dod,create_using=Graph())
        assert_equal(sorted(G.nodes()), sorted(GW.nodes()))
        assert_equal(sorted(G.edges()), sorted(GW.edges()))
        GI=Graph(dod)
        assert_equal(sorted(G.nodes()), sorted(GI.nodes()))
        assert_equal(sorted(G.edges()), sorted(GI.edges()))

        # Dict of lists
        dol=to_dict_of_lists(G)
        GG=from_dict_of_lists(dol,create_using=Graph())
        # dict of lists throws away edge data so set it to none
        enone=[(u,v,{}) for (u,v,d) in G.edges(data=True)]
        assert_equal(sorted(G.nodes()), sorted(GG.nodes()))
        assert_equal(enone, sorted(GG.edges(data=True)))
        GW=to_networkx_graph(dol,create_using=Graph())
        assert_equal(sorted(G.nodes()), sorted(GW.nodes()))
        assert_equal(enone, sorted(GW.edges(data=True)))
        GI=Graph(dol)
        assert_equal(sorted(G.nodes()), sorted(GI.nodes()))
        assert_equal(enone, sorted(GI.edges(data=True)))
示例#10
0
def test_correctness():
    # note: in the future can restrict all graphs to have the same number of nodes, for analysis
    graphs = [lambda: basic_graph(), lambda: complete_graph(10), lambda: balanced_tree(3, 5), lambda: barbell_graph(6, 7),
              lambda: binomial_tree(10), lambda: cycle_graph(50),
              lambda: path_graph(200), lambda: star_graph(200)]
    names = ["basic_graph", "complete_graph", "balanced_tree", "barbell_graph", "binomial_tree", "cycle_graph",
             "path_graph", "star_graph"]
    for graph, name in zip(graphs, names):
        print(f"Testing graph {name}...")
        
        # Initialize both graphs
        G_dinitz = graph()
        G_gr = graph()

        # Set random capacities of graph edges
        for u, v in G_dinitz.edges:
            cap = randint(1, 20)
            G_dinitz.edges[u, v]["capacity"] = cap
            G_gr.edges[u, v]["capacity"] = cap

        # Pick random start and end node
        start_node = randint(0, len(G_dinitz.nodes)-1)
        end_node = randint(0, len(G_dinitz.nodes)-1)
        while start_node == end_node: end_node = randint(0, len(G_dinitz.nodes)-1)

        # Run max-flow
        R_dinitz = dinitz(G_dinitz, start_node, end_node)
        R_gr = goldberg_rao(G_gr, start_node, end_node)

        # Check correctness
        d_mf = R_dinitz.graph["flow_value"]
        gr_mf = R_gr.graph["flow_value"]
        assert d_mf == gr_mf, f"Computed max flow in {name} graph is {d_mf}, but goldberg_rao function computed {gr_mf}"
示例#11
0
def frucht_graph(create_using=None):
    """Returns the Frucht Graph.

    The Frucht Graph is the smallest cubical graph whose
    automorphism group consists only of the identity element.

    """
    G = cycle_graph(7, create_using)
    G.add_edges_from(
        [
            [0, 7],
            [1, 7],
            [2, 8],
            [3, 9],
            [4, 9],
            [5, 10],
            [6, 10],
            [7, 11],
            [8, 11],
            [8, 9],
            [10, 11],
        ]
    )

    G.name = "Frucht Graph"
    return G
示例#12
0
def get_graph(max_size):
    graph_type = np.random.randint(1, 5)
    num_nodes = np.random.randint(5, max(max_size, 5) + 1)

    if graph_type == 1:
        return path_graph(num_nodes), graph_type
    elif graph_type == 2:
        g = random_tree(num_nodes)

        max_degree = 0

        for n in g.degree:
            max_degree = max(max_degree, n[1])

        if max_degree <= 2:
            graph_type = 1

        return g, graph_type
    elif graph_type == 3:
        part1 = np.random.randint(2, max(max_size / 2, 2) + 1)
        part2 = np.random.randint(3, max(max_size / 2, 3) + 1)
        return complete_bipartite_graph(part1, part2), graph_type
    elif graph_type == 4:
        return cycle_graph(num_nodes), graph_type
    else:
        sys.exit('Something unexpected happened!')
示例#13
0
def LCF_graph(n, shift_list, repeats, create_using=None):
    """
    Return the cubic graph specified in LCF notation.

    LCF notation (LCF=Lederberg-Coxeter-Fruchte) is a compressed
    notation used in the generation of various cubic Hamiltonian
    graphs of high symmetry. See, for example, dodecahedral_graph,
    desargues_graph, heawood_graph and pappus_graph below.
    
    n (number of nodes)
      The starting graph is the n-cycle with nodes 0,...,n-1.
      (The null graph is returned if n < 0.)

    shift_list = [s1,s2,..,sk], a list of integer shifts mod n,

    repeats
      integer specifying the number of times that shifts in shift_list
      are successively applied to each v_current in the n-cycle
      to generate an edge between v_current and v_current+shift mod n.

    For v1 cycling through the n-cycle a total of k*repeats
    with shift cycling through shiftlist repeats times connect
    v1 with v1+shift mod n
          
    The utility graph K_{3,3}

    >>> G=nx.LCF_graph(6,[3,-3],3)
    
    The Heawood graph

    >>> G=nx.LCF_graph(14,[5,-5],7)

    See http://mathworld.wolfram.com/LCFNotation.html for a description
    and references.
    
    """
    if create_using is not None and create_using.is_directed():
        raise NetworkXError("Directed Graph not supported")

    if n <= 0:
        return empty_graph(0, create_using)

    # start with the n-cycle
    G = cycle_graph(n, create_using)
    G.name = "LCF_graph"
    nodes = G.nodes()

    n_extra_edges = repeats * len(shift_list)
    # edges are added n_extra_edges times
    # (not all of these need be new)
    if n_extra_edges < 1:
        return G

    for i in range(n_extra_edges):
        shift = shift_list[i % len(shift_list)]  # cycle through shift_list
        v1 = nodes[i % n]  # cycle repeatedly through nodes
        v2 = nodes[(i + shift) % n]
        G.add_edge(v1, v2)
    return G
示例#14
0
文件: small.py 项目: nickp60/Ragout
def LCF_graph(n, shift_list, repeats, create_using=None):
    """
    Return the cubic graph specified in LCF notation.

    LCF notation (LCF=Lederberg-Coxeter-Fruchte) is a compressed
    notation used in the generation of various cubic Hamiltonian
    graphs of high symmetry. See, for example, dodecahedral_graph,
    desargues_graph, heawood_graph and pappus_graph below.
    
    n (number of nodes)
      The starting graph is the n-cycle with nodes 0,...,n-1.
      (The null graph is returned if n < 0.)

    shift_list = [s1,s2,..,sk], a list of integer shifts mod n,

    repeats
      integer specifying the number of times that shifts in shift_list
      are successively applied to each v_current in the n-cycle
      to generate an edge between v_current and v_current+shift mod n.

    For v1 cycling through the n-cycle a total of k*repeats
    with shift cycling through shiftlist repeats times connect
    v1 with v1+shift mod n
          
    The utility graph K_{3,3}

    >>> G=nx.LCF_graph(6,[3,-3],3)
    
    The Heawood graph

    >>> G=nx.LCF_graph(14,[5,-5],7)

    See http://mathworld.wolfram.com/LCFNotation.html for a description
    and references.
    
    """
    if create_using is not None and create_using.is_directed():
        raise NetworkXError("Directed Graph not supported")

    if n <= 0:
        return empty_graph(0, create_using)

    # start with the n-cycle
    G = cycle_graph(n, create_using)
    G.name = "LCF_graph"
    nodes = G.nodes()

    n_extra_edges = repeats * len(shift_list)
    # edges are added n_extra_edges times
    # (not all of these need be new)
    if n_extra_edges < 1:
        return G

    for i in range(n_extra_edges):
        shift = shift_list[i % len(shift_list)]  #cycle through shift_list
        v1 = nodes[i % n]  # cycle repeatedly through nodes
        v2 = nodes[(i + shift) % n]
        G.add_edge(v1, v2)
    return G
示例#15
0
 def create_weighted(self, G):
     g = cycle_graph(4)
     e = list(g.edges())
     source = [u for u,v in e]
     dest = [v for u,v in e]
     weight = [s+10 for s in source]
     ex = zip(source, dest, weight)
     G.add_weighted_edges_from(ex)
     return G
示例#16
0
 def create_weighted(self, G):
     g = cycle_graph(4)
     e = list(g.edges())
     source = [u for u, v in e]
     dest = [v for u, v in e]
     weight = [s + 10 for s in source]
     ex = zip(source, dest, weight)
     G.add_weighted_edges_from(ex)
     return G
示例#17
0
def frucht_graph(create_using=None):
    """Return the Frucht Graph.

    The Frucht Graph is the smallest cubical graph whose
    automorphism group consists only of the identity element.

    """
    G = cycle_graph(7, create_using)
    G.add_edges_from([[0, 7], [1, 7], [2, 8], [3, 9], [4, 9], [5, 10], [6, 10], [7, 11], [8, 11], [8, 9], [10, 11]])

    G.name = "Frucht Graph"
    return G
示例#18
0
def run_analysis_n_nodes(n, unit_cap, n_runs=3):
    print(f"Running analysis for {n} nodes...")
    graphs = [lambda: balanced_tree(2, int(round(np.log2(n)-1))),
              lambda: binomial_tree(int(round(np.log2(n)))), lambda: cycle_graph(n),
              lambda: path_graph(n), lambda: star_graph(n-1), lambda: random_regular_graph(3, n), lambda: random_regular_graph(5, n)]

    results_gr = {}
    results_dinitz = {}
    for graph, name in zip(graphs, names):
        # Initialize both graphs
        G_dinitz = graph()
        G_gr = G_dinitz.copy()

        total_time_gr = 0
        total_time_dinitz = 0
        for _ in range(n_runs):
            # Set random capacities of graph edges
            for u, v in G_dinitz.edges:
                cap = randint(1, 100) if not unit_cap else 1
                G_dinitz.edges[u, v]["capacity"] = cap
                G_gr.edges[u, v]["capacity"] = cap

            # Pick random start and end node
            start_node = randint(0, len(G_dinitz.nodes)-1)
            end_node = randint(0, len(G_dinitz.nodes)-1)
            while start_node == end_node: end_node = randint(0, len(G_dinitz.nodes)-1)

            # Run max-flow
            init_time = time.time()
            R_dinitz = dinitz(G_dinitz, start_node, end_node)
            total_time_dinitz += time.time() - init_time
        
            init_time = time.time()
            R_gr = goldberg_rao(G_gr, start_node, end_node)
            total_time_gr += time.time() - init_time
            
            # Check correctness
            d_mf = R_dinitz.graph["flow_value"]
            gr_mf = R_gr.graph["flow_value"]
            if d_mf != gr_mf:
                vprint(f"\t\t\tComputed max flow in {name} graph is {d_mf}, but goldberg_rao function computed {gr_mf}".upper())

        vprint(f"{name} with {len(G_gr.nodes)} nodes took {total_time_gr / n_runs} seconds with goldberg_rao")
        vprint(f"{name} with {len(G_dinitz.nodes)} nodes took {total_time_dinitz / n_runs} seconds with dinitz")
        results_gr[name] = total_time_gr / n_runs
        results_dinitz[name] = total_time_dinitz / n_runs

    return results_gr, results_dinitz
示例#19
0
def frucht_graph(create_using=None):
    """
    Returns the Frucht Graph.

    The Frucht Graph is the smallest cubical graph whose
    automorphism group consists only of the identity element [1]_.
    It has 12 nodes and 18 edges and no nontrivial symmetries.
    It is planar and Hamiltonian [2]_.

    Parameters
    ----------
    create_using : NetworkX graph constructor, optional (default=nx.Graph)
       Graph type to create. If graph instance, then cleared before populated.

    Returns
    -------
    G : networkx Graph
        Frucht Graph with 12 nodes and 18 edges

    References
    ----------
    .. [1] https://en.wikipedia.org/wiki/Frucht_graph
    .. [2] https://mathworld.wolfram.com/FruchtGraph.html

    """
    G = cycle_graph(7, create_using)
    G.add_edges_from([
        [0, 7],
        [1, 7],
        [2, 8],
        [3, 9],
        [4, 9],
        [5, 10],
        [6, 10],
        [7, 11],
        [8, 11],
        [8, 9],
        [10, 11],
    ])

    G.name = "Frucht Graph"
    return G
def run_analysis_n_nodes(n, unit_cap, n_runs=3):
    print(f"Running analysis for {n} nodes...")
    graphs = [
        lambda: balanced_tree(2, int(round(np.log2(n) - 1))),
        lambda: binomial_tree(int(round(np.log2(n)))), lambda: cycle_graph(n),
        lambda: path_graph(n), lambda: star_graph(n - 1),
        lambda: random_regular_graph(3, n), lambda: random_regular_graph(5, n)
    ]

    results_dinitz = {}
    for graph, name in zip(graphs, names):
        # Initialize both graphs
        G_dinitz = graph()

        total_time_dinitz = 0
        for _ in range(n_runs):
            # Set random capacities of graph edges
            for u, v in G_dinitz.edges:
                cap = randint(1, 100) if not unit_cap else 1
                G_dinitz.edges[u, v]["capacity"] = cap

            # Pick random start and end node
            start_node = randint(0, len(G_dinitz.nodes) - 1)
            end_node = randint(0, len(G_dinitz.nodes) - 1)
            while start_node == end_node:
                end_node = randint(0, len(G_dinitz.nodes) - 1)

            # Run max-flow
            init_time = time.time()
            R_dinitz = dinitz(G_dinitz, start_node, end_node)
            total_time_dinitz += time.time() - init_time

        vprint(
            f"{name} with {len(G_dinitz.nodes)} nodes took {total_time_dinitz / n_runs} seconds with dinitz"
        )
        results_dinitz[name] = total_time_dinitz / n_runs

    return results_dinitz
示例#21
0
    def setup_method(self):
        self.G1 = barbell_graph(10, 3)
        self.G2 = cycle_graph(10, create_using=nx.DiGraph)

        self.G3 = self.create_weighted(nx.Graph())
        self.G4 = self.create_weighted(nx.DiGraph())
示例#22
0
    def __init__(self):
        self.G1 = barbell_graph(10, 3)
        self.G2 = cycle_graph(10, create_using=nx.DiGraph())

        self.G3 = self.create_weighted(nx.Graph())
        self.G4 = self.create_weighted(nx.DiGraph())
示例#23
0
    def __init__(self):
        self.G1 = barbell_graph(10, 3)
        self.G2 = cycle_graph(10, create_using=nx.DiGraph())

        self.G3 = self.create_weighted(nx.Graph())
        self.G4 = self.create_weighted(nx.DiGraph())
示例#24
0
    def test_with_multiedges_self_loops(self):
        G = cycle_graph(10)
        XG = nx.Graph()
        XG.add_nodes_from(G)
        XG.add_weighted_edges_from((u, v, u) for u, v in G.edges())
        XGM = nx.MultiGraph()
        XGM.add_nodes_from(G)
        XGM.add_weighted_edges_from((u, v, u) for u, v in G.edges())
        XGM.add_edge(0, 1, weight=2)  # multiedge
        XGS = nx.Graph()
        XGS.add_nodes_from(G)
        XGS.add_weighted_edges_from((u, v, u) for u, v in G.edges())
        XGS.add_edge(0, 0, weight=100)  # self loop

        # Dict of dicts
        # with self loops, OK
        dod = to_dict_of_dicts(XGS)
        GG = from_dict_of_dicts(dod, create_using=nx.Graph)
        assert_nodes_equal(XGS.nodes(), GG.nodes())
        assert_edges_equal(XGS.edges(), GG.edges())
        GW = to_networkx_graph(dod, create_using=nx.Graph)
        assert_nodes_equal(XGS.nodes(), GW.nodes())
        assert_edges_equal(XGS.edges(), GW.edges())
        GI = nx.Graph(dod)
        assert_nodes_equal(XGS.nodes(), GI.nodes())
        assert_edges_equal(XGS.edges(), GI.edges())

        # Dict of lists
        # with self loops, OK
        dol = to_dict_of_lists(XGS)
        GG = from_dict_of_lists(dol, create_using=nx.Graph)
        # dict of lists throws away edge data so set it to none
        enone = [(u, v, {}) for (u, v, d) in XGS.edges(data=True)]
        assert_nodes_equal(sorted(XGS.nodes()), sorted(GG.nodes()))
        assert_edges_equal(enone, sorted(GG.edges(data=True)))
        GW = to_networkx_graph(dol, create_using=nx.Graph)
        assert_nodes_equal(sorted(XGS.nodes()), sorted(GW.nodes()))
        assert_edges_equal(enone, sorted(GW.edges(data=True)))
        GI = nx.Graph(dol)
        assert_nodes_equal(sorted(XGS.nodes()), sorted(GI.nodes()))
        assert_edges_equal(enone, sorted(GI.edges(data=True)))

        # Dict of dicts
        # with multiedges, OK
        dod = to_dict_of_dicts(XGM)
        GG = from_dict_of_dicts(dod,
                                create_using=nx.MultiGraph,
                                multigraph_input=True)
        assert_nodes_equal(sorted(XGM.nodes()), sorted(GG.nodes()))
        assert_edges_equal(sorted(XGM.edges()), sorted(GG.edges()))
        GW = to_networkx_graph(dod,
                               create_using=nx.MultiGraph,
                               multigraph_input=True)
        assert_nodes_equal(sorted(XGM.nodes()), sorted(GW.nodes()))
        assert_edges_equal(sorted(XGM.edges()), sorted(GW.edges()))
        GI = nx.MultiGraph(
            dod)  # convert can't tell whether to duplicate edges!
        assert_nodes_equal(sorted(XGM.nodes()), sorted(GI.nodes()))
        # assert_not_equal(sorted(XGM.edges()), sorted(GI.edges()))
        assert not sorted(XGM.edges()) == sorted(GI.edges())
        GE = from_dict_of_dicts(dod,
                                create_using=nx.MultiGraph,
                                multigraph_input=False)
        assert_nodes_equal(sorted(XGM.nodes()), sorted(GE.nodes()))
        assert sorted(XGM.edges()) != sorted(GE.edges())
        GI = nx.MultiGraph(XGM)
        assert_nodes_equal(sorted(XGM.nodes()), sorted(GI.nodes()))
        assert_edges_equal(sorted(XGM.edges()), sorted(GI.edges()))
        GM = nx.MultiGraph(G)
        assert_nodes_equal(sorted(GM.nodes()), sorted(G.nodes()))
        assert_edges_equal(sorted(GM.edges()), sorted(G.edges()))

        # Dict of lists
        # with multiedges, OK, but better write as DiGraph else you'll
        # get double edges
        dol = to_dict_of_lists(G)
        GG = from_dict_of_lists(dol, create_using=nx.MultiGraph)
        assert_nodes_equal(sorted(G.nodes()), sorted(GG.nodes()))
        assert_edges_equal(sorted(G.edges()), sorted(GG.edges()))
        GW = to_networkx_graph(dol, create_using=nx.MultiGraph)
        assert_nodes_equal(sorted(G.nodes()), sorted(GW.nodes()))
        assert_edges_equal(sorted(G.edges()), sorted(GW.edges()))
        GI = nx.MultiGraph(dol)
        assert_nodes_equal(sorted(G.nodes()), sorted(GI.nodes()))
        assert_edges_equal(sorted(G.edges()), sorted(GI.edges()))
示例#25
0
 def create_weighted(self, G):
     g = cycle_graph(4)
     G.add_nodes_from(g)
     G.add_weighted_edges_from((u, v, 10 + u) for u, v in g.edges())
     return G
示例#26
0
 def create_weighted(self, G):
     g = cycle_graph(4)
     G.add_nodes_from(g)
     G.add_weighted_edges_from( (u,v,10+u) for u,v in g.edges())
     return G
示例#27
0
    def test_with_multiedges_self_loops(self):
        G = cycle_graph(10)
        e = G.edges()
        source, dest = list(zip(*e))
        ex = list(zip(source, dest, source))
        XG = Graph()
        XG.add_weighted_edges_from(ex)
        XGM = MultiGraph()
        XGM.add_weighted_edges_from(ex)
        XGM.add_edge(0, 1, weight=2)  # multiedge
        XGS = Graph()
        XGS.add_weighted_edges_from(ex)
        XGS.add_edge(0, 0, weight=100)  # self loop

        # Dict of dicts
        # with self loops, OK
        dod = to_dict_of_dicts(XGS)
        GG = from_dict_of_dicts(dod, create_using=Graph())
        assert_equal(sorted(XGS.nodes()), sorted(GG.nodes()))
        assert_equal(sorted(XGS.edges()), sorted(GG.edges()))
        GW = from_whatever(dod, create_using=Graph())
        assert_equal(sorted(XGS.nodes()), sorted(GW.nodes()))
        assert_equal(sorted(XGS.edges()), sorted(GW.edges()))
        GI = Graph(dod)
        assert_equal(sorted(XGS.nodes()), sorted(GI.nodes()))
        assert_equal(sorted(XGS.edges()), sorted(GI.edges()))

        # Dict of lists
        # with self loops, OK
        dol = to_dict_of_lists(XGS)
        GG = from_dict_of_lists(dol, create_using=Graph())
        # dict of lists throws away edge data so set it to none
        enone = [(u, v, {}) for (u, v, d) in XGS.edges(data=True)]
        assert_equal(sorted(XGS.nodes()), sorted(GG.nodes()))
        assert_equal(enone, sorted(GG.edges(data=True)))
        GW = from_whatever(dol, create_using=Graph())
        assert_equal(sorted(XGS.nodes()), sorted(GW.nodes()))
        assert_equal(enone, sorted(GW.edges(data=True)))
        GI = Graph(dol)
        assert_equal(sorted(XGS.nodes()), sorted(GI.nodes()))
        assert_equal(enone, sorted(GI.edges(data=True)))

        # Dict of dicts
        # with multiedges, OK
        dod = to_dict_of_dicts(XGM)
        GG = from_dict_of_dicts(dod,
                                create_using=MultiGraph(),
                                multigraph_input=True)
        assert_equal(sorted(XGM.nodes()), sorted(GG.nodes()))
        assert_equal(sorted(XGM.edges()), sorted(GG.edges()))
        GW = from_whatever(dod,
                           create_using=MultiGraph(),
                           multigraph_input=True)
        assert_equal(sorted(XGM.nodes()), sorted(GW.nodes()))
        assert_equal(sorted(XGM.edges()), sorted(GW.edges()))
        GI = MultiGraph(dod)  # convert can't tell whether to duplicate edges!
        assert_equal(sorted(XGM.nodes()), sorted(GI.nodes()))
        #assert_not_equal(sorted(XGM.edges()), sorted(GI.edges()))
        assert_false(sorted(XGM.edges()) == sorted(GI.edges()))
        GE = from_dict_of_dicts(dod,
                                create_using=MultiGraph(),
                                multigraph_input=False)
        assert_equal(sorted(XGM.nodes()), sorted(GE.nodes()))
        assert_not_equal(sorted(XGM.edges()), sorted(GE.edges()))
        GI = MultiGraph(XGM)
        assert_equal(sorted(XGM.nodes()), sorted(GI.nodes()))
        assert_equal(sorted(XGM.edges()), sorted(GI.edges()))
        GM = MultiGraph(G)
        assert_equal(sorted(GM.nodes()), sorted(G.nodes()))
        assert_equal(sorted(GM.edges()), sorted(G.edges()))

        # Dict of lists
        # with multiedges, OK, but better write as DiGraph else you'll
        # get double edges
        dol = to_dict_of_lists(G)
        GG = from_dict_of_lists(dol, create_using=MultiGraph())
        assert_equal(sorted(G.nodes()), sorted(GG.nodes()))
        assert_equal(sorted(G.edges()), sorted(GG.edges()))
        GW = from_whatever(dol, create_using=MultiGraph())
        assert_equal(sorted(G.nodes()), sorted(GW.nodes()))
        assert_equal(sorted(G.edges()), sorted(GW.edges()))
        GI = MultiGraph(dol)
        assert_equal(sorted(G.nodes()), sorted(GI.nodes()))
        assert_equal(sorted(G.edges()), sorted(GI.edges()))
示例#28
0
    def test_with_multiedges_self_loops(self):
        G = cycle_graph(10)
        XG = nx.Graph()
        XG.add_nodes_from(G)
        XG.add_weighted_edges_from((u, v, u) for u, v in G.edges())
        XGM = nx.MultiGraph()
        XGM.add_nodes_from(G)
        XGM.add_weighted_edges_from((u, v, u) for u, v in G.edges())
        XGM.add_edge(0, 1, weight=2)  # multiedge
        XGS = nx.Graph()
        XGS.add_nodes_from(G)
        XGS.add_weighted_edges_from((u, v, u) for u, v in G.edges())
        XGS.add_edge(0, 0, weight=100)  # self loop

        # Dict of dicts
        # with self loops, OK
        dod = to_dict_of_dicts(XGS)
        GG = from_dict_of_dicts(dod, create_using=nx.Graph())
        assert_nodes_equal(XGS.nodes(), GG.nodes())
        assert_edges_equal(XGS.edges(), GG.edges())
        GW = to_networkx_graph(dod, create_using=nx.Graph())
        assert_nodes_equal(XGS.nodes(), GW.nodes())
        assert_edges_equal(XGS.edges(), GW.edges())
        GI = nx.Graph(dod)
        assert_nodes_equal(XGS.nodes(), GI.nodes())
        assert_edges_equal(XGS.edges(), GI.edges())

        # Dict of lists
        # with self loops, OK
        dol = to_dict_of_lists(XGS)
        GG = from_dict_of_lists(dol, create_using=nx.Graph())
        # dict of lists throws away edge data so set it to none
        enone = [(u, v, {}) for (u, v, d) in XGS.edges(data=True)]
        assert_nodes_equal(sorted(XGS.nodes()), sorted(GG.nodes()))
        assert_edges_equal(enone, sorted(GG.edges(data=True)))
        GW = to_networkx_graph(dol, create_using=nx.Graph())
        assert_nodes_equal(sorted(XGS.nodes()), sorted(GW.nodes()))
        assert_edges_equal(enone, sorted(GW.edges(data=True)))
        GI = nx.Graph(dol)
        assert_nodes_equal(sorted(XGS.nodes()), sorted(GI.nodes()))
        assert_edges_equal(enone, sorted(GI.edges(data=True)))

        # Dict of dicts
        # with multiedges, OK
        dod = to_dict_of_dicts(XGM)
        GG = from_dict_of_dicts(dod, create_using=nx.MultiGraph(),
                                multigraph_input=True)
        assert_nodes_equal(sorted(XGM.nodes()), sorted(GG.nodes()))
        assert_edges_equal(sorted(XGM.edges()), sorted(GG.edges()))
        GW = to_networkx_graph(dod, create_using=nx.MultiGraph(), multigraph_input=True)
        assert_nodes_equal(sorted(XGM.nodes()), sorted(GW.nodes()))
        assert_edges_equal(sorted(XGM.edges()), sorted(GW.edges()))
        GI = nx.MultiGraph(dod)  # convert can't tell whether to duplicate edges!
        assert_nodes_equal(sorted(XGM.nodes()), sorted(GI.nodes()))
        #assert_not_equal(sorted(XGM.edges()), sorted(GI.edges()))
        assert_false(sorted(XGM.edges()) == sorted(GI.edges()))
        GE = from_dict_of_dicts(dod, create_using=nx.MultiGraph(),
                                multigraph_input=False)
        assert_nodes_equal(sorted(XGM.nodes()), sorted(GE.nodes()))
        assert_not_equal(sorted(XGM.edges()), sorted(GE.edges()))
        GI = nx.MultiGraph(XGM)
        assert_nodes_equal(sorted(XGM.nodes()), sorted(GI.nodes()))
        assert_edges_equal(sorted(XGM.edges()), sorted(GI.edges()))
        GM = nx.MultiGraph(G)
        assert_nodes_equal(sorted(GM.nodes()), sorted(G.nodes()))
        assert_edges_equal(sorted(GM.edges()), sorted(G.edges()))

        # Dict of lists
        # with multiedges, OK, but better write as DiGraph else you'll
        # get double edges
        dol = to_dict_of_lists(G)
        GG = from_dict_of_lists(dol, create_using=nx.MultiGraph())
        assert_nodes_equal(sorted(G.nodes()), sorted(GG.nodes()))
        assert_edges_equal(sorted(G.edges()), sorted(GG.edges()))
        GW = to_networkx_graph(dol, create_using=nx.MultiGraph())
        assert_nodes_equal(sorted(G.nodes()), sorted(GW.nodes()))
        assert_edges_equal(sorted(G.edges()), sorted(GW.edges()))
        GI = nx.MultiGraph(dol)
        assert_nodes_equal(sorted(G.nodes()), sorted(GI.nodes()))
        assert_edges_equal(sorted(G.edges()), sorted(GI.edges()))