diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/drawing/__pycache__/__init__.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/drawing/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6cc77e381603c3997b64ed7268468ff2c665dcd6 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/drawing/__pycache__/__init__.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/drawing/__pycache__/layout.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/drawing/__pycache__/layout.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..438aa0b3ea80be6005be9f335e2a2f66ca490015 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/drawing/__pycache__/layout.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_agraph.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_agraph.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..799d27d1e8c1e45bade5f75f6e59484b0ebb1f63 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_agraph.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_latex.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_latex.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b051e29ddcaac2a1b34cdacb7d06c2d85a4ed3c3 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_latex.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_pydot.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_pydot.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..650eeba7ba07095aadc809a08ecf8d59fd9d2371 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_pydot.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_pylab.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_pylab.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ea6e1603e4e0b815778396224b6bc5231ea63a1 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_pylab.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/drawing/tests/__init__.py b/env-llmeval/lib/python3.10/site-packages/networkx/drawing/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/drawing/tests/test_agraph.py b/env-llmeval/lib/python3.10/site-packages/networkx/drawing/tests/test_agraph.py new file mode 100644 index 0000000000000000000000000000000000000000..75d5957bf8f0017ed6e57cd5735c9892c8b5000e --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/networkx/drawing/tests/test_agraph.py @@ -0,0 +1,240 @@ +"""Unit tests for PyGraphviz interface.""" +import warnings + +import pytest + +pygraphviz = pytest.importorskip("pygraphviz") + + +import networkx as nx +from networkx.utils import edges_equal, graphs_equal, nodes_equal + + +class TestAGraph: + def build_graph(self, G): + edges = [("A", "B"), ("A", "C"), ("A", "C"), ("B", "C"), ("A", "D")] + G.add_edges_from(edges) + G.add_node("E") + G.graph["metal"] = "bronze" + return G + + def assert_equal(self, G1, G2): + assert nodes_equal(G1.nodes(), G2.nodes()) + assert edges_equal(G1.edges(), G2.edges()) + assert G1.graph["metal"] == G2.graph["metal"] + + @pytest.mark.parametrize( + "G", (nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()) + ) + def test_agraph_roundtripping(self, G, tmp_path): + G = self.build_graph(G) + A = nx.nx_agraph.to_agraph(G) + H = nx.nx_agraph.from_agraph(A) + self.assert_equal(G, H) + + fname = tmp_path / "test.dot" + nx.drawing.nx_agraph.write_dot(H, fname) + Hin = nx.nx_agraph.read_dot(fname) + self.assert_equal(H, Hin) + + fname = tmp_path / "fh_test.dot" + with open(fname, "w") as fh: + nx.drawing.nx_agraph.write_dot(H, fh) + + with open(fname) as fh: + Hin = nx.nx_agraph.read_dot(fh) + self.assert_equal(H, Hin) + + def test_from_agraph_name(self): + G = nx.Graph(name="test") + A = nx.nx_agraph.to_agraph(G) + H = nx.nx_agraph.from_agraph(A) + assert G.name == "test" + + @pytest.mark.parametrize( + "graph_class", (nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph) + ) + def test_from_agraph_create_using(self, graph_class): + G = nx.path_graph(3) + A = nx.nx_agraph.to_agraph(G) + H = nx.nx_agraph.from_agraph(A, create_using=graph_class) + assert isinstance(H, graph_class) + + def test_from_agraph_named_edges(self): + # Create an AGraph from an existing (non-multi) Graph + G = nx.Graph() + G.add_nodes_from([0, 1]) + A = nx.nx_agraph.to_agraph(G) + # Add edge (+ name, given by key) to the AGraph + A.add_edge(0, 1, key="foo") + # Verify a.name roundtrips out to 'key' in from_agraph + H = nx.nx_agraph.from_agraph(A) + assert isinstance(H, nx.Graph) + assert ("0", "1", {"key": "foo"}) in H.edges(data=True) + + def test_to_agraph_with_nodedata(self): + G = nx.Graph() + G.add_node(1, color="red") + A = nx.nx_agraph.to_agraph(G) + assert dict(A.nodes()[0].attr) == {"color": "red"} + + @pytest.mark.parametrize("graph_class", (nx.Graph, nx.MultiGraph)) + def test_to_agraph_with_edgedata(self, graph_class): + G = graph_class() + G.add_nodes_from([0, 1]) + G.add_edge(0, 1, color="yellow") + A = nx.nx_agraph.to_agraph(G) + assert dict(A.edges()[0].attr) == {"color": "yellow"} + + def test_view_pygraphviz_path(self, tmp_path): + G = nx.complete_graph(3) + input_path = str(tmp_path / "graph.png") + out_path, A = nx.nx_agraph.view_pygraphviz(G, path=input_path, show=False) + assert out_path == input_path + # Ensure file is not empty + with open(input_path, "rb") as fh: + data = fh.read() + assert len(data) > 0 + + def test_view_pygraphviz_file_suffix(self, tmp_path): + G = nx.complete_graph(3) + path, A = nx.nx_agraph.view_pygraphviz(G, suffix=1, show=False) + assert path[-6:] == "_1.png" + + def test_view_pygraphviz(self): + G = nx.Graph() # "An empty graph cannot be drawn." + pytest.raises(nx.NetworkXException, nx.nx_agraph.view_pygraphviz, G) + G = nx.barbell_graph(4, 6) + nx.nx_agraph.view_pygraphviz(G, show=False) + + def test_view_pygraphviz_edgelabel(self): + G = nx.Graph() + G.add_edge(1, 2, weight=7) + G.add_edge(2, 3, weight=8) + path, A = nx.nx_agraph.view_pygraphviz(G, edgelabel="weight", show=False) + for edge in A.edges(): + assert edge.attr["weight"] in ("7", "8") + + def test_view_pygraphviz_callable_edgelabel(self): + G = nx.complete_graph(3) + + def foo_label(data): + return "foo" + + path, A = nx.nx_agraph.view_pygraphviz(G, edgelabel=foo_label, show=False) + for edge in A.edges(): + assert edge.attr["label"] == "foo" + + def test_view_pygraphviz_multigraph_edgelabels(self): + G = nx.MultiGraph() + G.add_edge(0, 1, key=0, name="left_fork") + G.add_edge(0, 1, key=1, name="right_fork") + path, A = nx.nx_agraph.view_pygraphviz(G, edgelabel="name", show=False) + edges = A.edges() + assert len(edges) == 2 + for edge in edges: + assert edge.attr["label"].strip() in ("left_fork", "right_fork") + + def test_graph_with_reserved_keywords(self): + # test attribute/keyword clash case for #1582 + # node: n + # edges: u,v + G = nx.Graph() + G = self.build_graph(G) + G.nodes["E"]["n"] = "keyword" + G.edges[("A", "B")]["u"] = "keyword" + G.edges[("A", "B")]["v"] = "keyword" + A = nx.nx_agraph.to_agraph(G) + + def test_view_pygraphviz_no_added_attrs_to_input(self): + G = nx.complete_graph(2) + path, A = nx.nx_agraph.view_pygraphviz(G, show=False) + assert G.graph == {} + + @pytest.mark.xfail(reason="known bug in clean_attrs") + def test_view_pygraphviz_leaves_input_graph_unmodified(self): + G = nx.complete_graph(2) + # Add entries to graph dict that to_agraph handles specially + G.graph["node"] = {"width": "0.80"} + G.graph["edge"] = {"fontsize": "14"} + path, A = nx.nx_agraph.view_pygraphviz(G, show=False) + assert G.graph == {"node": {"width": "0.80"}, "edge": {"fontsize": "14"}} + + def test_graph_with_AGraph_attrs(self): + G = nx.complete_graph(2) + # Add entries to graph dict that to_agraph handles specially + G.graph["node"] = {"width": "0.80"} + G.graph["edge"] = {"fontsize": "14"} + path, A = nx.nx_agraph.view_pygraphviz(G, show=False) + # Ensure user-specified values are not lost + assert dict(A.node_attr)["width"] == "0.80" + assert dict(A.edge_attr)["fontsize"] == "14" + + def test_round_trip_empty_graph(self): + G = nx.Graph() + A = nx.nx_agraph.to_agraph(G) + H = nx.nx_agraph.from_agraph(A) + # assert graphs_equal(G, H) + AA = nx.nx_agraph.to_agraph(H) + HH = nx.nx_agraph.from_agraph(AA) + assert graphs_equal(H, HH) + G.graph["graph"] = {} + G.graph["node"] = {} + G.graph["edge"] = {} + assert graphs_equal(G, HH) + + @pytest.mark.xfail(reason="integer->string node conversion in round trip") + def test_round_trip_integer_nodes(self): + G = nx.complete_graph(3) + A = nx.nx_agraph.to_agraph(G) + H = nx.nx_agraph.from_agraph(A) + assert graphs_equal(G, H) + + def test_graphviz_alias(self): + G = self.build_graph(nx.Graph()) + pos_graphviz = nx.nx_agraph.graphviz_layout(G) + pos_pygraphviz = nx.nx_agraph.pygraphviz_layout(G) + assert pos_graphviz == pos_pygraphviz + + @pytest.mark.parametrize("root", range(5)) + def test_pygraphviz_layout_root(self, root): + # NOTE: test depends on layout prog being deterministic + G = nx.complete_graph(5) + A = nx.nx_agraph.to_agraph(G) + # Get layout with root arg is not None + pygv_layout = nx.nx_agraph.pygraphviz_layout(G, prog="circo", root=root) + # Equivalent layout directly on AGraph + A.layout(args=f"-Groot={root}", prog="circo") + # Parse AGraph layout + a1_pos = tuple(float(v) for v in dict(A.get_node("1").attr)["pos"].split(",")) + assert pygv_layout[1] == a1_pos + + def test_2d_layout(self): + G = nx.Graph() + G = self.build_graph(G) + G.graph["dimen"] = 2 + pos = nx.nx_agraph.pygraphviz_layout(G, prog="neato") + pos = list(pos.values()) + assert len(pos) == 5 + assert len(pos[0]) == 2 + + def test_3d_layout(self): + G = nx.Graph() + G = self.build_graph(G) + G.graph["dimen"] = 3 + pos = nx.nx_agraph.pygraphviz_layout(G, prog="neato") + pos = list(pos.values()) + assert len(pos) == 5 + assert len(pos[0]) == 3 + + def test_no_warnings_raised(self): + # Test that no warnings are raised when Networkx graph + # is converted to Pygraphviz graph and 'pos' + # attribute is given + G = nx.Graph() + G.add_node(0, pos=(0, 0)) + G.add_node(1, pos=(1, 1)) + A = nx.nx_agraph.to_agraph(G) + with warnings.catch_warnings(record=True) as record: + A.layout() + assert len(record) == 0 diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/drawing/tests/test_pydot.py b/env-llmeval/lib/python3.10/site-packages/networkx/drawing/tests/test_pydot.py new file mode 100644 index 0000000000000000000000000000000000000000..671afac07c5c05f0f376a116db40cdc98e09b4dc --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/networkx/drawing/tests/test_pydot.py @@ -0,0 +1,180 @@ +"""Unit tests for pydot drawing functions.""" +from io import StringIO + +import pytest + +import networkx as nx +from networkx.utils import graphs_equal + +pydot = pytest.importorskip("pydot") + + +class TestPydot: + @pytest.mark.parametrize("G", (nx.Graph(), nx.DiGraph())) + @pytest.mark.parametrize("prog", ("neato", "dot")) + def test_pydot(self, G, prog, tmp_path): + """ + Validate :mod:`pydot`-based usage of the passed NetworkX graph with the + passed basename of an external GraphViz command (e.g., `dot`, `neato`). + """ + + # Set the name of this graph to... "G". Failing to do so will + # subsequently trip an assertion expecting this name. + G.graph["name"] = "G" + + # Add arbitrary nodes and edges to the passed empty graph. + G.add_edges_from([("A", "B"), ("A", "C"), ("B", "C"), ("A", "D")]) + G.add_node("E") + + # Validate layout of this graph with the passed GraphViz command. + graph_layout = nx.nx_pydot.pydot_layout(G, prog=prog) + assert isinstance(graph_layout, dict) + + # Convert this graph into a "pydot.Dot" instance. + P = nx.nx_pydot.to_pydot(G) + + # Convert this "pydot.Dot" instance back into a graph of the same type. + G2 = G.__class__(nx.nx_pydot.from_pydot(P)) + + # Validate the original and resulting graphs to be the same. + assert graphs_equal(G, G2) + + fname = tmp_path / "out.dot" + + # Serialize this "pydot.Dot" instance to a temporary file in dot format + P.write_raw(fname) + + # Deserialize a list of new "pydot.Dot" instances back from this file. + Pin_list = pydot.graph_from_dot_file(path=fname, encoding="utf-8") + + # Validate this file to contain only one graph. + assert len(Pin_list) == 1 + + # The single "pydot.Dot" instance deserialized from this file. + Pin = Pin_list[0] + + # Sorted list of all nodes in the original "pydot.Dot" instance. + n1 = sorted(p.get_name() for p in P.get_node_list()) + + # Sorted list of all nodes in the deserialized "pydot.Dot" instance. + n2 = sorted(p.get_name() for p in Pin.get_node_list()) + + # Validate these instances to contain the same nodes. + assert n1 == n2 + + # Sorted list of all edges in the original "pydot.Dot" instance. + e1 = sorted((e.get_source(), e.get_destination()) for e in P.get_edge_list()) + + # Sorted list of all edges in the original "pydot.Dot" instance. + e2 = sorted((e.get_source(), e.get_destination()) for e in Pin.get_edge_list()) + + # Validate these instances to contain the same edges. + assert e1 == e2 + + # Deserialize a new graph of the same type back from this file. + Hin = nx.nx_pydot.read_dot(fname) + Hin = G.__class__(Hin) + + # Validate the original and resulting graphs to be the same. + assert graphs_equal(G, Hin) + + def test_read_write(self): + G = nx.MultiGraph() + G.graph["name"] = "G" + G.add_edge("1", "2", key="0") # read assumes strings + fh = StringIO() + nx.nx_pydot.write_dot(G, fh) + fh.seek(0) + H = nx.nx_pydot.read_dot(fh) + assert graphs_equal(G, H) + + +def test_pydot_issue_258(): + G = nx.Graph([("Example:A", 1)]) + with pytest.raises(ValueError): + nx.nx_pydot.to_pydot(G) + with pytest.raises(ValueError): + nx.nx_pydot.pydot_layout(G) + + G = nx.Graph() + G.add_node("1.2", style="filled", fillcolor="red:yellow") + with pytest.raises(ValueError): + nx.nx_pydot.to_pydot(G) + G.remove_node("1.2") + G.add_node("1.2", style="filled", fillcolor='"red:yellow"') + assert ( + G.nodes.data() == nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G)).nodes.data() + ) + + G = nx.DiGraph() + G.add_edge("1", "2", foo="bar:1") + with pytest.raises(ValueError): + nx.nx_pydot.to_pydot(G) + G = nx.DiGraph() + G.add_edge("1", "2", foo='"bar:1"') + assert G["1"]["2"] == nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G))["1"]["2"] + + G = nx.MultiGraph() + G.add_edge("1", "2", foo="b:1") + G.add_edge("1", "2", bar="foo:foo") + with pytest.raises(ValueError): + nx.nx_pydot.to_pydot(G) + G = nx.MultiGraph() + G.add_edge("1", "2", foo='"b:1"') + G.add_edge("1", "2", bar='"foo:foo"') + # Keys as integers aren't preserved in the conversion. They are read as strings. + assert [attr for _, _, attr in G.edges.data()] == [ + attr + for _, _, attr in nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G)).edges.data() + ] + + G = nx.Graph() + G.add_edge("1", "2") + G["1"]["2"]["f:oo"] = "bar" + with pytest.raises(ValueError): + nx.nx_pydot.to_pydot(G) + G = nx.Graph() + G.add_edge("1", "2") + G["1"]["2"]['"f:oo"'] = "bar" + assert G["1"]["2"] == nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G))["1"]["2"] + + G = nx.Graph([('"Example:A"', 1)]) + layout = nx.nx_pydot.pydot_layout(G) + assert isinstance(layout, dict) + + +@pytest.mark.parametrize( + "graph_type", [nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph] +) +def test_hashable_pydot(graph_type): + # gh-5790 + G = graph_type() + G.add_edge("5", frozenset([1]), t='"Example:A"', l=False) + G.add_edge("1", 2, w=True, t=("node1",), l=frozenset(["node1"])) + G.add_edge("node", (3, 3), w="string") + + assert [ + {"t": '"Example:A"', "l": "False"}, + {"w": "True", "t": "('node1',)", "l": "frozenset({'node1'})"}, + {"w": "string"}, + ] == [ + attr + for _, _, attr in nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G)).edges.data() + ] + + assert {str(i) for i in G.nodes()} == set( + nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G)).nodes + ) + + +def test_pydot_numerical_name(): + G = nx.Graph() + G.add_edges_from([("A", "B"), (0, 1)]) + graph_layout = nx.nx_pydot.pydot_layout(G, prog="dot") + assert isinstance(graph_layout, dict) + assert "0" not in graph_layout + assert 0 in graph_layout + assert "1" not in graph_layout + assert 1 in graph_layout + assert "A" in graph_layout + assert "B" in graph_layout diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/drawing/tests/test_pylab.py b/env-llmeval/lib/python3.10/site-packages/networkx/drawing/tests/test_pylab.py new file mode 100644 index 0000000000000000000000000000000000000000..5015435a5c173f1c6ec878fc0c98433d4470d9dd --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/networkx/drawing/tests/test_pylab.py @@ -0,0 +1,879 @@ +"""Unit tests for matplotlib drawing functions.""" +import itertools +import os +import warnings + +import pytest + +mpl = pytest.importorskip("matplotlib") +np = pytest.importorskip("numpy") +mpl.use("PS") +plt = pytest.importorskip("matplotlib.pyplot") +plt.rcParams["text.usetex"] = False + + +import networkx as nx + +barbell = nx.barbell_graph(4, 6) + + +def test_draw(): + try: + functions = [ + nx.draw_circular, + nx.draw_kamada_kawai, + nx.draw_planar, + nx.draw_random, + nx.draw_spectral, + nx.draw_spring, + nx.draw_shell, + ] + options = [{"node_color": "black", "node_size": 100, "width": 3}] + for function, option in itertools.product(functions, options): + function(barbell, **option) + plt.savefig("test.ps") + except ModuleNotFoundError: # draw_kamada_kawai requires scipy + pass + finally: + try: + os.unlink("test.ps") + except OSError: + pass + + +def test_draw_shell_nlist(): + try: + nlist = [list(range(4)), list(range(4, 10)), list(range(10, 14))] + nx.draw_shell(barbell, nlist=nlist) + plt.savefig("test.ps") + finally: + try: + os.unlink("test.ps") + except OSError: + pass + + +def test_edge_colormap(): + colors = range(barbell.number_of_edges()) + nx.draw_spring( + barbell, edge_color=colors, width=4, edge_cmap=plt.cm.Blues, with_labels=True + ) + # plt.show() + + +def test_arrows(): + nx.draw_spring(barbell.to_directed()) + # plt.show() + + +@pytest.mark.parametrize( + ("edge_color", "expected"), + ( + (None, "black"), # Default + ("r", "red"), # Non-default color string + (["r"], "red"), # Single non-default color in a list + ((1.0, 1.0, 0.0), "yellow"), # single color as rgb tuple + ([(1.0, 1.0, 0.0)], "yellow"), # single color as rgb tuple in list + ((0, 1, 0, 1), "lime"), # single color as rgba tuple + ([(0, 1, 0, 1)], "lime"), # single color as rgba tuple in list + ("#0000ff", "blue"), # single color hex code + (["#0000ff"], "blue"), # hex code in list + ), +) +@pytest.mark.parametrize("edgelist", (None, [(0, 1)])) +def test_single_edge_color_undirected(edge_color, expected, edgelist): + """Tests ways of specifying all edges have a single color for edges + drawn with a LineCollection""" + + G = nx.path_graph(3) + drawn_edges = nx.draw_networkx_edges( + G, pos=nx.random_layout(G), edgelist=edgelist, edge_color=edge_color + ) + assert mpl.colors.same_color(drawn_edges.get_color(), expected) + + +@pytest.mark.parametrize( + ("edge_color", "expected"), + ( + (None, "black"), # Default + ("r", "red"), # Non-default color string + (["r"], "red"), # Single non-default color in a list + ((1.0, 1.0, 0.0), "yellow"), # single color as rgb tuple + ([(1.0, 1.0, 0.0)], "yellow"), # single color as rgb tuple in list + ((0, 1, 0, 1), "lime"), # single color as rgba tuple + ([(0, 1, 0, 1)], "lime"), # single color as rgba tuple in list + ("#0000ff", "blue"), # single color hex code + (["#0000ff"], "blue"), # hex code in list + ), +) +@pytest.mark.parametrize("edgelist", (None, [(0, 1)])) +def test_single_edge_color_directed(edge_color, expected, edgelist): + """Tests ways of specifying all edges have a single color for edges drawn + with FancyArrowPatches""" + + G = nx.path_graph(3, create_using=nx.DiGraph) + drawn_edges = nx.draw_networkx_edges( + G, pos=nx.random_layout(G), edgelist=edgelist, edge_color=edge_color + ) + for fap in drawn_edges: + assert mpl.colors.same_color(fap.get_edgecolor(), expected) + + +def test_edge_color_tuple_interpretation(): + """If edge_color is a sequence with the same length as edgelist, then each + value in edge_color is mapped onto each edge via colormap.""" + G = nx.path_graph(6, create_using=nx.DiGraph) + pos = {n: (n, n) for n in range(len(G))} + + # num edges != 3 or 4 --> edge_color interpreted as rgb(a) + for ec in ((0, 0, 1), (0, 0, 1, 1)): + # More than 4 edges + drawn_edges = nx.draw_networkx_edges(G, pos, edge_color=ec) + for fap in drawn_edges: + assert mpl.colors.same_color(fap.get_edgecolor(), ec) + # Fewer than 3 edges + drawn_edges = nx.draw_networkx_edges( + G, pos, edgelist=[(0, 1), (1, 2)], edge_color=ec + ) + for fap in drawn_edges: + assert mpl.colors.same_color(fap.get_edgecolor(), ec) + + # num edges == 3, len(edge_color) == 4: interpreted as rgba + drawn_edges = nx.draw_networkx_edges( + G, pos, edgelist=[(0, 1), (1, 2), (2, 3)], edge_color=(0, 0, 1, 1) + ) + for fap in drawn_edges: + assert mpl.colors.same_color(fap.get_edgecolor(), "blue") + + # num edges == 4, len(edge_color) == 3: interpreted as rgb + drawn_edges = nx.draw_networkx_edges( + G, pos, edgelist=[(0, 1), (1, 2), (2, 3), (3, 4)], edge_color=(0, 0, 1) + ) + for fap in drawn_edges: + assert mpl.colors.same_color(fap.get_edgecolor(), "blue") + + # num edges == len(edge_color) == 3: interpreted with cmap, *not* as rgb + drawn_edges = nx.draw_networkx_edges( + G, pos, edgelist=[(0, 1), (1, 2), (2, 3)], edge_color=(0, 0, 1) + ) + assert mpl.colors.same_color( + drawn_edges[0].get_edgecolor(), drawn_edges[1].get_edgecolor() + ) + for fap in drawn_edges: + assert not mpl.colors.same_color(fap.get_edgecolor(), "blue") + + # num edges == len(edge_color) == 4: interpreted with cmap, *not* as rgba + drawn_edges = nx.draw_networkx_edges( + G, pos, edgelist=[(0, 1), (1, 2), (2, 3), (3, 4)], edge_color=(0, 0, 1, 1) + ) + assert mpl.colors.same_color( + drawn_edges[0].get_edgecolor(), drawn_edges[1].get_edgecolor() + ) + assert mpl.colors.same_color( + drawn_edges[2].get_edgecolor(), drawn_edges[3].get_edgecolor() + ) + for fap in drawn_edges: + assert not mpl.colors.same_color(fap.get_edgecolor(), "blue") + + +def test_fewer_edge_colors_than_num_edges_directed(): + """Test that the edge colors are cycled when there are fewer specified + colors than edges.""" + G = barbell.to_directed() + pos = nx.random_layout(barbell) + edgecolors = ("r", "g", "b") + drawn_edges = nx.draw_networkx_edges(G, pos, edge_color=edgecolors) + for fap, expected in zip(drawn_edges, itertools.cycle(edgecolors)): + assert mpl.colors.same_color(fap.get_edgecolor(), expected) + + +def test_more_edge_colors_than_num_edges_directed(): + """Test that extra edge colors are ignored when there are more specified + colors than edges.""" + G = nx.path_graph(4, create_using=nx.DiGraph) # 3 edges + pos = nx.random_layout(barbell) + edgecolors = ("r", "g", "b", "c") # 4 edge colors + drawn_edges = nx.draw_networkx_edges(G, pos, edge_color=edgecolors) + for fap, expected in zip(drawn_edges, edgecolors[:-1]): + assert mpl.colors.same_color(fap.get_edgecolor(), expected) + + +def test_edge_color_string_with_global_alpha_undirected(): + edge_collection = nx.draw_networkx_edges( + barbell, + pos=nx.random_layout(barbell), + edgelist=[(0, 1), (1, 2)], + edge_color="purple", + alpha=0.2, + ) + ec = edge_collection.get_color().squeeze() # as rgba tuple + assert len(edge_collection.get_paths()) == 2 + assert mpl.colors.same_color(ec[:-1], "purple") + assert ec[-1] == 0.2 + + +def test_edge_color_string_with_global_alpha_directed(): + drawn_edges = nx.draw_networkx_edges( + barbell.to_directed(), + pos=nx.random_layout(barbell), + edgelist=[(0, 1), (1, 2)], + edge_color="purple", + alpha=0.2, + ) + assert len(drawn_edges) == 2 + for fap in drawn_edges: + ec = fap.get_edgecolor() # As rgba tuple + assert mpl.colors.same_color(ec[:-1], "purple") + assert ec[-1] == 0.2 + + +@pytest.mark.parametrize("graph_type", (nx.Graph, nx.DiGraph)) +def test_edge_width_default_value(graph_type): + """Test the default linewidth for edges drawn either via LineCollection or + FancyArrowPatches.""" + G = nx.path_graph(2, create_using=graph_type) + pos = {n: (n, n) for n in range(len(G))} + drawn_edges = nx.draw_networkx_edges(G, pos) + if isinstance(drawn_edges, list): # directed case: list of FancyArrowPatch + drawn_edges = drawn_edges[0] + assert drawn_edges.get_linewidth() == 1 + + +@pytest.mark.parametrize( + ("edgewidth", "expected"), + ( + (3, 3), # single-value, non-default + ([3], 3), # Single value as a list + ), +) +def test_edge_width_single_value_undirected(edgewidth, expected): + G = nx.path_graph(4) + pos = {n: (n, n) for n in range(len(G))} + drawn_edges = nx.draw_networkx_edges(G, pos, width=edgewidth) + assert len(drawn_edges.get_paths()) == 3 + assert drawn_edges.get_linewidth() == expected + + +@pytest.mark.parametrize( + ("edgewidth", "expected"), + ( + (3, 3), # single-value, non-default + ([3], 3), # Single value as a list + ), +) +def test_edge_width_single_value_directed(edgewidth, expected): + G = nx.path_graph(4, create_using=nx.DiGraph) + pos = {n: (n, n) for n in range(len(G))} + drawn_edges = nx.draw_networkx_edges(G, pos, width=edgewidth) + assert len(drawn_edges) == 3 + for fap in drawn_edges: + assert fap.get_linewidth() == expected + + +@pytest.mark.parametrize( + "edgelist", + ( + [(0, 1), (1, 2), (2, 3)], # one width specification per edge + None, # fewer widths than edges - widths cycle + [(0, 1), (1, 2)], # More widths than edges - unused widths ignored + ), +) +def test_edge_width_sequence(edgelist): + G = barbell.to_directed() + pos = nx.random_layout(G) + widths = (0.5, 2.0, 12.0) + drawn_edges = nx.draw_networkx_edges(G, pos, edgelist=edgelist, width=widths) + for fap, expected_width in zip(drawn_edges, itertools.cycle(widths)): + assert fap.get_linewidth() == expected_width + + +def test_edge_color_with_edge_vmin_vmax(): + """Test that edge_vmin and edge_vmax properly set the dynamic range of the + color map when num edges == len(edge_colors).""" + G = nx.path_graph(3, create_using=nx.DiGraph) + pos = nx.random_layout(G) + # Extract colors from the original (unscaled) colormap + drawn_edges = nx.draw_networkx_edges(G, pos, edge_color=[0, 1.0]) + orig_colors = [e.get_edgecolor() for e in drawn_edges] + # Colors from scaled colormap + drawn_edges = nx.draw_networkx_edges( + G, pos, edge_color=[0.2, 0.8], edge_vmin=0.2, edge_vmax=0.8 + ) + scaled_colors = [e.get_edgecolor() for e in drawn_edges] + assert mpl.colors.same_color(orig_colors, scaled_colors) + + +def test_directed_edges_linestyle_default(): + """Test default linestyle for edges drawn with FancyArrowPatches.""" + G = nx.path_graph(4, create_using=nx.DiGraph) # Graph with 3 edges + pos = {n: (n, n) for n in range(len(G))} + + # edge with default style + drawn_edges = nx.draw_networkx_edges(G, pos) + assert len(drawn_edges) == 3 + for fap in drawn_edges: + assert fap.get_linestyle() == "solid" + + +@pytest.mark.parametrize( + "style", + ( + "dashed", # edge with string style + "--", # edge with simplified string style + (1, (1, 1)), # edge with (offset, onoffseq) style + ), +) +def test_directed_edges_linestyle_single_value(style): + """Tests support for specifying linestyles with a single value to be applied to + all edges in ``draw_networkx_edges`` for FancyArrowPatch outputs + (e.g. directed edges).""" + + G = nx.path_graph(4, create_using=nx.DiGraph) # Graph with 3 edges + pos = {n: (n, n) for n in range(len(G))} + + drawn_edges = nx.draw_networkx_edges(G, pos, style=style) + assert len(drawn_edges) == 3 + for fap in drawn_edges: + assert fap.get_linestyle() == style + + +@pytest.mark.parametrize( + "style_seq", + ( + ["dashed"], # edge with string style in list + ["--"], # edge with simplified string style in list + [(1, (1, 1))], # edge with (offset, onoffseq) style in list + ["--", "-", ":"], # edges with styles for each edge + ["--", "-"], # edges with fewer styles than edges (styles cycle) + ["--", "-", ":", "-."], # edges with more styles than edges (extra unused) + ), +) +def test_directed_edges_linestyle_sequence(style_seq): + """Tests support for specifying linestyles with sequences in + ``draw_networkx_edges`` for FancyArrowPatch outputs (e.g. directed edges).""" + + G = nx.path_graph(4, create_using=nx.DiGraph) # Graph with 3 edges + pos = {n: (n, n) for n in range(len(G))} + + drawn_edges = nx.draw_networkx_edges(G, pos, style=style_seq) + assert len(drawn_edges) == 3 + for fap, style in zip(drawn_edges, itertools.cycle(style_seq)): + assert fap.get_linestyle() == style + + +def test_labels_and_colors(): + G = nx.cubical_graph() + pos = nx.spring_layout(G) # positions for all nodes + # nodes + nx.draw_networkx_nodes( + G, pos, nodelist=[0, 1, 2, 3], node_color="r", node_size=500, alpha=0.75 + ) + nx.draw_networkx_nodes( + G, + pos, + nodelist=[4, 5, 6, 7], + node_color="b", + node_size=500, + alpha=[0.25, 0.5, 0.75, 1.0], + ) + # edges + nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5) + nx.draw_networkx_edges( + G, + pos, + edgelist=[(0, 1), (1, 2), (2, 3), (3, 0)], + width=8, + alpha=0.5, + edge_color="r", + ) + nx.draw_networkx_edges( + G, + pos, + edgelist=[(4, 5), (5, 6), (6, 7), (7, 4)], + width=8, + alpha=0.5, + edge_color="b", + ) + nx.draw_networkx_edges( + G, + pos, + edgelist=[(4, 5), (5, 6), (6, 7), (7, 4)], + arrows=True, + min_source_margin=0.5, + min_target_margin=0.75, + width=8, + edge_color="b", + ) + # some math labels + labels = {} + labels[0] = r"$a$" + labels[1] = r"$b$" + labels[2] = r"$c$" + labels[3] = r"$d$" + labels[4] = r"$\alpha$" + labels[5] = r"$\beta$" + labels[6] = r"$\gamma$" + labels[7] = r"$\delta$" + nx.draw_networkx_labels(G, pos, labels, font_size=16) + nx.draw_networkx_edge_labels(G, pos, edge_labels=None, rotate=False) + nx.draw_networkx_edge_labels(G, pos, edge_labels={(4, 5): "4-5"}) + # plt.show() + + +@pytest.mark.mpl_image_compare +def test_house_with_colors(): + G = nx.house_graph() + # explicitly set positions + fig, ax = plt.subplots() + pos = {0: (0, 0), 1: (1, 0), 2: (0, 1), 3: (1, 1), 4: (0.5, 2.0)} + + # Plot nodes with different properties for the "wall" and "roof" nodes + nx.draw_networkx_nodes( + G, + pos, + node_size=3000, + nodelist=[0, 1, 2, 3], + node_color="tab:blue", + ) + nx.draw_networkx_nodes( + G, pos, node_size=2000, nodelist=[4], node_color="tab:orange" + ) + nx.draw_networkx_edges(G, pos, alpha=0.5, width=6) + # Customize axes + ax.margins(0.11) + plt.tight_layout() + plt.axis("off") + return fig + + +def test_axes(): + fig, ax = plt.subplots() + nx.draw(barbell, ax=ax) + nx.draw_networkx_edge_labels(barbell, nx.circular_layout(barbell), ax=ax) + + +def test_empty_graph(): + G = nx.Graph() + nx.draw(G) + + +def test_draw_empty_nodes_return_values(): + # See Issue #3833 + import matplotlib.collections # call as mpl.collections + + G = nx.Graph([(1, 2), (2, 3)]) + DG = nx.DiGraph([(1, 2), (2, 3)]) + pos = nx.circular_layout(G) + assert isinstance( + nx.draw_networkx_nodes(G, pos, nodelist=[]), mpl.collections.PathCollection + ) + assert isinstance( + nx.draw_networkx_nodes(DG, pos, nodelist=[]), mpl.collections.PathCollection + ) + + # drawing empty edges used to return an empty LineCollection or empty list. + # Now it is always an empty list (because edges are now lists of FancyArrows) + assert nx.draw_networkx_edges(G, pos, edgelist=[], arrows=True) == [] + assert nx.draw_networkx_edges(G, pos, edgelist=[], arrows=False) == [] + assert nx.draw_networkx_edges(DG, pos, edgelist=[], arrows=False) == [] + assert nx.draw_networkx_edges(DG, pos, edgelist=[], arrows=True) == [] + + +def test_multigraph_edgelist_tuples(): + # See Issue #3295 + G = nx.path_graph(3, create_using=nx.MultiDiGraph) + nx.draw_networkx(G, edgelist=[(0, 1, 0)]) + nx.draw_networkx(G, edgelist=[(0, 1, 0)], node_size=[10, 20, 0]) + + +def test_alpha_iter(): + pos = nx.random_layout(barbell) + fig = plt.figure() + # with fewer alpha elements than nodes + fig.add_subplot(131) # Each test in a new axis object + nx.draw_networkx_nodes(barbell, pos, alpha=[0.1, 0.2]) + # with equal alpha elements and nodes + num_nodes = len(barbell.nodes) + alpha = [x / num_nodes for x in range(num_nodes)] + colors = range(num_nodes) + fig.add_subplot(132) + nx.draw_networkx_nodes(barbell, pos, node_color=colors, alpha=alpha) + # with more alpha elements than nodes + alpha.append(1) + fig.add_subplot(133) + nx.draw_networkx_nodes(barbell, pos, alpha=alpha) + + +def test_error_invalid_kwds(): + with pytest.raises(ValueError, match="Received invalid argument"): + nx.draw(barbell, foo="bar") + + +def test_draw_networkx_arrowsize_incorrect_size(): + G = nx.DiGraph([(0, 1), (0, 2), (0, 3), (1, 3)]) + arrowsize = [1, 2, 3] + with pytest.raises( + ValueError, match="arrowsize should have the same length as edgelist" + ): + nx.draw(G, arrowsize=arrowsize) + + +@pytest.mark.parametrize("arrowsize", (30, [10, 20, 30])) +def test_draw_edges_arrowsize(arrowsize): + G = nx.DiGraph([(0, 1), (0, 2), (1, 2)]) + pos = {0: (0, 0), 1: (0, 1), 2: (1, 0)} + edges = nx.draw_networkx_edges(G, pos=pos, arrowsize=arrowsize) + + arrowsize = itertools.repeat(arrowsize) if isinstance(arrowsize, int) else arrowsize + + for fap, expected in zip(edges, arrowsize): + assert isinstance(fap, mpl.patches.FancyArrowPatch) + assert fap.get_mutation_scale() == expected + + +def test_np_edgelist(): + # see issue #4129 + nx.draw_networkx(barbell, edgelist=np.array([(0, 2), (0, 3)])) + + +def test_draw_nodes_missing_node_from_position(): + G = nx.path_graph(3) + pos = {0: (0, 0), 1: (1, 1)} # No position for node 2 + with pytest.raises(nx.NetworkXError, match="has no position"): + nx.draw_networkx_nodes(G, pos) + + +# NOTE: parametrizing on marker to test both branches of internal +# nx.draw_networkx_edges.to_marker_edge function +@pytest.mark.parametrize("node_shape", ("o", "s")) +def test_draw_edges_min_source_target_margins(node_shape): + """Test that there is a wider gap between the node and the start of an + incident edge when min_source_margin is specified. + + This test checks that the use of min_{source/target}_margin kwargs result + in shorter (more padding) between the edges and source and target nodes. + As a crude visual example, let 's' and 't' represent source and target + nodes, respectively: + + Default: + s-----------------------------t + + With margins: + s ----------------------- t + + """ + # Create a single axis object to get consistent pixel coords across + # multiple draws + fig, ax = plt.subplots() + G = nx.DiGraph([(0, 1)]) + pos = {0: (0, 0), 1: (1, 0)} # horizontal layout + # Get leftmost and rightmost points of the FancyArrowPatch object + # representing the edge between nodes 0 and 1 (in pixel coordinates) + default_patch = nx.draw_networkx_edges(G, pos, ax=ax, node_shape=node_shape)[0] + default_extent = default_patch.get_extents().corners()[::2, 0] + # Now, do the same but with "padding" for the source and target via the + # min_{source/target}_margin kwargs + padded_patch = nx.draw_networkx_edges( + G, + pos, + ax=ax, + node_shape=node_shape, + min_source_margin=100, + min_target_margin=100, + )[0] + padded_extent = padded_patch.get_extents().corners()[::2, 0] + + # With padding, the left-most extent of the edge should be further to the + # right + assert padded_extent[0] > default_extent[0] + # And the rightmost extent of the edge, further to the left + assert padded_extent[1] < default_extent[1] + + +def test_nonzero_selfloop_with_single_node(): + """Ensure that selfloop extent is non-zero when there is only one node.""" + # Create explicit axis object for test + fig, ax = plt.subplots() + # Graph with single node + self loop + G = nx.DiGraph() + G.add_node(0) + G.add_edge(0, 0) + # Draw + patch = nx.draw_networkx_edges(G, {0: (0, 0)})[0] + # The resulting patch must have non-zero extent + bbox = patch.get_extents() + assert bbox.width > 0 and bbox.height > 0 + # Cleanup + plt.delaxes(ax) + plt.close() + + +def test_nonzero_selfloop_with_single_edge_in_edgelist(): + """Ensure that selfloop extent is non-zero when only a single edge is + specified in the edgelist. + """ + # Create explicit axis object for test + fig, ax = plt.subplots() + # Graph with selfloop + G = nx.path_graph(2, create_using=nx.DiGraph) + G.add_edge(1, 1) + pos = {n: (n, n) for n in G.nodes} + # Draw only the selfloop edge via the `edgelist` kwarg + patch = nx.draw_networkx_edges(G, pos, edgelist=[(1, 1)])[0] + # The resulting patch must have non-zero extent + bbox = patch.get_extents() + assert bbox.width > 0 and bbox.height > 0 + # Cleanup + plt.delaxes(ax) + plt.close() + + +def test_apply_alpha(): + """Test apply_alpha when there is a mismatch between the number of + supplied colors and elements. + """ + nodelist = [0, 1, 2] + colorlist = ["r", "g", "b"] + alpha = 0.5 + rgba_colors = nx.drawing.nx_pylab.apply_alpha(colorlist, alpha, nodelist) + assert all(rgba_colors[:, -1] == alpha) + + +def test_draw_edges_toggling_with_arrows_kwarg(): + """ + The `arrows` keyword argument is used as a 3-way switch to select which + type of object to use for drawing edges: + - ``arrows=None`` -> default (FancyArrowPatches for directed, else LineCollection) + - ``arrows=True`` -> FancyArrowPatches + - ``arrows=False`` -> LineCollection + """ + import matplotlib.collections + import matplotlib.patches + + UG = nx.path_graph(3) + DG = nx.path_graph(3, create_using=nx.DiGraph) + pos = {n: (n, n) for n in UG} + + # Use FancyArrowPatches when arrows=True, regardless of graph type + for G in (UG, DG): + edges = nx.draw_networkx_edges(G, pos, arrows=True) + assert len(edges) == len(G.edges) + assert isinstance(edges[0], mpl.patches.FancyArrowPatch) + + # Use LineCollection when arrows=False, regardless of graph type + for G in (UG, DG): + edges = nx.draw_networkx_edges(G, pos, arrows=False) + assert isinstance(edges, mpl.collections.LineCollection) + + # Default behavior when arrows=None: FAPs for directed, LC's for undirected + edges = nx.draw_networkx_edges(UG, pos) + assert isinstance(edges, mpl.collections.LineCollection) + edges = nx.draw_networkx_edges(DG, pos) + assert len(edges) == len(G.edges) + assert isinstance(edges[0], mpl.patches.FancyArrowPatch) + + +@pytest.mark.parametrize("drawing_func", (nx.draw, nx.draw_networkx)) +def test_draw_networkx_arrows_default_undirected(drawing_func): + import matplotlib.collections + + G = nx.path_graph(3) + fig, ax = plt.subplots() + drawing_func(G, ax=ax) + assert any(isinstance(c, mpl.collections.LineCollection) for c in ax.collections) + assert not ax.patches + plt.delaxes(ax) + plt.close() + + +@pytest.mark.parametrize("drawing_func", (nx.draw, nx.draw_networkx)) +def test_draw_networkx_arrows_default_directed(drawing_func): + import matplotlib.collections + + G = nx.path_graph(3, create_using=nx.DiGraph) + fig, ax = plt.subplots() + drawing_func(G, ax=ax) + assert not any( + isinstance(c, mpl.collections.LineCollection) for c in ax.collections + ) + assert ax.patches + plt.delaxes(ax) + plt.close() + + +def test_edgelist_kwarg_not_ignored(): + # See gh-4994 + G = nx.path_graph(3) + G.add_edge(0, 0) + fig, ax = plt.subplots() + nx.draw(G, edgelist=[(0, 1), (1, 2)], ax=ax) # Exclude self-loop from edgelist + assert not ax.patches + plt.delaxes(ax) + plt.close() + + +@pytest.mark.parametrize( + ("G", "expected_n_edges"), + ([nx.DiGraph(), 2], [nx.MultiGraph(), 4], [nx.MultiDiGraph(), 4]), +) +def test_draw_networkx_edges_multiedge_connectionstyle(G, expected_n_edges): + """Draws edges correctly for 3 types of graphs and checks for valid length""" + for i, (u, v) in enumerate([(0, 1), (0, 1), (0, 1), (0, 2)]): + G.add_edge(u, v, weight=round(i / 3, 2)) + pos = {n: (n, n) for n in G} + # Raises on insuficient connectionstyle length + for conn_style in [ + "arc3,rad=0.1", + ["arc3,rad=0.1", "arc3,rad=0.1"], + ["arc3,rad=0.1", "arc3,rad=0.1", "arc3,rad=0.2"], + ]: + nx.draw_networkx_edges(G, pos, connectionstyle=conn_style) + arrows = nx.draw_networkx_edges(G, pos, connectionstyle=conn_style) + assert len(arrows) == expected_n_edges + + +@pytest.mark.parametrize( + ("G", "expected_n_edges"), + ([nx.DiGraph(), 2], [nx.MultiGraph(), 4], [nx.MultiDiGraph(), 4]), +) +def test_draw_networkx_edge_labels_multiedge_connectionstyle(G, expected_n_edges): + """Draws labels correctly for 3 types of graphs and checks for valid length and class names""" + for i, (u, v) in enumerate([(0, 1), (0, 1), (0, 1), (0, 2)]): + G.add_edge(u, v, weight=round(i / 3, 2)) + pos = {n: (n, n) for n in G} + # Raises on insuficient connectionstyle length + arrows = nx.draw_networkx_edges( + G, pos, connectionstyle=["arc3,rad=0.1", "arc3,rad=0.1", "arc3,rad=0.1"] + ) + for conn_style in [ + "arc3,rad=0.1", + ["arc3,rad=0.1", "arc3,rad=0.2"], + ["arc3,rad=0.1", "arc3,rad=0.1", "arc3,rad=0.1"], + ]: + text_items = nx.draw_networkx_edge_labels(G, pos, connectionstyle=conn_style) + assert len(text_items) == expected_n_edges + for ti in text_items.values(): + assert ti.__class__.__name__ == "CurvedArrowText" + + +def test_draw_networkx_edge_label_multiedge(): + G = nx.MultiGraph() + G.add_edge(0, 1, weight=10) + G.add_edge(0, 1, weight=20) + edge_labels = nx.get_edge_attributes(G, "weight") # Includes edge keys + pos = {n: (n, n) for n in G} + text_items = nx.draw_networkx_edge_labels( + G, + pos, + edge_labels=edge_labels, + connectionstyle=["arc3,rad=0.1", "arc3,rad=0.2"], + ) + assert len(text_items) == 2 + + +def test_draw_networkx_edge_label_empty_dict(): + """Regression test for draw_networkx_edge_labels with empty dict. See + gh-5372.""" + G = nx.path_graph(3) + pos = {n: (n, n) for n in G.nodes} + assert nx.draw_networkx_edge_labels(G, pos, edge_labels={}) == {} + + +def test_draw_networkx_edges_undirected_selfloop_colors(): + """When an edgelist is supplied along with a sequence of colors, check that + the self-loops have the correct colors.""" + fig, ax = plt.subplots() + # Edge list and corresponding colors + edgelist = [(1, 3), (1, 2), (2, 3), (1, 1), (3, 3), (2, 2)] + edge_colors = ["pink", "cyan", "black", "red", "blue", "green"] + + G = nx.Graph(edgelist) + pos = {n: (n, n) for n in G.nodes} + nx.draw_networkx_edges(G, pos, ax=ax, edgelist=edgelist, edge_color=edge_colors) + + # Verify that there are three fancy arrow patches (1 per self loop) + assert len(ax.patches) == 3 + + # These are points that should be contained in the self loops. For example, + # sl_points[0] will be (1, 1.1), which is inside the "path" of the first + # self-loop but outside the others + sl_points = np.array(edgelist[-3:]) + np.array([0, 0.1]) + + # Check that the mapping between self-loop locations and their colors is + # correct + for fap, clr, slp in zip(ax.patches, edge_colors[-3:], sl_points): + assert fap.get_path().contains_point(slp) + assert mpl.colors.same_color(fap.get_edgecolor(), clr) + plt.delaxes(ax) + plt.close() + + +@pytest.mark.parametrize( + "fap_only_kwarg", # Non-default values for kwargs that only apply to FAPs + ( + {"arrowstyle": "-"}, + {"arrowsize": 20}, + {"connectionstyle": "arc3,rad=0.2"}, + {"min_source_margin": 10}, + {"min_target_margin": 10}, + ), +) +def test_user_warnings_for_unused_edge_drawing_kwargs(fap_only_kwarg): + """Users should get a warning when they specify a non-default value for + one of the kwargs that applies only to edges drawn with FancyArrowPatches, + but FancyArrowPatches aren't being used under the hood.""" + G = nx.path_graph(3) + pos = {n: (n, n) for n in G} + fig, ax = plt.subplots() + # By default, an undirected graph will use LineCollection to represent + # the edges + kwarg_name = list(fap_only_kwarg.keys())[0] + with pytest.warns( + UserWarning, match=f"\n\nThe {kwarg_name} keyword argument is not applicable" + ): + nx.draw_networkx_edges(G, pos, ax=ax, **fap_only_kwarg) + # FancyArrowPatches are always used when `arrows=True` is specified. + # Check that warnings are *not* raised in this case + with warnings.catch_warnings(): + # Escalate warnings -> errors so tests fail if warnings are raised + warnings.simplefilter("error") + nx.draw_networkx_edges(G, pos, ax=ax, arrows=True, **fap_only_kwarg) + + plt.delaxes(ax) + plt.close() + + +@pytest.mark.parametrize("draw_fn", (nx.draw, nx.draw_circular)) +def test_no_warning_on_default_draw_arrowstyle(draw_fn): + # See gh-7284 + fig, ax = plt.subplots() + G = nx.cycle_graph(5) + with warnings.catch_warnings(record=True) as w: + draw_fn(G, ax=ax) + assert len(w) == 0 + + plt.delaxes(ax) + plt.close() + + +@pytest.mark.parametrize("hide_ticks", [False, True]) +@pytest.mark.parametrize( + "method", + [ + nx.draw_networkx, + nx.draw_networkx_edge_labels, + nx.draw_networkx_edges, + nx.draw_networkx_labels, + nx.draw_networkx_nodes, + ], +) +def test_hide_ticks(method, hide_ticks): + G = nx.path_graph(3) + pos = {n: (n, n) for n in G.nodes} + _, ax = plt.subplots() + method(G, pos=pos, ax=ax, hide_ticks=hide_ticks) + for axis in [ax.xaxis, ax.yaxis]: + assert bool(axis.get_ticklabels()) != hide_ticks + + plt.delaxes(ax) + plt.close() diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/__init__.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2fa5a6cf2e1ad63ed2b1e6cdff237d3fe7bb5a15 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/__init__.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/atlas.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/atlas.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3da924e0abf208dab17b8e5d3d1fec5cb4914111 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/atlas.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/classic.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/classic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1b910dbea45a08e8a6d7631bc114fe99e61ecf7 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/classic.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/cographs.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/cographs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..948fdd72129b71ce72e77881d785348dd8b48171 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/cographs.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/community.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/community.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d7c244d20e23f23bfe105e611e9b59da57d23b4 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/community.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/degree_seq.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/degree_seq.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ccd8b87ec6d53a0b7e4691c49c6c3835c71f8584 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/degree_seq.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/directed.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/directed.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..927adab72b2513232a9e37dc10dc2c9b00ca632b Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/directed.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/duplication.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/duplication.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..153f33a63cda9e8b1e88998286923224d3341b5b Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/duplication.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/ego.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/ego.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..185886a1ed9b18fa1c5e0f1992e1842e78b3ee25 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/ego.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/expanders.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/expanders.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a52e2c43a30b27b6c264033d4227114767e93d1f Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/expanders.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/geometric.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/geometric.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ff0cb034d69e9d28a67e6ee313798edb11a4ff7 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/geometric.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/harary_graph.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/harary_graph.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb0df74b60c296cc863f4236749dd1aca00047d4 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/harary_graph.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/internet_as_graphs.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/internet_as_graphs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e4754049271ba756ea7dafc23c4f1014979488d Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/internet_as_graphs.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/intersection.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/intersection.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dbeffdf52b3ce92a59ac7ec45a03ffda0dabfc1d Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/intersection.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/interval_graph.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/interval_graph.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2d68b24341711b0c8710b8159c3c0cd4d272bf6 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/interval_graph.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/joint_degree_seq.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/joint_degree_seq.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4eb9e697819590bc8020001d201eca1a97835dd Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/joint_degree_seq.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/lattice.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/lattice.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3282960b2b5598e8dd35f445b708b3ffb5e075c5 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/lattice.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/line.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/line.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7109960b9a6f6acbe38a325cc069e2f87491d845 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/line.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/mycielski.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/mycielski.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e167d8e928e67f64bb2d78ebe61bbf75e55cf36 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/mycielski.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/nonisomorphic_trees.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/nonisomorphic_trees.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd0f5bcfc7751a5cfdd57ee18fc0a0a01169a7a6 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/nonisomorphic_trees.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/random_clustered.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/random_clustered.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae4885cf201be338a70edf9da4fa7a8686414480 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/random_clustered.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/random_graphs.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/random_graphs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3022139e19ba76182c9635de8dcc727d5850ab52 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/random_graphs.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/small.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/small.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7109840b11fc14a1c40673a408f05268b4f1371 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/small.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/social.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/social.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e75f0631dd7c8fbb8f481650c52178593cef1e7 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/social.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/spectral_graph_forge.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/spectral_graph_forge.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c492d8989b4e63325af468aaf665e1e1020c113f Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/spectral_graph_forge.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/stochastic.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/stochastic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d03265c8b46f82173f5e82681ec428e5066f05b7 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/stochastic.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/sudoku.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/sudoku.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..301eece0c418fb1871f7d570b8e1201c4f301bfc Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/sudoku.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/time_series.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/time_series.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38af6e5f2974c5612cbdee9d912e973118b9c1cd Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/time_series.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/trees.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/trees.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d27aba34898ec03f5b85ba6dc4bd4a34bcc00ed0 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/trees.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/triads.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/triads.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..042febc8bab2a1353476cf0d726ff0e7c0e8c066 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/__pycache__/triads.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/__init__.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e48e36d4fc7929be92b648104f369a4738abd3e Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_atlas.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_atlas.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc7c44cd11461f767050570062fac9cfe673e956 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_atlas.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_classic.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_classic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f8d29bec411137bfde8039f78a567792e92027f Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_classic.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_cographs.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_cographs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9a8e81b11ff1129640fa079169b5cd8bf2e8918 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_cographs.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_community.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_community.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d08cebc3ab2d62a3957facf66f033380de082478 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_community.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_degree_seq.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_degree_seq.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15bc62f559744458566d52363bd1d0a05dabe45f Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_degree_seq.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_directed.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_directed.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5602a38522478f9645d7ee22cd237ff47f0af166 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_directed.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_duplication.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_duplication.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19f12afa64d4c8594b814ce2abdf8b40d99e9454 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_duplication.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_ego.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_ego.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99f1b7a9909bef817590bd86562968420c4cb7f5 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_ego.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_expanders.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_expanders.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6cd25826bc0d91daec08c3c77dd5cce7a0b6d11e Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_expanders.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_geometric.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_geometric.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3b750247748bab4d2c2fe14f103a5c7e7e9fa56 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_geometric.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_harary_graph.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_harary_graph.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6278b80d92a83d9dd214de73b447c021572ee572 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_harary_graph.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_internet_as_graphs.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_internet_as_graphs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..778138d4dbf01880406d546e0c9cc08bffcdbdac Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_internet_as_graphs.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_intersection.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_intersection.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ec7a7825fac78d49f80878a152368ba8ffc0736 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_intersection.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_interval_graph.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_interval_graph.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5307c64b6deee54e465fa24b376100686a66b709 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_interval_graph.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_joint_degree_seq.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_joint_degree_seq.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ffd9351e97d7857d0f19bf7ee871dced3164f56 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_joint_degree_seq.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_lattice.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_lattice.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..540ddc9bbbffb170671d71bb2396ae21ea0cd6a0 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_lattice.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_line.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_line.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0563cd343b3d383131c73d8bb0aea257a9cbe98a Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_line.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_mycielski.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_mycielski.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ee8cabbdcf778f5f6e35a916a178fa759018460 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_mycielski.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_nonisomorphic_trees.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_nonisomorphic_trees.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c940bf868384db588b7efc59de3d2de5be6f861 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_nonisomorphic_trees.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_random_clustered.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_random_clustered.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bcc722429decf302c428b18e1a74ca23b4a016cb Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_random_clustered.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_random_graphs.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_random_graphs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9648f2b78091078793c129b49875793fd5797fbf Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_random_graphs.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_small.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_small.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51799c6acd8f0cd087d77853cec4db4201b826b9 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_small.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_spectral_graph_forge.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_spectral_graph_forge.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce294090766ba2949a0c66d002fef517d7e1ad00 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_spectral_graph_forge.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_stochastic.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_stochastic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd9c6d045421b75f765d58286e74a5368080eece Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_stochastic.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_sudoku.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_sudoku.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ab8a8c475058f15d1246a5fcc8ffa8b0452b0a7 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_sudoku.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_time_series.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_time_series.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..568d8f940e7f21375da4aa810061cca2b83b1ce7 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_time_series.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_trees.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_trees.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59a6e778364f5eaf5c8cb8aa2afcecf7486469c9 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_trees.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_triads.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_triads.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05830e93c1a971932bc70abc02c26a9aaa7a8acf Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/__pycache__/test_triads.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_directed.py b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_directed.py new file mode 100644 index 0000000000000000000000000000000000000000..356bf45834c0b832592b9b1bc1b12090eaf64467 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_directed.py @@ -0,0 +1,162 @@ +"""Generators - Directed Graphs +---------------------------- +""" +import pytest + +import networkx as nx +from networkx.classes import Graph, MultiDiGraph +from networkx.generators.directed import ( + gn_graph, + gnc_graph, + gnr_graph, + random_k_out_graph, + random_uniform_k_out_graph, + scale_free_graph, +) + + +class TestGeneratorsDirected: + def test_smoke_test_random_graphs(self): + gn_graph(100) + gnr_graph(100, 0.5) + gnc_graph(100) + scale_free_graph(100) + + gn_graph(100, seed=42) + gnr_graph(100, 0.5, seed=42) + gnc_graph(100, seed=42) + scale_free_graph(100, seed=42) + + def test_create_using_keyword_arguments(self): + pytest.raises(nx.NetworkXError, gn_graph, 100, create_using=Graph()) + pytest.raises(nx.NetworkXError, gnr_graph, 100, 0.5, create_using=Graph()) + pytest.raises(nx.NetworkXError, gnc_graph, 100, create_using=Graph()) + G = gn_graph(100, seed=1) + MG = gn_graph(100, create_using=MultiDiGraph(), seed=1) + assert sorted(G.edges()) == sorted(MG.edges()) + G = gnr_graph(100, 0.5, seed=1) + MG = gnr_graph(100, 0.5, create_using=MultiDiGraph(), seed=1) + assert sorted(G.edges()) == sorted(MG.edges()) + G = gnc_graph(100, seed=1) + MG = gnc_graph(100, create_using=MultiDiGraph(), seed=1) + assert sorted(G.edges()) == sorted(MG.edges()) + + G = scale_free_graph( + 100, + alpha=0.3, + beta=0.4, + gamma=0.3, + delta_in=0.3, + delta_out=0.1, + initial_graph=nx.cycle_graph(4, create_using=MultiDiGraph), + seed=1, + ) + pytest.raises(ValueError, scale_free_graph, 100, 0.5, 0.4, 0.3) + pytest.raises(ValueError, scale_free_graph, 100, alpha=-0.3) + pytest.raises(ValueError, scale_free_graph, 100, beta=-0.3) + pytest.raises(ValueError, scale_free_graph, 100, gamma=-0.3) + + def test_parameters(self): + G = nx.DiGraph() + G.add_node(0) + + def kernel(x): + return x + + assert nx.is_isomorphic(gn_graph(1), G) + assert nx.is_isomorphic(gn_graph(1, kernel=kernel), G) + assert nx.is_isomorphic(gnc_graph(1), G) + assert nx.is_isomorphic(gnr_graph(1, 0.5), G) + + +def test_scale_free_graph_negative_delta(): + with pytest.raises(ValueError, match="delta_in must be >= 0."): + scale_free_graph(10, delta_in=-1) + with pytest.raises(ValueError, match="delta_out must be >= 0."): + scale_free_graph(10, delta_out=-1) + + +def test_non_numeric_ordering(): + G = MultiDiGraph([("a", "b"), ("b", "c"), ("c", "a")]) + s = scale_free_graph(3, initial_graph=G) + assert len(s) == 3 + assert len(s.edges) == 3 + + +@pytest.mark.parametrize("ig", (nx.Graph(), nx.DiGraph([(0, 1)]))) +def test_scale_free_graph_initial_graph_kwarg(ig): + with pytest.raises(nx.NetworkXError): + scale_free_graph(100, initial_graph=ig) + + +class TestRandomKOutGraph: + """Unit tests for the + :func:`~networkx.generators.directed.random_k_out_graph` function. + + """ + + def test_regularity(self): + """Tests that the generated graph is `k`-out-regular.""" + n = 10 + k = 3 + alpha = 1 + G = random_k_out_graph(n, k, alpha) + assert all(d == k for v, d in G.out_degree()) + G = random_k_out_graph(n, k, alpha, seed=42) + assert all(d == k for v, d in G.out_degree()) + + def test_no_self_loops(self): + """Tests for forbidding self-loops.""" + n = 10 + k = 3 + alpha = 1 + G = random_k_out_graph(n, k, alpha, self_loops=False) + assert nx.number_of_selfloops(G) == 0 + + def test_negative_alpha(self): + with pytest.raises(ValueError, match="alpha must be positive"): + random_k_out_graph(10, 3, -1) + + +class TestUniformRandomKOutGraph: + """Unit tests for the + :func:`~networkx.generators.directed.random_uniform_k_out_graph` + function. + + """ + + def test_regularity(self): + """Tests that the generated graph is `k`-out-regular.""" + n = 10 + k = 3 + G = random_uniform_k_out_graph(n, k) + assert all(d == k for v, d in G.out_degree()) + G = random_uniform_k_out_graph(n, k, seed=42) + assert all(d == k for v, d in G.out_degree()) + + def test_no_self_loops(self): + """Tests for forbidding self-loops.""" + n = 10 + k = 3 + G = random_uniform_k_out_graph(n, k, self_loops=False) + assert nx.number_of_selfloops(G) == 0 + assert all(d == k for v, d in G.out_degree()) + + def test_with_replacement(self): + n = 10 + k = 3 + G = random_uniform_k_out_graph(n, k, with_replacement=True) + assert G.is_multigraph() + assert all(d == k for v, d in G.out_degree()) + n = 10 + k = 9 + G = random_uniform_k_out_graph(n, k, with_replacement=False, self_loops=False) + assert nx.number_of_selfloops(G) == 0 + assert all(d == k for v, d in G.out_degree()) + + def test_without_replacement(self): + n = 10 + k = 3 + G = random_uniform_k_out_graph(n, k, with_replacement=False) + assert not G.is_multigraph() + assert all(d == k for v, d in G.out_degree()) diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_expanders.py b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_expanders.py new file mode 100644 index 0000000000000000000000000000000000000000..6c0259124393ef3b75aef9db75af99e8093a3b13 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_expanders.py @@ -0,0 +1,164 @@ +"""Unit tests for the :mod:`networkx.generators.expanders` module. + +""" + +import pytest + +import networkx as nx + + +@pytest.mark.parametrize("n", (2, 3, 5, 6, 10)) +def test_margulis_gabber_galil_graph_properties(n): + g = nx.margulis_gabber_galil_graph(n) + assert g.number_of_nodes() == n * n + for node in g: + assert g.degree(node) == 8 + assert len(node) == 2 + for i in node: + assert int(i) == i + assert 0 <= i < n + + +@pytest.mark.parametrize("n", (2, 3, 5, 6, 10)) +def test_margulis_gabber_galil_graph_eigvals(n): + np = pytest.importorskip("numpy") + sp = pytest.importorskip("scipy") + + g = nx.margulis_gabber_galil_graph(n) + # Eigenvalues are already sorted using the scipy eigvalsh, + # but the implementation in numpy does not guarantee order. + w = sorted(sp.linalg.eigvalsh(nx.adjacency_matrix(g).toarray())) + assert w[-2] < 5 * np.sqrt(2) + + +@pytest.mark.parametrize("p", (3, 5, 7, 11)) # Primes +def test_chordal_cycle_graph(p): + """Test for the :func:`networkx.chordal_cycle_graph` function.""" + G = nx.chordal_cycle_graph(p) + assert len(G) == p + # TODO The second largest eigenvalue should be smaller than a constant, + # independent of the number of nodes in the graph: + # + # eigs = sorted(sp.linalg.eigvalsh(nx.adjacency_matrix(G).toarray())) + # assert_less(eigs[-2], ...) + # + + +@pytest.mark.parametrize("p", (3, 5, 7, 11, 13)) # Primes +def test_paley_graph(p): + """Test for the :func:`networkx.paley_graph` function.""" + G = nx.paley_graph(p) + # G has p nodes + assert len(G) == p + # G is (p-1)/2-regular + in_degrees = {G.in_degree(node) for node in G.nodes} + out_degrees = {G.out_degree(node) for node in G.nodes} + assert len(in_degrees) == 1 and in_degrees.pop() == (p - 1) // 2 + assert len(out_degrees) == 1 and out_degrees.pop() == (p - 1) // 2 + + # If p = 1 mod 4, -1 is a square mod 4 and therefore the + # edge in the Paley graph are symmetric. + if p % 4 == 1: + for u, v in G.edges: + assert (v, u) in G.edges + + +@pytest.mark.parametrize("d, n", [(2, 7), (4, 10), (4, 16)]) +def test_maybe_regular_expander(d, n): + pytest.importorskip("numpy") + G = nx.maybe_regular_expander(n, d) + + assert len(G) == n, "Should have n nodes" + assert len(G.edges) == n * d / 2, "Should have n*d/2 edges" + assert nx.is_k_regular(G, d), "Should be d-regular" + + +@pytest.mark.parametrize("n", (3, 5, 6, 10)) +def test_is_regular_expander(n): + pytest.importorskip("numpy") + pytest.importorskip("scipy") + G = nx.complete_graph(n) + + assert nx.is_regular_expander(G) == True, "Should be a regular expander" + + +@pytest.mark.parametrize("d, n", [(2, 7), (4, 10), (4, 16)]) +def test_random_regular_expander(d, n): + pytest.importorskip("numpy") + pytest.importorskip("scipy") + G = nx.random_regular_expander_graph(n, d) + + assert len(G) == n, "Should have n nodes" + assert len(G.edges) == n * d / 2, "Should have n*d/2 edges" + assert nx.is_k_regular(G, d), "Should be d-regular" + assert nx.is_regular_expander(G) == True, "Should be a regular expander" + + +def test_random_regular_expander_explicit_construction(): + pytest.importorskip("numpy") + pytest.importorskip("scipy") + G = nx.random_regular_expander_graph(d=4, n=5) + + assert len(G) == 5 and len(G.edges) == 10, "Should be a complete graph" + + +@pytest.mark.parametrize("graph_type", (nx.Graph, nx.DiGraph, nx.MultiDiGraph)) +def test_margulis_gabber_galil_graph_badinput(graph_type): + with pytest.raises( + nx.NetworkXError, match="`create_using` must be an undirected multigraph" + ): + nx.margulis_gabber_galil_graph(3, create_using=graph_type) + + +@pytest.mark.parametrize("graph_type", (nx.Graph, nx.DiGraph, nx.MultiDiGraph)) +def test_chordal_cycle_graph_badinput(graph_type): + with pytest.raises( + nx.NetworkXError, match="`create_using` must be an undirected multigraph" + ): + nx.chordal_cycle_graph(3, create_using=graph_type) + + +def test_paley_graph_badinput(): + with pytest.raises( + nx.NetworkXError, match="`create_using` cannot be a multigraph." + ): + nx.paley_graph(3, create_using=nx.MultiGraph) + + +def test_maybe_regular_expander_badinput(): + pytest.importorskip("numpy") + pytest.importorskip("scipy") + + with pytest.raises(nx.NetworkXError, match="n must be a positive integer"): + nx.maybe_regular_expander(n=-1, d=2) + + with pytest.raises(nx.NetworkXError, match="d must be greater than or equal to 2"): + nx.maybe_regular_expander(n=10, d=0) + + with pytest.raises(nx.NetworkXError, match="Need n-1>= d to have room"): + nx.maybe_regular_expander(n=5, d=6) + + +def test_is_regular_expander_badinput(): + pytest.importorskip("numpy") + pytest.importorskip("scipy") + + with pytest.raises(nx.NetworkXError, match="epsilon must be non negative"): + nx.is_regular_expander(nx.Graph(), epsilon=-1) + + +def test_random_regular_expander_badinput(): + pytest.importorskip("numpy") + pytest.importorskip("scipy") + + with pytest.raises(nx.NetworkXError, match="n must be a positive integer"): + nx.random_regular_expander_graph(n=-1, d=2) + + with pytest.raises(nx.NetworkXError, match="d must be greater than or equal to 2"): + nx.random_regular_expander_graph(n=10, d=0) + + with pytest.raises(nx.NetworkXError, match="Need n-1>= d to have room"): + nx.random_regular_expander_graph(n=5, d=6) + + with pytest.raises(nx.NetworkXError, match="epsilon must be non negative"): + nx.random_regular_expander_graph(n=4, d=2, epsilon=-1) diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_interval_graph.py b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_interval_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..a64d9c41d71d615487fd5a27973f6a222ad4044b --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_interval_graph.py @@ -0,0 +1,145 @@ +"""Unit tests for the :mod:`networkx.generators.interval_graph` module. + +""" +import math + +import pytest + +import networkx as nx +from networkx.generators.interval_graph import interval_graph +from networkx.utils import edges_equal + + +class TestIntervalGraph: + """Unit tests for :func:`networkx.generators.interval_graph.interval_graph`""" + + def test_empty(self): + """Tests for trivial case of empty input""" + assert len(interval_graph([])) == 0 + + def test_interval_graph_check_invalid(self): + """Tests for conditions that raise Exceptions""" + + invalids_having_none = [None, (1, 2)] + with pytest.raises(TypeError): + interval_graph(invalids_having_none) + + invalids_having_set = [{1, 2}] + with pytest.raises(TypeError): + interval_graph(invalids_having_set) + + invalids_having_seq_but_not_length2 = [(1, 2, 3)] + with pytest.raises(TypeError): + interval_graph(invalids_having_seq_but_not_length2) + + invalids_interval = [[3, 2]] + with pytest.raises(ValueError): + interval_graph(invalids_interval) + + def test_interval_graph_0(self): + intervals = [(1, 2), (1, 3)] + + expected_graph = nx.Graph() + expected_graph.add_edge(*intervals) + + actual_g = interval_graph(intervals) + + assert set(actual_g.nodes) == set(expected_graph.nodes) + assert edges_equal(expected_graph, actual_g) + + def test_interval_graph_1(self): + intervals = [(1, 2), (2, 3), (3, 4), (1, 4)] + + expected_graph = nx.Graph() + expected_graph.add_nodes_from(intervals) + e1 = ((1, 4), (1, 2)) + e2 = ((1, 4), (2, 3)) + e3 = ((1, 4), (3, 4)) + e4 = ((3, 4), (2, 3)) + e5 = ((1, 2), (2, 3)) + + expected_graph.add_edges_from([e1, e2, e3, e4, e5]) + + actual_g = interval_graph(intervals) + + assert set(actual_g.nodes) == set(expected_graph.nodes) + assert edges_equal(expected_graph, actual_g) + + def test_interval_graph_2(self): + intervals = [(1, 2), [3, 5], [6, 8], (9, 10)] + + expected_graph = nx.Graph() + expected_graph.add_nodes_from([(1, 2), (3, 5), (6, 8), (9, 10)]) + + actual_g = interval_graph(intervals) + + assert set(actual_g.nodes) == set(expected_graph.nodes) + assert edges_equal(expected_graph, actual_g) + + def test_interval_graph_3(self): + intervals = [(1, 4), [3, 5], [2.5, 4]] + + expected_graph = nx.Graph() + expected_graph.add_nodes_from([(1, 4), (3, 5), (2.5, 4)]) + e1 = ((1, 4), (3, 5)) + e2 = ((1, 4), (2.5, 4)) + e3 = ((3, 5), (2.5, 4)) + + expected_graph.add_edges_from([e1, e2, e3]) + + actual_g = interval_graph(intervals) + + assert set(actual_g.nodes) == set(expected_graph.nodes) + assert edges_equal(expected_graph, actual_g) + + def test_interval_graph_4(self): + """test all possible overlaps""" + intervals = [ + (0, 2), + (-2, -1), + (-2, 0), + (-2, 1), + (-2, 2), + (-2, 3), + (0, 1), + (0, 2), + (0, 3), + (1, 2), + (1, 3), + (2, 3), + (3, 4), + ] + + expected_graph = nx.Graph() + expected_graph.add_nodes_from(intervals) + expected_nbrs = { + (-2, 0), + (-2, 1), + (-2, 2), + (-2, 3), + (0, 1), + (0, 2), + (0, 3), + (1, 2), + (1, 3), + (2, 3), + } + actual_g = nx.interval_graph(intervals) + actual_nbrs = nx.neighbors(actual_g, (0, 2)) + + assert set(actual_nbrs) == expected_nbrs + + def test_interval_graph_5(self): + """this test is to see that an interval supports infinite number""" + intervals = {(-math.inf, 0), (-1, -1), (0.5, 0.5), (1, 1), (1, math.inf)} + + expected_graph = nx.Graph() + expected_graph.add_nodes_from(intervals) + e1 = ((-math.inf, 0), (-1, -1)) + e2 = ((1, 1), (1, math.inf)) + + expected_graph.add_edges_from([e1, e2]) + actual_g = interval_graph(intervals) + + assert set(actual_g.nodes) == set(expected_graph.nodes) + assert edges_equal(expected_graph, actual_g) diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_stochastic.py b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_stochastic.py new file mode 100644 index 0000000000000000000000000000000000000000..09be4c197de372a67356e5e55f66baf3cb9e2f16 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/networkx/generators/tests/test_stochastic.py @@ -0,0 +1,71 @@ +"""Unit tests for the :mod:`networkx.generators.stochastic` module.""" +import pytest + +import networkx as nx + + +class TestStochasticGraph: + """Unit tests for the :func:`~networkx.stochastic_graph` function.""" + + def test_default_weights(self): + G = nx.DiGraph() + G.add_edge(0, 1) + G.add_edge(0, 2) + S = nx.stochastic_graph(G) + assert nx.is_isomorphic(G, S) + assert sorted(S.edges(data=True)) == [ + (0, 1, {"weight": 0.5}), + (0, 2, {"weight": 0.5}), + ] + + def test_in_place(self): + """Tests for an in-place reweighting of the edges of the graph.""" + G = nx.DiGraph() + G.add_edge(0, 1, weight=1) + G.add_edge(0, 2, weight=1) + nx.stochastic_graph(G, copy=False) + assert sorted(G.edges(data=True)) == [ + (0, 1, {"weight": 0.5}), + (0, 2, {"weight": 0.5}), + ] + + def test_arbitrary_weights(self): + G = nx.DiGraph() + G.add_edge(0, 1, weight=1) + G.add_edge(0, 2, weight=1) + S = nx.stochastic_graph(G) + assert sorted(S.edges(data=True)) == [ + (0, 1, {"weight": 0.5}), + (0, 2, {"weight": 0.5}), + ] + + def test_multidigraph(self): + G = nx.MultiDiGraph() + G.add_edges_from([(0, 1), (0, 1), (0, 2), (0, 2)]) + S = nx.stochastic_graph(G) + d = {"weight": 0.25} + assert sorted(S.edges(data=True)) == [ + (0, 1, d), + (0, 1, d), + (0, 2, d), + (0, 2, d), + ] + + def test_zero_weights(self): + """Smoke test: ensure ZeroDivisionError is not raised.""" + G = nx.DiGraph() + G.add_edge(0, 1, weight=0) + G.add_edge(0, 2, weight=0) + S = nx.stochastic_graph(G) + assert sorted(S.edges(data=True)) == [ + (0, 1, {"weight": 0}), + (0, 2, {"weight": 0}), + ] + + def test_graph_disallowed(self): + with pytest.raises(nx.NetworkXNotImplemented): + nx.stochastic_graph(nx.Graph()) + + def test_multigraph_disallowed(self): + with pytest.raises(nx.NetworkXNotImplemented): + nx.stochastic_graph(nx.MultiGraph()) diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/linalg/attrmatrix.py b/env-llmeval/lib/python3.10/site-packages/networkx/linalg/attrmatrix.py new file mode 100644 index 0000000000000000000000000000000000000000..4882c35af4b8e64a668dbe092a064653aaa73b8c --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/networkx/linalg/attrmatrix.py @@ -0,0 +1,464 @@ +""" + Functions for constructing matrix-like objects from graph attributes. +""" +import networkx as nx + +__all__ = ["attr_matrix", "attr_sparse_matrix"] + + +def _node_value(G, node_attr): + """Returns a function that returns a value from G.nodes[u]. + + We return a function expecting a node as its sole argument. Then, in the + simplest scenario, the returned function will return G.nodes[u][node_attr]. + However, we also handle the case when `node_attr` is None or when it is a + function itself. + + Parameters + ---------- + G : graph + A NetworkX graph + + node_attr : {None, str, callable} + Specification of how the value of the node attribute should be obtained + from the node attribute dictionary. + + Returns + ------- + value : function + A function expecting a node as its sole argument. The function will + returns a value from G.nodes[u] that depends on `edge_attr`. + + """ + if node_attr is None: + + def value(u): + return u + + elif not callable(node_attr): + # assume it is a key for the node attribute dictionary + def value(u): + return G.nodes[u][node_attr] + + else: + # Advanced: Allow users to specify something else. + # + # For example, + # node_attr = lambda u: G.nodes[u].get('size', .5) * 3 + # + value = node_attr + + return value + + +def _edge_value(G, edge_attr): + """Returns a function that returns a value from G[u][v]. + + Suppose there exists an edge between u and v. Then we return a function + expecting u and v as arguments. For Graph and DiGraph, G[u][v] is + the edge attribute dictionary, and the function (essentially) returns + G[u][v][edge_attr]. However, we also handle cases when `edge_attr` is None + and when it is a function itself. For MultiGraph and MultiDiGraph, G[u][v] + is a dictionary of all edges between u and v. In this case, the returned + function sums the value of `edge_attr` for every edge between u and v. + + Parameters + ---------- + G : graph + A NetworkX graph + + edge_attr : {None, str, callable} + Specification of how the value of the edge attribute should be obtained + from the edge attribute dictionary, G[u][v]. For multigraphs, G[u][v] + is a dictionary of all the edges between u and v. This allows for + special treatment of multiedges. + + Returns + ------- + value : function + A function expecting two nodes as parameters. The nodes should + represent the from- and to- node of an edge. The function will + return a value from G[u][v] that depends on `edge_attr`. + + """ + + if edge_attr is None: + # topological count of edges + + if G.is_multigraph(): + + def value(u, v): + return len(G[u][v]) + + else: + + def value(u, v): + return 1 + + elif not callable(edge_attr): + # assume it is a key for the edge attribute dictionary + + if edge_attr == "weight": + # provide a default value + if G.is_multigraph(): + + def value(u, v): + return sum(d.get(edge_attr, 1) for d in G[u][v].values()) + + else: + + def value(u, v): + return G[u][v].get(edge_attr, 1) + + else: + # otherwise, the edge attribute MUST exist for each edge + if G.is_multigraph(): + + def value(u, v): + return sum(d[edge_attr] for d in G[u][v].values()) + + else: + + def value(u, v): + return G[u][v][edge_attr] + + else: + # Advanced: Allow users to specify something else. + # + # Alternative default value: + # edge_attr = lambda u,v: G[u][v].get('thickness', .5) + # + # Function on an attribute: + # edge_attr = lambda u,v: abs(G[u][v]['weight']) + # + # Handle Multi(Di)Graphs differently: + # edge_attr = lambda u,v: numpy.prod([d['size'] for d in G[u][v].values()]) + # + # Ignore multiple edges + # edge_attr = lambda u,v: 1 if len(G[u][v]) else 0 + # + value = edge_attr + + return value + + +@nx._dispatchable(edge_attrs={"edge_attr": None}, node_attrs="node_attr") +def attr_matrix( + G, + edge_attr=None, + node_attr=None, + normalized=False, + rc_order=None, + dtype=None, + order=None, +): + """Returns the attribute matrix using attributes from `G` as a numpy array. + + If only `G` is passed in, then the adjacency matrix is constructed. + + Let A be a discrete set of values for the node attribute `node_attr`. Then + the elements of A represent the rows and columns of the constructed matrix. + Now, iterate through every edge e=(u,v) in `G` and consider the value + of the edge attribute `edge_attr`. If ua and va are the values of the + node attribute `node_attr` for u and v, respectively, then the value of + the edge attribute is added to the matrix element at (ua, va). + + Parameters + ---------- + G : graph + The NetworkX graph used to construct the attribute matrix. + + edge_attr : str, optional + Each element of the matrix represents a running total of the + specified edge attribute for edges whose node attributes correspond + to the rows/cols of the matrix. The attribute must be present for + all edges in the graph. If no attribute is specified, then we + just count the number of edges whose node attributes correspond + to the matrix element. + + node_attr : str, optional + Each row and column in the matrix represents a particular value + of the node attribute. The attribute must be present for all nodes + in the graph. Note, the values of this attribute should be reliably + hashable. So, float values are not recommended. If no attribute is + specified, then the rows and columns will be the nodes of the graph. + + normalized : bool, optional + If True, then each row is normalized by the summation of its values. + + rc_order : list, optional + A list of the node attribute values. This list specifies the ordering + of rows and columns of the array. If no ordering is provided, then + the ordering will be random (and also, a return value). + + Other Parameters + ---------------- + dtype : NumPy data-type, optional + A valid NumPy dtype used to initialize the array. Keep in mind certain + dtypes can yield unexpected results if the array is to be normalized. + The parameter is passed to numpy.zeros(). If unspecified, the NumPy + default is used. + + order : {'C', 'F'}, optional + Whether to store multidimensional data in C- or Fortran-contiguous + (row- or column-wise) order in memory. This parameter is passed to + numpy.zeros(). If unspecified, the NumPy default is used. + + Returns + ------- + M : 2D NumPy ndarray + The attribute matrix. + + ordering : list + If `rc_order` was specified, then only the attribute matrix is returned. + However, if `rc_order` was None, then the ordering used to construct + the matrix is returned as well. + + Examples + -------- + Construct an adjacency matrix: + + >>> G = nx.Graph() + >>> G.add_edge(0, 1, thickness=1, weight=3) + >>> G.add_edge(0, 2, thickness=2) + >>> G.add_edge(1, 2, thickness=3) + >>> nx.attr_matrix(G, rc_order=[0, 1, 2]) + array([[0., 1., 1.], + [1., 0., 1.], + [1., 1., 0.]]) + + Alternatively, we can obtain the matrix describing edge thickness. + + >>> nx.attr_matrix(G, edge_attr="thickness", rc_order=[0, 1, 2]) + array([[0., 1., 2.], + [1., 0., 3.], + [2., 3., 0.]]) + + We can also color the nodes and ask for the probability distribution over + all edges (u,v) describing: + + Pr(v has color Y | u has color X) + + >>> G.nodes[0]["color"] = "red" + >>> G.nodes[1]["color"] = "red" + >>> G.nodes[2]["color"] = "blue" + >>> rc = ["red", "blue"] + >>> nx.attr_matrix(G, node_attr="color", normalized=True, rc_order=rc) + array([[0.33333333, 0.66666667], + [1. , 0. ]]) + + For example, the above tells us that for all edges (u,v): + + Pr( v is red | u is red) = 1/3 + Pr( v is blue | u is red) = 2/3 + + Pr( v is red | u is blue) = 1 + Pr( v is blue | u is blue) = 0 + + Finally, we can obtain the total weights listed by the node colors. + + >>> nx.attr_matrix(G, edge_attr="weight", node_attr="color", rc_order=rc) + array([[3., 2.], + [2., 0.]]) + + Thus, the total weight over all edges (u,v) with u and v having colors: + + (red, red) is 3 # the sole contribution is from edge (0,1) + (red, blue) is 2 # contributions from edges (0,2) and (1,2) + (blue, red) is 2 # same as (red, blue) since graph is undirected + (blue, blue) is 0 # there are no edges with blue endpoints + + """ + import numpy as np + + edge_value = _edge_value(G, edge_attr) + node_value = _node_value(G, node_attr) + + if rc_order is None: + ordering = list({node_value(n) for n in G}) + else: + ordering = rc_order + + N = len(ordering) + undirected = not G.is_directed() + index = dict(zip(ordering, range(N))) + M = np.zeros((N, N), dtype=dtype, order=order) + + seen = set() + for u, nbrdict in G.adjacency(): + for v in nbrdict: + # Obtain the node attribute values. + i, j = index[node_value(u)], index[node_value(v)] + if v not in seen: + M[i, j] += edge_value(u, v) + if undirected: + M[j, i] = M[i, j] + + if undirected: + seen.add(u) + + if normalized: + M /= M.sum(axis=1).reshape((N, 1)) + + if rc_order is None: + return M, ordering + else: + return M + + +@nx._dispatchable(edge_attrs={"edge_attr": None}, node_attrs="node_attr") +def attr_sparse_matrix( + G, edge_attr=None, node_attr=None, normalized=False, rc_order=None, dtype=None +): + """Returns a SciPy sparse array using attributes from G. + + If only `G` is passed in, then the adjacency matrix is constructed. + + Let A be a discrete set of values for the node attribute `node_attr`. Then + the elements of A represent the rows and columns of the constructed matrix. + Now, iterate through every edge e=(u,v) in `G` and consider the value + of the edge attribute `edge_attr`. If ua and va are the values of the + node attribute `node_attr` for u and v, respectively, then the value of + the edge attribute is added to the matrix element at (ua, va). + + Parameters + ---------- + G : graph + The NetworkX graph used to construct the NumPy matrix. + + edge_attr : str, optional + Each element of the matrix represents a running total of the + specified edge attribute for edges whose node attributes correspond + to the rows/cols of the matrix. The attribute must be present for + all edges in the graph. If no attribute is specified, then we + just count the number of edges whose node attributes correspond + to the matrix element. + + node_attr : str, optional + Each row and column in the matrix represents a particular value + of the node attribute. The attribute must be present for all nodes + in the graph. Note, the values of this attribute should be reliably + hashable. So, float values are not recommended. If no attribute is + specified, then the rows and columns will be the nodes of the graph. + + normalized : bool, optional + If True, then each row is normalized by the summation of its values. + + rc_order : list, optional + A list of the node attribute values. This list specifies the ordering + of rows and columns of the array. If no ordering is provided, then + the ordering will be random (and also, a return value). + + Other Parameters + ---------------- + dtype : NumPy data-type, optional + A valid NumPy dtype used to initialize the array. Keep in mind certain + dtypes can yield unexpected results if the array is to be normalized. + The parameter is passed to numpy.zeros(). If unspecified, the NumPy + default is used. + + Returns + ------- + M : SciPy sparse array + The attribute matrix. + + ordering : list + If `rc_order` was specified, then only the matrix is returned. + However, if `rc_order` was None, then the ordering used to construct + the matrix is returned as well. + + Examples + -------- + Construct an adjacency matrix: + + >>> G = nx.Graph() + >>> G.add_edge(0, 1, thickness=1, weight=3) + >>> G.add_edge(0, 2, thickness=2) + >>> G.add_edge(1, 2, thickness=3) + >>> M = nx.attr_sparse_matrix(G, rc_order=[0, 1, 2]) + >>> M.toarray() + array([[0., 1., 1.], + [1., 0., 1.], + [1., 1., 0.]]) + + Alternatively, we can obtain the matrix describing edge thickness. + + >>> M = nx.attr_sparse_matrix(G, edge_attr="thickness", rc_order=[0, 1, 2]) + >>> M.toarray() + array([[0., 1., 2.], + [1., 0., 3.], + [2., 3., 0.]]) + + We can also color the nodes and ask for the probability distribution over + all edges (u,v) describing: + + Pr(v has color Y | u has color X) + + >>> G.nodes[0]["color"] = "red" + >>> G.nodes[1]["color"] = "red" + >>> G.nodes[2]["color"] = "blue" + >>> rc = ["red", "blue"] + >>> M = nx.attr_sparse_matrix(G, node_attr="color", normalized=True, rc_order=rc) + >>> M.toarray() + array([[0.33333333, 0.66666667], + [1. , 0. ]]) + + For example, the above tells us that for all edges (u,v): + + Pr( v is red | u is red) = 1/3 + Pr( v is blue | u is red) = 2/3 + + Pr( v is red | u is blue) = 1 + Pr( v is blue | u is blue) = 0 + + Finally, we can obtain the total weights listed by the node colors. + + >>> M = nx.attr_sparse_matrix(G, edge_attr="weight", node_attr="color", rc_order=rc) + >>> M.toarray() + array([[3., 2.], + [2., 0.]]) + + Thus, the total weight over all edges (u,v) with u and v having colors: + + (red, red) is 3 # the sole contribution is from edge (0,1) + (red, blue) is 2 # contributions from edges (0,2) and (1,2) + (blue, red) is 2 # same as (red, blue) since graph is undirected + (blue, blue) is 0 # there are no edges with blue endpoints + + """ + import numpy as np + import scipy as sp + + edge_value = _edge_value(G, edge_attr) + node_value = _node_value(G, node_attr) + + if rc_order is None: + ordering = list({node_value(n) for n in G}) + else: + ordering = rc_order + + N = len(ordering) + undirected = not G.is_directed() + index = dict(zip(ordering, range(N))) + M = sp.sparse.lil_array((N, N), dtype=dtype) + + seen = set() + for u, nbrdict in G.adjacency(): + for v in nbrdict: + # Obtain the node attribute values. + i, j = index[node_value(u)], index[node_value(v)] + if v not in seen: + M[i, j] += edge_value(u, v) + if undirected: + M[j, i] = M[i, j] + + if undirected: + seen.add(u) + + if normalized: + M *= 1 / M.sum(axis=1)[:, np.newaxis] # in-place mult preserves sparse + + if rc_order is None: + return M, ordering + else: + return M diff --git a/env-llmeval/lib/python3.10/site-packages/networkx/linalg/bethehessianmatrix.py b/env-llmeval/lib/python3.10/site-packages/networkx/linalg/bethehessianmatrix.py new file mode 100644 index 0000000000000000000000000000000000000000..382e5181047c9dae2ab87436a88b1c76997acdeb --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/networkx/linalg/bethehessianmatrix.py @@ -0,0 +1,78 @@ +"""Bethe Hessian or deformed Laplacian matrix of graphs.""" +import networkx as nx +from networkx.utils import not_implemented_for + +__all__ = ["bethe_hessian_matrix"] + + +@not_implemented_for("directed") +@not_implemented_for("multigraph") +@nx._dispatchable +def bethe_hessian_matrix(G, r=None, nodelist=None): + r"""Returns the Bethe Hessian matrix of G. + + The Bethe Hessian is a family of matrices parametrized by r, defined as + H(r) = (r^2 - 1) I - r A + D where A is the adjacency matrix, D is the + diagonal matrix of node degrees, and I is the identify matrix. It is equal + to the graph laplacian when the regularizer r = 1. + + The default choice of regularizer should be the ratio [2]_ + + .. math:: + r_m = \left(\sum k_i \right)^{-1}\left(\sum k_i^2 \right) - 1 + + Parameters + ---------- + G : Graph + A NetworkX graph + r : float + Regularizer parameter + nodelist : list, optional + The rows and columns are ordered according to the nodes in nodelist. + If nodelist is None, then the ordering is produced by ``G.nodes()``. + + Returns + ------- + H : scipy.sparse.csr_array + The Bethe Hessian matrix of `G`, with parameter `r`. + + Examples + -------- + >>> k = [3, 2, 2, 1, 0] + >>> G = nx.havel_hakimi_graph(k) + >>> H = nx.bethe_hessian_matrix(G) + >>> H.toarray() + array([[ 3.5625, -1.25 , -1.25 , -1.25 , 0. ], + [-1.25 , 2.5625, -1.25 , 0. , 0. ], + [-1.25 , -1.25 , 2.5625, 0. , 0. ], + [-1.25 , 0. , 0. , 1.5625, 0. ], + [ 0. , 0. , 0. , 0. , 0.5625]]) + + See Also + -------- + bethe_hessian_spectrum + adjacency_matrix + laplacian_matrix + + References + ---------- + .. [1] A. Saade, F. Krzakala and L. Zdeborová + "Spectral Clustering of Graphs with the Bethe Hessian", + Advances in Neural Information Processing Systems, 2014. + .. [2] C. M. Le, E. Levina + "Estimating the number of communities in networks by spectral methods" + arXiv:1507.00827, 2015. + """ + import scipy as sp + + if nodelist is None: + nodelist = list(G) + if r is None: + r = sum(d**2 for v, d in nx.degree(G)) / sum(d for v, d in nx.degree(G)) - 1 + A = nx.to_scipy_sparse_array(G, nodelist=nodelist, format="csr") + n, m = A.shape + # TODO: Rm csr_array wrapper when spdiags array creation becomes available + D = sp.sparse.csr_array(sp.sparse.spdiags(A.sum(axis=1), 0, m, n, format="csr")) + # TODO: Rm csr_array wrapper when eye array creation becomes available + I = sp.sparse.csr_array(sp.sparse.eye(m, n, format="csr")) + return (r**2 - 1) * I - r * A + D