internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: networkx/networkx

Issue:
Parallel betweenness example bad runtimes in docs
There is a nice example in the gallery for [computing betweenness centrality with multiprocessing](https://networkx.org/documentation/stable/auto_examples/advanced/plot_parallel_betweenness.html). Unfortunately, the example in the docs show poorer performance for the parallel version than the non-parallelized version, likely due to the CI service only using single-core (or otherwise not very performant) nodes for computation. At the very least it might be worth adding some text somewhere to the example to explain why the example shows performance results that differ from what is expected.

It's also probably worth taking a look at the example in its entirety and consider alternative approaches to multiprocessing, e.g. `concurrent.futures`.


Discussion:
Hi, @rossbar. I am new to networkx community and interested in tackling this issue. Should I focus on adding texts to the example or focus more on finding other parallel alternatives? Thank you.  
Hi @berlincho - if you are interested in investigating other parallelization approaches that might be a fun project. It's unlikely that we can do anything to improve the parallel performance of the example in the rendered documentation, as I suspect that is just a limitation related to the CI hardware. A quick note in the explanation for that example might help clear up this point for readers.

Resolving patch:
diff --git a/examples/algorithms/plot_parallel_betweenness.py b/examples/algorithms/plot_parallel_betweenness.py
--- a/examples/algorithms/plot_parallel_betweenness.py
+++ b/examples/algorithms/plot_parallel_betweenness.py
@@ -10,8 +10,12 @@
 the contribution of those nodes to the betweenness centrality of the whole
 network. Here we divide the network in chunks of nodes and we compute their
 contribution to the betweenness centrality of the whole network.
-"""
 
+Note: The example output below shows that the non-parallel implementation is
+faster. This is a limitation of our CI/CD pipeline running on a single core.
+
+Depending on your setup, you will likely observe a speedup.
+"""
 from multiprocessing import Pool
 import time
 import itertools


Test patch:
Repository: networkx/networkx

Issue:
`edgelist` is ignored when drawing selfloops
An issue with self-loop drawing was identified in the discussion in #4991. The `edgelist` parameter for `nx.draw_networkx_edges` is not properly handled for self-loop drawing.

### Steps to Reproduce

```python
>>> import matplotlib.pyplot as plt
>>> G = nx.path_graph(3)
>>> G.add_edge(0, 0)
>>> G.edges()
EdgeView([(0, 1), (0, 0), (1, 2)])
>>> nx.draw(G)  # Draws self-loop, as expected
>>> plt.figure();
>>> nx.draw(G, edgelist=[(0, 1), (1, 2)])  # Still draws self-loop (bug)
```

### Environment
<!--- Please provide details about your local environment -->
Python version: 3.9.6
NetworkX version: 2.6.2


### Additional context

At first glance, it seems the problem lies here:

https://github.com/networkx/networkx/blob/2eb274e39f712047cebf5666ee9caf2ba2e51ee4/networkx/drawing/nx_pylab.py#L853-L856

This code was added to ensure that self-loop edges are drawn even when edges are represented by a LineCollection object, but there should be some additional logic to check whether `edgelist` is `None` before setting it.



Discussion:

Resolving patch:
diff --git a/networkx/drawing/nx_pylab.py b/networkx/drawing/nx_pylab.py
--- a/networkx/drawing/nx_pylab.py
+++ b/networkx/drawing/nx_pylab.py
@@ -852,10 +852,10 @@ def _connectionstyle(posA, posB, *args, **kwargs):
     # Draw the edges
     if use_linecollection:
         edge_viz_obj = _draw_networkx_edges_line_collection()
-        # Make sure selfloop edges are also drawn.
-        edgelist = list(nx.selfloop_edges(G))
-        if edgelist:
-            edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist])
+        # Make sure selfloop edges are also drawn
+        selfloops_to_draw = [loop for loop in nx.selfloop_edges(G) if loop in edgelist]
+        if selfloops_to_draw:
+            edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in selfloops_to_draw])
             arrowstyle = "-"
             _draw_networkx_edges_fancy_arrow_patch()
     else:


Test patch:
diff --git a/networkx/drawing/tests/test_pylab.py b/networkx/drawing/tests/test_pylab.py
--- a/networkx/drawing/tests/test_pylab.py
+++ b/networkx/drawing/tests/test_pylab.py
@@ -423,3 +423,13 @@ def test_draw_networkx_arrows_default_directed(drawing_func):
     )
     assert ax.patches
     plt.delaxes(ax)
+
+
+def test_edgelist_kwarg_not_ignored():
+    # See gh-4994
+    G = nx.path_graph(3)
+    G.add_edge(0, 0)
+    fig, ax = plt.subplots()
+    nx.draw(G, edgelist=[(0, 1), (1, 2)], ax=ax)  # Exclude self-loop from edgelist
+    assert not ax.patches
+    plt.delaxes(ax)
Repository: networkx/networkx

Issue:
`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



Discussion:

Resolving patch:
diff --git a/networkx/readwrite/json_graph/tree.py b/networkx/readwrite/json_graph/tree.py
--- 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:


Test patch:
diff --git a/networkx/readwrite/json_graph/tests/test_tree.py b/networkx/readwrite/json_graph/tests/test_tree.py
--- 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)
Repository: networkx/networkx

Issue:
`to_numpy_recarray` throws `KeyError: weight`
Hello! I am running into trouble with `networkx` version 2.6.3 running an extremely simple script: 

     import networkx as nx
     c_50 = nx.complete_graph(50)
     nx.to_numpy_recarray(c_50)

Which throws a `KeyError: weight` in `convert_matrix.py`. 


Discussion:
`to_numpy_recarray` expects to be passed a structured dtype with named fields, which are used to determine which attributes to use in constructing the adjacency matrix. If you don't supply a dtype, then it's assumed that `"weight"` is the attribute of interest (though this fact is not adequately documented). This explains the exception you're seeing.

In your particular case it's not clear why you'd want a recarray instead of a `ndarray` given that your graph does not have edge attributes. You should probably be using `nx.to_numpy_array(c_50)` instead. If (for whatever reason) you *really* wanted a `recarray` (even though there are no named fields to access in the case above) you could do `nx.to_numpy_array(c_50).view(np.recarray)`.
That is useful to know! I was writing a function which relied on the `recarray` output and the unweighted graph was a case I wanted to handle. In the general case I guess `nx.to_numpy_array` makes the most sense. 

Resolving patch:
diff --git a/networkx/convert_matrix.py b/networkx/convert_matrix.py
--- a/networkx/convert_matrix.py
+++ b/networkx/convert_matrix.py
@@ -706,7 +706,7 @@ def to_numpy_recarray(G, nodelist=None, dtype=None, order=None):
     dtype : NumPy data-type, optional
         A valid NumPy named dtype used to initialize the NumPy recarray.
         The data type names are assumed to be keys in the graph edge attribute
-        dictionary.
+        dictionary. The default is ``dtype([("weight", float)])``.
 
     order : {'C', 'F'}, optional
         Whether to store multidimensional data in C- or Fortran-contiguous


Test patch:
Repository: networkx/networkx

Issue:
Improve Examples Section of ```set_edge_attributes```
<!-- 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 -->


<!--- Tell us what happens instead of the expected behavior -->
While looking at the ```set_edge_attributes``` function, it doesn't include an example using multigraphs. As the ```values``` argument is passed different for non-multigraphs and multigraphs, I figured having a small example will show the difference easily. 

<!--- Tell us what should happen -->

<!--- Provide a minimal example that reproduces the bug -->

<!--- Please provide details about your local environment -->
NetworkX version: 2.6.2

<!--- Add any other context about the problem here, screenshots, etc. -->



Discussion:
I agree that a multigraph example would be a nice improvement. The fact that `values` expects the dict keyed by 3-tuples is definitely worth highlighting.
Okay thanks! I will try to include an example and add a PR. Can you guide me on which file in the repo to be edited? 
> Can you guide me on which file in the repo to be edited?

Check out [our new contributor FAQ](https://networkx.org/documentation/latest/developer/new_contributor_faq.html#q-i-want-to-work-on-a-specific-function-how-do-i-find-it-in-the-source-code) which will hopefully give you some ideas for how to navigate the code base!

Resolving patch:
diff --git a/networkx/classes/function.py b/networkx/classes/function.py
--- a/networkx/classes/function.py
+++ b/networkx/classes/function.py
@@ -787,6 +787,11 @@ def set_edge_attributes(G, values, name=None):
         >>> G[1][2]["attr2"]
         3
 
+    The attributes of one Graph can be used to set those of another.
+
+        >>> H = nx.path_graph(3)
+        >>> nx.set_edge_attributes(H, G.edges)
+
     Note that if the dict contains edges that are not in `G`, they are
     silently ignored::
 
@@ -795,6 +800,29 @@ def set_edge_attributes(G, values, name=None):
         >>> (1, 2) in G.edges()
         False
 
+    For multigraphs, the `values` dict is expected to be keyed by 3-tuples
+    including the edge key::
+
+        >>> MG = nx.MultiGraph()
+        >>> edges = [(0, 1), (0, 1)]
+        >>> MG.add_edges_from(edges)  # Returns list of edge keys
+        [0, 1]
+        >>> attributes = {(0, 1, 0): {"cost": 21}, (0, 1, 1): {"cost": 7}}
+        >>> nx.set_edge_attributes(MG, attributes)
+        >>> MG[0][1][0]["cost"]
+        21
+        >>> MG[0][1][1]["cost"]
+        7
+
+    If MultiGraph attributes are desired for a Graph, you must convert the 3-tuple
+    multiedge to a 2-tuple edge and the last multiedge's attribute value will
+    overwrite the previous values. Continuing from the previous case we get::
+
+        >>> H = nx.path_graph([0, 1, 2])
+        >>> nx.set_edge_attributes(H, {(u, v): ed for u, v, ed in MG.edges.data()})
+        >>> nx.get_edge_attributes(H, "cost")
+        {(0, 1): 7}
+
     """
     if name is not None:
         # `values` does not contain attribute names


Test patch:
Repository: networkx/networkx

Issue:
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


Discussion:
I would love to work on this! 🙋‍♂️

For more context, what all should be added onto the documentation of `PlanarEmbedding` class?
I think the main trouble #5079 revealed is that it is not clear where to start using the features we have. It is tempting to go straight to the class. But the better place to start is with the function `check_planarity`.  So I think a pointer in the class documentation would be good, a statement in the function doc_string that it is the primary interface to the routines for planarity, and a paragraph in the module documentation about the various parts and that you want to start with `check_planarity`.  Of course as you read more and learn more, other items might come up. The goal is to make it clear for someone who has done a search for "networkx planarity".
Sir, I am an Outreachy applicant. Is this issue still open? Can I try to make any updates to the documentation to make it more clear? If so please do guide me in what you expect , as to how I can improve it?
@MridulS Hi, Is this issue still open? And if so can you guide me on how I can improve it?

Resolving patch:
diff --git a/networkx/algorithms/planarity.py b/networkx/algorithms/planarity.py
--- 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
     --------
 


Test patch:
Repository: networkx/networkx

Issue:
Missing `f` prefix on f-strings
Some strings looks like they're meant to be f-strings but are missing the `f` prefix meaning variable interpolation won't happen.

https://github.com/networkx/networkx/blob/e48d5f27e7026c5d104d3042dbd9b4d603c062bf/networkx/utils/decorators.py#L248
https://github.com/networkx/networkx/blob/e48d5f27e7026c5d104d3042dbd9b4d603c062bf/networkx/readwrite/gml.py#L594

I found this issue automatically. I'm a bot. Beep Boop 🦊. See other issues I found in your repo [here](https://codereview.doctor/networkx/networkx)


Discussion:

Resolving patch:
diff --git a/networkx/readwrite/gml.py b/networkx/readwrite/gml.py
--- a/networkx/readwrite/gml.py
+++ b/networkx/readwrite/gml.py
@@ -591,7 +591,7 @@ def stringize(value):
                 stringize(item)
             buf.write("}")
         else:
-            msg = "{value!r} cannot be converted into a Python literal"
+            msg = f"{value!r} cannot be converted into a Python literal"
             raise ValueError(msg)
 
     buf = StringIO()
diff --git a/networkx/utils/decorators.py b/networkx/utils/decorators.py
--- a/networkx/utils/decorators.py
+++ b/networkx/utils/decorators.py
@@ -245,7 +245,7 @@ def _nodes_or_number(n):
             nodes = tuple(n)
         else:
             if n < 0:
-                msg = "Negative number of nodes not valid: {n}"
+                msg = f"Negative number of nodes not valid: {n}"
                 raise nx.NetworkXError(msg)
         return (n, nodes)
 


Test patch:
Repository: networkx/networkx

Issue:
induced_subgraph docs show unrelated example
<!-- 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 -->
The example on the documentation for induced_subgraph [here](https://networkx.org/documentation/stable/reference/generated/networkx.classes.function.induced_subgraph.html) shows an example of a generic subgraph function, not the induced_subgraph function. 

### Current Behavior
<!--- Tell us what happens instead of the expected behavior -->
Currently the doc page in question does not show an example of the function it is documenting in the example. It shows an example of the `subgraph()` method, instead of the `induced_subgraph()` method. Perhaps this is for a reason, but it seems wrong.

### Expected Behavior
<!--- Tell us what should happen -->
I expect the documentation example to show an example using the function being documented (in this case a call to the induced_subgraph function somewhere on this page).

### Steps to Reproduce
<!--- Provide a minimal example that reproduces the bug -->

### Environment
<!--- Please provide details about your local environment -->
Python version: 3.7
NetworkX version: 2.8


### Additional context
<!--- Add any other context about the problem here, screenshots, etc. -->



Discussion:
If this is something that should be fixed, I'm happy to take this on! Reading a few other issues, I'm not sure if this may be better placed in this repo (https://github.com/networkx/nx-guides), so just lmk and I can close/reopen there/whatever the proper channel is.
This is a bit tricky... if you look at the implementation of the `subgraph` method (i.e. `G.subgraph`) it looks like it returns the induced subgraph. I agree that the docstring for `induced_subgraph` should probably show the function itself being used though, and perhaps mention that the subgraph method of graphs also returns the induced subgraph.
Agree. I can give this one a shot and put a PR up in the next few days.

Resolving patch:
diff --git a/networkx/classes/function.py b/networkx/classes/function.py
--- a/networkx/classes/function.py
+++ b/networkx/classes/function.py
@@ -385,9 +385,11 @@ def induced_subgraph(G, nbunch):
     Examples
     --------
     >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
-    >>> H = G.subgraph([0, 1, 2])
+    >>> H = nx.induced_subgraph(G, [0, 1, 3])
     >>> list(H.edges)
-    [(0, 1), (1, 2)]
+    [(0, 1)]
+    >>> list(H.nodes)
+    [0, 1, 3]
     """
     induced_nodes = nx.filters.show_nodes(G.nbunch_iter(nbunch))
     return nx.graphviews.subgraph_view(G, induced_nodes)


Test patch:
Repository: networkx/networkx

Issue:
Line graph with attributes
If we have some graph with edge attributes, is it possible to generate the line graph somehow with the original edge attributes embedded into the line graph nodes? Would save a lot of hassle. 


Discussion:
It looks like one additional line of code will transfer all the edge attributes of the original graph to the line graph as node attributes.

```python
G = nx.path_graph(4)
G.add_edges_from((u, v, {'krill': u+v}) for u, v in G.edges)
H = nx.line_graph(G)
H.add_nodes_from((node, G.edges[node]) for node in H)
```
I think @dschult 's comment very nicely answers the question and IMO would be a nice addition to the docstring examples.

Resolving patch:
diff --git a/networkx/generators/line.py b/networkx/generators/line.py
--- a/networkx/generators/line.py
+++ b/networkx/generators/line.py
@@ -43,6 +43,18 @@ def line_graph(G, create_using=None):
     >>> print(sorted(map(sorted, L.edges())))  # makes a 3-clique, K3
     [[(0, 1), (0, 2)], [(0, 1), (0, 3)], [(0, 2), (0, 3)]]
 
+    Edge attributes from `G` are not copied over as node attributes in `L`, but
+    attributes can be copied manually:
+
+    >>> G = nx.path_graph(4)
+    >>> G.add_edges_from((u, v, {"tot": u+v}) for u, v in G.edges)
+    >>> G.edges(data=True)
+    EdgeDataView([(0, 1, {'tot': 1}), (1, 2, {'tot': 3}), (2, 3, {'tot': 5})])
+    >>> H = nx.line_graph(G)
+    >>> H.add_nodes_from((node, G.edges[node]) for node in H)
+    >>> H.nodes(data=True)
+    NodeDataView({(0, 1): {'tot': 1}, (2, 3): {'tot': 5}, (1, 2): {'tot': 3}})
+
     Notes
     -----
     Graph, node, and edge data are not propagated to the new graph. For


Test patch:
Repository: networkx/networkx

Issue:
Add default distance metric to `geometric_edges`
The `nx.generators.geometric.geometric_edges` function currently takes 3 varpos parameters. The last of these parameters `p` is the "Minkovsky distance metric", which allows users to select the power used to compute the distances. 

Having looked at the function a bit, I was wondering if it wasn't worth perhaps turning `p` into an optional kwarg and giving it a default value. IIUC, `p=2` corresponds to Euclidean distance, which is the default distance measure used for many of the other functions in the module. Thoughts about making this the default value for this function?


Discussion:
It seems to me that most geometric networks would use euclidean distance and this change shouldn't mess up any backward compatibility.  Sounds good to me. :}

Resolving patch:
diff --git a/networkx/generators/geometric.py b/networkx/generators/geometric.py
--- a/networkx/generators/geometric.py
+++ b/networkx/generators/geometric.py
@@ -37,7 +37,7 @@ def euclidean(x, y):
     return math.dist(x, y)
 
 
-def geometric_edges(G, radius, p):
+def geometric_edges(G, radius, p=2):
     """Returns edge list of node pairs within `radius` of each other.
 
     Parameters
@@ -49,10 +49,10 @@ def geometric_edges(G, radius, p):
     radius : scalar
         The distance threshold. Edges are included in the edge list if the
         distance between the two nodes is less than `radius`.
-    p : scalar
+    p : scalar, default=2
         The `Minkowski distance metric
-        <https://en.wikipedia.org/wiki/Minkowski_distance>`_ use to compute
-        distances.
+        <https://en.wikipedia.org/wiki/Minkowski_distance>`_ used to compute
+        distances. The default value is 2, i.e. Euclidean distance.
 
     Returns
     -------
@@ -75,14 +75,13 @@ def geometric_edges(G, radius, p):
     ...     (1, {"pos": (3, 0)}),
     ...     (2, {"pos": (8, 0)}),
     ... ])
-    >>> p = 2  # Euclidean distance
-    >>> nx.geometric_edges(G, radius=1, p=p)
+    >>> nx.geometric_edges(G, radius=1)
     []
-    >>> nx.geometric_edges(G, radius=4, p=p)
+    >>> nx.geometric_edges(G, radius=4)
     [(0, 1)]
-    >>> nx.geometric_edges(G, radius=6, p=p)
+    >>> nx.geometric_edges(G, radius=6)
     [(0, 1), (1, 2)]
-    >>> nx.geometric_edges(G, radius=9, p=p)
+    >>> nx.geometric_edges(G, radius=9)
     [(0, 1), (0, 2), (1, 2)]
     """
     nodes_pos = G.nodes(data="pos")


Test patch: