How to specify a specific node / edge in networkx?

Assume the one below is the tree structure in the networkx column:

 n-----n1----n11 | |----n12 | |----n13 | |----n131 |----n2 | | |-----n21 X | |-----n22 | | |----n221 |----n3 n4------n41 n5 
  • How to list all nodes with "subnode" and its depth, here: n, n1, n13, n2, n22, n4
  • How to list all nodes without a "subnode", here: n11, n12, n21, n41, n5
  • How to list the orphan node, here: n5 and how to list the edge "orphan" does not belong to the root edge of n, here n4-n41,
  • How to list a node with more than 2 "subnode", here n, n1
  • How to fight, if n131, n221 have an edge around nodes, will an infinity loop happen?

Thanks.

+7
source share
1 answer

Graph Design:

 >>> import networkx as nx >>> G = nx.DiGraph() >>> G.add_edges_from([('n', 'n1'), ('n', 'n2'), ('n', 'n3')]) >>> G.add_edges_from([('n4', 'n41'), ('n1', 'n11'), ('n1', 'n12'), ('n1', 'n13')]) >>> G.add_edges_from([('n2', 'n21'), ('n2', 'n22')]) >>> G.add_edges_from([('n13', 'n131'), ('n22', 'n221')]) >>> G.add_edges_from([('n131', 'n221'), ('n221', 'n131')] >>> G.add_node('n5') 
  • Using the out_degree function to find all nodes with children:

     >>> [k for k,v in G.out_degree().iteritems() if v > 0] ['n13', 'n', 'n131', 'n1', 'n22', 'n2', 'n221', 'n4'] 

    Note that n131 and n221 are also displayed here, since both of them have an edge to each other. You can filter them if you want.

  • All nodes without children:

     >>> [k for k,v in G.out_degree().iteritems() if v == 0] ['n12', 'n11', 'n3', 'n41', 'n21', 'n5'] 
  • All orphan nodes, i.e. nodes with degree 0:

     >>> [k for k,v in G.degree().iteritems() if v == 0] ['n5'] 

    To get all orphaned "edges", you can get a list of the components of the graph, filter out those that do not contain n , and then save only those that have edges:

     >>> [G.edges(component) for component in nx.connected_components(G.to_undirected()) if len(G.edges(component)) > 0 and 'n' not in component] [[('n4', 'n41')]] 
  • Nodes with more than two children:

     >>> [k for k,v in G.out_degree().iteritems() if v > 2] ['n', 'n1'] 
  • If you go through a tree, you will not get an infinite loop. NetworkX has workarounds that are robust for this.

+8
source

All Articles