Retaining specific nodes while using k-core in Networkx

Viewed 191

I've a random graph created using Netwrokx and I want to delete nodes with degree less than 2 except for 2 user-defined nodes that have degree = 1. To remove all nodes with degree < 2, I could use Networkx's k-core. But I am not sure how to retain the 2 user-defined nodes. For example, the following code generates,

import networkx as nx
import matplotlib.pyplot as plt

# fig 1
G = nx.gnm_random_graph(n=20, m=30, seed=1)
nx.draw(G, with_labels=True, pos=nx.spring_layout(G))
plt.show()

G = nx.k_core(G, k=2)
nx.draw(G, with_labels=True, pos=nx.spring_layout(G))
plt.show()

Figure 1:

enter image description here

Figure 2:

enter image description here

I would like to ask for suggestions on how to retain 2 user-defined nodes: e.g

retain_node_ids = [1,2]

EDIT:

I could use remove_nodes_from as suggested below. But if we delete nodes with degree < 2 we may end up with new nodes, which originally had degree >=2, with degree <2. To repeat the process until no nodes with degree < 2 is found, k-core has been used.

1 Answers

Here is how you can do it:

degrees = nx.classes.degree(G)
G.remove_nodes_from([node
                     for node in G.nodes
                     if node not in retain_node_ids and degrees[node] <= 2])

Of course this piece of code does not find a maximal subgraph (as k_core function does): it simply remove all nodes with degree less than or equal to 2, and which are not in the retain_node_ids list.


EDIT: You can add two fake nodes, connect nodes to retain to them, compute the k-core and then get rid of them:

G.add_edges_from([(u, v) for u in retain_node_ids for v in (n, n+1)])
G = nx.k_core(G, k=2)
G.remove_nodes_from([n, n+1])

Figure 1 Figure 2

Related