def setup(self): g = sx.Graph() g.add_nodes_from([0, 1, 2]) # This is what we expect the AtlasView for node 0 to look like self.atlas = {0: {'color': 'blue', 'weight': 1.2}, 1: {}, 2: {'color': 'green'}} for key in self.atlas.keys(): g.add_edge(0, key) g.edges[(0, key)].update(self.atlas[key]) self.g = g self.av = sx.classes.coreviews.AtlasView(g, 0)
def connected_components(G): """Generate connected components. Parameters ---------- G : NetworkX graph An undirected graph Returns ------- comp : generator of sets A generator of sets of nodes, one for each component of G. Raises ------ NetworkXNotImplemented If G is directed. Examples -------- Generate a sorted list of connected components, largest first. >>> G = nx.path_graph(4) >>> nx.add_path(G, [10, 11, 12]) >>> [len(c) for c in sorted(nx.connected_components(G), key=len, reverse=True)] [4, 3] If you only want the largest connected component, it's more efficient to use max instead of sort. >>> largest_cc = max(nx.connected_components(G), key=len) To create the induced subgraph of each component use: >>> S = [G.subgraph(c).copy() for c in nx.connected_components(G)] See Also -------- strongly_connected_components weakly_connected_components Notes ----- For undirected graphs only. """ Components = TCnComV() Graphs = [] GetSccs(G._graph, Components) for CnCom in Components: Graphs.append(sx.Graph(incoming_graph_data=CnCom)) return Graphs
def test_update(self): # specify both edgees and nodes G = self.K3.copy() G.update(nodes=[3, (4, {'size': 2})], edges=[(4, 5), (6, 7, {'weight': 2})]) nlist = [(0, {}), (1, {}), (2, {}), (3, {}), (4, {'size': 2}), (5, {}), (6, {}), (7, {})] assert sorted(G.nodes.data()) == nlist if G.is_directed(): elist = [(0, 1, {}), (0, 2, {}), (1, 0, {}), (1, 2, {}), (2, 0, {}), (2, 1, {}), (4, 5, {}), (6, 7, {'weight': 2})] else: elist = [(0, 1, {}), (0, 2, {}), (1, 2, {}), (4, 5, {}), (6, 7, {'weight': 2})] assert sorted(G.edges.data()) == elist assert G.graph == {} # no keywords -- order is edges, nodes G = self.K3.copy() G.update([(4, 5), (6, 7, {'weight': 2})], [3, (4, {'size': 2})]) assert sorted(G.nodes.data()) == nlist assert sorted(G.edges.data()) == elist assert G.graph == {} # update using only a graph G = self.Graph() G.graph['foo'] = 'bar' G.add_node(2, data=4) G.add_edge(0, 1, weight=0.5) GG = G.copy() H = self.Graph() GG.update(H) assert_graphs_equal(G, GG) H.update(G) assert_graphs_equal(H, G) # update nodes only H = self.Graph() H.update(nodes=[3, 4]) assert H.nodes ^ {3, 4} == set() assert H.size() == 0 # update edges only H = self.Graph() H.update(edges=[(3, 4)]) assert sorted(H.edges.data()) == [(3, 4, {})] assert H.size() == 1 # No inputs -> exception with pytest.raises(sx.SnapXError): sx.Graph().update()
def setup(self): g = sx.Graph() g.add_nodes_from([0, 1, 2, 3]) dd03 = {'color': 'blue', 'weight': 1.2} dd23 = {'color': 'green'} # This is what we expect the AdjacencyView to look like: self.adj = {0: {3: dd03}, 1: {}, 2: {3: dd23}, 3: {0: dd03, 2: dd23}} for src in self.adj.keys(): for dst in self.adj[src]: g.add_edge(src, dst) g.edges[(src, dst)].update(self.adj[src][dst]) self.g = g self.adjview = sx.classes.coreviews.AdjacencyView(g)
def setup(self): """By design, is impossible to decouple the graph from the AttributeDict, so I am setting up a graph first in this series of tests. I certainly don't enjoy passing around states, but I also don't have a better idea at the moment. Maybe someone can refine the design and reduce the amount of inter- dependence between Views, Graphs, and AttributeDict. """ g = sx.Graph() g.add_nodes_from([0, 1, 2]) g.add_edges_from([(0, 1), (0, 2), (1, 2)]) self.g = g self.ndicts = { 0: { "int": 1, "float": 1.234, "str": "This is a test string." }, 1: { "float": 0.4, "foo": ["bar", "baz"] }, 2: { "str": "string", "list": [1, 2], "dict": { "hello": "world" } } } self.edicts = { (0, 1): { "int": 2, "dict": { "aa": "bbb" } }, (0, 2): { "float": 0.23, "tuple": (1, 2, 4), "str": "abc", "int": 3 }, (1, 2): { "str": "bar", "list": [3, "aaa"] } } # Implicitly calling __setitem__ for n in self.ndicts.keys(): self.g.nodes[n].update(self.ndicts[n]) for e in self.edicts.keys(): self.g.edges[e].update(self.edicts[e])
def test_specify_graph_backend_init(self): G = sx.Graph() G.add_nodes_from(range(100)) G.add_edges_from([[0, 4], [1, 5], [2, 6]]) graph = Graph(G, netlib=sx) self.assertTrue(isinstance(graph.G, sx.Graph)) self.assertEqual(list(graph.edge_index.shape), [2, 6]) self.assertEqual(list(graph.edge_label_index.shape), [2, 6]) self.assertEqual(list(graph.node_label_index.shape), [100]) import networkx as nx G = nx.Graph() G.add_nodes_from(range(100)) G.add_edges_from([[0, 4], [1, 5], [2, 6]]) graph = Graph(G, netlib=nx) self.assertTrue(isinstance(graph.G, nx.Graph)) self.assertEqual(list(graph.edge_index.shape), [2, 6]) self.assertEqual(list(graph.edge_label_index.shape), [2, 6]) self.assertEqual(list(graph.node_label_index.shape), [100])
def test_init_fail(self): """Checks if initialization successfully fails for invalid inputs""" g = sx.Graph() # Invalid node ID (not integer) with pytest.raises(sx.SnapXTypeError): sx.AttributeDict(g, "hoge") # Invalid format with pytest.raises(sx.SnapXTypeError): sx.AttributeDict(g, (1, 2, 3)) # Invalid edge (not integer) with pytest.raises(sx.SnapXTypeError): sx.AttributeDict(g, (0, "hoge")) with pytest.raises(sx.SnapXTypeError): sx.AttributeDict(g, ("foo", 2)) g.add_nodes_from([0, 1]) # Nonexistent edge with pytest.raises(sx.SnapXKeyError): sx.AttributeDict(g, (0, 1))
def ego_graph(G, n, radius=1, sample=-1.0, traversal='in', copy_attr=True): """PORTED FROM NETWORKX Returns induced subgraph of neighbors centered at node n within a given radius. Parameters ---------- G : graph A NetworkX Graph or DiGraph n : node A single node radius : number, optional Include all neighbors of distance<=radius from n. center : bool, optional - NOT ADDED If False, do not include center node in graph undirected : bool, optional - NOT ADDED If True use both in- and out-neighbors of directed graphs. distance : key, optional - NOT ADDED Use specified edge data key as distance. For example, setting distance='weight' will use the edge weight to measure the distance from the node n. sample : int/float, optional Number of nodes to sample as neighbors. Either positive int or float between 0.0 and 1.0. traversal : str, optional, either 'in', 'out', 'all' Get in, out or both ego neighborhoods copy_attr : bool, optional Copy node and edge attributes to ego graph """ if traversal == 'in': if copy_attr: if sample != -1.0: if type(sample) is int: if 0 > sample: raise RuntimeError else: snapGraph = snap.GetInEgonetSubAttr( G._graph, n, radius, sample, -1.0) return sx.Graph(incoming_graph_data=snapGraph) else: if not 0.0 <= sample <= 1.0: raise RuntimeError else: snapGraph = snap.GetInEgonetSubAttr( G._graph, n, radius, 0, sample) return sx.Graph(incoming_graph_data=snapGraph) else: snapGraph = snap.GetInEgonetAttr(G._graph, n, radius) return sx.Graph(incoming_graph_data=snapGraph) else: raise NotImplementedError else: raise NotImplementedError
def max_connected_component(G): return sx.Graph(incoming_graph_data=GetMxScc(G._graph)) # def number_connected_components(G): # """Returns the number of connected components. # Parameters # ---------- # G : NetworkX graph # An undirected graph. # Returns # ------- # n : integer # Number of connected components # See Also # -------- # connected_components # number_weakly_connected_components # number_strongly_connected_components # Notes # ----- # For undirected graphs only. # """ # return sum(1 for cc in connected_components(G)) # @not_implemented_for("directed") # def is_connected(G): # """Returns True if the graph is connected, False otherwise. # Parameters # ---------- # G : NetworkX Graph # An undirected graph. # Returns # ------- # connected : bool # True if the graph is connected, false otherwise. # Raises # ------ # NetworkXNotImplemented # If G is directed. # Examples # -------- # >>> G = nx.path_graph(4) # >>> print(nx.is_connected(G)) # True # See Also # -------- # is_strongly_connected # is_weakly_connected # is_semiconnected # is_biconnected # connected_components # Notes # ----- # For undirected graphs only. # """ # if len(G) == 0: # raise nx.NetworkXPointlessConcept( # "Connectivity is undefined ", "for the null graph." # ) # return sum(1 for node in _plain_bfs(G, arbitrary_element(G))) == len(G) # @not_implemented_for("directed") # def node_connected_component(G, n): # """Returns the set of nodes in the component of graph containing node n. # Parameters # ---------- # G : NetworkX Graph # An undirected graph. # n : node label # A node in G # Returns # ------- # comp : set # A set of nodes in the component of G containing node n. # Raises # ------ # NetworkXNotImplemented # If G is directed. # See Also # -------- # connected_components # Notes # ----- # For undirected graphs only. # """ # return _plain_bfs(G, n)