ioftools / networkxMiCe / networkxmaster / networkx / algorithms / isolate.py @ 5cef0f13
History  View  Annotate  Download (2.6 KB)
1 
# * encoding: utf8 *


2 
# Copyright 2015 NetworkX developers.

3 
# Copyright (C) 20042019 by

4 
# Aric Hagberg <hagberg@lanl.gov>

5 
# Dan Schult <dschult@colgate.edu>

6 
# Pieter Swart <swart@lanl.gov>

7 
# All rights reserved.

8 
# BSD license.

9 
"""

10 
Functions for identifying isolate (degree zero) nodes.

11 
"""

12 
import networkx as nx 
13  
14 
__author__ = """\n""".join(['Drew Conway <drew.conway@nyu.edu>', 
15 
'Aric Hagberg <hagberg@lanl.gov>'])

16  
17 
__all__ = ['is_isolate', 'isolates', 'number_of_isolates'] 
18  
19  
20 
def is_isolate(G, n): 
21 
"""Determines whether a node is an isolate.

22 

23 
An *isolate* is a node with no neighbors (that is, with degree

24 
zero). For directed graphs, this means no inneighbors and no

25 
outneighbors.

26 

27 
Parameters

28 


29 
G : NetworkX graph

30 

31 
n : node

32 
A node in `G`.

33 

34 
Returns

35 


36 
is_isolate : bool

37 
True if and only if `n` has no neighbors.

38 

39 
Examples

40 


41 
>>> G=nx.Graph()

42 
>>> G.add_edge(1,2)

43 
>>> G.add_node(3)

44 
>>> nx.is_isolate(G,2)

45 
False

46 
>>> nx.is_isolate(G,3)

47 
True

48 
"""

49 
return G.degree(n) == 0 
50  
51  
52 
def isolates(G): 
53 
"""Iterator over isolates in the graph.

54 

55 
An *isolate* is a node with no neighbors (that is, with degree

56 
zero). For directed graphs, this means no inneighbors and no

57 
outneighbors.

58 

59 
Parameters

60 


61 
G : NetworkX graph

62 

63 
Returns

64 


65 
iterator

66 
An iterator over the isolates of `G`.

67 

68 
Examples

69 


70 
To get a list of all isolates of a graph, use the :class:`list`

71 
constructor::

72 

73 
>>> G = nx.Graph()

74 
>>> G.add_edge(1, 2)

75 
>>> G.add_node(3)

76 
>>> list(nx.isolates(G))

77 
[3]

78 

79 
To remove all isolates in the graph, first create a list of the

80 
isolates, then use :meth:`Graph.remove_nodes_from`::

81 

82 
>>> G.remove_nodes_from(list(nx.isolates(G)))

83 
>>> list(G)

84 
[1, 2]

85 

86 
For digraphs, isolates have zero indegree and zero out_degre::

87 

88 
>>> G = nx.DiGraph([(0, 1), (1, 2)])

89 
>>> G.add_node(3)

90 
>>> list(nx.isolates(G))

91 
[3]

92 

93 
"""

94 
return (n for n, d in G.degree() if d == 0) 
95  
96  
97 
def number_of_isolates(G): 
98 
"""Returns the number of isolates in the graph.

99 

100 
An *isolate* is a node with no neighbors (that is, with degree

101 
zero). For directed graphs, this means no inneighbors and no

102 
outneighbors.

103 

104 
Parameters

105 


106 
G : NetworkX graph

107 

108 
Returns

109 


110 
int

111 
The number of degree zero nodes in the graph `G`.

112 

113 
"""

114 
# TODO This can be parallelized.

115 
return sum(1 for v in isolates(G)) 