instance_id
stringlengths 12
53
| patch
stringlengths 264
37.7k
| repo
stringlengths 8
49
| base_commit
stringlengths 40
40
| hints_text
stringclasses 114
values | test_patch
stringlengths 224
315k
| problem_statement
stringlengths 40
10.4k
| version
stringclasses 1
value | FAIL_TO_PASS
sequencelengths 1
4.94k
| PASS_TO_PASS
sequencelengths 0
6.23k
| created_at
stringlengths 25
25
| __index_level_0__
int64 4.13k
6.41k
|
---|---|---|---|---|---|---|---|---|---|---|---|
networkx__networkx-2713 | diff --git a/networkx/algorithms/community/quality.py b/networkx/algorithms/community/quality.py
index 7de690af7..e04ff260d 100644
--- a/networkx/algorithms/community/quality.py
+++ b/networkx/algorithms/community/quality.py
@@ -114,7 +114,10 @@ def inter_community_edges(G, partition):
# for block in partition))
# return sum(1 for u, v in G.edges() if aff[u] != aff[v])
#
- return nx.quotient_graph(G, partition, create_using=nx.MultiGraph()).size()
+ if G.is_directed():
+ return nx.quotient_graph(G, partition, create_using=nx.MultiDiGraph()).size()
+ else:
+ return nx.quotient_graph(G, partition, create_using=nx.MultiGraph()).size()
def inter_community_non_edges(G, partition):
diff --git a/networkx/algorithms/simple_paths.py b/networkx/algorithms/simple_paths.py
index 763fa24d7..a2ef79671 100644
--- a/networkx/algorithms/simple_paths.py
+++ b/networkx/algorithms/simple_paths.py
@@ -333,7 +333,6 @@ def shortest_simple_paths(G, source, target, weight=None):
for path in listA:
if path[:i] == root:
ignore_edges.add((path[i - 1], path[i]))
- ignore_nodes.add(root[-1])
try:
length, spur = shortest_path_func(G, root[-1], target,
ignore_nodes=ignore_nodes,
@@ -343,6 +342,7 @@ def shortest_simple_paths(G, source, target, weight=None):
listB.push(root_length + length, path)
except nx.NetworkXNoPath:
pass
+ ignore_nodes.add(root[-1])
if listB:
path = listB.pop()
@@ -447,6 +447,8 @@ def _bidirectional_pred_succ(G, source, target, ignore_nodes=None, ignore_edges=
succ is a dictionary of successors from w to the target.
"""
# does BFS from both source and target and meets in the middle
+ if ignore_nodes and (source in ignore_nodes or target in ignore_nodes):
+ raise nx.NetworkXNoPath("No path between %s and %s." % (source, target))
if target == source:
return ({target: None}, {source: None}, source)
@@ -605,6 +607,8 @@ def _bidirectional_dijkstra(G, source, target, weight='weight',
shortest_path
shortest_path_length
"""
+ if ignore_nodes and (source in ignore_nodes or target in ignore_nodes):
+ raise nx.NetworkXNoPath("No path between %s and %s." % (source, target))
if source == target:
return (0, [source])
| networkx/networkx | 9f6c9cd6a561d41192bc29f14fd9bc16bcaad919 | diff --git a/networkx/algorithms/community/tests/test_quality.py b/networkx/algorithms/community/tests/test_quality.py
index 0c5b94c5a..79ce7e7f6 100644
--- a/networkx/algorithms/community/tests/test_quality.py
+++ b/networkx/algorithms/community/tests/test_quality.py
@@ -12,6 +12,7 @@ module.
"""
from __future__ import division
+from nose.tools import assert_equal
from nose.tools import assert_almost_equal
import networkx as nx
@@ -19,6 +20,7 @@ from networkx import barbell_graph
from networkx.algorithms.community import coverage
from networkx.algorithms.community import modularity
from networkx.algorithms.community import performance
+from networkx.algorithms.community.quality import inter_community_edges
class TestPerformance(object):
@@ -61,3 +63,17 @@ def test_modularity():
assert_almost_equal(-16 / (14 ** 2), modularity(G, C))
C = [{0, 1, 2}, {3, 4, 5}]
assert_almost_equal((35 * 2) / (14 ** 2), modularity(G, C))
+
+
+def test_inter_community_edges_with_digraphs():
+ G = nx.complete_graph(2, create_using = nx.DiGraph())
+ partition = [{0}, {1}]
+ assert_equal(inter_community_edges(G, partition), 2)
+
+ G = nx.complete_graph(10, create_using = nx.DiGraph())
+ partition = [{0}, {1, 2}, {3, 4, 5}, {6, 7, 8, 9}]
+ assert_equal(inter_community_edges(G, partition), 70)
+
+ G = nx.cycle_graph(4, create_using = nx.DiGraph())
+ partition = [{0, 1}, {2, 3}]
+ assert_equal(inter_community_edges(G, partition), 2)
diff --git a/networkx/algorithms/tests/test_simple_paths.py b/networkx/algorithms/tests/test_simple_paths.py
index e29255c32..4c701e487 100644
--- a/networkx/algorithms/tests/test_simple_paths.py
+++ b/networkx/algorithms/tests/test_simple_paths.py
@@ -220,6 +220,40 @@ def test_directed_weighted_shortest_simple_path():
cost = this_cost
+def test_weighted_shortest_simple_path_issue2427():
+ G = nx.Graph()
+ G.add_edge('IN', 'OUT', weight = 2)
+ G.add_edge('IN', 'A', weight = 1)
+ G.add_edge('IN', 'B', weight = 2)
+ G.add_edge('B', 'OUT', weight = 2)
+ assert_equal(list(nx.shortest_simple_paths(G, 'IN', 'OUT', weight = "weight")),
+ [['IN', 'OUT'], ['IN', 'B', 'OUT']])
+ G = nx.Graph()
+ G.add_edge('IN', 'OUT', weight = 10)
+ G.add_edge('IN', 'A', weight = 1)
+ G.add_edge('IN', 'B', weight = 1)
+ G.add_edge('B', 'OUT', weight = 1)
+ assert_equal(list(nx.shortest_simple_paths(G, 'IN', 'OUT', weight = "weight")),
+ [['IN', 'B', 'OUT'], ['IN', 'OUT']])
+
+
+def test_directed_weighted_shortest_simple_path_issue2427():
+ G = nx.DiGraph()
+ G.add_edge('IN', 'OUT', weight = 2)
+ G.add_edge('IN', 'A', weight = 1)
+ G.add_edge('IN', 'B', weight = 2)
+ G.add_edge('B', 'OUT', weight = 2)
+ assert_equal(list(nx.shortest_simple_paths(G, 'IN', 'OUT', weight = "weight")),
+ [['IN', 'OUT'], ['IN', 'B', 'OUT']])
+ G = nx.DiGraph()
+ G.add_edge('IN', 'OUT', weight = 10)
+ G.add_edge('IN', 'A', weight = 1)
+ G.add_edge('IN', 'B', weight = 1)
+ G.add_edge('B', 'OUT', weight = 1)
+ assert_equal(list(nx.shortest_simple_paths(G, 'IN', 'OUT', weight = "weight")),
+ [['IN', 'B', 'OUT'], ['IN', 'OUT']])
+
+
def test_weight_name():
G = nx.cycle_graph(7)
nx.set_edge_attributes(G, 1, 'weight')
@@ -303,6 +337,38 @@ def test_bidirectional_shortest_path_restricted_directed_cycle():
)
+def test_bidirectional_shortest_path_ignore():
+ G = nx.Graph()
+ nx.add_path(G, [1, 2])
+ nx.add_path(G, [1, 3])
+ nx.add_path(G, [1, 4])
+ assert_raises(
+ nx.NetworkXNoPath,
+ _bidirectional_shortest_path,
+ G,
+ 1, 2,
+ ignore_nodes=[1],
+ )
+ assert_raises(
+ nx.NetworkXNoPath,
+ _bidirectional_shortest_path,
+ G,
+ 1, 2,
+ ignore_nodes=[2],
+ )
+ G = nx.Graph()
+ nx.add_path(G, [1, 3])
+ nx.add_path(G, [1, 4])
+ nx.add_path(G, [3, 2])
+ assert_raises(
+ nx.NetworkXNoPath,
+ _bidirectional_shortest_path,
+ G,
+ 1, 2,
+ ignore_nodes=[1, 2],
+ )
+
+
def validate_path(G, s, t, soln_len, path):
assert_equal(path[0], s)
assert_equal(path[-1], t)
@@ -362,3 +428,30 @@ def test_bidirectional_dijkstra_no_path():
nx.add_path(G, [1, 2, 3])
nx.add_path(G, [4, 5, 6])
path = _bidirectional_dijkstra(G, 1, 6)
+
+
+def test_bidirectional_dijkstra_ignore():
+ G = nx.Graph()
+ nx.add_path(G, [1, 2, 10])
+ nx.add_path(G, [1, 3, 10])
+ assert_raises(
+ nx.NetworkXNoPath,
+ _bidirectional_dijkstra,
+ G,
+ 1, 2,
+ ignore_nodes=[1],
+ )
+ assert_raises(
+ nx.NetworkXNoPath,
+ _bidirectional_dijkstra,
+ G,
+ 1, 2,
+ ignore_nodes=[2],
+ )
+ assert_raises(
+ nx.NetworkXNoPath,
+ _bidirectional_dijkstra,
+ G,
+ 1, 2,
+ ignore_nodes=[1, 2],
+ )
| inter_community_non_edges ignore directionality
Hi,
I think the function:
nx.algorithms.community.quality.inter_community_non_edges()
does not work properly for directed graph. It always return the non-edge of a undirected graph, basically halving the number of edges. This mean that the performance function (nx.algorithms.community.performance) will never by higher than 50% for a directed graph.
I'm using version '2.0.dev_20170801111157', python 3.5.1
Best,
Nicolas | 0.0 | [
"networkx/algorithms/community/tests/test_quality.py::TestPerformance::test_bad_partition",
"networkx/algorithms/community/tests/test_quality.py::TestPerformance::test_good_partition",
"networkx/algorithms/community/tests/test_quality.py::TestCoverage::test_bad_partition",
"networkx/algorithms/community/tests/test_quality.py::TestCoverage::test_good_partition",
"networkx/algorithms/community/tests/test_quality.py::test_modularity",
"networkx/algorithms/community/tests/test_quality.py::test_inter_community_edges_with_digraphs",
"networkx/algorithms/tests/test_simple_paths.py::TestIsSimplePath::test_empty_list",
"networkx/algorithms/tests/test_simple_paths.py::TestIsSimplePath::test_trivial_path",
"networkx/algorithms/tests/test_simple_paths.py::TestIsSimplePath::test_trivial_nonpath",
"networkx/algorithms/tests/test_simple_paths.py::TestIsSimplePath::test_simple_path",
"networkx/algorithms/tests/test_simple_paths.py::TestIsSimplePath::test_non_simple_path",
"networkx/algorithms/tests/test_simple_paths.py::TestIsSimplePath::test_cycle",
"networkx/algorithms/tests/test_simple_paths.py::TestIsSimplePath::test_missing_node",
"networkx/algorithms/tests/test_simple_paths.py::TestIsSimplePath::test_directed_path",
"networkx/algorithms/tests/test_simple_paths.py::TestIsSimplePath::test_directed_non_path",
"networkx/algorithms/tests/test_simple_paths.py::TestIsSimplePath::test_directed_cycle",
"networkx/algorithms/tests/test_simple_paths.py::TestIsSimplePath::test_multigraph",
"networkx/algorithms/tests/test_simple_paths.py::TestIsSimplePath::test_multidigraph",
"networkx/algorithms/tests/test_simple_paths.py::test_all_simple_paths",
"networkx/algorithms/tests/test_simple_paths.py::test_all_simple_paths_cutoff",
"networkx/algorithms/tests/test_simple_paths.py::test_all_simple_paths_multigraph",
"networkx/algorithms/tests/test_simple_paths.py::test_all_simple_paths_multigraph_with_cutoff",
"networkx/algorithms/tests/test_simple_paths.py::test_all_simple_paths_directed",
"networkx/algorithms/tests/test_simple_paths.py::test_all_simple_paths_empty",
"networkx/algorithms/tests/test_simple_paths.py::test_hamiltonian_path",
"networkx/algorithms/tests/test_simple_paths.py::test_cutoff_zero",
"networkx/algorithms/tests/test_simple_paths.py::test_source_missing",
"networkx/algorithms/tests/test_simple_paths.py::test_target_missing",
"networkx/algorithms/tests/test_simple_paths.py::test_shortest_simple_paths",
"networkx/algorithms/tests/test_simple_paths.py::test_shortest_simple_paths_directed",
"networkx/algorithms/tests/test_simple_paths.py::test_Greg_Bernstein",
"networkx/algorithms/tests/test_simple_paths.py::test_weighted_shortest_simple_path",
"networkx/algorithms/tests/test_simple_paths.py::test_directed_weighted_shortest_simple_path",
"networkx/algorithms/tests/test_simple_paths.py::test_weighted_shortest_simple_path_issue2427",
"networkx/algorithms/tests/test_simple_paths.py::test_directed_weighted_shortest_simple_path_issue2427",
"networkx/algorithms/tests/test_simple_paths.py::test_weight_name",
"networkx/algorithms/tests/test_simple_paths.py::test_ssp_source_missing",
"networkx/algorithms/tests/test_simple_paths.py::test_ssp_target_missing",
"networkx/algorithms/tests/test_simple_paths.py::test_ssp_multigraph",
"networkx/algorithms/tests/test_simple_paths.py::test_bidirectional_shortest_path_restricted_cycle",
"networkx/algorithms/tests/test_simple_paths.py::test_bidirectional_shortest_path_restricted_wheel",
"networkx/algorithms/tests/test_simple_paths.py::test_bidirectional_shortest_path_restricted_directed_cycle",
"networkx/algorithms/tests/test_simple_paths.py::test_bidirectional_shortest_path_ignore",
"networkx/algorithms/tests/test_simple_paths.py::test_bidirectional_dijksta_restricted",
"networkx/algorithms/tests/test_simple_paths.py::test_bidirectional_dijkstra_no_path",
"networkx/algorithms/tests/test_simple_paths.py::test_bidirectional_dijkstra_ignore"
] | [] | 2017-10-15 17:09:15+00:00 | 4,131 |
|
networkx__networkx-3822 | diff --git a/networkx/generators/random_graphs.py b/networkx/generators/random_graphs.py
index e4f2c569d..745f64e4d 100644
--- a/networkx/generators/random_graphs.py
+++ b/networkx/generators/random_graphs.py
@@ -1000,6 +1000,11 @@ def random_lobster(n, p1, p2, seed=None):
leaf nodes. A caterpillar is a tree that reduces to a path graph
when pruning all leaf nodes; setting `p2` to zero produces a caterpillar.
+ This implementation iterates on the probabilities `p1` and `p2` to add
+ edges at levels 1 and 2, respectively. Graphs are therefore constructed
+ iteratively with uniform randomness at each level rather than being selected
+ uniformly at random from the set of all possible lobsters.
+
Parameters
----------
n : int
@@ -1011,19 +1016,29 @@ def random_lobster(n, p1, p2, seed=None):
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
+
+ Raises
+ ------
+ NetworkXError
+ If `p1` or `p2` parameters are >= 1 because the while loops would never finish.
"""
+ p1, p2 = abs(p1), abs(p2)
+ if any([p >= 1 for p in [p1, p2]]):
+ raise nx.NetworkXError("Probability values for `p1` and `p2` must both be < 1.")
+
# a necessary ingredient in any self-respecting graph library
llen = int(2 * seed.random() * n + 0.5)
L = path_graph(llen)
# build caterpillar: add edges to path graph with probability p1
current_node = llen - 1
for n in range(llen):
- if seed.random() < p1: # add fuzzy caterpillar parts
+ while seed.random() < p1: # add fuzzy caterpillar parts
current_node += 1
L.add_edge(n, current_node)
- if seed.random() < p2: # add crunchy lobster bits
+ cat_node = current_node
+ while seed.random() < p2: # add crunchy lobster bits
current_node += 1
- L.add_edge(current_node - 1, current_node)
+ L.add_edge(cat_node, current_node)
return L # voila, un lobster!
| networkx/networkx | a4d024c54f06d17d2f9ab26595a0b20ed6858f5c | diff --git a/networkx/generators/tests/test_random_graphs.py b/networkx/generators/tests/test_random_graphs.py
index f958dceab..8f2d68415 100644
--- a/networkx/generators/tests/test_random_graphs.py
+++ b/networkx/generators/tests/test_random_graphs.py
@@ -91,7 +91,38 @@ class TestGeneratorsRandom:
constructor = [(10, 20, 0.8), (20, 40, 0.8)]
G = random_shell_graph(constructor, seed)
+ def is_caterpillar(g):
+ """
+ A tree is a caterpillar iff all nodes of degree >=3 are surrounded
+ by at most two nodes of degree two or greater.
+ ref: http://mathworld.wolfram.com/CaterpillarGraph.html
+ """
+ deg_over_3 = [n for n in g if g.degree(n) >= 3]
+ for n in deg_over_3:
+ nbh_deg_over_2 = [nbh for nbh in g.neighbors(n) if g.degree(nbh) >= 2]
+ if not len(nbh_deg_over_2) <= 2:
+ return False
+ return True
+
+ def is_lobster(g):
+ """
+ A tree is a lobster if it has the property that the removal of leaf
+ nodes leaves a caterpillar graph (Gallian 2007)
+ ref: http://mathworld.wolfram.com/LobsterGraph.html
+ """
+ non_leafs = [n for n in g if g.degree(n) > 1]
+ return is_caterpillar(g.subgraph(non_leafs))
+
G = random_lobster(10, 0.1, 0.5, seed)
+ assert max([G.degree(n) for n in G.nodes()]) > 3
+ assert is_lobster(G)
+ pytest.raises(NetworkXError, random_lobster, 10, 0.1, 1, seed)
+ pytest.raises(NetworkXError, random_lobster, 10, 1, 1, seed)
+ pytest.raises(NetworkXError, random_lobster, 10, 1, 0.5, seed)
+
+ # docstring says this should be a caterpillar
+ G = random_lobster(10, 0.1, 0.0, seed)
+ assert is_caterpillar(G)
# difficult to find seed that requires few tries
seq = random_powerlaw_tree_sequence(10, 3, seed=14, tries=1)
| Wrong random_lobster implementation?
Hi, it seems that [networkx.random_lobster's implementation logic](https://github.com/networkx/networkx/blob/4e9771f04192e94a5cbdd71249a983d124a56593/networkx/generators/random_graphs.py#L1009) is not aligned with the common definition as given in [wolfram mathworld](http://mathworld.wolfram.com/LobsterGraph.html) or [Wikipedia](https://en.wikipedia.org/wiki/List_of_graphs#Lobster).
For example, it can not produce the simplest lobster graph examples such as . | 0.0 | [
"networkx/generators/tests/test_random_graphs.py::TestGeneratorsRandom::test_random_graph"
] | [
"networkx/generators/tests/test_random_graphs.py::TestGeneratorsRandom::test_dual_barabasi_albert",
"networkx/generators/tests/test_random_graphs.py::TestGeneratorsRandom::test_extended_barabasi_albert",
"networkx/generators/tests/test_random_graphs.py::TestGeneratorsRandom::test_random_zero_regular_graph",
"networkx/generators/tests/test_random_graphs.py::TestGeneratorsRandom::test_gnp",
"networkx/generators/tests/test_random_graphs.py::TestGeneratorsRandom::test_gnm",
"networkx/generators/tests/test_random_graphs.py::TestGeneratorsRandom::test_watts_strogatz_big_k",
"networkx/generators/tests/test_random_graphs.py::TestGeneratorsRandom::test_random_kernel_graph"
] | 2020-02-16 23:49:40+00:00 | 4,132 |
|
networkx__networkx-3848 | diff --git a/networkx/algorithms/connectivity/cuts.py b/networkx/algorithms/connectivity/cuts.py
index 846cd4729..dd59e3db9 100644
--- a/networkx/algorithms/connectivity/cuts.py
+++ b/networkx/algorithms/connectivity/cuts.py
@@ -281,7 +281,7 @@ def minimum_st_node_cut(G, s, t, flow_func=None, auxiliary=None, residual=None):
if mapping is None:
raise nx.NetworkXError('Invalid auxiliary digraph.')
if G.has_edge(s, t) or G.has_edge(t, s):
- return []
+ return {}
kwargs = dict(flow_func=flow_func, residual=residual, auxiliary=H)
# The edge cut in the auxiliary digraph corresponds to the node cut in the
| networkx/networkx | 3f4f9c3379a5d70fc58852154aab7b1051ff96d6 | diff --git a/networkx/algorithms/connectivity/tests/test_cuts.py b/networkx/algorithms/connectivity/tests/test_cuts.py
index b98fbfa5e..257797a6f 100644
--- a/networkx/algorithms/connectivity/tests/test_cuts.py
+++ b/networkx/algorithms/connectivity/tests/test_cuts.py
@@ -268,7 +268,7 @@ def tests_minimum_st_node_cut():
G.add_nodes_from([0, 1, 2, 3, 7, 8, 11, 12])
G.add_edges_from([(7, 11), (1, 11), (1, 12), (12, 8), (0, 1)])
nodelist = minimum_st_node_cut(G, 7, 11)
- assert(nodelist == [])
+ assert(nodelist == {})
def test_invalid_auxiliary():
| `minimum_st_node_cut` returns empty list instead of set for adjacent nodes
https://github.com/networkx/networkx/blob/3f4f9c3379a5d70fc58852154aab7b1051ff96d6/networkx/algorithms/connectivity/cuts.py#L284
Should read `return {}`. Was questioning my sanity for a bit there 😉 | 0.0 | [
"networkx/algorithms/connectivity/tests/test_cuts.py::tests_minimum_st_node_cut"
] | [
"networkx/algorithms/connectivity/tests/test_cuts.py::test_articulation_points",
"networkx/algorithms/connectivity/tests/test_cuts.py::test_brandes_erlebach_book",
"networkx/algorithms/connectivity/tests/test_cuts.py::test_white_harary_paper",
"networkx/algorithms/connectivity/tests/test_cuts.py::test_petersen_cutset",
"networkx/algorithms/connectivity/tests/test_cuts.py::test_octahedral_cutset",
"networkx/algorithms/connectivity/tests/test_cuts.py::test_icosahedral_cutset",
"networkx/algorithms/connectivity/tests/test_cuts.py::test_node_cutset_exception",
"networkx/algorithms/connectivity/tests/test_cuts.py::test_node_cutset_random_graphs",
"networkx/algorithms/connectivity/tests/test_cuts.py::test_edge_cutset_random_graphs",
"networkx/algorithms/connectivity/tests/test_cuts.py::test_empty_graphs",
"networkx/algorithms/connectivity/tests/test_cuts.py::test_unbounded",
"networkx/algorithms/connectivity/tests/test_cuts.py::test_missing_source",
"networkx/algorithms/connectivity/tests/test_cuts.py::test_missing_target",
"networkx/algorithms/connectivity/tests/test_cuts.py::test_not_weakly_connected",
"networkx/algorithms/connectivity/tests/test_cuts.py::test_not_connected",
"networkx/algorithms/connectivity/tests/test_cuts.py::tests_min_cut_complete",
"networkx/algorithms/connectivity/tests/test_cuts.py::tests_min_cut_complete_directed",
"networkx/algorithms/connectivity/tests/test_cuts.py::test_invalid_auxiliary",
"networkx/algorithms/connectivity/tests/test_cuts.py::test_interface_only_source",
"networkx/algorithms/connectivity/tests/test_cuts.py::test_interface_only_target"
] | 2020-03-04 08:11:36+00:00 | 4,133 |
|
networkx__networkx-4066 | diff --git a/networkx/relabel.py b/networkx/relabel.py
index 737b5af3d..26f50d241 100644
--- a/networkx/relabel.py
+++ b/networkx/relabel.py
@@ -13,7 +13,7 @@ def relabel_nodes(G, mapping, copy=True):
mapping : dictionary
A dictionary with the old labels as keys and new labels as values.
- A partial mapping is allowed.
+ A partial mapping is allowed. Mapping 2 nodes to a single node is allowed.
copy : bool (optional, default=True)
If True return a copy, or if False relabel the nodes in place.
@@ -64,6 +64,27 @@ def relabel_nodes(G, mapping, copy=True):
>>> list(H)
[0, 1, 4]
+ In a multigraph, relabeling two or more nodes to the same new node
+ will retain all edges, but may change the edge keys in the process:
+
+ >>> G = nx.MultiGraph()
+ >>> G.add_edge(0, 1, value="a") # returns the key for this edge
+ 0
+ >>> G.add_edge(0, 2, value="b")
+ 0
+ >>> G.add_edge(0, 3, value="c")
+ 0
+ >>> mapping = {1: 4, 2: 4, 3: 4}
+ >>> H = nx.relabel_nodes(G, mapping, copy=True)
+ >>> print(H[0])
+ {4: {0: {'value': 'a'}, 1: {'value': 'b'}, 2: {'value': 'c'}}}
+
+ This works for in-place relabeling too:
+
+ >>> G = nx.relabel_nodes(G, mapping, copy=False)
+ >>> print(G[0])
+ {4: {0: {'value': 'a'}, 1: {'value': 'b'}, 2: {'value': 'c'}}}
+
Notes
-----
Only the nodes specified in the mapping will be relabeled.
@@ -77,6 +98,13 @@ def relabel_nodes(G, mapping, copy=True):
graph is not possible in-place and an exception is raised.
In that case, use copy=True.
+ If a relabel operation on a multigraph would cause two or more
+ edges to have the same source, target and key, the second edge must
+ be assigned a new key to retain all edges. The new key is set
+ to the lowest non-negative integer not already used as a key
+ for edges between these two nodes. Note that this means non-numeric
+ keys may be replaced by numeric keys.
+
See Also
--------
convert_node_labels_to_integers
@@ -136,6 +164,15 @@ def _relabel_inplace(G, mapping):
(new if old == source else source, new, key, data)
for (source, _, key, data) in G.in_edges(old, data=True, keys=True)
]
+ # Ensure new edges won't overwrite existing ones
+ seen = set()
+ for i, (source, target, key, data) in enumerate(new_edges):
+ if (target in G[source] and key in G[source][target]):
+ new_key = 0 if not isinstance(key, (int, float)) else key
+ while (new_key in G[source][target] or (target, new_key) in seen):
+ new_key += 1
+ new_edges[i] = (source, target, new_key, data)
+ seen.add((target, new_key))
else:
new_edges = [
(new, new if old == target else target, data)
@@ -156,10 +193,25 @@ def _relabel_copy(G, mapping):
H.add_nodes_from(mapping.get(n, n) for n in G)
H._node.update((mapping.get(n, n), d.copy()) for n, d in G.nodes.items())
if G.is_multigraph():
- H.add_edges_from(
+ new_edges = [
(mapping.get(n1, n1), mapping.get(n2, n2), k, d.copy())
for (n1, n2, k, d) in G.edges(keys=True, data=True)
- )
+ ]
+
+ # check for conflicting edge-keys
+ undirected = not G.is_directed()
+ seen_edges = set()
+ for i, (source, target, key, data) in enumerate(new_edges):
+ while (source, target, key) in seen_edges:
+ if not isinstance(key, (int, float)):
+ key = 0
+ key += 1
+ seen_edges.add((source, target, key))
+ if undirected:
+ seen_edges.add((target, source, key))
+ new_edges[i] = (source, target, key, data)
+
+ H.add_edges_from(new_edges)
else:
H.add_edges_from(
(mapping.get(n1, n1), mapping.get(n2, n2), d.copy())
| networkx/networkx | 5638e1ff3d01e21c7d950615a699eb1f99987b8d | diff --git a/networkx/tests/test_relabel.py b/networkx/tests/test_relabel.py
index 9b8ad2998..909904bc9 100644
--- a/networkx/tests/test_relabel.py
+++ b/networkx/tests/test_relabel.py
@@ -183,3 +183,109 @@ class TestRelabel:
G = nx.MultiDiGraph([(1, 1)])
G = nx.relabel_nodes(G, {1: 0}, copy=False)
assert_nodes_equal(G.nodes(), [0])
+
+# def test_relabel_multidigraph_inout_inplace(self):
+# pass
+ def test_relabel_multidigraph_inout_merge_nodes(self):
+ for MG in (nx.MultiGraph, nx.MultiDiGraph):
+ for cc in (True, False):
+ G = MG([(0, 4), (1, 4), (4, 2), (4, 3)])
+ G[0][4][0]["value"] = "a"
+ G[1][4][0]["value"] = "b"
+ G[4][2][0]["value"] = "c"
+ G[4][3][0]["value"] = "d"
+ G.add_edge(0, 4, key="x", value="e")
+ G.add_edge(4, 3, key="x", value="f")
+ mapping = {0: 9, 1: 9, 2: 9, 3: 9}
+ H = nx.relabel_nodes(G, mapping, copy=cc)
+ # No ordering on keys enforced
+ assert {"value": "a"} in H[9][4].values()
+ assert {"value": "b"} in H[9][4].values()
+ assert {"value": "c"} in H[4][9].values()
+ assert len(H[4][9]) == 3 if G.is_directed() else 6
+ assert {"value": "d"} in H[4][9].values()
+ assert {"value": "e"} in H[9][4].values()
+ assert {"value": "f"} in H[4][9].values()
+ assert len(H[9][4]) == 3 if G.is_directed() else 6
+
+ def test_relabel_multigraph_merge_inplace(self):
+ G = nx.MultiGraph([(0, 1), (0, 2), (0, 3), (0, 1), (0, 2), (0, 3)])
+ G[0][1][0]["value"] = "a"
+ G[0][2][0]["value"] = "b"
+ G[0][3][0]["value"] = "c"
+ mapping = {1: 4, 2: 4, 3: 4}
+ nx.relabel_nodes(G, mapping, copy=False)
+ # No ordering on keys enforced
+ assert {"value": "a"} in G[0][4].values()
+ assert {"value": "b"} in G[0][4].values()
+ assert {"value": "c"} in G[0][4].values()
+
+ def test_relabel_multidigraph_merge_inplace(self):
+ G = nx.MultiDiGraph([(0, 1), (0, 2), (0, 3)])
+ G[0][1][0]["value"] = "a"
+ G[0][2][0]["value"] = "b"
+ G[0][3][0]["value"] = "c"
+ mapping = {1: 4, 2: 4, 3: 4}
+ nx.relabel_nodes(G, mapping, copy=False)
+ # No ordering on keys enforced
+ assert {"value": "a"} in G[0][4].values()
+ assert {"value": "b"} in G[0][4].values()
+ assert {"value": "c"} in G[0][4].values()
+
+ def test_relabel_multidigraph_inout_copy(self):
+ G = nx.MultiDiGraph([(0, 4), (1, 4), (4, 2), (4, 3)])
+ G[0][4][0]["value"] = "a"
+ G[1][4][0]["value"] = "b"
+ G[4][2][0]["value"] = "c"
+ G[4][3][0]["value"] = "d"
+ G.add_edge(0, 4, key="x", value="e")
+ G.add_edge(4, 3, key="x", value="f")
+ mapping = {0: 9, 1: 9, 2: 9, 3: 9}
+ H = nx.relabel_nodes(G, mapping, copy=True)
+ # No ordering on keys enforced
+ assert {"value": "a"} in H[9][4].values()
+ assert {"value": "b"} in H[9][4].values()
+ assert {"value": "c"} in H[4][9].values()
+ assert len(H[4][9]) == 3
+ assert {"value": "d"} in H[4][9].values()
+ assert {"value": "e"} in H[9][4].values()
+ assert {"value": "f"} in H[4][9].values()
+ assert len(H[9][4]) == 3
+
+ def test_relabel_multigraph_merge_copy(self):
+ G = nx.MultiGraph([(0, 1), (0, 2), (0, 3)])
+ G[0][1][0]["value"] = "a"
+ G[0][2][0]["value"] = "b"
+ G[0][3][0]["value"] = "c"
+ mapping = {1: 4, 2: 4, 3: 4}
+ H = nx.relabel_nodes(G, mapping, copy=True)
+ assert {"value": "a"} in H[0][4].values()
+ assert {"value": "b"} in H[0][4].values()
+ assert {"value": "c"} in H[0][4].values()
+
+ def test_relabel_multidigraph_merge_copy(self):
+ G = nx.MultiDiGraph([(0, 1), (0, 2), (0, 3)])
+ G[0][1][0]["value"] = "a"
+ G[0][2][0]["value"] = "b"
+ G[0][3][0]["value"] = "c"
+ mapping = {1: 4, 2: 4, 3: 4}
+ H = nx.relabel_nodes(G, mapping, copy=True)
+ assert {"value": "a"} in H[0][4].values()
+ assert {"value": "b"} in H[0][4].values()
+ assert {"value": "c"} in H[0][4].values()
+
+ def test_relabel_multigraph_nonnumeric_key(self):
+ for MG in (nx.MultiGraph, nx.MultiDiGraph):
+ for cc in (True, False):
+ G = nx.MultiGraph()
+ G.add_edge(0, 1, key="I", value="a")
+ G.add_edge(0, 2, key="II", value="b")
+ G.add_edge(0, 3, key="II", value="c")
+ mapping = {1: 4, 2: 4, 3: 4}
+ nx.relabel_nodes(G, mapping, copy=False)
+ assert {"value": "a"} in G[0][4].values()
+ assert {"value": "b"} in G[0][4].values()
+ assert {"value": "c"} in G[0][4].values()
+ assert 0 in G[0][4]
+ assert "I" in G[0][4]
+ assert "II" in G[0][4]
| relabel_nodes on MultiGraphs does not preserve both edges when two nodes are replaced by one
When the graph contains edges (0,1) and (0,2), and I relabel both 1 and 2 to 3, I expected two edges from (0,3) but only one node is preserved.
Multi*Graph supports parallel edges between nodes and I expected it to preserve both edges when "merging" the two old nodes together.
Tested on both networkx 2.4 and the latest version on master.
```python
import networkx as nx
G = nx.MultiDiGraph([(0,1),(0,2)])
G[0][1][0]["value"] = "a"
G[0][2][0]["value"] = "b"
print(G[0])
# Output:
# {1: {0: {'value': 'a'}}, 2: {0: {'value': 'b'}}}
mapping = {1:3, 2:3}
nx.relabel_nodes(G, mapping, copy=False)
print(G[0])
# Output:
# {3: {0: {'value': 'b'}}}
# Expected:
# {3: {0: {'value': 'a'}, 1: {'value': 'b'}}}
``` | 0.0 | [
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_multidigraph_inout_merge_nodes",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_multigraph_merge_inplace",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_multidigraph_merge_inplace",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_multidigraph_inout_copy",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_multigraph_merge_copy",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_multidigraph_merge_copy",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_multigraph_nonnumeric_key"
] | [
"networkx/tests/test_relabel.py::TestRelabel::test_convert_node_labels_to_integers",
"networkx/tests/test_relabel.py::TestRelabel::test_convert_to_integers2",
"networkx/tests/test_relabel.py::TestRelabel::test_convert_to_integers_raise",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_nodes_copy",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_nodes_function",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_nodes_graph",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_nodes_orderedgraph",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_nodes_digraph",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_nodes_multigraph",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_nodes_multidigraph",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_isolated_nodes_to_same",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_nodes_missing",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_copy_name",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_toposort",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_selfloop"
] | 2020-07-11 12:56:42+00:00 | 4,134 |
|
networkx__networkx-4125 | diff --git a/networkx/readwrite/edgelist.py b/networkx/readwrite/edgelist.py
index 72afe1a7c..5183071d1 100644
--- a/networkx/readwrite/edgelist.py
+++ b/networkx/readwrite/edgelist.py
@@ -270,7 +270,11 @@ def parse_edgelist(
elif data is True:
# no edge types specified
try: # try to evaluate as dictionary
- edgedata = dict(literal_eval(" ".join(d)))
+ if delimiter == ",":
+ edgedata_str = ",".join(d)
+ else:
+ edgedata_str = " ".join(d)
+ edgedata = dict(literal_eval(edgedata_str.strip()))
except BaseException as e:
raise TypeError(
f"Failed to convert edge data ({d}) " f"to dictionary."
| networkx/networkx | ab7429c62806f1242c36fb81c1b1d801b4cca7a3 | diff --git a/networkx/readwrite/tests/test_edgelist.py b/networkx/readwrite/tests/test_edgelist.py
index 2e1a2424f..31f214566 100644
--- a/networkx/readwrite/tests/test_edgelist.py
+++ b/networkx/readwrite/tests/test_edgelist.py
@@ -100,6 +100,48 @@ class TestEdgelist:
G.edges(data=True), [(1, 2, {"weight": 2.0}), (2, 3, {"weight": 3.0})]
)
+ def test_read_edgelist_5(self):
+ s = b"""\
+# comment line
+1 2 {'weight':2.0, 'color':'green'}
+# comment line
+2 3 {'weight':3.0, 'color':'red'}
+"""
+ bytesIO = io.BytesIO(s)
+ G = nx.read_edgelist(bytesIO, nodetype=int, data=False)
+ assert_edges_equal(G.edges(), [(1, 2), (2, 3)])
+
+ bytesIO = io.BytesIO(s)
+ G = nx.read_edgelist(bytesIO, nodetype=int, data=True)
+ assert_edges_equal(
+ G.edges(data=True),
+ [
+ (1, 2, {"weight": 2.0, "color": "green"}),
+ (2, 3, {"weight": 3.0, "color": "red"}),
+ ],
+ )
+
+ def test_read_edgelist_6(self):
+ s = b"""\
+# comment line
+1, 2, {'weight':2.0, 'color':'green'}
+# comment line
+2, 3, {'weight':3.0, 'color':'red'}
+"""
+ bytesIO = io.BytesIO(s)
+ G = nx.read_edgelist(bytesIO, nodetype=int, data=False, delimiter=",")
+ assert_edges_equal(G.edges(), [(1, 2), (2, 3)])
+
+ bytesIO = io.BytesIO(s)
+ G = nx.read_edgelist(bytesIO, nodetype=int, data=True, delimiter=",")
+ assert_edges_equal(
+ G.edges(data=True),
+ [
+ (1, 2, {"weight": 2.0, "color": "green"}),
+ (2, 3, {"weight": 3.0, "color": "red"}),
+ ],
+ )
+
def test_write_edgelist_1(self):
fh = io.BytesIO()
G = nx.OrderedGraph()
| Parse edgelist bug
When calling `parse_edgelist()` using comma delimiters, it will fail to parse correctly fro edges with multiple attributes.
Ex. of bad edge:
`1,2,{'test':1, 'test_other':2}`
`parse_edgelist()` will recognize the comma in the braces as delimiter and try to split them up. | 0.0 | [
"networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_read_edgelist_6"
] | [
"networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_read_edgelist_1",
"networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_read_edgelist_2",
"networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_read_edgelist_3",
"networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_read_edgelist_4",
"networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_read_edgelist_5",
"networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_write_edgelist_1",
"networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_write_edgelist_2",
"networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_write_edgelist_3",
"networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_write_edgelist_4",
"networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_unicode",
"networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_latin1_issue",
"networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_latin1",
"networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_edgelist_graph",
"networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_edgelist_digraph",
"networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_edgelist_integers",
"networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_edgelist_multigraph",
"networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_edgelist_multidigraph"
] | 2020-08-03 00:13:47+00:00 | 4,135 |
|
networkx__networkx-4246 | diff --git a/networkx/algorithms/centrality/betweenness.py b/networkx/algorithms/centrality/betweenness.py
index 0829d9b0b..6907f25b1 100644
--- a/networkx/algorithms/centrality/betweenness.py
+++ b/networkx/algorithms/centrality/betweenness.py
@@ -101,20 +101,20 @@ def betweenness_centrality(
.. [1] Ulrik Brandes:
A Faster Algorithm for Betweenness Centrality.
Journal of Mathematical Sociology 25(2):163-177, 2001.
- http://www.inf.uni-konstanz.de/algo/publications/b-fabc-01.pdf
+ https://doi.org/10.1080/0022250X.2001.9990249
.. [2] Ulrik Brandes:
On Variants of Shortest-Path Betweenness
Centrality and their Generic Computation.
Social Networks 30(2):136-145, 2008.
- http://www.inf.uni-konstanz.de/algo/publications/b-vspbc-08.pdf
+ https://doi.org/10.1016/j.socnet.2007.11.001
.. [3] Ulrik Brandes and Christian Pich:
Centrality Estimation in Large Networks.
International Journal of Bifurcation and Chaos 17(7):2303-2318, 2007.
- http://www.inf.uni-konstanz.de/algo/publications/bp-celn-06.pdf
+ https://dx.doi.org/10.1142/S0218127407018403
.. [4] Linton C. Freeman:
A set of measures of centrality based on betweenness.
Sociometry 40: 35–41, 1977
- http://moreno.ss.uci.edu/23.pdf
+ https://doi.org/10.2307/3033543
"""
betweenness = dict.fromkeys(G, 0.0) # b[v]=0 for v in G
if k is None:
diff --git a/networkx/algorithms/euler.py b/networkx/algorithms/euler.py
index 6f8283f27..52042580a 100644
--- a/networkx/algorithms/euler.py
+++ b/networkx/algorithms/euler.py
@@ -224,7 +224,7 @@ def has_eulerian_path(G):
- at most one vertex has in_degree - out_degree = 1,
- every other vertex has equal in_degree and out_degree,
- and all of its vertices with nonzero degree belong to a
- - single connected component of the underlying undirected graph.
+ single connected component of the underlying undirected graph.
An undirected graph has an Eulerian path iff:
- exactly zero or two vertices have odd degree,
@@ -246,16 +246,28 @@ def has_eulerian_path(G):
eulerian_path
"""
if G.is_directed():
+ # Remove isolated nodes (if any) without altering the input graph
+ nodes_remove = [v for v in G if G.in_degree[v] == 0 and G.out_degree[v] == 0]
+ if nodes_remove:
+ G = G.copy()
+ G.remove_nodes_from(nodes_remove)
+
ins = G.in_degree
outs = G.out_degree
- semibalanced_ins = sum(ins(v) - outs(v) == 1 for v in G)
- semibalanced_outs = sum(outs(v) - ins(v) == 1 for v in G)
+ unbalanced_ins = 0
+ unbalanced_outs = 0
+ for v in G:
+ if ins[v] - outs[v] == 1:
+ unbalanced_ins += 1
+ elif outs[v] - ins[v] == 1:
+ unbalanced_outs += 1
+ elif ins[v] != outs[v]:
+ return False
+
return (
- semibalanced_ins <= 1
- and semibalanced_outs <= 1
- and sum(G.in_degree(v) != G.out_degree(v) for v in G) <= 2
- and nx.is_weakly_connected(G)
+ unbalanced_ins <= 1 and unbalanced_outs <= 1 and nx.is_weakly_connected(G)
)
+
else:
return sum(d % 2 == 1 for v, d in G.degree()) in (0, 2) and nx.is_connected(G)
diff --git a/networkx/algorithms/minors.py b/networkx/algorithms/minors.py
index 336fe254f..7958bceca 100644
--- a/networkx/algorithms/minors.py
+++ b/networkx/algorithms/minors.py
@@ -445,37 +445,36 @@ def contracted_nodes(G, u, v, self_loops=True, copy=True):
not be the same as the edge keys for the old edges. This is
natural because edge keys are unique only within each pair of nodes.
+ This function is also available as `identified_nodes`.
+
Examples
--------
Contracting two nonadjacent nodes of the cycle graph on four nodes `C_4`
yields the path graph (ignoring parallel edges)::
- >>> G = nx.cycle_graph(4)
- >>> M = nx.contracted_nodes(G, 1, 3)
- >>> P3 = nx.path_graph(3)
- >>> nx.is_isomorphic(M, P3)
- True
-
- >>> G = nx.MultiGraph(P3)
- >>> M = nx.contracted_nodes(G, 0, 2)
- >>> M.edges
- MultiEdgeView([(0, 1, 0), (0, 1, 1)])
-
- >>> G = nx.Graph([(1, 2), (2, 2)])
- >>> H = nx.contracted_nodes(G, 1, 2, self_loops=False)
- >>> list(H.nodes())
- [1]
- >>> list(H.edges())
- [(1, 1)]
-
- See also
+ >>> G = nx.cycle_graph(4)
+ >>> M = nx.contracted_nodes(G, 1, 3)
+ >>> P3 = nx.path_graph(3)
+ >>> nx.is_isomorphic(M, P3)
+ True
+
+ >>> G = nx.MultiGraph(P3)
+ >>> M = nx.contracted_nodes(G, 0, 2)
+ >>> M.edges
+ MultiEdgeView([(0, 1, 0), (0, 1, 1)])
+
+ >>> G = nx.Graph([(1, 2), (2, 2)])
+ >>> H = nx.contracted_nodes(G, 1, 2, self_loops=False)
+ >>> list(H.nodes())
+ [1]
+ >>> list(H.edges())
+ [(1, 1)]
+
+ See Also
--------
contracted_edge
quotient_graph
- Notes
- -----
- This function is also available as `identified_nodes`.
"""
# Copying has significant overhead and can be disabled if needed
if copy:
diff --git a/networkx/classes/function.py b/networkx/classes/function.py
index d17e22f60..700cac158 100644
--- a/networkx/classes/function.py
+++ b/networkx/classes/function.py
@@ -576,23 +576,14 @@ def info(G, n=None):
"""
if n is None:
- n_nodes = G.number_of_nodes()
- n_edges = G.number_of_edges()
- return "".join(
- [
- type(G).__name__,
- f" named '{G.name}'" if G.name else "",
- f" with {n_nodes} nodes and {n_edges} edges",
- ]
- )
- else:
- if n not in G:
- raise nx.NetworkXError(f"node {n} not in graph")
- info = "" # append this all to a string
- info += f"Node {n} has the following properties:\n"
- info += f"Degree: {G.degree(n)}\n"
- info += "Neighbors: "
- info += " ".join(str(nbr) for nbr in G.neighbors(n))
+ return str(G)
+ if n not in G:
+ raise nx.NetworkXError(f"node {n} not in graph")
+ info = "" # append this all to a string
+ info += f"Node {n} has the following properties:\n"
+ info += f"Degree: {G.degree(n)}\n"
+ info += "Neighbors: "
+ info += " ".join(str(nbr) for nbr in G.neighbors(n))
return info
diff --git a/networkx/classes/graph.py b/networkx/classes/graph.py
index ae34047bc..8629ee808 100644
--- a/networkx/classes/graph.py
+++ b/networkx/classes/graph.py
@@ -370,20 +370,31 @@ class Graph:
self.graph["name"] = s
def __str__(self):
- """Returns the graph name.
+ """Returns a short summary of the graph.
Returns
-------
- name : string
- The name of the graph.
+ info : string
+ Graph information as provided by `nx.info`
Examples
--------
>>> G = nx.Graph(name="foo")
>>> str(G)
- 'foo'
+ "Graph named 'foo' with 0 nodes and 0 edges"
+
+ >>> G = nx.path_graph(3)
+ >>> str(G)
+ 'Graph with 3 nodes and 2 edges'
+
"""
- return self.name
+ return "".join(
+ [
+ type(self).__name__,
+ f" named '{self.name}'" if self.name else "",
+ f" with {self.number_of_nodes()} nodes and {self.number_of_edges()} edges",
+ ]
+ )
def __iter__(self):
"""Iterate over the nodes. Use: 'for n in G'.
| networkx/networkx | 2f0c56ffdc923c5fce04935447772ba9f68b69f9 | diff --git a/networkx/algorithms/tests/test_euler.py b/networkx/algorithms/tests/test_euler.py
index f136ab0ff..4a0905bc8 100644
--- a/networkx/algorithms/tests/test_euler.py
+++ b/networkx/algorithms/tests/test_euler.py
@@ -134,6 +134,22 @@ class TestHasEulerianPath:
G = nx.path_graph(6, create_using=nx.DiGraph)
assert nx.has_eulerian_path(G)
+ def test_has_eulerian_path_directed_graph(self):
+ # Test directed graphs and returns False
+ G = nx.DiGraph()
+ G.add_edges_from([(0, 1), (1, 2), (0, 2)])
+ assert not nx.has_eulerian_path(G)
+
+ def test_has_eulerian_path_isolated_node(self):
+ # Test directed graphs without isolated node returns True
+ G = nx.DiGraph()
+ G.add_edges_from([(0, 1), (1, 2), (2, 0)])
+ assert nx.has_eulerian_path(G)
+
+ # Test directed graphs with isolated node returns True
+ G.add_node(3)
+ assert nx.has_eulerian_path(G)
+
class TestFindPathStart:
def testfind_path_start(self):
diff --git a/networkx/classes/tests/historical_tests.py b/networkx/classes/tests/historical_tests.py
index 8f53c4c53..c19396add 100644
--- a/networkx/classes/tests/historical_tests.py
+++ b/networkx/classes/tests/historical_tests.py
@@ -21,7 +21,6 @@ class HistoricalTests:
def test_name(self):
G = self.G(name="test")
- assert str(G) == "test"
assert G.name == "test"
H = self.G()
assert H.name == ""
diff --git a/networkx/classes/tests/test_graph.py b/networkx/classes/tests/test_graph.py
index 03902b092..e90f99510 100644
--- a/networkx/classes/tests/test_graph.py
+++ b/networkx/classes/tests/test_graph.py
@@ -182,9 +182,18 @@ class BaseAttrGraphTester(BaseGraphTester):
G = self.Graph(name="")
assert G.name == ""
G = self.Graph(name="test")
- assert G.__str__() == "test"
assert G.name == "test"
+ def test_str_unnamed(self):
+ G = self.Graph()
+ G.add_edges_from([(1, 2), (2, 3)])
+ assert str(G) == f"{type(G).__name__} with 3 nodes and 2 edges"
+
+ def test_str_named(self):
+ G = self.Graph(name="foo")
+ G.add_edges_from([(1, 2), (2, 3)])
+ assert str(G) == f"{type(G).__name__} named 'foo' with 3 nodes and 2 edges"
+
def test_graph_chain(self):
G = self.Graph([(0, 1), (1, 2)])
DG = G.to_directed(as_view=True)
| Issue with networkx.has_eulerian_path()
This issue adds to #3976
There appears to be a problem with the `has_eulerian_path` function. It returns the wrong answer on this example:
```
test_graph = nx.DiGraph()
test_graph.add_edges_from([(0, 1), (1,2), (0,2)])
print(nx.has_eulerian_path(test_graph))
print(list(nx.eulerian_path(test_graph)))
```
Output:
```
True
[(0, 0), (0, 1), (1, 2)]
```
This directed graph does not have a Eulerian path, and, adding to #3976, the path returned by `eulerian_path` is not an actual Eulerian path, since it (1) does not include the edge `(0,2)` and (2) includes a self-loop `(0,0)` that is not in the graph.
My hunch is that the problem is in this line: https://github.com/networkx/networkx/blob/3351206a3ce5b3a39bb2fc451e93ef545b96c95b/networkx/algorithms/euler.py#L256
I think changing that `2` to be `semibalanced_ins+semibalanced_outs` may do the trick, since the definition is
>"...every _other_ vertex has equal in\_degree and out\_degree..."
Going to see about fixing and adding this test. Appreciate any clues, ideas or tips.
| 0.0 | [
"networkx/algorithms/tests/test_euler.py::TestHasEulerianPath::test_has_eulerian_path_directed_graph",
"networkx/algorithms/tests/test_euler.py::TestHasEulerianPath::test_has_eulerian_path_isolated_node",
"networkx/classes/tests/test_graph.py::TestGraph::test_str_unnamed",
"networkx/classes/tests/test_graph.py::TestGraph::test_str_named"
] | [
"networkx/algorithms/tests/test_euler.py::TestIsEulerian::test_is_eulerian",
"networkx/algorithms/tests/test_euler.py::TestIsEulerian::test_is_eulerian2",
"networkx/algorithms/tests/test_euler.py::TestEulerianCircuit::test_eulerian_circuit_cycle",
"networkx/algorithms/tests/test_euler.py::TestEulerianCircuit::test_eulerian_circuit_digraph",
"networkx/algorithms/tests/test_euler.py::TestEulerianCircuit::test_multigraph",
"networkx/algorithms/tests/test_euler.py::TestEulerianCircuit::test_multigraph_with_keys",
"networkx/algorithms/tests/test_euler.py::TestEulerianCircuit::test_not_eulerian",
"networkx/algorithms/tests/test_euler.py::TestIsSemiEulerian::test_is_semieulerian",
"networkx/algorithms/tests/test_euler.py::TestHasEulerianPath::test_has_eulerian_path_cyclic",
"networkx/algorithms/tests/test_euler.py::TestHasEulerianPath::test_has_eulerian_path_non_cyclic",
"networkx/algorithms/tests/test_euler.py::TestFindPathStart::testfind_path_start",
"networkx/algorithms/tests/test_euler.py::TestEulerianPath::test_eulerian_path",
"networkx/algorithms/tests/test_euler.py::TestEulerize::test_disconnected",
"networkx/algorithms/tests/test_euler.py::TestEulerize::test_null_graph",
"networkx/algorithms/tests/test_euler.py::TestEulerize::test_null_multigraph",
"networkx/algorithms/tests/test_euler.py::TestEulerize::test_on_empty_graph",
"networkx/algorithms/tests/test_euler.py::TestEulerize::test_on_eulerian",
"networkx/algorithms/tests/test_euler.py::TestEulerize::test_on_eulerian_multigraph",
"networkx/algorithms/tests/test_euler.py::TestEulerize::test_on_complete_graph",
"networkx/classes/tests/test_graph.py::TestGraph::test_contains",
"networkx/classes/tests/test_graph.py::TestGraph::test_order",
"networkx/classes/tests/test_graph.py::TestGraph::test_nodes",
"networkx/classes/tests/test_graph.py::TestGraph::test_has_node",
"networkx/classes/tests/test_graph.py::TestGraph::test_has_edge",
"networkx/classes/tests/test_graph.py::TestGraph::test_neighbors",
"networkx/classes/tests/test_graph.py::TestGraph::test_memory_leak",
"networkx/classes/tests/test_graph.py::TestGraph::test_edges",
"networkx/classes/tests/test_graph.py::TestGraph::test_degree",
"networkx/classes/tests/test_graph.py::TestGraph::test_size",
"networkx/classes/tests/test_graph.py::TestGraph::test_nbunch_iter",
"networkx/classes/tests/test_graph.py::TestGraph::test_nbunch_iter_node_format_raise",
"networkx/classes/tests/test_graph.py::TestGraph::test_selfloop_degree",
"networkx/classes/tests/test_graph.py::TestGraph::test_selfloops",
"networkx/classes/tests/test_graph.py::TestGraph::test_weighted_degree",
"networkx/classes/tests/test_graph.py::TestGraph::test_name",
"networkx/classes/tests/test_graph.py::TestGraph::test_graph_chain",
"networkx/classes/tests/test_graph.py::TestGraph::test_copy",
"networkx/classes/tests/test_graph.py::TestGraph::test_class_copy",
"networkx/classes/tests/test_graph.py::TestGraph::test_fresh_copy",
"networkx/classes/tests/test_graph.py::TestGraph::test_graph_attr",
"networkx/classes/tests/test_graph.py::TestGraph::test_node_attr",
"networkx/classes/tests/test_graph.py::TestGraph::test_node_attr2",
"networkx/classes/tests/test_graph.py::TestGraph::test_edge_lookup",
"networkx/classes/tests/test_graph.py::TestGraph::test_edge_attr",
"networkx/classes/tests/test_graph.py::TestGraph::test_edge_attr2",
"networkx/classes/tests/test_graph.py::TestGraph::test_edge_attr3",
"networkx/classes/tests/test_graph.py::TestGraph::test_edge_attr4",
"networkx/classes/tests/test_graph.py::TestGraph::test_to_undirected",
"networkx/classes/tests/test_graph.py::TestGraph::test_to_directed",
"networkx/classes/tests/test_graph.py::TestGraph::test_subgraph",
"networkx/classes/tests/test_graph.py::TestGraph::test_selfloops_attr",
"networkx/classes/tests/test_graph.py::TestGraph::test_pickle",
"networkx/classes/tests/test_graph.py::TestGraph::test_data_input",
"networkx/classes/tests/test_graph.py::TestGraph::test_adjacency",
"networkx/classes/tests/test_graph.py::TestGraph::test_getitem",
"networkx/classes/tests/test_graph.py::TestGraph::test_add_node",
"networkx/classes/tests/test_graph.py::TestGraph::test_add_nodes_from",
"networkx/classes/tests/test_graph.py::TestGraph::test_remove_node",
"networkx/classes/tests/test_graph.py::TestGraph::test_remove_nodes_from",
"networkx/classes/tests/test_graph.py::TestGraph::test_add_edge",
"networkx/classes/tests/test_graph.py::TestGraph::test_add_edges_from",
"networkx/classes/tests/test_graph.py::TestGraph::test_remove_edge",
"networkx/classes/tests/test_graph.py::TestGraph::test_remove_edges_from",
"networkx/classes/tests/test_graph.py::TestGraph::test_clear",
"networkx/classes/tests/test_graph.py::TestGraph::test_clear_edges",
"networkx/classes/tests/test_graph.py::TestGraph::test_edges_data",
"networkx/classes/tests/test_graph.py::TestGraph::test_get_edge_data",
"networkx/classes/tests/test_graph.py::TestGraph::test_update",
"networkx/classes/tests/test_graph.py::TestEdgeSubgraph::test_correct_nodes",
"networkx/classes/tests/test_graph.py::TestEdgeSubgraph::test_correct_edges",
"networkx/classes/tests/test_graph.py::TestEdgeSubgraph::test_add_node",
"networkx/classes/tests/test_graph.py::TestEdgeSubgraph::test_remove_node",
"networkx/classes/tests/test_graph.py::TestEdgeSubgraph::test_node_attr_dict",
"networkx/classes/tests/test_graph.py::TestEdgeSubgraph::test_edge_attr_dict",
"networkx/classes/tests/test_graph.py::TestEdgeSubgraph::test_graph_attr_dict"
] | 2020-10-08 20:32:04+00:00 | 4,136 |
|
networkx__networkx-4461 | diff --git a/doc/reference/algorithms/approximation.rst b/doc/reference/algorithms/approximation.rst
index 5b207d4fb..fe3dc53e0 100644
--- a/doc/reference/algorithms/approximation.rst
+++ b/doc/reference/algorithms/approximation.rst
@@ -107,3 +107,13 @@ Vertex Cover
:toctree: generated/
min_weighted_vertex_cover
+
+
+Max Cut
+-------
+.. automodule:: networkx.algorithms.approximation.maxcut
+.. autosummary::
+ :toctree: generated/
+
+ randomized_partitioning
+ one_exchange
diff --git a/networkx/algorithms/approximation/__init__.py b/networkx/algorithms/approximation/__init__.py
index 99e8340b4..631a2c353 100644
--- a/networkx/algorithms/approximation/__init__.py
+++ b/networkx/algorithms/approximation/__init__.py
@@ -20,3 +20,4 @@ from networkx.algorithms.approximation.ramsey import *
from networkx.algorithms.approximation.steinertree import *
from networkx.algorithms.approximation.vertex_cover import *
from networkx.algorithms.approximation.treewidth import *
+from networkx.algorithms.approximation.maxcut import *
diff --git a/networkx/algorithms/approximation/maxcut.py b/networkx/algorithms/approximation/maxcut.py
new file mode 100644
index 000000000..47e5c70ca
--- /dev/null
+++ b/networkx/algorithms/approximation/maxcut.py
@@ -0,0 +1,111 @@
+import networkx as nx
+from networkx.utils.decorators import py_random_state
+
+__all__ = ["randomized_partitioning", "one_exchange"]
+
+
[email protected]_implemented_for("directed", "multigraph")
+@py_random_state(1)
+def randomized_partitioning(G, seed=None, p=0.5, weight=None):
+ """Compute a random partitioning of the graph nodes and its cut value.
+
+ A partitioning is calculated by observing each node
+ and deciding to add it to the partition with probability `p`,
+ returning a random cut and its corresponding value (the
+ sum of weights of edges connecting different partitions).
+
+ Parameters
+ ----------
+ G : NetworkX graph
+
+ seed : integer, random_state, or None (default)
+ Indicator of random number generation state.
+ See :ref:`Randomness<randomness>`.
+
+ p : scalar
+ Probability for each node to be part of the first partition.
+ Should be in [0,1]
+
+ weight : object
+ Edge attribute key to use as weight. If not specified, edges
+ have weight one.
+
+ Returns
+ -------
+ cut_size : scalar
+ Value of the minimum cut.
+
+ partition : pair of node sets
+ A partitioning of the nodes that defines a minimum cut.
+ """
+ cut = {node for node in G.nodes() if seed.random() < p}
+ cut_size = nx.algorithms.cut_size(G, cut, weight=weight)
+ partition = (cut, G.nodes - cut)
+ return cut_size, partition
+
+
+def _swap_node_partition(cut, node):
+ return cut - {node} if node in cut else cut.union({node})
+
+
[email protected]_implemented_for("directed", "multigraph")
+@py_random_state(2)
+def one_exchange(G, initial_cut=None, seed=None, weight=None):
+ """Compute a partitioning of the graphs nodes and the corresponding cut value.
+
+ Use a greedy one exchange strategy to find a locally maximal cut
+ and its value, it works by finding the best node (one that gives
+ the highest gain to the cut value) to add to the current cut
+ and repeats this process until no improvement can be made.
+
+ Parameters
+ ----------
+ G : networkx Graph
+ Graph to find a maximum cut for.
+
+ initial_cut : set
+ Cut to use as a starting point. If not supplied the algorithm
+ starts with an empty cut.
+
+ seed : integer, random_state, or None (default)
+ Indicator of random number generation state.
+ See :ref:`Randomness<randomness>`.
+
+ weight : object
+ Edge attribute key to use as weight. If not specified, edges
+ have weight one.
+
+ Returns
+ -------
+ cut_value : scalar
+ Value of the maximum cut.
+
+ partition : pair of node sets
+ A partitioning of the nodes that defines a maximum cut.
+ """
+ if initial_cut is None:
+ initial_cut = set()
+ cut = set(initial_cut)
+ current_cut_size = nx.algorithms.cut_size(G, cut, weight=weight)
+ while True:
+ nodes = list(G.nodes())
+ # Shuffling the nodes ensures random tie-breaks in the following call to max
+ seed.shuffle(nodes)
+ best_node_to_swap = max(
+ nodes,
+ key=lambda v: nx.algorithms.cut_size(
+ G, _swap_node_partition(cut, v), weight=weight
+ ),
+ default=None,
+ )
+ potential_cut = _swap_node_partition(cut, best_node_to_swap)
+ potential_cut_size = nx.algorithms.cut_size(G, potential_cut, weight=weight)
+
+ if potential_cut_size > current_cut_size:
+ cut = potential_cut
+ current_cut_size = potential_cut_size
+ else:
+ break
+
+ partition = (cut, G.nodes - cut)
+ return current_cut_size, partition
diff --git a/networkx/generators/classic.py b/networkx/generators/classic.py
index 9968d20f7..b89aca3dc 100644
--- a/networkx/generators/classic.py
+++ b/networkx/generators/classic.py
@@ -188,7 +188,7 @@ def barbell_graph(m1, m2, create_using=None):
return G
-def binomial_tree(n):
+def binomial_tree(n, create_using=None):
"""Returns the Binomial Tree of order n.
The binomial tree of order 0 consists of a single node. A binomial tree of order k
@@ -200,16 +200,21 @@ def binomial_tree(n):
n : int
Order of the binomial tree.
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
+ Graph type to create. If graph instance, then cleared before populated.
+
Returns
-------
G : NetworkX graph
A binomial tree of $2^n$ nodes and $2^n - 1$ edges.
"""
- G = nx.empty_graph(1)
+ G = nx.empty_graph(1, create_using)
+
N = 1
for i in range(n):
- edges = [(u + N, v + N) for (u, v) in G.edges]
+ # Use G.edges() to ensure 2-tuples. G.edges is 3-tuple for MultiGraph
+ edges = [(u + N, v + N) for (u, v) in G.edges()]
G.add_edges_from(edges)
G.add_edge(0, N)
N *= 2
| networkx/networkx | f542e5fb92d12ec42570d14df867d144a9e8ba4f | diff --git a/networkx/algorithms/approximation/tests/test_maxcut.py b/networkx/algorithms/approximation/tests/test_maxcut.py
new file mode 100644
index 000000000..897d25594
--- /dev/null
+++ b/networkx/algorithms/approximation/tests/test_maxcut.py
@@ -0,0 +1,82 @@
+import random
+
+import networkx as nx
+from networkx.algorithms.approximation import maxcut
+
+
+def _is_valid_cut(G, set1, set2):
+ union = set1.union(set2)
+ assert union == set(G.nodes)
+ assert len(set1) + len(set2) == G.number_of_nodes()
+
+
+def _cut_is_locally_optimal(G, cut_size, set1):
+ # test if cut can be locally improved
+ for i, node in enumerate(set1):
+ cut_size_without_node = nx.algorithms.cut_size(
+ G, set1 - {node}, weight="weight"
+ )
+ assert cut_size_without_node <= cut_size
+
+
+def test_random_partitioning():
+ G = nx.complete_graph(5)
+ _, (set1, set2) = maxcut.randomized_partitioning(G, seed=5)
+ _is_valid_cut(G, set1, set2)
+
+
+def test_random_partitioning_all_to_one():
+ G = nx.complete_graph(5)
+ _, (set1, set2) = maxcut.randomized_partitioning(G, p=1)
+ _is_valid_cut(G, set1, set2)
+ assert len(set1) == G.number_of_nodes()
+ assert len(set2) == 0
+
+
+def test_one_exchange_basic():
+ G = nx.complete_graph(5)
+ random.seed(5)
+ for (u, v, w) in G.edges(data=True):
+ w["weight"] = random.randrange(-100, 100, 1) / 10
+
+ initial_cut = set(random.sample(G.nodes(), k=5))
+ cut_size, (set1, set2) = maxcut.one_exchange(
+ G, initial_cut, weight="weight", seed=5
+ )
+
+ _is_valid_cut(G, set1, set2)
+ _cut_is_locally_optimal(G, cut_size, set1)
+
+
+def test_one_exchange_optimal():
+ # Greedy one exchange should find the optimal solution for this graph (14)
+ G = nx.Graph()
+ G.add_edge(1, 2, weight=3)
+ G.add_edge(1, 3, weight=3)
+ G.add_edge(1, 4, weight=3)
+ G.add_edge(1, 5, weight=3)
+ G.add_edge(2, 3, weight=5)
+
+ cut_size, (set1, set2) = maxcut.one_exchange(G, weight="weight", seed=5)
+
+ _is_valid_cut(G, set1, set2)
+ _cut_is_locally_optimal(G, cut_size, set1)
+ # check global optimality
+ assert cut_size == 14
+
+
+def test_negative_weights():
+ G = nx.complete_graph(5)
+ random.seed(5)
+ for (u, v, w) in G.edges(data=True):
+ w["weight"] = -1 * random.random()
+
+ initial_cut = set(random.sample(G.nodes(), k=5))
+ cut_size, (set1, set2) = maxcut.one_exchange(G, initial_cut, weight="weight")
+
+ # make sure it is a valid cut
+ _is_valid_cut(G, set1, set2)
+ # check local optimality
+ _cut_is_locally_optimal(G, cut_size, set1)
+ # test that all nodes are in the same partition
+ assert len(set1) == len(G.nodes) or len(set2) == len(G.nodes)
diff --git a/networkx/generators/tests/test_classic.py b/networkx/generators/tests/test_classic.py
index c98eb8f5a..3ec36f0f9 100644
--- a/networkx/generators/tests/test_classic.py
+++ b/networkx/generators/tests/test_classic.py
@@ -138,10 +138,12 @@ class TestGeneratorClassic:
assert_edges_equal(mb.edges(), b.edges())
def test_binomial_tree(self):
- for n in range(0, 4):
- b = nx.binomial_tree(n)
- assert nx.number_of_nodes(b) == 2 ** n
- assert nx.number_of_edges(b) == (2 ** n - 1)
+ graphs = (None, nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph)
+ for create_using in graphs:
+ for n in range(0, 4):
+ b = nx.binomial_tree(n, create_using)
+ assert nx.number_of_nodes(b) == 2 ** n
+ assert nx.number_of_edges(b) == (2 ** n - 1)
def test_complete_graph(self):
# complete_graph(m) is a connected graph with
| Allow binomial_tree() to create directed graphs (via create_using parameter)
`binomial_tree() ` doesn't seem to allow the `create_using` parameter to get passed and as a result, one can't create a directed binomial graph.
This seem like a inadvertent omission and easy to fix. I will put in a PR to address this soon. | 0.0 | [
"networkx/algorithms/approximation/tests/test_maxcut.py::test_random_partitioning",
"networkx/algorithms/approximation/tests/test_maxcut.py::test_random_partitioning_all_to_one",
"networkx/algorithms/approximation/tests/test_maxcut.py::test_one_exchange_basic",
"networkx/algorithms/approximation/tests/test_maxcut.py::test_one_exchange_optimal",
"networkx/algorithms/approximation/tests/test_maxcut.py::test_negative_weights",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_balanced_tree",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_balanced_tree_star",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_balanced_tree_path",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_full_rary_tree",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_full_rary_tree_balanced",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_full_rary_tree_path",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_full_rary_tree_empty",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_full_rary_tree_3_20",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_barbell_graph",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_binomial_tree",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_complete_graph",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_complete_digraph",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_circular_ladder_graph",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_circulant_graph",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_cycle_graph",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_dorogovtsev_goltsev_mendes_graph",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_create_using",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_empty_graph",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_ladder_graph",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_lollipop_graph",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_null_graph",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_path_graph",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_star_graph",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_trivial_graph",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_turan_graph",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_wheel_graph",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_complete_0_partite_graph",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_complete_1_partite_graph",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_complete_2_partite_graph",
"networkx/generators/tests/test_classic.py::TestGeneratorClassic::test_complete_multipartite_graph"
] | [] | 2020-12-14 02:51:50+00:00 | 4,137 |
|
networkx__networkx-4667 | diff --git a/networkx/algorithms/bipartite/matching.py b/networkx/algorithms/bipartite/matching.py
index 279e01604..2059d6bdf 100644
--- a/networkx/algorithms/bipartite/matching.py
+++ b/networkx/algorithms/bipartite/matching.py
@@ -346,14 +346,14 @@ def _is_connected_by_alternating_path(G, v, matched_edges, unmatched_edges, targ
will continue only through edges *not* in the given matching.
"""
- if along_matched:
- edges = itertools.cycle([matched_edges, unmatched_edges])
- else:
- edges = itertools.cycle([unmatched_edges, matched_edges])
visited = set()
- stack = [(u, iter(G[u]), next(edges))]
+ # Follow matched edges when depth is even,
+ # and follow unmatched edges when depth is odd.
+ initial_depth = 0 if along_matched else 1
+ stack = [(u, iter(G[u]), initial_depth)]
while stack:
- parent, children, valid_edges = stack[-1]
+ parent, children, depth = stack[-1]
+ valid_edges = matched_edges if depth % 2 else unmatched_edges
try:
child = next(children)
if child not in visited:
@@ -361,7 +361,7 @@ def _is_connected_by_alternating_path(G, v, matched_edges, unmatched_edges, targ
if child in targets:
return True
visited.add(child)
- stack.append((child, iter(G[child]), next(edges)))
+ stack.append((child, iter(G[child]), depth + 1))
except StopIteration:
stack.pop()
return False
diff --git a/networkx/algorithms/tournament.py b/networkx/algorithms/tournament.py
index 2205f5556..cedd2bc06 100644
--- a/networkx/algorithms/tournament.py
+++ b/networkx/algorithms/tournament.py
@@ -276,7 +276,6 @@ def is_reachable(G, s, t):
tournaments."
*Electronic Colloquium on Computational Complexity*. 2001.
<http://eccc.hpi-web.de/report/2001/092/>
-
"""
def two_neighborhood(G, v):
| networkx/networkx | e03144e0780898fed4afa976fff86f2710aa5d40 | diff --git a/networkx/algorithms/bipartite/tests/test_matching.py b/networkx/algorithms/bipartite/tests/test_matching.py
index d4fcd9802..3c6cc35fd 100644
--- a/networkx/algorithms/bipartite/tests/test_matching.py
+++ b/networkx/algorithms/bipartite/tests/test_matching.py
@@ -180,6 +180,16 @@ class TestMatching:
for u, v in G.edges():
assert u in vertex_cover or v in vertex_cover
+ def test_vertex_cover_issue_3306(self):
+ G = nx.Graph()
+ edges = [(0, 2), (1, 0), (1, 1), (1, 2), (2, 2)]
+ G.add_edges_from([((i, "L"), (j, "R")) for i, j in edges])
+
+ matching = maximum_matching(G)
+ vertex_cover = to_vertex_cover(G, matching)
+ for u, v in G.edges():
+ assert u in vertex_cover or v in vertex_cover
+
def test_unorderable_nodes(self):
a = object()
b = object()
diff --git a/networkx/algorithms/tests/test_tournament.py b/networkx/algorithms/tests/test_tournament.py
index 8de6f7c3e..42a31f9be 100644
--- a/networkx/algorithms/tests/test_tournament.py
+++ b/networkx/algorithms/tests/test_tournament.py
@@ -1,132 +1,157 @@
"""Unit tests for the :mod:`networkx.algorithms.tournament` module."""
from itertools import combinations
-
-
+import pytest
from networkx import DiGraph
from networkx.algorithms.tournament import is_reachable
from networkx.algorithms.tournament import is_strongly_connected
from networkx.algorithms.tournament import is_tournament
from networkx.algorithms.tournament import random_tournament
from networkx.algorithms.tournament import hamiltonian_path
+from networkx.algorithms.tournament import score_sequence
+from networkx.algorithms.tournament import tournament_matrix
+from networkx.algorithms.tournament import index_satisfying
+
+
+def test_condition_not_satisfied():
+ condition = lambda x: x > 0
+ iter_in = [0]
+ assert index_satisfying(iter_in, condition) == 1
+
+
+def test_empty_iterable():
+ condition = lambda x: x > 0
+ with pytest.raises(ValueError):
+ index_satisfying([], condition)
-class TestIsTournament:
- """Unit tests for the :func:`networkx.tournament.is_tournament`
- function.
+def test_is_tournament():
+ G = DiGraph()
+ G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 0), (1, 3), (0, 2)])
+ assert is_tournament(G)
+
+
+def test_self_loops():
+ """A tournament must have no self-loops."""
+ G = DiGraph()
+ G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 0), (1, 3), (0, 2)])
+ G.add_edge(0, 0)
+ assert not is_tournament(G)
+
+
+def test_missing_edges():
+ """A tournament must not have any pair of nodes without at least
+ one edge joining the pair.
"""
+ G = DiGraph()
+ G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 0), (1, 3)])
+ assert not is_tournament(G)
+
- def test_is_tournament(self):
- G = DiGraph()
- G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 0), (1, 3), (0, 2)])
+def test_bidirectional_edges():
+ """A tournament must not have any pair of nodes with greater
+ than one edge joining the pair.
+
+ """
+ G = DiGraph()
+ G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 0), (1, 3), (0, 2)])
+ G.add_edge(1, 0)
+ assert not is_tournament(G)
+
+
+def test_graph_is_tournament():
+ for _ in range(10):
+ G = random_tournament(5)
assert is_tournament(G)
- def test_self_loops(self):
- """A tournament must have no self-loops."""
- G = DiGraph()
- G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 0), (1, 3), (0, 2)])
- G.add_edge(0, 0)
- assert not is_tournament(G)
- def test_missing_edges(self):
- """A tournament must not have any pair of nodes without at least
- one edge joining the pair.
+def test_graph_is_tournament_seed():
+ for _ in range(10):
+ G = random_tournament(5, seed=1)
+ assert is_tournament(G)
- """
- G = DiGraph()
- G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 0), (1, 3)])
- assert not is_tournament(G)
- def test_bidirectional_edges(self):
- """A tournament must not have any pair of nodes with greater
- than one edge joining the pair.
+def test_graph_is_tournament_one_node():
+ G = random_tournament(1)
+ assert is_tournament(G)
- """
- G = DiGraph()
- G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 0), (1, 3), (0, 2)])
- G.add_edge(1, 0)
- assert not is_tournament(G)
+def test_graph_is_tournament_zero_node():
+ G = random_tournament(0)
+ assert is_tournament(G)
-class TestRandomTournament:
- """Unit tests for the :func:`networkx.tournament.random_tournament`
- function.
- """
+def test_hamiltonian_empty_graph():
+ path = hamiltonian_path(DiGraph())
+ assert len(path) == 0
- def test_graph_is_tournament(self):
- for n in range(10):
- G = random_tournament(5)
- assert is_tournament(G)
- def test_graph_is_tournament_seed(self):
- for n in range(10):
- G = random_tournament(5, seed=1)
- assert is_tournament(G)
+def test_path_is_hamiltonian():
+ G = DiGraph()
+ G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 0), (1, 3), (0, 2)])
+ path = hamiltonian_path(G)
+ assert len(path) == 4
+ assert all(v in G[u] for u, v in zip(path, path[1:]))
-class TestHamiltonianPath:
- """Unit tests for the :func:`networkx.tournament.hamiltonian_path`
- function.
+def test_hamiltonian_cycle():
+ """Tests that :func:`networkx.tournament.hamiltonian_path`
+ returns a Hamiltonian cycle when provided a strongly connected
+ tournament.
"""
+ G = DiGraph()
+ G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 0), (1, 3), (0, 2)])
+ path = hamiltonian_path(G)
+ assert len(path) == 4
+ assert all(v in G[u] for u, v in zip(path, path[1:]))
+ assert path[0] in G[path[-1]]
- def test_path_is_hamiltonian(self):
- G = DiGraph()
- G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 0), (1, 3), (0, 2)])
- path = hamiltonian_path(G)
- assert len(path) == 4
- assert all(v in G[u] for u, v in zip(path, path[1:]))
- def test_hamiltonian_cycle(self):
- """Tests that :func:`networkx.tournament.hamiltonian_path`
- returns a Hamiltonian cycle when provided a strongly connected
- tournament.
+def test_score_sequence_edge():
+ G = DiGraph([(0, 1)])
+ assert score_sequence(G) == [0, 1]
- """
- G = DiGraph()
- G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 0), (1, 3), (0, 2)])
- path = hamiltonian_path(G)
- assert len(path) == 4
- assert all(v in G[u] for u, v in zip(path, path[1:]))
- assert path[0] in G[path[-1]]
+def test_score_sequence_triangle():
+ G = DiGraph([(0, 1), (1, 2), (2, 0)])
+ assert score_sequence(G) == [1, 1, 1]
-class TestReachability:
- """Unit tests for the :func:`networkx.tournament.is_reachable`
- function.
- """
+def test_tournament_matrix():
+ np = pytest.importorskip("numpy")
+ npt = pytest.importorskip("numpy.testing")
+ G = DiGraph([(0, 1)])
+ m = tournament_matrix(G)
+ npt.assert_array_equal(m.todense(), np.array([[0, 1], [-1, 0]]))
- def test_reachable_pair(self):
- """Tests for a reachable pair of nodes."""
- G = DiGraph([(0, 1), (1, 2), (2, 0)])
- assert is_reachable(G, 0, 2)
- def test_same_node_is_reachable(self):
- """Tests that a node is always reachable from itself."""
- # G is an arbitrary tournament on ten nodes.
- G = DiGraph(sorted(p) for p in combinations(range(10), 2))
- assert all(is_reachable(G, v, v) for v in G)
+def test_reachable_pair():
+ """Tests for a reachable pair of nodes."""
+ G = DiGraph([(0, 1), (1, 2), (2, 0)])
+ assert is_reachable(G, 0, 2)
- def test_unreachable_pair(self):
- """Tests for an unreachable pair of nodes."""
- G = DiGraph([(0, 1), (0, 2), (1, 2)])
- assert not is_reachable(G, 1, 0)
+def test_same_node_is_reachable():
+ """Tests that a node is always reachable from it."""
+ # G is an arbitrary tournament on ten nodes.
+ G = DiGraph(sorted(p) for p in combinations(range(10), 2))
+ assert all(is_reachable(G, v, v) for v in G)
-class TestStronglyConnected:
- """Unit tests for the
- :func:`networkx.tournament.is_strongly_connected` function.
- """
+def test_unreachable_pair():
+ """Tests for an unreachable pair of nodes."""
+ G = DiGraph([(0, 1), (0, 2), (1, 2)])
+ assert not is_reachable(G, 1, 0)
+
+
+def test_is_strongly_connected():
+ """Tests for a strongly connected tournament."""
+ G = DiGraph([(0, 1), (1, 2), (2, 0)])
+ assert is_strongly_connected(G)
- def test_is_strongly_connected(self):
- """Tests for a strongly connected tournament."""
- G = DiGraph([(0, 1), (1, 2), (2, 0)])
- assert is_strongly_connected(G)
- def test_not_strongly_connected(self):
- """Tests for a tournament that is not strongly connected."""
- G = DiGraph([(0, 1), (0, 2), (1, 2)])
- assert not is_strongly_connected(G)
+def test_not_strongly_connected():
+ """Tests for a tournament that is not strongly connected."""
+ G = DiGraph([(0, 1), (0, 2), (1, 2)])
+ assert not is_strongly_connected(G)
| hopcroft_karp_matching / to_vertex_cover bug
`to_vertex_cover` must give the **minimum vertex cover** as documented. Wasn't it fixed in #2384 ?
The following code gives random results:
```python
import networkx as nx
nodesU = ['r1','r2','r3','r4','r5','r6','r7','r8']
nodesV = ['c1','c2','c3','c4','c5','c6','c7','c8']
edges = [
('r1','c2'),('r1','c4'),('r1','c5'),('r1','c8'),
('r2','c1'),('r2','c2'),('r2','c3'),('r2','c6'),('r2','c7'),
('r3','c4'),('r3','c5'),
('r4','c2'),('r4','c8'),
('r5','c2'),('r5','c8'),
('r6','c1'),('r6','c2'),('r6','c3'),('r6','c5'),('r6','c6'),('r6','c7'),
('r7','c2'),('r7','c8'),
('r8','c2'),('r8','c4')]
G = nx.Graph()
G.add_nodes_from(nodesU, bipartite=0)
G.add_nodes_from(nodesV, bipartite=1)
G.add_edges_from(edges)
M = nx.bipartite.hopcroft_karp_matching(G, top_nodes = nodesU)
print('matchings M = ', M)
print('|M| = ', len(M))
K = nx.bipartite.to_vertex_cover(G, M, top_nodes = nodesU)
print('minimum cover K = ', K)
print('|K| = ', len(K))
```
Here are the results of multiple runs:
```
matchings M = {'c1': 'r6', 'r7': 'c2', 'r5': 'c8', 'r1': 'c5', 'r8': 'c4', 'r6': 'c1', 'c5': 'r1', 'c8': 'r5', 'r2': 'c7', 'c7': 'r2', 'c2': 'r7', 'c4': 'r8'}
|M| = 12
minimum cover K = {'c1', 'c5', 'c7', 'c2', 'c8', 'c4'}
|K| = 6
matchings M = {'c6': 'r6', 'r6': 'c6', 'r1': 'c4', 'r4': 'c2', 'c3': 'r2', 'r5': 'c8', 'c5': 'r3', 'r3': 'c5', 'c8': 'r5', 'r2': 'c3', 'c4': 'r1', 'c2': 'r4'}
|M| = 12
minimum cover K = {'c6', 'r6', 'c4', 'c5', 'c2', 'c3', 'c8', 'r2'}
|K| = 8
matchings M = {'c8': 'r7', 'r7': 'c8', 'c1': 'r2', 'r3': 'c4', 'r6': 'c7', 'c5': 'r1', 'c2': 'r4', 'c7': 'r6', 'r4': 'c2', 'r2': 'c1', 'c4': 'r3', 'r1': 'c5'}
|M| = 12
minimum cover K = {'r2', 'c8', 'c4', 'c2', 'c5'}
|K| = 5
matchings M = {'r3': 'c4', 'r6': 'c1', 'r1': 'c5', 'c2': 'r7', 'r7': 'c2', 'c8': 'r5', 'r2': 'c7', 'c5': 'r1', 'r5': 'c8', 'c1': 'r6', 'c7': 'r2', 'c4': 'r3'}
|M| = 12
minimum cover K = {'c8', 'c5', 'c7', 'r6', 'c2', 'c4'}
|K| = 6
```
I'm using networkx 2.2 on debian/python3 and windows miniconda3.
The graph is from: [http://tryalgo.org/en/matching/2016/08/05/konig/](http://tryalgo.org/en/matching/2016/08/05/konig/)
Also why `hopcroft_karp_matching` returns matchings and opposite edges ? | 0.0 | [
"networkx/algorithms/bipartite/tests/test_matching.py::TestMatching::test_vertex_cover_issue_3306"
] | [
"networkx/algorithms/bipartite/tests/test_matching.py::TestMatching::test_issue_2127",
"networkx/algorithms/bipartite/tests/test_matching.py::TestMatching::test_vertex_cover_issue_2384",
"networkx/algorithms/bipartite/tests/test_matching.py::TestMatching::test_unorderable_nodes",
"networkx/algorithms/bipartite/tests/test_matching.py::test_eppstein_matching",
"networkx/algorithms/bipartite/tests/test_matching.py::TestMinimumWeightFullMatching::test_minimum_weight_full_matching_incomplete_graph",
"networkx/algorithms/bipartite/tests/test_matching.py::TestMinimumWeightFullMatching::test_minimum_weight_full_matching_with_no_full_matching",
"networkx/algorithms/bipartite/tests/test_matching.py::TestMinimumWeightFullMatching::test_minimum_weight_full_matching_square",
"networkx/algorithms/bipartite/tests/test_matching.py::TestMinimumWeightFullMatching::test_minimum_weight_full_matching_smaller_left",
"networkx/algorithms/bipartite/tests/test_matching.py::TestMinimumWeightFullMatching::test_minimum_weight_full_matching_smaller_top_nodes_right",
"networkx/algorithms/bipartite/tests/test_matching.py::TestMinimumWeightFullMatching::test_minimum_weight_full_matching_smaller_right",
"networkx/algorithms/bipartite/tests/test_matching.py::TestMinimumWeightFullMatching::test_minimum_weight_full_matching_negative_weights",
"networkx/algorithms/bipartite/tests/test_matching.py::TestMinimumWeightFullMatching::test_minimum_weight_full_matching_different_weight_key",
"networkx/algorithms/tests/test_tournament.py::test_condition_not_satisfied",
"networkx/algorithms/tests/test_tournament.py::test_empty_iterable",
"networkx/algorithms/tests/test_tournament.py::test_is_tournament",
"networkx/algorithms/tests/test_tournament.py::test_self_loops",
"networkx/algorithms/tests/test_tournament.py::test_missing_edges",
"networkx/algorithms/tests/test_tournament.py::test_bidirectional_edges",
"networkx/algorithms/tests/test_tournament.py::test_graph_is_tournament",
"networkx/algorithms/tests/test_tournament.py::test_graph_is_tournament_seed",
"networkx/algorithms/tests/test_tournament.py::test_graph_is_tournament_one_node",
"networkx/algorithms/tests/test_tournament.py::test_graph_is_tournament_zero_node",
"networkx/algorithms/tests/test_tournament.py::test_hamiltonian_empty_graph",
"networkx/algorithms/tests/test_tournament.py::test_path_is_hamiltonian",
"networkx/algorithms/tests/test_tournament.py::test_hamiltonian_cycle",
"networkx/algorithms/tests/test_tournament.py::test_score_sequence_edge",
"networkx/algorithms/tests/test_tournament.py::test_score_sequence_triangle",
"networkx/algorithms/tests/test_tournament.py::test_tournament_matrix",
"networkx/algorithms/tests/test_tournament.py::test_reachable_pair",
"networkx/algorithms/tests/test_tournament.py::test_same_node_is_reachable",
"networkx/algorithms/tests/test_tournament.py::test_unreachable_pair",
"networkx/algorithms/tests/test_tournament.py::test_is_strongly_connected",
"networkx/algorithms/tests/test_tournament.py::test_not_strongly_connected"
] | 2021-03-11 07:17:35+00:00 | 4,138 |
|
networkx__networkx-4753 | diff --git a/networkx/utils/misc.py b/networkx/utils/misc.py
index 4caffbe18..bd58a4ed6 100644
--- a/networkx/utils/misc.py
+++ b/networkx/utils/misc.py
@@ -19,6 +19,30 @@ import uuid
from itertools import tee, chain
import networkx as nx
+__all__ = [
+ "is_string_like",
+ "iterable",
+ "empty_generator",
+ "flatten",
+ "make_list_of_ints",
+ "is_list_of_ints",
+ "make_str",
+ "generate_unique_node",
+ "default_opener",
+ "dict_to_numpy_array",
+ "dict_to_numpy_array1",
+ "dict_to_numpy_array2",
+ "is_iterator",
+ "arbitrary_element",
+ "consume",
+ "pairwise",
+ "groups",
+ "to_tuple",
+ "create_random_state",
+ "create_py_random_state",
+ "PythonRandomInterface",
+]
+
# some cookbook stuff
# used in deciding whether something is a bunch of nodes, edges, etc.
diff --git a/networkx/utils/random_sequence.py b/networkx/utils/random_sequence.py
index 7bd68c798..ad9b34a3c 100644
--- a/networkx/utils/random_sequence.py
+++ b/networkx/utils/random_sequence.py
@@ -7,6 +7,16 @@ import networkx as nx
from networkx.utils import py_random_state
+__all__ = [
+ "powerlaw_sequence",
+ "zipf_rv",
+ "cumulative_distribution",
+ "discrete_sequence",
+ "random_weighted_sample",
+ "weighted_choice",
+]
+
+
# The same helpers for choosing random sequences from distributions
# uses Python's random module
# https://docs.python.org/3/library/random.html
| networkx/networkx | 63f550fef6712d5ea3ae09bbc341d696d65e55e3 | diff --git a/networkx/utils/tests/test__init.py b/networkx/utils/tests/test__init.py
new file mode 100644
index 000000000..ecbcce36d
--- /dev/null
+++ b/networkx/utils/tests/test__init.py
@@ -0,0 +1,11 @@
+import pytest
+
+
+def test_utils_namespace():
+ """Ensure objects are not unintentionally exposed in utils namespace."""
+ with pytest.raises(ImportError):
+ from networkx.utils import nx
+ with pytest.raises(ImportError):
+ from networkx.utils import sys
+ with pytest.raises(ImportError):
+ from networkx.utils import defaultdict, deque
| `networkx.utils.misc` missing `__all__`
The `misc` module in the `utils` package doesn't define an `__all__`. As a consequence, some non-networkx functionality including e.g. objects from `collections` and builtin modules are incorrectly exposed in the `networkx.utils` namespace, including networkx itself:
```python
from networkx.utils import nx # yikes
``` | 0.0 | [
"networkx/utils/tests/test__init.py::test_utils_namespace"
] | [] | 2021-04-23 18:53:02+00:00 | 4,139 |
|
networkx__networkx-5287 | diff --git a/networkx/algorithms/community/louvain.py b/networkx/algorithms/community/louvain.py
index ba7153521..9ee9f51c4 100644
--- a/networkx/algorithms/community/louvain.py
+++ b/networkx/algorithms/community/louvain.py
@@ -185,6 +185,7 @@ def louvain_partitions(
)
if new_mod - mod <= threshold:
return
+ mod = new_mod
graph = _gen_graph(graph, inner_partition)
partition, inner_partition, improvement = _one_level(
graph, m, partition, resolution, is_directed, seed
diff --git a/networkx/readwrite/json_graph/tree.py b/networkx/readwrite/json_graph/tree.py
index 2de2ca9b6..615907eeb 100644
--- a/networkx/readwrite/json_graph/tree.py
+++ b/networkx/readwrite/json_graph/tree.py
@@ -75,6 +75,8 @@ def tree_data(G, root, attrs=None, ident="id", children="children"):
raise TypeError("G is not a tree.")
if not G.is_directed():
raise TypeError("G is not directed.")
+ if not nx.is_weakly_connected(G):
+ raise TypeError("G is not weakly connected.")
# NOTE: to be removed in 3.0
if attrs is not None:
| networkx/networkx | 0cc70051fa0a979b1f1eab4af5b6587a6ebf8334 | diff --git a/networkx/algorithms/community/tests/test_louvain.py b/networkx/algorithms/community/tests/test_louvain.py
index 81bde05b6..8f623fab1 100644
--- a/networkx/algorithms/community/tests/test_louvain.py
+++ b/networkx/algorithms/community/tests/test_louvain.py
@@ -110,3 +110,15 @@ def test_resolution():
partition3 = louvain_communities(G, resolution=2, seed=12)
assert len(partition1) <= len(partition2) <= len(partition3)
+
+
+def test_threshold():
+ G = nx.LFR_benchmark_graph(
+ 250, 3, 1.5, 0.009, average_degree=5, min_community=20, seed=10
+ )
+ partition1 = louvain_communities(G, threshold=0.2, seed=2)
+ partition2 = louvain_communities(G, seed=2)
+ mod1 = modularity(G, partition1)
+ mod2 = modularity(G, partition2)
+
+ assert mod1 < mod2
diff --git a/networkx/readwrite/json_graph/tests/test_tree.py b/networkx/readwrite/json_graph/tests/test_tree.py
index bfbf18163..848edd0b1 100644
--- a/networkx/readwrite/json_graph/tests/test_tree.py
+++ b/networkx/readwrite/json_graph/tests/test_tree.py
@@ -35,6 +35,11 @@ def test_exceptions():
with pytest.raises(TypeError, match="is not directed."):
G = nx.path_graph(3)
tree_data(G, 0)
+ with pytest.raises(TypeError, match="is not weakly connected."):
+ G = nx.path_graph(3, create_using=nx.DiGraph)
+ G.add_edge(2, 0)
+ G.add_node(3)
+ tree_data(G, 0)
with pytest.raises(nx.NetworkXError, match="must be different."):
G = nx.MultiDiGraph()
G.add_node(0)
| `json_graph.tree_data` can cause maximum recursion depth error.
<!-- If you have a general question about NetworkX, please use the discussions tab to create a new discussion -->
<!--- Provide a general summary of the issue in the Title above -->
### Current Behavior
<!--- Tell us what happens instead of the expected behavior -->
Currently the algorithm compares the `n_nodes` with `n_edges` to check if `G` is a tree. https://github.com/networkx/networkx/blob/0cc70051fa0a979b1f1eab4af5b6587a6ebf8334/networkx/readwrite/json_graph/tree.py#L74-L75
This check can be bypassed with specific inputs and cause a recursion error.
### Expected Behavior
<!--- Tell us what should happen -->
The code should check whether there are cycles with `root` as the source and raise an exception.
Another possible fix would be to check if the graph is not weakly connected.
### Steps to Reproduce
<!--- Provide a minimal example that reproduces the bug -->
```Python3
>>> import networkx as nx
>>> G = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
>>> G.add_node(4)
>>> data = nx.json_graph.tree_data(G, 1)
RecursionError: maximum recursion depth exceeded
```
### Environment
<!--- Please provide details about your local environment -->
Python version: 3.8.10
NetworkX version: 2.7rc1.dev0
| 0.0 | [
"networkx/algorithms/community/tests/test_louvain.py::test_threshold",
"networkx/readwrite/json_graph/tests/test_tree.py::test_exceptions"
] | [
"networkx/algorithms/community/tests/test_louvain.py::test_modularity_increase",
"networkx/algorithms/community/tests/test_louvain.py::test_valid_partition",
"networkx/algorithms/community/tests/test_louvain.py::test_partition",
"networkx/algorithms/community/tests/test_louvain.py::test_none_weight_param",
"networkx/algorithms/community/tests/test_louvain.py::test_quality",
"networkx/algorithms/community/tests/test_louvain.py::test_multigraph",
"networkx/algorithms/community/tests/test_louvain.py::test_resolution",
"networkx/readwrite/json_graph/tests/test_tree.py::test_graph",
"networkx/readwrite/json_graph/tests/test_tree.py::test_graph_attributes",
"networkx/readwrite/json_graph/tests/test_tree.py::test_attrs_deprecation"
] | 2022-01-28 11:20:36+00:00 | 4,140 |
|
networkx__networkx-5394 | diff --git a/doc/developer/deprecations.rst b/doc/developer/deprecations.rst
index 77d814532..a155ab765 100644
--- a/doc/developer/deprecations.rst
+++ b/doc/developer/deprecations.rst
@@ -114,3 +114,4 @@ Version 3.0
* In ``algorithms/distance_measures.py`` remove ``extrema_bounding``.
* In ``utils/misc.py`` remove ``dict_to_numpy_array1`` and ``dict_to_numpy_array2``.
* In ``utils/misc.py`` remove ``to_tuple``.
+* In ``algorithms/matching.py``, remove parameter ``maxcardinality`` from ``min_weight_matching``.
diff --git a/doc/release/release_dev.rst b/doc/release/release_dev.rst
index 53b5562bb..dc6240670 100644
--- a/doc/release/release_dev.rst
+++ b/doc/release/release_dev.rst
@@ -46,6 +46,10 @@ Improvements
API Changes
-----------
+- [`#5394 <https://github.com/networkx/networkx/pull/5394>`_]
+ The function ``min_weight_matching`` no longer acts upon the parameter ``maxcardinality``
+ because setting it to False would result in the min_weight_matching being no edges
+ at all. The only resonable option is True. The parameter will be removed completely in v3.0.
Deprecations
------------
diff --git a/networkx/algorithms/matching.py b/networkx/algorithms/matching.py
index 2a57e9a13..fda0b42cd 100644
--- a/networkx/algorithms/matching.py
+++ b/networkx/algorithms/matching.py
@@ -227,28 +227,49 @@ def is_perfect_matching(G, matching):
@not_implemented_for("multigraph")
@not_implemented_for("directed")
-def min_weight_matching(G, maxcardinality=False, weight="weight"):
+def min_weight_matching(G, maxcardinality=None, weight="weight"):
"""Computing a minimum-weight maximal matching of G.
- Use reciprocal edge weights with the maximum-weight algorithm.
+ Use the maximum-weight algorithm with edge weights subtracted
+ from the maximum weight of all edges.
A matching is a subset of edges in which no node occurs more than once.
The weight of a matching is the sum of the weights of its edges.
A maximal matching cannot add more edges and still be a matching.
The cardinality of a matching is the number of matched edges.
- This method replaces the weights with their reciprocal and
- then runs :func:`max_weight_matching`.
- Read the documentation of max_weight_matching for more information.
+ This method replaces the edge weights with 1 plus the maximum edge weight
+ minus the original edge weight.
+
+ new_weight = (max_weight + 1) - edge_weight
+
+ then runs :func:`max_weight_matching` with the new weights.
+ The max weight matching with these new weights corresponds
+ to the min weight matching using the original weights.
+ Adding 1 to the max edge weight keeps all edge weights positive
+ and as integers if they started as integers.
+
+ You might worry that adding 1 to each weight would make the algorithm
+ favor matchings with more edges. But we use the parameter
+ `maxcardinality=True` in `max_weight_matching` to ensure that the
+ number of edges in the competing matchings are the same and thus
+ the optimum does not change due to changes in the number of edges.
+
+ Read the documentation of `max_weight_matching` for more information.
Parameters
----------
G : NetworkX graph
Undirected graph
- maxcardinality: bool, optional (default=False)
- If maxcardinality is True, compute the maximum-cardinality matching
- with minimum weight among all maximum-cardinality matchings.
+ maxcardinality: bool
+ .. deprecated:: 2.8
+ The `maxcardinality` parameter will be removed in v3.0.
+ It doesn't make sense to set it to False when looking for
+ a min weight matching because then we just return no edges.
+
+ If maxcardinality is True, compute the maximum-cardinality matching
+ with minimum weight among all maximum-cardinality matchings.
weight: string, optional (default='weight')
Edge data key corresponding to the edge weight.
@@ -258,15 +279,25 @@ def min_weight_matching(G, maxcardinality=False, weight="weight"):
-------
matching : set
A minimal weight matching of the graph.
+
+ See Also
+ --------
+ max_weight_matching
"""
+ if maxcardinality not in (True, None):
+ raise nx.NetworkXError(
+ "The argument maxcardinality does not make sense "
+ "in the context of minimum weight matchings."
+ "It is deprecated and will be removed in v3.0."
+ )
if len(G.edges) == 0:
- return max_weight_matching(G, maxcardinality, weight)
+ return max_weight_matching(G, maxcardinality=True, weight=weight)
G_edges = G.edges(data=weight, default=1)
- min_weight = min(w for _, _, w in G_edges)
+ max_weight = 1 + max(w for _, _, w in G_edges)
InvG = nx.Graph()
- edges = ((u, v, 1 / (1 + w - min_weight)) for u, v, w in G_edges)
+ edges = ((u, v, max_weight - w) for u, v, w in G_edges)
InvG.add_weighted_edges_from(edges, weight=weight)
- return max_weight_matching(InvG, maxcardinality, weight)
+ return max_weight_matching(InvG, maxcardinality=True, weight=weight)
@not_implemented_for("multigraph")
| networkx/networkx | c39511522b272bf65b6a415169cd48d1bf3ff5c1 | diff --git a/networkx/algorithms/tests/test_matching.py b/networkx/algorithms/tests/test_matching.py
index ed436aada..1dcc69dc6 100644
--- a/networkx/algorithms/tests/test_matching.py
+++ b/networkx/algorithms/tests/test_matching.py
@@ -19,15 +19,13 @@ class TestMaxWeightMatching:
assert nx.max_weight_matching(G) == set()
assert nx.min_weight_matching(G) == set()
- def test_trivial2(self):
- """Self loop"""
+ def test_selfloop(self):
G = nx.Graph()
G.add_edge(0, 0, weight=100)
assert nx.max_weight_matching(G) == set()
assert nx.min_weight_matching(G) == set()
- def test_trivial3(self):
- """Single edge"""
+ def test_single_edge(self):
G = nx.Graph()
G.add_edge(0, 1)
assert edges_equal(
@@ -37,8 +35,7 @@ class TestMaxWeightMatching:
nx.min_weight_matching(G), matching_dict_to_set({0: 1, 1: 0})
)
- def test_trivial4(self):
- """Small graph"""
+ def test_two_path(self):
G = nx.Graph()
G.add_edge("one", "two", weight=10)
G.add_edge("two", "three", weight=11)
@@ -51,8 +48,7 @@ class TestMaxWeightMatching:
matching_dict_to_set({"one": "two", "two": "one"}),
)
- def test_trivial5(self):
- """Path"""
+ def test_path(self):
G = nx.Graph()
G.add_edge(1, 2, weight=5)
G.add_edge(2, 3, weight=11)
@@ -70,8 +66,20 @@ class TestMaxWeightMatching:
nx.min_weight_matching(G, 1), matching_dict_to_set({1: 2, 3: 4})
)
- def test_trivial6(self):
- """Small graph with arbitrary weight attribute"""
+ def test_square(self):
+ G = nx.Graph()
+ G.add_edge(1, 4, weight=2)
+ G.add_edge(2, 3, weight=2)
+ G.add_edge(1, 2, weight=1)
+ G.add_edge(3, 4, weight=4)
+ assert edges_equal(
+ nx.max_weight_matching(G), matching_dict_to_set({1: 2, 3: 4})
+ )
+ assert edges_equal(
+ nx.min_weight_matching(G), matching_dict_to_set({1: 4, 2: 3})
+ )
+
+ def test_edge_attribute_name(self):
G = nx.Graph()
G.add_edge("one", "two", weight=10, abcd=11)
G.add_edge("two", "three", weight=11, abcd=10)
@@ -85,7 +93,6 @@ class TestMaxWeightMatching:
)
def test_floating_point_weights(self):
- """Floating point weights"""
G = nx.Graph()
G.add_edge(1, 2, weight=math.pi)
G.add_edge(2, 3, weight=math.exp(1))
@@ -99,7 +106,6 @@ class TestMaxWeightMatching:
)
def test_negative_weights(self):
- """Negative weights"""
G = nx.Graph()
G.add_edge(1, 2, weight=2)
G.add_edge(1, 3, weight=-2)
| min_weight_matching gives incorrect results
<!-- If you have a general question about NetworkX, please use the discussions tab to create a new discussion -->
<!--- Provide a general summary of the issue in the Title above -->
Consider the following graph:
```python
G = nx.Graph()
G.add_edge(1, 4, weight=2)
G.add_edge(2, 3, weight=2)
G.add_edge(1, 2, weight=1)
G.add_edge(3, 4, weight=4)
nx.min_weight_matching(G)
```
### Current Behavior
<!--- Tell us what happens instead of the expected behavior -->
The program returns `{(2, 1), (4, 3)}`
### Expected Behavior
<!--- Tell us what should happen -->
There are two maximal matchings in the graph, (1,2)(3,4) with weight 1+4=5, and (1,4)(2,3) with weight 2+2=4. The minimum weight maximal matching should be (1,4)(2,3) which has weight 4.
### Steps to Reproduce
<!--- Provide a minimal example that reproduces the bug -->
Run the code provided
### Environment
<!--- Please provide details about your local environment -->
Python version: 3.9
NetworkX version: 2.7.1
### Additional context
<!--- Add any other context about the problem here, screenshots, etc. -->
From the documentation and the code, `min_weight_matching` is simply taking the reciprocal of the weights and uses `max_weight_matching`. This logic seems to be faulty in this example: 1/1+1/4>1/2+1/2. | 0.0 | [
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_square"
] | [
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_trivial1",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_selfloop",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_single_edge",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_two_path",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_path",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_edge_attribute_name",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_floating_point_weights",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_negative_weights",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_s_blossom",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_s_t_blossom",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_nested_s_blossom",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_nested_s_blossom_relabel",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_nested_s_blossom_expand",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_s_blossom_relabel_expand",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_nested_s_blossom_relabel_expand",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_nasty_blossom1",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_nasty_blossom2",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_nasty_blossom_least_slack",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_nasty_blossom_augmenting",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_nasty_blossom_expand_recursively",
"networkx/algorithms/tests/test_matching.py::TestMaxWeightMatching::test_wrong_graph_type",
"networkx/algorithms/tests/test_matching.py::TestIsMatching::test_dict",
"networkx/algorithms/tests/test_matching.py::TestIsMatching::test_empty_matching",
"networkx/algorithms/tests/test_matching.py::TestIsMatching::test_single_edge",
"networkx/algorithms/tests/test_matching.py::TestIsMatching::test_edge_order",
"networkx/algorithms/tests/test_matching.py::TestIsMatching::test_valid_matching",
"networkx/algorithms/tests/test_matching.py::TestIsMatching::test_invalid_input",
"networkx/algorithms/tests/test_matching.py::TestIsMatching::test_selfloops",
"networkx/algorithms/tests/test_matching.py::TestIsMatching::test_invalid_matching",
"networkx/algorithms/tests/test_matching.py::TestIsMatching::test_invalid_edge",
"networkx/algorithms/tests/test_matching.py::TestIsMaximalMatching::test_dict",
"networkx/algorithms/tests/test_matching.py::TestIsMaximalMatching::test_valid",
"networkx/algorithms/tests/test_matching.py::TestIsMaximalMatching::test_not_matching",
"networkx/algorithms/tests/test_matching.py::TestIsMaximalMatching::test_not_maximal",
"networkx/algorithms/tests/test_matching.py::TestIsPerfectMatching::test_dict",
"networkx/algorithms/tests/test_matching.py::TestIsPerfectMatching::test_valid",
"networkx/algorithms/tests/test_matching.py::TestIsPerfectMatching::test_valid_not_path",
"networkx/algorithms/tests/test_matching.py::TestIsPerfectMatching::test_not_matching",
"networkx/algorithms/tests/test_matching.py::TestIsPerfectMatching::test_maximal_but_not_perfect",
"networkx/algorithms/tests/test_matching.py::TestMaximalMatching::test_valid_matching",
"networkx/algorithms/tests/test_matching.py::TestMaximalMatching::test_single_edge_matching",
"networkx/algorithms/tests/test_matching.py::TestMaximalMatching::test_self_loops",
"networkx/algorithms/tests/test_matching.py::TestMaximalMatching::test_ordering",
"networkx/algorithms/tests/test_matching.py::TestMaximalMatching::test_wrong_graph_type"
] | 2022-03-15 22:32:49+00:00 | 4,141 |
|
networkx__networkx-5523 | diff --git a/networkx/algorithms/planarity.py b/networkx/algorithms/planarity.py
index 4d1441efc..8f4b29096 100644
--- a/networkx/algorithms/planarity.py
+++ b/networkx/algorithms/planarity.py
@@ -24,6 +24,18 @@ def check_planarity(G, counterexample=False):
If the graph is planar `certificate` is a PlanarEmbedding
otherwise it is a Kuratowski subgraph.
+ Examples
+ --------
+ >>> G = nx.Graph([(0, 1), (0, 2)])
+ >>> is_planar, P = nx.check_planarity(G)
+ >>> print(is_planar)
+ True
+
+ When `G` is planar, a `PlanarEmbedding` instance is returned:
+
+ >>> P.get_data()
+ {0: [1, 2], 1: [0], 2: [0]}
+
Notes
-----
A (combinatorial) embedding consists of cyclic orderings of the incident
@@ -716,6 +728,8 @@ class PlanarEmbedding(nx.DiGraph):
The planar embedding is given by a `combinatorial embedding
<https://en.wikipedia.org/wiki/Graph_embedding#Combinatorial_embedding>`_.
+ .. note:: `check_planarity` is the preferred way to check if a graph is planar.
+
**Neighbor ordering:**
In comparison to a usual graph structure, the embedding also stores the
@@ -761,6 +775,13 @@ class PlanarEmbedding(nx.DiGraph):
For a half-edge (u, v) that is orientated such that u is below v then the
face that belongs to (u, v) is to the right of this half-edge.
+ See Also
+ --------
+ is _planar :
+ Preferred way to check if an existing graph is planar.
+ check_planarity :
+ A convenient way to create a `PlanarEmbedding`. If not planar, it returns a subgraph that shows this.
+
Examples
--------
diff --git a/networkx/algorithms/similarity.py b/networkx/algorithms/similarity.py
index d5f463536..2447a9dce 100644
--- a/networkx/algorithms/similarity.py
+++ b/networkx/algorithms/similarity.py
@@ -745,18 +745,30 @@ def optimize_edit_paths(
N = len(pending_h)
# assert Ce.C.shape == (M + N, M + N)
- g_ind = [
- i
- for i in range(M)
- if pending_g[i][:2] == (u, u)
- or any(pending_g[i][:2] in ((p, u), (u, p)) for p, q in matched_uv)
- ]
- h_ind = [
- j
- for j in range(N)
- if pending_h[j][:2] == (v, v)
- or any(pending_h[j][:2] in ((q, v), (v, q)) for p, q in matched_uv)
- ]
+ # only attempt to match edges after one node match has been made
+ # this will stop self-edges on the first node being automatically deleted
+ # even when a substitution is the better option
+ if matched_uv:
+ g_ind = [
+ i
+ for i in range(M)
+ if pending_g[i][:2] == (u, u)
+ or any(
+ pending_g[i][:2] in ((p, u), (u, p), (p, p)) for p, q in matched_uv
+ )
+ ]
+ h_ind = [
+ j
+ for j in range(N)
+ if pending_h[j][:2] == (v, v)
+ or any(
+ pending_h[j][:2] in ((q, v), (v, q), (q, q)) for p, q in matched_uv
+ )
+ ]
+ else:
+ g_ind = []
+ h_ind = []
+
m = len(g_ind)
n = len(h_ind)
@@ -782,9 +794,9 @@ def optimize_edit_paths(
for p, q in matched_uv
):
continue
- if g == (u, u):
+ if g == (u, u) or any(g == (p, p) for p, q in matched_uv):
continue
- if h == (v, v):
+ if h == (v, v) or any(h == (q, q) for p, q in matched_uv):
continue
C[k, l] = inf
diff --git a/networkx/algorithms/tree/recognition.py b/networkx/algorithms/tree/recognition.py
index 5fbff544e..52da959b6 100644
--- a/networkx/algorithms/tree/recognition.py
+++ b/networkx/algorithms/tree/recognition.py
@@ -157,6 +157,21 @@ def is_forest(G):
b : bool
A boolean that is True if `G` is a forest.
+ Raises
+ ------
+ NetworkXPointlessConcept
+ If `G` is empty.
+
+ Examples
+ --------
+ >>> G = nx.Graph()
+ >>> G.add_edges_from([(1, 2), (1, 3), (2, 4), (2, 5)])
+ >>> nx.is_forest(G)
+ True
+ >>> G.add_edge(4, 1)
+ >>> nx.is_forest(G)
+ False
+
Notes
-----
In another convention, a directed forest is known as a *polyforest* and
@@ -198,6 +213,21 @@ def is_tree(G):
b : bool
A boolean that is True if `G` is a tree.
+ Raises
+ ------
+ NetworkXPointlessConcept
+ If `G` is empty.
+
+ Examples
+ --------
+ >>> G = nx.Graph()
+ >>> G.add_edges_from([(1, 2), (1, 3), (2, 4), (2, 5)])
+ >>> nx.is_tree(G) # n-1 edges
+ True
+ >>> G.add_edge(3, 4)
+ >>> nx.is_tree(G) # n edges
+ False
+
Notes
-----
In another convention, a directed tree is known as a *polytree* and then
diff --git a/networkx/utils/decorators.py b/networkx/utils/decorators.py
index e8e4bff55..4e065c50b 100644
--- a/networkx/utils/decorators.py
+++ b/networkx/utils/decorators.py
@@ -464,6 +464,9 @@ class argmap:
function constructs an object (like a file handle) that requires
post-processing (like closing).
+ Note: try_finally decorators cannot be used to decorate generator
+ functions.
+
Examples
--------
Most of these examples use `@argmap(...)` to apply the decorator to
@@ -606,6 +609,38 @@ class argmap:
# this code doesn't need to worry about closing the file
print(file.read())
+ Decorators with try_finally = True cannot be used with generator functions,
+ because the `finally` block is evaluated before the generator is exhausted::
+
+ @argmap(open_file, "file", try_finally=True)
+ def file_to_lines(file):
+ for line in file.readlines():
+ yield line
+
+ is equivalent to::
+
+ def file_to_lines_wrapped(file):
+ for line in file.readlines():
+ yield line
+
+ def file_to_lines_wrapper(file):
+ try:
+ file = open_file(file)
+ return file_to_lines_wrapped(file)
+ finally:
+ file.close()
+
+ which behaves similarly to::
+
+ def file_to_lines_whoops(file):
+ file = open_file(file)
+ file.close()
+ for line in file.readlines():
+ yield line
+
+ because the `finally` block of `file_to_lines_wrapper` is executed before
+ the caller has a chance to exhaust the iterator.
+
Notes
-----
An object of this class is callable and intended to be used when
@@ -805,15 +840,8 @@ class argmap:
argmap._lazy_compile
"""
- if inspect.isgeneratorfunction(f):
-
- def func(*args, __wrapper=None, **kwargs):
- yield from argmap._lazy_compile(__wrapper)(*args, **kwargs)
-
- else:
-
- def func(*args, __wrapper=None, **kwargs):
- return argmap._lazy_compile(__wrapper)(*args, **kwargs)
+ def func(*args, __wrapper=None, **kwargs):
+ return argmap._lazy_compile(__wrapper)(*args, **kwargs)
# standard function-wrapping stuff
func.__name__ = f.__name__
@@ -843,6 +871,14 @@ class argmap:
# this is used to variously call self.assemble and self.compile
func.__argmap__ = self
+ if hasattr(f, "__argmap__"):
+ func.__is_generator = f.__is_generator
+ else:
+ func.__is_generator = inspect.isgeneratorfunction(f)
+
+ if self._finally and func.__is_generator:
+ raise nx.NetworkXError("argmap cannot decorate generators with try_finally")
+
return func
__count = 0
@@ -1162,12 +1198,7 @@ class argmap:
fname = cls._name(f)
def_sig = f'def {fname}({", ".join(def_sig)}):'
- if inspect.isgeneratorfunction(f):
- _return = "yield from"
- else:
- _return = "return"
-
- call_sig = f"{_return} {{}}({', '.join(call_sig)})"
+ call_sig = f"return {{}}({', '.join(call_sig)})"
return cls.Signature(fname, sig, def_sig, call_sig, names, npos, args, kwargs)
| networkx/networkx | b79768389070c5533a5ae21afce15dd06cd2cff0 | diff --git a/networkx/algorithms/tests/test_similarity.py b/networkx/algorithms/tests/test_similarity.py
index c4fd17f12..9b620dece 100644
--- a/networkx/algorithms/tests/test_similarity.py
+++ b/networkx/algorithms/tests/test_similarity.py
@@ -894,3 +894,27 @@ class TestSimilarity:
assert expected_paths == list(paths)
assert expected_map == index_map
+
+ def test_symmetry_with_custom_matching(self):
+ print("G2 is edge (a,b) and G3 is edge (a,a)")
+ print("but node order for G2 is (a,b) while for G3 it is (b,a)")
+
+ a, b = "A", "B"
+ G2 = nx.Graph()
+ G2.add_nodes_from((a, b))
+ G2.add_edges_from([(a, b)])
+ G3 = nx.Graph()
+ G3.add_nodes_from((b, a))
+ G3.add_edges_from([(a, a)])
+ for G in (G2, G3):
+ for n in G:
+ G.nodes[n]["attr"] = n
+ for e in G.edges:
+ G.edges[e]["attr"] = e
+ match = lambda x, y: x == y
+
+ print("Starting G2 to G3 GED calculation")
+ assert nx.graph_edit_distance(G2, G3, node_match=match, edge_match=match) == 1
+
+ print("Starting G3 to G2 GED calculation")
+ assert nx.graph_edit_distance(G3, G2, node_match=match, edge_match=match) == 1
diff --git a/networkx/utils/tests/test_decorators.py b/networkx/utils/tests/test_decorators.py
index eee48fd48..3be29e549 100644
--- a/networkx/utils/tests/test_decorators.py
+++ b/networkx/utils/tests/test_decorators.py
@@ -380,29 +380,25 @@ class TestArgmap:
# context exits are called in reverse
assert container == ["c", "b", "a"]
- def test_contextmanager_iterator(self):
+ def test_tryfinally_generator(self):
container = []
- def contextmanager(x):
- nonlocal container
- return x, lambda: container.append(x)
+ def singleton(x):
+ return (x,)
- @argmap(contextmanager, 0, 1, 2, try_finally=True)
+ with pytest.raises(nx.NetworkXError):
+
+ @argmap(singleton, 0, 1, 2, try_finally=True)
+ def foo(x, y, z):
+ yield from (x, y, z)
+
+ @argmap(singleton, 0, 1, 2)
def foo(x, y, z):
- yield from (x, y, z)
+ return x + y + z
q = foo("a", "b", "c")
- assert next(q) == "a"
- assert container == []
- assert next(q) == "b"
- assert container == []
- assert next(q) == "c"
- assert container == []
- with pytest.raises(StopIteration):
- next(q)
- # context exits are called in reverse
- assert container == ["c", "b", "a"]
+ assert q == ("a", "b", "c")
def test_actual_vararg(self):
@argmap(lambda x: -x, 4)
@@ -485,7 +481,25 @@ finally:
pass#"""
)
- def nop(self):
- print(foo.__argmap__.assemble(foo.__wrapped__))
- argmap._lazy_compile(foo)
- print(foo._code)
+ def test_immediate_raise(self):
+ @not_implemented_for("directed")
+ def yield_nodes(G):
+ yield from G
+
+ G = nx.Graph([(1, 2)])
+ D = nx.DiGraph()
+
+ # test first call (argmap is compiled and executed)
+ with pytest.raises(nx.NetworkXNotImplemented):
+ node_iter = yield_nodes(D)
+
+ # test second call (argmap is only executed)
+ with pytest.raises(nx.NetworkXNotImplemented):
+ node_iter = yield_nodes(D)
+
+ # ensure that generators still make generators
+ node_iter = yield_nodes(G)
+ next(node_iter)
+ next(node_iter)
+ with pytest.raises(StopIteration):
+ next(node_iter)
| Update documentation for planar embedding
Let's update the documentation to make it clear that the `check_planarity` function is the primary interface for the planar embedding tools. Also, the class `PlanarEmbedding` is tricky to make sure it maintains the planar data structure. People not familiar with those ideas should definitely start with the `check_planarity` function.
See discussion in #5079 | 0.0 | [
"networkx/utils/tests/test_decorators.py::TestArgmap::test_tryfinally_generator",
"networkx/utils/tests/test_decorators.py::TestArgmap::test_immediate_raise"
] | [
"networkx/utils/tests/test_decorators.py::test_not_implemented_decorator",
"networkx/utils/tests/test_decorators.py::test_not_implemented_decorator_key",
"networkx/utils/tests/test_decorators.py::test_not_implemented_decorator_raise",
"networkx/utils/tests/test_decorators.py::TestOpenFileDecorator::test_writer_arg0_str",
"networkx/utils/tests/test_decorators.py::TestOpenFileDecorator::test_writer_arg0_fobj",
"networkx/utils/tests/test_decorators.py::TestOpenFileDecorator::test_writer_arg0_pathlib",
"networkx/utils/tests/test_decorators.py::TestOpenFileDecorator::test_writer_arg1_str",
"networkx/utils/tests/test_decorators.py::TestOpenFileDecorator::test_writer_arg1_fobj",
"networkx/utils/tests/test_decorators.py::TestOpenFileDecorator::test_writer_arg2default_str",
"networkx/utils/tests/test_decorators.py::TestOpenFileDecorator::test_writer_arg2default_fobj",
"networkx/utils/tests/test_decorators.py::TestOpenFileDecorator::test_writer_arg2default_fobj_path_none",
"networkx/utils/tests/test_decorators.py::TestOpenFileDecorator::test_writer_arg4default_fobj",
"networkx/utils/tests/test_decorators.py::TestOpenFileDecorator::test_writer_kwarg_str",
"networkx/utils/tests/test_decorators.py::TestOpenFileDecorator::test_writer_kwarg_fobj",
"networkx/utils/tests/test_decorators.py::TestOpenFileDecorator::test_writer_kwarg_path_none",
"networkx/utils/tests/test_decorators.py::test_preserve_random_state",
"networkx/utils/tests/test_decorators.py::test_random_state_string_arg_index",
"networkx/utils/tests/test_decorators.py::test_py_random_state_string_arg_index",
"networkx/utils/tests/test_decorators.py::test_random_state_invalid_arg_index",
"networkx/utils/tests/test_decorators.py::test_py_random_state_invalid_arg_index",
"networkx/utils/tests/test_decorators.py::TestArgmap::test_trivial_function",
"networkx/utils/tests/test_decorators.py::TestArgmap::test_trivial_iterator",
"networkx/utils/tests/test_decorators.py::TestArgmap::test_contextmanager",
"networkx/utils/tests/test_decorators.py::TestArgmap::test_actual_vararg",
"networkx/utils/tests/test_decorators.py::TestArgmap::test_signature_destroying_intermediate_decorator",
"networkx/utils/tests/test_decorators.py::TestArgmap::test_actual_kwarg",
"networkx/utils/tests/test_decorators.py::TestArgmap::test_nested_tuple",
"networkx/utils/tests/test_decorators.py::TestArgmap::test_flatten",
"networkx/utils/tests/test_decorators.py::TestArgmap::test_indent"
] | 2022-04-12 17:38:58+00:00 | 4,142 |
|
networkx__networkx-5550 | diff --git a/doc/reference/algorithms/planarity.rst b/doc/reference/algorithms/planarity.rst
index cad00dc8e..03ded5fa8 100644
--- a/doc/reference/algorithms/planarity.rst
+++ b/doc/reference/algorithms/planarity.rst
@@ -7,5 +7,5 @@ Planarity
:toctree: generated/
check_planarity
-.. autoclass:: PlanarEmbedding
- :members:
\ No newline at end of file
+ is_planar
+ PlanarEmbedding
diff --git a/networkx/algorithms/bridges.py b/networkx/algorithms/bridges.py
index 959a67fec..eda4a4f6d 100644
--- a/networkx/algorithms/bridges.py
+++ b/networkx/algorithms/bridges.py
@@ -35,6 +35,9 @@ def bridges(G, root=None):
NodeNotFound
If `root` is not in the graph `G`.
+ NetworkXNotImplemented
+ If `G` is a directed graph.
+
Examples
--------
The barbell graph with parameter zero has a single bridge:
@@ -99,6 +102,9 @@ def has_bridges(G, root=None):
NodeNotFound
If `root` is not in the graph `G`.
+ NetworkXNotImplemented
+ If `G` is a directed graph.
+
Examples
--------
The barbell graph with parameter zero has a single bridge::
@@ -158,6 +164,11 @@ def local_bridges(G, with_span=True, weight=None):
The local bridges as an edge 2-tuple of nodes `(u, v)` or
as a 3-tuple `(u, v, span)` when `with_span is True`.
+ Raises
+ ------
+ NetworkXNotImplemented
+ If `G` is a directed graph or multigraph.
+
Examples
--------
A cycle graph has every edge a local bridge with span N-1.
diff --git a/networkx/algorithms/community/modularity_max.py b/networkx/algorithms/community/modularity_max.py
index 264a0dc07..ca1cfb9e2 100644
--- a/networkx/algorithms/community/modularity_max.py
+++ b/networkx/algorithms/community/modularity_max.py
@@ -326,6 +326,8 @@ def greedy_modularity_communities(
raise ValueError(f"best_n must be between 1 and {len(G)}. Got {best_n}.")
if best_n < cutoff:
raise ValueError(f"Must have best_n >= cutoff. Got {best_n} < {cutoff}")
+ if best_n == 1:
+ return [set(G)]
else:
best_n = G.number_of_nodes()
if n_communities is not None:
@@ -351,7 +353,19 @@ def greedy_modularity_communities(
# continue merging communities until one of the breaking criteria is satisfied
while len(communities) > cutoff:
- dq = next(community_gen)
+ try:
+ dq = next(community_gen)
+ # StopIteration occurs when communities are the connected components
+ except StopIteration:
+ communities = sorted(communities, key=len, reverse=True)
+ # if best_n requires more merging, merge big sets for highest modularity
+ while len(communities) > best_n:
+ comm1, comm2, *rest = communities
+ communities = [comm1 ^ comm2]
+ communities.extend(rest)
+ return communities
+
+ # keep going unless max_mod is reached or best_n says to merge more
if dq < 0 and len(communities) <= best_n:
break
communities = next(community_gen)
diff --git a/networkx/algorithms/covering.py b/networkx/algorithms/covering.py
index 174044270..b2aeb82b5 100644
--- a/networkx/algorithms/covering.py
+++ b/networkx/algorithms/covering.py
@@ -12,36 +12,42 @@ __all__ = ["min_edge_cover", "is_edge_cover"]
@not_implemented_for("directed")
@not_implemented_for("multigraph")
def min_edge_cover(G, matching_algorithm=None):
- """Returns a set of edges which constitutes
- the minimum edge cover of the graph.
+ """Returns the min cardinality edge cover of the graph as a set of edges.
A smallest edge cover can be found in polynomial time by finding
a maximum matching and extending it greedily so that all nodes
- are covered.
+ are covered. This function follows that process. A maximum matching
+ algorithm can be specified for the first step of the algorithm.
+ The resulting set may return a set with one 2-tuple for each edge,
+ (the usual case) or with both 2-tuples `(u, v)` and `(v, u)` for
+ each edge. The latter is only done when a bipartite matching algorithm
+ is specified as `matching_algorithm`.
Parameters
----------
G : NetworkX graph
- An undirected bipartite graph.
+ An undirected graph.
matching_algorithm : function
- A function that returns a maximum cardinality matching in a
- given bipartite graph. The function must take one input, the
- graph ``G``, and return a dictionary mapping each node to its
- mate. If not specified,
+ A function that returns a maximum cardinality matching for `G`.
+ The function must take one input, the graph `G`, and return
+ either a set of edges (with only one direction for the pair of nodes)
+ or a dictionary mapping each node to its mate. If not specified,
+ :func:`~networkx.algorithms.matching.max_weight_matching` is used.
+ Common bipartite matching functions include
:func:`~networkx.algorithms.bipartite.matching.hopcroft_karp_matching`
- will be used. Other possibilities include
- :func:`~networkx.algorithms.bipartite.matching.eppstein_matching`,
- or matching algorithms in the
- :mod:`networkx.algorithms.matching` module.
+ or
+ :func:`~networkx.algorithms.bipartite.matching.eppstein_matching`.
Returns
-------
min_cover : set
- It contains all the edges of minimum edge cover
- in form of tuples. It contains both the edges `(u, v)` and `(v, u)`
- for given nodes `u` and `v` among the edges of minimum edge cover.
+ A set of the edges in a minimum edge cover in the form of tuples.
+ It contains only one of the equivalent 2-tuples `(u, v)` and `(v, u)`
+ for each edge. If a bipartite method is used to compute the matching,
+ the returned set contains both the 2-tuples `(u, v)` and `(v, u)`
+ for each edge of a minimum edge cover.
Notes
-----
@@ -53,9 +59,13 @@ def min_edge_cover(G, matching_algorithm=None):
is bounded by the worst-case running time of the function
``matching_algorithm``.
- Minimum edge cover for bipartite graph can also be found using the
- function present in :mod:`networkx.algorithms.bipartite.covering`
+ Minimum edge cover for `G` can also be found using the `min_edge_covering`
+ function in :mod:`networkx.algorithms.bipartite.covering` which is
+ simply this function with a default matching algorithm of
+ :func:`~networkx.algorithms.bipartite.matching.hopcraft_karp_matching`
"""
+ if len(G) == 0:
+ return set()
if nx.number_of_isolates(G) > 0:
# ``min_cover`` does not exist as there is an isolated node
raise nx.NetworkXException(
@@ -66,11 +76,12 @@ def min_edge_cover(G, matching_algorithm=None):
maximum_matching = matching_algorithm(G)
# ``min_cover`` is superset of ``maximum_matching``
try:
- min_cover = set(
- maximum_matching.items()
- ) # bipartite matching case returns dict
+ # bipartite matching algs return dict so convert if needed
+ min_cover = set(maximum_matching.items())
+ bipartite_cover = True
except AttributeError:
min_cover = maximum_matching
+ bipartite_cover = False
# iterate for uncovered nodes
uncovered_nodes = set(G) - {v for u, v in min_cover} - {u for u, v in min_cover}
for v in uncovered_nodes:
@@ -82,7 +93,8 @@ def min_edge_cover(G, matching_algorithm=None):
# multigraph.)
u = arbitrary_element(G[v])
min_cover.add((u, v))
- min_cover.add((v, u))
+ if bipartite_cover:
+ min_cover.add((v, u))
return min_cover
diff --git a/networkx/algorithms/planarity.py b/networkx/algorithms/planarity.py
index 4d1441efc..bc6ff2f0f 100644
--- a/networkx/algorithms/planarity.py
+++ b/networkx/algorithms/planarity.py
@@ -1,7 +1,39 @@
from collections import defaultdict
import networkx as nx
-__all__ = ["check_planarity", "PlanarEmbedding"]
+__all__ = ["check_planarity", "is_planar", "PlanarEmbedding"]
+
+
+def is_planar(G):
+ """Returns True if and only if `G` is planar.
+
+ A graph is *planar* iff it can be drawn in a plane without
+ any edge intersections.
+
+ Parameters
+ ----------
+ G : NetworkX graph
+
+ Returns
+ -------
+ bool
+ Whether the graph is planar.
+
+ Examples
+ --------
+ >>> G = nx.Graph([(0, 1), (0, 2)])
+ >>> nx.is_planar(G)
+ True
+ >>> nx.is_planar(nx.complete_graph(5))
+ False
+
+ See Also
+ --------
+ check_planarity :
+ Check if graph is planar *and* return a `PlanarEmbedding` instance if True.
+ """
+
+ return check_planarity(G, counterexample=False)[0]
def check_planarity(G, counterexample=False):
@@ -24,6 +56,18 @@ def check_planarity(G, counterexample=False):
If the graph is planar `certificate` is a PlanarEmbedding
otherwise it is a Kuratowski subgraph.
+ Examples
+ --------
+ >>> G = nx.Graph([(0, 1), (0, 2)])
+ >>> is_planar, P = nx.check_planarity(G)
+ >>> print(is_planar)
+ True
+
+ When `G` is planar, a `PlanarEmbedding` instance is returned:
+
+ >>> P.get_data()
+ {0: [1, 2], 1: [0], 2: [0]}
+
Notes
-----
A (combinatorial) embedding consists of cyclic orderings of the incident
@@ -37,6 +81,11 @@ def check_planarity(G, counterexample=False):
A counterexample is only generated if the corresponding parameter is set,
because the complexity of the counterexample generation is higher.
+ See also
+ --------
+ is_planar :
+ Check for planarity without creating a `PlanarEmbedding` or counterexample.
+
References
----------
.. [1] Ulrik Brandes:
@@ -716,6 +765,8 @@ class PlanarEmbedding(nx.DiGraph):
The planar embedding is given by a `combinatorial embedding
<https://en.wikipedia.org/wiki/Graph_embedding#Combinatorial_embedding>`_.
+ .. note:: `check_planarity` is the preferred way to check if a graph is planar.
+
**Neighbor ordering:**
In comparison to a usual graph structure, the embedding also stores the
@@ -761,6 +812,15 @@ class PlanarEmbedding(nx.DiGraph):
For a half-edge (u, v) that is orientated such that u is below v then the
face that belongs to (u, v) is to the right of this half-edge.
+ See Also
+ --------
+ is_planar :
+ Preferred way to check if an existing graph is planar.
+
+ check_planarity :
+ A convenient way to create a `PlanarEmbedding`. If not planar,
+ it returns a subgraph that shows this.
+
Examples
--------
diff --git a/networkx/algorithms/tournament.py b/networkx/algorithms/tournament.py
index bace64bae..a002e022e 100644
--- a/networkx/algorithms/tournament.py
+++ b/networkx/algorithms/tournament.py
@@ -82,6 +82,13 @@ def is_tournament(G):
bool
Whether the given graph is a tournament graph.
+ Examples
+ --------
+ >>> from networkx.algorithms import tournament
+ >>> G = nx.DiGraph([(0, 1), (1, 2), (2, 0)])
+ >>> tournament.is_tournament(G)
+ True
+
Notes
-----
Some definitions require a self-loop on each node, but that is not
@@ -114,6 +121,13 @@ def hamiltonian_path(G):
path : list
A list of nodes which form a Hamiltonian path in `G`.
+ Examples
+ --------
+ >>> from networkx.algorithms import tournament
+ >>> G = nx.DiGraph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)])
+ >>> tournament.hamiltonian_path(G)
+ [0, 1, 2, 3]
+
Notes
-----
This is a recursive implementation with an asymptotic running time
@@ -185,6 +199,13 @@ def score_sequence(G):
list
A sorted list of the out-degrees of the nodes of `G`.
+ Examples
+ --------
+ >>> from networkx.algorithms import tournament
+ >>> G = nx.DiGraph([(1, 0), (1, 3), (0, 2), (0, 3), (2, 1), (3, 2)])
+ >>> tournament.score_sequence(G)
+ [1, 1, 2, 2]
+
"""
return sorted(d for v, d in G.out_degree())
@@ -260,6 +281,15 @@ def is_reachable(G, s, t):
bool
Whether there is a path from `s` to `t` in `G`.
+ Examples
+ --------
+ >>> from networkx.algorithms import tournament
+ >>> G = nx.DiGraph([(1, 0), (1, 3), (1, 2), (2, 3), (2, 0), (3, 0)])
+ >>> tournament.is_reachable(G, 1, 3)
+ True
+ >>> tournament.is_reachable(G, 3, 2)
+ False
+
Notes
-----
Although this function is more theoretically efficient than the
@@ -331,6 +361,16 @@ def is_strongly_connected(G):
bool
Whether the tournament is strongly connected.
+ Examples
+ --------
+ >>> from networkx.algorithms import tournament
+ >>> G = nx.DiGraph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3), (3, 0)])
+ >>> tournament.is_strongly_connected(G)
+ True
+ >>> G.remove_edge(1, 3)
+ >>> tournament.is_strongly_connected(G)
+ False
+
Notes
-----
Although this function is more theoretically efficient than the
diff --git a/networkx/algorithms/tree/recognition.py b/networkx/algorithms/tree/recognition.py
index 52da959b6..88b2abe8b 100644
--- a/networkx/algorithms/tree/recognition.py
+++ b/networkx/algorithms/tree/recognition.py
@@ -96,6 +96,16 @@ def is_arborescence(G):
b : bool
A boolean that is True if `G` is an arborescence.
+ Examples
+ --------
+ >>> G = nx.DiGraph([(0, 1), (0, 2), (2, 3), (3, 4)])
+ >>> nx.is_arborescence(G)
+ True
+ >>> G.remove_edge(0, 1)
+ >>> G.add_edge(1, 2) # maximum in-degree is 2
+ >>> nx.is_arborescence(G)
+ False
+
Notes
-----
In another convention, an arborescence is known as a *tree*.
@@ -125,6 +135,16 @@ def is_branching(G):
b : bool
A boolean that is True if `G` is a branching.
+ Examples
+ --------
+ >>> G = nx.DiGraph([(0, 1), (1, 2), (2, 3), (3, 4)])
+ >>> nx.is_branching(G)
+ True
+ >>> G.remove_edge(2, 3)
+ >>> G.add_edge(3, 1) # maximum in-degree is 2
+ >>> nx.is_branching(G)
+ False
+
Notes
-----
In another convention, a branching is also known as a *forest*.
| networkx/networkx | 1e5f0bde4cf4cbe4b65bf6e7be775a49556dcf23 | diff --git a/networkx/algorithms/community/tests/test_modularity_max.py b/networkx/algorithms/community/tests/test_modularity_max.py
index 784e4a97b..acdb19d64 100644
--- a/networkx/algorithms/community/tests/test_modularity_max.py
+++ b/networkx/algorithms/community/tests/test_modularity_max.py
@@ -44,6 +44,17 @@ def test_modularity_communities_categorical_labels(func):
assert set(func(G)) == expected
+def test_greedy_modularity_communities_components():
+ # Test for gh-5530
+ G = nx.Graph([(0, 1), (2, 3), (4, 5), (5, 6)])
+ # usual case with 3 components
+ assert greedy_modularity_communities(G) == [{4, 5, 6}, {0, 1}, {2, 3}]
+ # best_n can make the algorithm continue even when modularity goes down
+ assert greedy_modularity_communities(G, best_n=3) == [{4, 5, 6}, {0, 1}, {2, 3}]
+ assert greedy_modularity_communities(G, best_n=2) == [{0, 1, 4, 5, 6}, {2, 3}]
+ assert greedy_modularity_communities(G, best_n=1) == [{0, 1, 2, 3, 4, 5, 6}]
+
+
def test_greedy_modularity_communities_relabeled():
# Test for gh-4966
G = nx.balanced_tree(2, 2)
@@ -306,7 +317,7 @@ def test_cutoff_parameter():
def test_best_n():
G = nx.barbell_graph(5, 3)
- # Same result as without enforcing n_communities:
+ # Same result as without enforcing cutoff:
best_n = 3
expected = [frozenset(range(5)), frozenset(range(8, 13)), frozenset(range(5, 8))]
assert greedy_modularity_communities(G, best_n=best_n) == expected
diff --git a/networkx/algorithms/tests/test_covering.py b/networkx/algorithms/tests/test_covering.py
index 78487b734..40971963e 100644
--- a/networkx/algorithms/tests/test_covering.py
+++ b/networkx/algorithms/tests/test_covering.py
@@ -14,28 +14,44 @@ class TestMinEdgeCover:
assert nx.min_edge_cover(G) == {(0, 0)}
def test_graph_single_edge(self):
- G = nx.Graph()
- G.add_edge(0, 1)
+ G = nx.Graph([(0, 1)])
assert nx.min_edge_cover(G) in ({(0, 1)}, {(1, 0)})
+ def test_graph_two_edge_path(self):
+ G = nx.path_graph(3)
+ min_cover = nx.min_edge_cover(G)
+ assert len(min_cover) == 2
+ for u, v in G.edges:
+ assert (u, v) in min_cover or (v, u) in min_cover
+
def test_bipartite_explicit(self):
G = nx.Graph()
G.add_nodes_from([1, 2, 3, 4], bipartite=0)
G.add_nodes_from(["a", "b", "c"], bipartite=1)
G.add_edges_from([(1, "a"), (1, "b"), (2, "b"), (2, "c"), (3, "c"), (4, "a")])
+ # Use bipartite method by prescribing the algorithm
min_cover = nx.min_edge_cover(
G, nx.algorithms.bipartite.matching.eppstein_matching
)
- min_cover2 = nx.min_edge_cover(G)
assert nx.is_edge_cover(G, min_cover)
assert len(min_cover) == 8
+ # Use the default method which is not specialized for bipartite
+ min_cover2 = nx.min_edge_cover(G)
+ assert nx.is_edge_cover(G, min_cover2)
+ assert len(min_cover2) == 4
- def test_complete_graph(self):
+ def test_complete_graph_even(self):
G = nx.complete_graph(10)
min_cover = nx.min_edge_cover(G)
assert nx.is_edge_cover(G, min_cover)
assert len(min_cover) == 5
+ def test_complete_graph_odd(self):
+ G = nx.complete_graph(11)
+ min_cover = nx.min_edge_cover(G)
+ assert nx.is_edge_cover(G, min_cover)
+ assert len(min_cover) == 6
+
class TestIsEdgeCover:
"""Tests for :func:`networkx.algorithms.is_edge_cover`"""
| greedy_modularity_communities raises StopIteration for unconnected (?) graph
<!--- Provide a general summary of the issue in the Title above -->
After an update of `networkx` from 2.6.3 to 2.8, one of my tests suddenly failed with
```
Traceback (most recent call last):
File "/usr/lib/python3.10/runpy.py", line 196, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/usr/lib/python3.10/runpy.py", line 86, in _run_code
exec(code, run_globals)
File "/home/gereon/Develop/lexedata/src/lexedata/report/nonconcatenative_morphemes.py", line 159, in <module>
networkx.algorithms.community.greedy_modularity_communities(graph),
File "/home/gereon/.local/etc/lexedata/lib/python3.10/site-packages/networkx/algorithms/community/modularity_max.py", line 354, in greedy_modularity_communities
dq = next(community_gen)
StopIteration
```
It turns out that the internals of `greedy_modularity_communities` have changed, so the function doesn't work any more with unconnected graphs.
### Current Behavior
<!--- Tell us what happens instead of the expected behavior -->
`networkx.algorithms.community.greedy_modularity_communities` fails with undocumented error message for unconnected graphs, or graphs without edges
### Expected Behavior
<!--- Tell us what should happen -->
- Either document the requirement to have a connected graph with at least one edge and throw `ValueError` instead of `StopIteration` when it is not fulfilled, or run the graph through `nx.connected_components()` first.
- If the graph has only one node and no edges, return that node.
### Steps to Reproduce
<!--- Provide a minimal example that reproduces the bug -->
```
>>> G = nx.Graph()
>>> G.add_edges_from([(0,1),(2,3)])
>>> greedy_modularity_communities(G)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/gereon/.local/etc/lexedata/lib/python3.10/site-packages/networkx/algorithms/community/modularity_max.py", line 354, in greedy_modularity_communities
dq = next(community_gen)
StopIteration
```
```
>>> G = nx.Graph()
>>> G.add_nodes_from([1])
>>> greedy_modularity_communities(G)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/gereon/.local/etc/lexedata/lib/python3.10/site-packages/networkx/algorithms/community/modularity_max.py", line 350, in greedy_modularity_communities
communities = next(community_gen)
File "/home/gereon/.local/etc/lexedata/lib/python3.10/site-packages/networkx/algorithms/community/modularity_max.py", line 79, in _greedy_modularity_communities_generator
q0 = 1 / m
ZeroDivisionError: division by zero
```
### Environment
<!--- Please provide details about your local environment -->
Python version: 3.10.2
NetworkX version: 2.8 | 0.0 | [
"networkx/algorithms/community/tests/test_modularity_max.py::test_greedy_modularity_communities_components",
"networkx/algorithms/tests/test_covering.py::TestMinEdgeCover::test_graph_two_edge_path",
"networkx/algorithms/tests/test_covering.py::TestMinEdgeCover::test_bipartite_explicit",
"networkx/algorithms/tests/test_covering.py::TestMinEdgeCover::test_complete_graph_odd"
] | [
"networkx/algorithms/community/tests/test_modularity_max.py::test_modularity_communities[greedy_modularity_communities]",
"networkx/algorithms/community/tests/test_modularity_max.py::test_modularity_communities[naive_greedy_modularity_communities]",
"networkx/algorithms/community/tests/test_modularity_max.py::test_modularity_communities_categorical_labels[greedy_modularity_communities]",
"networkx/algorithms/community/tests/test_modularity_max.py::test_modularity_communities_categorical_labels[naive_greedy_modularity_communities]",
"networkx/algorithms/community/tests/test_modularity_max.py::test_greedy_modularity_communities_relabeled",
"networkx/algorithms/community/tests/test_modularity_max.py::test_greedy_modularity_communities_directed",
"networkx/algorithms/community/tests/test_modularity_max.py::test_modularity_communities_weighted[greedy_modularity_communities]",
"networkx/algorithms/community/tests/test_modularity_max.py::test_modularity_communities_weighted[naive_greedy_modularity_communities]",
"networkx/algorithms/community/tests/test_modularity_max.py::test_modularity_communities_floating_point",
"networkx/algorithms/community/tests/test_modularity_max.py::test_modularity_communities_directed_weighted",
"networkx/algorithms/community/tests/test_modularity_max.py::test_greedy_modularity_communities_multigraph",
"networkx/algorithms/community/tests/test_modularity_max.py::test_greedy_modularity_communities_multigraph_weighted",
"networkx/algorithms/community/tests/test_modularity_max.py::test_greed_modularity_communities_multidigraph",
"networkx/algorithms/community/tests/test_modularity_max.py::test_greed_modularity_communities_multidigraph_weighted",
"networkx/algorithms/community/tests/test_modularity_max.py::test_resolution_parameter_impact",
"networkx/algorithms/community/tests/test_modularity_max.py::test_cutoff_parameter",
"networkx/algorithms/community/tests/test_modularity_max.py::test_best_n",
"networkx/algorithms/tests/test_covering.py::TestMinEdgeCover::test_empty_graph",
"networkx/algorithms/tests/test_covering.py::TestMinEdgeCover::test_graph_with_loop",
"networkx/algorithms/tests/test_covering.py::TestMinEdgeCover::test_graph_single_edge",
"networkx/algorithms/tests/test_covering.py::TestMinEdgeCover::test_complete_graph_even",
"networkx/algorithms/tests/test_covering.py::TestIsEdgeCover::test_empty_graph",
"networkx/algorithms/tests/test_covering.py::TestIsEdgeCover::test_graph_with_loop",
"networkx/algorithms/tests/test_covering.py::TestIsEdgeCover::test_graph_single_edge"
] | 2022-04-17 20:42:01+00:00 | 4,143 |
|
networkx__networkx-5894 | diff --git a/networkx/classes/graph.py b/networkx/classes/graph.py
index ebbc8b535..47d5f81d9 100644
--- a/networkx/classes/graph.py
+++ b/networkx/classes/graph.py
@@ -41,6 +41,28 @@ class _CachedPropertyResetterAdj:
del od["adj"]
+class _CachedPropertyResetterNode:
+ """Data Descriptor class for _node that resets ``nodes`` cached_property when needed
+
+ This assumes that the ``cached_property`` ``G.node`` should be reset whenever
+ ``G._node`` is set to a new value.
+
+ This object sits on a class and ensures that any instance of that
+ class clears its cached property "nodes" whenever the underlying
+ instance attribute "_node" is set to a new object. It only affects
+ the set process of the obj._adj attribute. All get/del operations
+ act as they normally would.
+
+ For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html
+ """
+
+ def __set__(self, obj, value):
+ od = obj.__dict__
+ od["_node"] = value
+ if "nodes" in od:
+ del od["nodes"]
+
+
class Graph:
"""
Base class for undirected graphs.
@@ -282,6 +304,7 @@ class Graph:
"""
_adj = _CachedPropertyResetterAdj()
+ _node = _CachedPropertyResetterNode()
node_dict_factory = dict
node_attr_dict_factory = dict
| networkx/networkx | 98060487ad192918cfc2415fc0b5c309ff2d3565 | diff --git a/networkx/algorithms/shortest_paths/unweighted.py b/networkx/algorithms/shortest_paths/unweighted.py
index 5363b24dc..9d1dff5b2 100644
--- a/networkx/algorithms/shortest_paths/unweighted.py
+++ b/networkx/algorithms/shortest_paths/unweighted.py
@@ -460,8 +460,7 @@ def all_pairs_shortest_path(G, cutoff=None):
def predecessor(G, source, target=None, cutoff=None, return_seen=None):
- """Returns dict of predecessors for the path from source to all nodes in G
-
+ """Returns dict of predecessors for the path from source to all nodes in G.
Parameters
----------
@@ -477,12 +476,23 @@ def predecessor(G, source, target=None, cutoff=None, return_seen=None):
cutoff : integer, optional
Depth to stop the search. Only paths of length <= cutoff are returned.
+ return_seen : bool, optional (default=None)
+ Whether to return a dictionary, keyed by node, of the level (number of
+ hops) to reach the node (as seen during breadth-first-search).
Returns
-------
pred : dictionary
Dictionary, keyed by node, of predecessors in the shortest path.
+
+ (pred, seen): tuple of dictionaries
+ If `return_seen` argument is set to `True`, then a tuple of dictionaries
+ is returned. The first element is the dictionary, keyed by node, of
+ predecessors in the shortest path. The second element is the dictionary,
+ keyed by node, of the level (number of hops) to reach the node (as seen
+ during breadth-first-search).
+
Examples
--------
>>> G = nx.path_graph(4)
@@ -490,6 +500,9 @@ def predecessor(G, source, target=None, cutoff=None, return_seen=None):
[0, 1, 2, 3]
>>> nx.predecessor(G, 0)
{0: [], 1: [0], 2: [1], 3: [2]}
+ >>> nx.predecessor(G, 0, return_seen=True)
+ ({0: [], 1: [0], 2: [1], 3: [2]}, {0: 0, 1: 1, 2: 2, 3: 3})
+
"""
if source not in G:
diff --git a/networkx/classes/tests/test_graph.py b/networkx/classes/tests/test_graph.py
index ebaa04bbd..2adb159bf 100644
--- a/networkx/classes/tests/test_graph.py
+++ b/networkx/classes/tests/test_graph.py
@@ -178,6 +178,11 @@ class BaseGraphTester:
G._adj = {}
assert id(G.adj) != id(old_adj)
+ old_nodes = G.nodes
+ assert id(G.nodes) == id(old_nodes)
+ G._node = {}
+ assert id(G.nodes) != id(old_nodes)
+
def test_attributes_cached(self):
G = self.K3.copy()
assert id(G.nodes) == id(G.nodes)
| Critical NetworkX 2.8.X bug with mutable cached_properties
### Current Behavior
The `nodes()` method of a Graph is decorated with `@cached_property`.<br>
This leads to the assumption that a Graph's `nodes()` method should return a static value.<br>
This assumption is incorrect.
Notably, the `@cached_property` decorator completely breaks `Graph.subgraph()`.<br>
Trace:
Graph.subgraph -> graphviews.subgraph_view -> [this line](https://github.com/networkx/networkx/blob/ead0e65bda59862e329f2e6f1da47919c6b07ca9/networkx/classes/graphviews.py#L149) prevents [this line](https://github.com/networkx/networkx/blob/ead0e65bda59862e329f2e6f1da47919c6b07ca9/networkx/classes/graphviews.py#L152) from functioning correctly
Subgraphs are shown as containing the wrong nodes as a result, until `del G.nodes` is manually run.<br>
This breaks things.
### Expected Behavior
`@cached_property` decorators should not break functionality.
### Steps to Reproduce
- Initialize a Graph, `G`
- Populate `G` with node objects that are complex enough that the following inequality assertion will pass: `newG = nx.freeze(G.__class__()); newG._graph = G; newG.graph = G.graph; assert(newG.nodes()!=G.nodes)`.
- Pick a subset of `G.nodes`, call this `subG_nodes`
- `subgraph = G.subgraph(subG_nodes)`
- In NetworkX 2.7, the nodes of `subgraph` will be a subset of the nodes of `G`. In NetworkX 2.8, the nodes of `subgraph` and the nodes of `G` will be a fully disjoint set.
### Environment
<!--- Please provide details about your local environment -->
Python version: 3.9.10
NetworkX version: 2.8.5 vs 2.7.0
| 0.0 | [
"networkx/classes/tests/test_graph.py::TestGraph::test_cache_reset"
] | [
"networkx/classes/tests/test_graph.py::TestGraph::test_contains",
"networkx/classes/tests/test_graph.py::TestGraph::test_order",
"networkx/classes/tests/test_graph.py::TestGraph::test_nodes",
"networkx/classes/tests/test_graph.py::TestGraph::test_none_node",
"networkx/classes/tests/test_graph.py::TestGraph::test_has_node",
"networkx/classes/tests/test_graph.py::TestGraph::test_has_edge",
"networkx/classes/tests/test_graph.py::TestGraph::test_neighbors",
"networkx/classes/tests/test_graph.py::TestGraph::test_memory_leak",
"networkx/classes/tests/test_graph.py::TestGraph::test_edges",
"networkx/classes/tests/test_graph.py::TestGraph::test_degree",
"networkx/classes/tests/test_graph.py::TestGraph::test_size",
"networkx/classes/tests/test_graph.py::TestGraph::test_nbunch_iter",
"networkx/classes/tests/test_graph.py::TestGraph::test_nbunch_iter_node_format_raise",
"networkx/classes/tests/test_graph.py::TestGraph::test_selfloop_degree",
"networkx/classes/tests/test_graph.py::TestGraph::test_selfloops",
"networkx/classes/tests/test_graph.py::TestGraph::test_attributes_cached",
"networkx/classes/tests/test_graph.py::TestGraph::test_weighted_degree",
"networkx/classes/tests/test_graph.py::TestGraph::test_name",
"networkx/classes/tests/test_graph.py::TestGraph::test_str_unnamed",
"networkx/classes/tests/test_graph.py::TestGraph::test_str_named",
"networkx/classes/tests/test_graph.py::TestGraph::test_graph_chain",
"networkx/classes/tests/test_graph.py::TestGraph::test_copy",
"networkx/classes/tests/test_graph.py::TestGraph::test_class_copy",
"networkx/classes/tests/test_graph.py::TestGraph::test_fresh_copy",
"networkx/classes/tests/test_graph.py::TestGraph::test_graph_attr",
"networkx/classes/tests/test_graph.py::TestGraph::test_node_attr",
"networkx/classes/tests/test_graph.py::TestGraph::test_node_attr2",
"networkx/classes/tests/test_graph.py::TestGraph::test_edge_lookup",
"networkx/classes/tests/test_graph.py::TestGraph::test_edge_attr",
"networkx/classes/tests/test_graph.py::TestGraph::test_edge_attr2",
"networkx/classes/tests/test_graph.py::TestGraph::test_edge_attr3",
"networkx/classes/tests/test_graph.py::TestGraph::test_edge_attr4",
"networkx/classes/tests/test_graph.py::TestGraph::test_to_undirected",
"networkx/classes/tests/test_graph.py::TestGraph::test_to_directed_as_view",
"networkx/classes/tests/test_graph.py::TestGraph::test_to_undirected_as_view",
"networkx/classes/tests/test_graph.py::TestGraph::test_directed_class",
"networkx/classes/tests/test_graph.py::TestGraph::test_to_directed",
"networkx/classes/tests/test_graph.py::TestGraph::test_subgraph",
"networkx/classes/tests/test_graph.py::TestGraph::test_selfloops_attr",
"networkx/classes/tests/test_graph.py::TestGraph::test_pickle",
"networkx/classes/tests/test_graph.py::TestGraph::test_data_input",
"networkx/classes/tests/test_graph.py::TestGraph::test_adjacency",
"networkx/classes/tests/test_graph.py::TestGraph::test_getitem",
"networkx/classes/tests/test_graph.py::TestGraph::test_add_node",
"networkx/classes/tests/test_graph.py::TestGraph::test_add_nodes_from",
"networkx/classes/tests/test_graph.py::TestGraph::test_remove_node",
"networkx/classes/tests/test_graph.py::TestGraph::test_remove_nodes_from",
"networkx/classes/tests/test_graph.py::TestGraph::test_add_edge",
"networkx/classes/tests/test_graph.py::TestGraph::test_add_edges_from",
"networkx/classes/tests/test_graph.py::TestGraph::test_remove_edge",
"networkx/classes/tests/test_graph.py::TestGraph::test_remove_edges_from",
"networkx/classes/tests/test_graph.py::TestGraph::test_clear",
"networkx/classes/tests/test_graph.py::TestGraph::test_clear_edges",
"networkx/classes/tests/test_graph.py::TestGraph::test_edges_data",
"networkx/classes/tests/test_graph.py::TestGraph::test_get_edge_data",
"networkx/classes/tests/test_graph.py::TestGraph::test_update",
"networkx/classes/tests/test_graph.py::TestEdgeSubgraph::test_correct_nodes",
"networkx/classes/tests/test_graph.py::TestEdgeSubgraph::test_correct_edges",
"networkx/classes/tests/test_graph.py::TestEdgeSubgraph::test_add_node",
"networkx/classes/tests/test_graph.py::TestEdgeSubgraph::test_remove_node",
"networkx/classes/tests/test_graph.py::TestEdgeSubgraph::test_node_attr_dict",
"networkx/classes/tests/test_graph.py::TestEdgeSubgraph::test_edge_attr_dict",
"networkx/classes/tests/test_graph.py::TestEdgeSubgraph::test_graph_attr_dict"
] | 2022-07-25 14:18:48+00:00 | 4,144 |
|
networkx__networkx-5903 | diff --git a/networkx/relabel.py b/networkx/relabel.py
index 35e71536a..65297d573 100644
--- a/networkx/relabel.py
+++ b/networkx/relabel.py
@@ -114,9 +114,13 @@ def relabel_nodes(G, mapping, copy=True):
--------
convert_node_labels_to_integers
"""
- # you can pass a function f(old_label)->new_label
+ # you can pass a function f(old_label) -> new_label
+ # or a class e.g. str(old_label) -> new_label
# but we'll just make a dictionary here regardless
- if not hasattr(mapping, "__getitem__"):
+ # To allow classes, we check if __getitem__ is a bound method using __self__
+ if not (
+ hasattr(mapping, "__getitem__") and hasattr(mapping.__getitem__, "__self__")
+ ):
m = {n: mapping(n) for n in G}
else:
m = mapping
| networkx/networkx | 28f78cfa9a386620ee1179582fda1db5ffc59f84 | diff --git a/networkx/tests/test_relabel.py b/networkx/tests/test_relabel.py
index 46b74482b..9a9db76eb 100644
--- a/networkx/tests/test_relabel.py
+++ b/networkx/tests/test_relabel.py
@@ -106,6 +106,12 @@ class TestRelabel:
H = nx.relabel_nodes(G, mapping)
assert nodes_equal(H.nodes(), [65, 66, 67, 68])
+ def test_relabel_nodes_classes(self):
+ G = nx.empty_graph()
+ G.add_edges_from([(0, 1), (0, 2), (1, 2), (2, 3)])
+ H = nx.relabel_nodes(G, str)
+ assert nodes_equal(H.nodes, ["0", "1", "2", "3"])
+
def test_relabel_nodes_graph(self):
G = nx.Graph([("A", "B"), ("A", "C"), ("B", "C"), ("C", "D")])
mapping = {"A": "aardvark", "B": "bear", "C": "cat", "D": "dog"}
| `relabel_nodes` does not work for callables with `__getitem__`
<!-- If you have a general question about NetworkX, please use the discussions tab to create a new discussion -->
<!--- Provide a general summary of the issue in the Title above -->
`relabel_nodes` accepts mappings in the form of functions. It differentiates function from mapping by testing`not hasattr(mapping, "__getitem__")`. This test is ambiguous for callables that do possess '__getitem__`, e.g. `str`.
Would it be better to test `isinstance(mapping, typing.Mapping)` and document accordingly?
### Current Behavior
<!--- Tell us what happens instead of the expected behavior -->
```python
import networkx as nx
G = nx.DiGraph()
G.add_nodes_from([1, 2])
# works
# nx.relabel_nodes(G, lambda x: str(x))
# error
nx.relabel_nodes(G, str)
```
```
Traceback (most recent call last):
File "...\networkx_2_8_4_relabel_callable.py", line 10, in <module>
nx.relabel_nodes(G, str)
File "...\lib\site-packages\networkx\relabel.py", line 121, in relabel_nodes
return _relabel_copy(G, m)
File "...\lib\site-packages\networkx\relabel.py", line 193, in _relabel_copy
H.add_nodes_from(mapping.get(n, n) for n in G)
File "...\lib\site-packages\networkx\classes\digraph.py", line 519, in add_nodes_from
for n in nodes_for_adding:
File "...\lib\site-packages\networkx\relabel.py", line 193, in <genexpr>
H.add_nodes_from(mapping.get(n, n) for n in G)
AttributeError: type object 'str' has no attribute 'get'
```
### Expected Behavior
<!--- Tell us what should happen -->
`relabel_nodes` works for callables.
### Steps to Reproduce
<!--- Provide a minimal example that reproduces the bug -->
See current behavior.
### Environment
<!--- Please provide details about your local environment -->
Python version: 3.9
NetworkX version: 2.8.5
### Additional context
<!--- Add any other context about the problem here, screenshots, etc. -->
| 0.0 | [
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_nodes_classes"
] | [
"networkx/tests/test_relabel.py::TestRelabel::test_convert_node_labels_to_integers",
"networkx/tests/test_relabel.py::TestRelabel::test_convert_to_integers2",
"networkx/tests/test_relabel.py::TestRelabel::test_convert_to_integers_raise",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_nodes_copy",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_nodes_function",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_nodes_graph",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_nodes_orderedgraph",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_nodes_digraph",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_nodes_multigraph",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_nodes_multidigraph",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_isolated_nodes_to_same",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_nodes_missing",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_copy_name",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_toposort",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_selfloop",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_multidigraph_inout_merge_nodes",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_multigraph_merge_inplace",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_multidigraph_merge_inplace",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_multidigraph_inout_copy",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_multigraph_merge_copy",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_multidigraph_merge_copy",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_multigraph_nonnumeric_key",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_circular",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_preserve_node_order_full_mapping_with_copy_true",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_preserve_node_order_full_mapping_with_copy_false",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_preserve_node_order_partial_mapping_with_copy_true",
"networkx/tests/test_relabel.py::TestRelabel::test_relabel_preserve_node_order_partial_mapping_with_copy_false"
] | 2022-07-29 02:02:29+00:00 | 4,145 |
|
networkx__networkx-5988 | diff --git a/networkx/algorithms/dag.py b/networkx/algorithms/dag.py
index 826b87ff6..d5e2735b1 100644
--- a/networkx/algorithms/dag.py
+++ b/networkx/algorithms/dag.py
@@ -1006,7 +1006,15 @@ def dag_longest_path(G, weight="weight", default_weight=1, topo_order=None):
dist = {} # stores {v : (length, u)}
for v in topo_order:
us = [
- (dist[u][0] + data.get(weight, default_weight), u)
+ (
+ dist[u][0]
+ + (
+ max(data.values(), key=lambda x: x.get(weight, default_weight))
+ if G.is_multigraph()
+ else data
+ ).get(weight, default_weight),
+ u,
+ )
for u, data in G.pred[v].items()
]
@@ -1068,8 +1076,13 @@ def dag_longest_path_length(G, weight="weight", default_weight=1):
"""
path = nx.dag_longest_path(G, weight, default_weight)
path_length = 0
- for (u, v) in pairwise(path):
- path_length += G[u][v].get(weight, default_weight)
+ if G.is_multigraph():
+ for u, v in pairwise(path):
+ i = max(G[u][v], key=lambda x: G[u][v][x].get(weight, default_weight))
+ path_length += G[u][v][i].get(weight, default_weight)
+ else:
+ for (u, v) in pairwise(path):
+ path_length += G[u][v].get(weight, default_weight)
return path_length
| networkx/networkx | 1ce75f0f3604abd0551fa9baf20c65c3747fb328 | diff --git a/networkx/algorithms/tests/test_dag.py b/networkx/algorithms/tests/test_dag.py
index 56f16c4f5..7ad6a77fe 100644
--- a/networkx/algorithms/tests/test_dag.py
+++ b/networkx/algorithms/tests/test_dag.py
@@ -60,6 +60,31 @@ class TestDagLongestPath:
# this will raise NotImplementedError when nodes need to be ordered
nx.dag_longest_path(G)
+ def test_multigraph_unweighted(self):
+ edges = [(1, 2), (2, 3), (2, 3), (3, 4), (4, 5), (1, 3), (1, 5), (3, 5)]
+ G = nx.MultiDiGraph(edges)
+ assert nx.dag_longest_path(G) == [1, 2, 3, 4, 5]
+
+ def test_multigraph_weighted(self):
+ G = nx.MultiDiGraph()
+ edges = [
+ (1, 2, 2),
+ (2, 3, 2),
+ (1, 3, 1),
+ (1, 3, 5),
+ (1, 3, 2),
+ ]
+ G.add_weighted_edges_from(edges)
+ assert nx.dag_longest_path(G) == [1, 3]
+
+ def test_multigraph_weighted_default_weight(self):
+ G = nx.MultiDiGraph([(1, 2), (2, 3)]) # Unweighted edges
+ G.add_weighted_edges_from([(1, 3, 1), (1, 3, 5), (1, 3, 2)])
+
+ # Default value for default weight is 1
+ assert nx.dag_longest_path(G) == [1, 3]
+ assert nx.dag_longest_path(G, default_weight=3) == [1, 2, 3]
+
class TestDagLongestPathLength:
"""Unit tests for computing the length of a longest path in a
@@ -91,6 +116,23 @@ class TestDagLongestPathLength:
G.add_weighted_edges_from(edges)
assert nx.dag_longest_path_length(G) == 5
+ def test_multigraph_unweighted(self):
+ edges = [(1, 2), (2, 3), (2, 3), (3, 4), (4, 5), (1, 3), (1, 5), (3, 5)]
+ G = nx.MultiDiGraph(edges)
+ assert nx.dag_longest_path_length(G) == 4
+
+ def test_multigraph_weighted(self):
+ G = nx.MultiDiGraph()
+ edges = [
+ (1, 2, 2),
+ (2, 3, 2),
+ (1, 3, 1),
+ (1, 3, 5),
+ (1, 3, 2),
+ ]
+ G.add_weighted_edges_from(edges)
+ assert nx.dag_longest_path_length(G) == 5
+
class TestDAG:
@classmethod
| Weighted MultiDiGraphs never use weights in dag_longest_path and dag_longest_path_length
### Current Behavior
Given any MultiDiGraph, using dag_longest_path will always evaluate using the default_weight keyword argument.
This is because dag_longest_path uses `G.pred[v].items()` to grab the data dictionary, but the data dictionary for a MultiDiGraph is embedded inside of another dictionary with the edge number as a key. When dag_longest_path calls `data.get(weight, default_weight)` on this, it will always raise a KeyError on weight and use default_weight instead.
dag_longest_path_length also calls dict.get() on the wrong dictionary, making it return bad results for weighted MultiDiGraphs even if dag_longest_path returns the correct path.
### Expected Behavior
A MultiDiGraph should either evaluate correctly using weights or raise a NotImplementedError.
### Steps to Reproduce
```
MDG = nx.MultiDiGraph([("A", "B", {"cost": 5}), ("B", "C", {"cost": 10}), ("A", "C", {"cost": 40})])
print(nx.dag_longest_path(MDG, weight="cost"), nx.dag_longest_path_length(MDG, weight="cost"))
# prints ['A', 'B', 'C'] 2
# should be ['A', 'C'] 40
```
Incorrect paths are especially noticeable when a weight key is given, but default_weight is set to 0, as it will always return a list containing only the starting node.
### Environment
Python version: 3.10
NetworkX version: 2.8.5
### Additional context
I have a fix for this issue ready if you would like the functions to support MultiDiGraphs. | 0.0 | [
"networkx/algorithms/tests/test_dag.py::TestDagLongestPath::test_multigraph_weighted",
"networkx/algorithms/tests/test_dag.py::TestDagLongestPath::test_multigraph_weighted_default_weight",
"networkx/algorithms/tests/test_dag.py::TestDagLongestPathLength::test_multigraph_weighted"
] | [
"networkx/algorithms/tests/test_dag.py::TestDagLongestPath::test_empty",
"networkx/algorithms/tests/test_dag.py::TestDagLongestPath::test_unweighted1",
"networkx/algorithms/tests/test_dag.py::TestDagLongestPath::test_unweighted2",
"networkx/algorithms/tests/test_dag.py::TestDagLongestPath::test_weighted",
"networkx/algorithms/tests/test_dag.py::TestDagLongestPath::test_undirected_not_implemented",
"networkx/algorithms/tests/test_dag.py::TestDagLongestPath::test_unorderable_nodes",
"networkx/algorithms/tests/test_dag.py::TestDagLongestPath::test_multigraph_unweighted",
"networkx/algorithms/tests/test_dag.py::TestDagLongestPathLength::test_unweighted",
"networkx/algorithms/tests/test_dag.py::TestDagLongestPathLength::test_undirected_not_implemented",
"networkx/algorithms/tests/test_dag.py::TestDagLongestPathLength::test_weighted",
"networkx/algorithms/tests/test_dag.py::TestDagLongestPathLength::test_multigraph_unweighted",
"networkx/algorithms/tests/test_dag.py::TestDAG::test_topological_sort1",
"networkx/algorithms/tests/test_dag.py::TestDAG::test_is_directed_acyclic_graph",
"networkx/algorithms/tests/test_dag.py::TestDAG::test_topological_sort2",
"networkx/algorithms/tests/test_dag.py::TestDAG::test_topological_sort3",
"networkx/algorithms/tests/test_dag.py::TestDAG::test_topological_sort4",
"networkx/algorithms/tests/test_dag.py::TestDAG::test_topological_sort5",
"networkx/algorithms/tests/test_dag.py::TestDAG::test_topological_sort6",
"networkx/algorithms/tests/test_dag.py::TestDAG::test_all_topological_sorts_1",
"networkx/algorithms/tests/test_dag.py::TestDAG::test_all_topological_sorts_2",
"networkx/algorithms/tests/test_dag.py::TestDAG::test_all_topological_sorts_3",
"networkx/algorithms/tests/test_dag.py::TestDAG::test_all_topological_sorts_4",
"networkx/algorithms/tests/test_dag.py::TestDAG::test_all_topological_sorts_multigraph_1",
"networkx/algorithms/tests/test_dag.py::TestDAG::test_all_topological_sorts_multigraph_2",
"networkx/algorithms/tests/test_dag.py::TestDAG::test_ancestors",
"networkx/algorithms/tests/test_dag.py::TestDAG::test_descendants",
"networkx/algorithms/tests/test_dag.py::TestDAG::test_transitive_closure",
"networkx/algorithms/tests/test_dag.py::TestDAG::test_reflexive_transitive_closure",
"networkx/algorithms/tests/test_dag.py::TestDAG::test_transitive_closure_dag",
"networkx/algorithms/tests/test_dag.py::TestDAG::test_transitive_reduction",
"networkx/algorithms/tests/test_dag.py::TestDAG::test_antichains",
"networkx/algorithms/tests/test_dag.py::TestDAG::test_lexicographical_topological_sort",
"networkx/algorithms/tests/test_dag.py::TestDAG::test_lexicographical_topological_sort2",
"networkx/algorithms/tests/test_dag.py::test_topological_generations",
"networkx/algorithms/tests/test_dag.py::test_topological_generations_empty",
"networkx/algorithms/tests/test_dag.py::test_topological_generations_cycle",
"networkx/algorithms/tests/test_dag.py::test_is_aperiodic_cycle",
"networkx/algorithms/tests/test_dag.py::test_is_aperiodic_cycle2",
"networkx/algorithms/tests/test_dag.py::test_is_aperiodic_cycle3",
"networkx/algorithms/tests/test_dag.py::test_is_aperiodic_cycle4",
"networkx/algorithms/tests/test_dag.py::test_is_aperiodic_selfloop",
"networkx/algorithms/tests/test_dag.py::test_is_aperiodic_raise",
"networkx/algorithms/tests/test_dag.py::test_is_aperiodic_bipartite",
"networkx/algorithms/tests/test_dag.py::test_is_aperiodic_rary_tree",
"networkx/algorithms/tests/test_dag.py::test_is_aperiodic_disconnected",
"networkx/algorithms/tests/test_dag.py::test_is_aperiodic_disconnected2",
"networkx/algorithms/tests/test_dag.py::TestDagToBranching::test_single_root",
"networkx/algorithms/tests/test_dag.py::TestDagToBranching::test_multiple_roots",
"networkx/algorithms/tests/test_dag.py::TestDagToBranching::test_already_arborescence",
"networkx/algorithms/tests/test_dag.py::TestDagToBranching::test_already_branching",
"networkx/algorithms/tests/test_dag.py::TestDagToBranching::test_not_acyclic",
"networkx/algorithms/tests/test_dag.py::TestDagToBranching::test_undirected",
"networkx/algorithms/tests/test_dag.py::TestDagToBranching::test_multigraph",
"networkx/algorithms/tests/test_dag.py::TestDagToBranching::test_multidigraph",
"networkx/algorithms/tests/test_dag.py::test_ancestors_descendants_undirected",
"networkx/algorithms/tests/test_dag.py::test_compute_v_structures_raise",
"networkx/algorithms/tests/test_dag.py::test_compute_v_structures"
] | 2022-09-17 21:14:45+00:00 | 4,146 |
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- 49