Python networkx.from_numpy_array() Examples
The following are 25
code examples of networkx.from_numpy_array().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
networkx
, or try the search function
.
Example #1
Source File: salts_solution.py From esoteric-python-challenges with GNU General Public License v3.0 | 6 votes |
def obfuscator(a_string): filename = a_string.replace(" ", "_") + ".png" #Create an image of our string using Imagemagick -- image must be square subprocess.run(["convert", "-background","white", "-fill", "black", "-size", f"{graph_order_and_image_dim}x{graph_order_and_image_dim}", "caption:" + a_string, filename]) #Turn our image into a numpy array string_as_image = Image.open(filename) string_as_array = np.array(string_as_image) #We just need an array of 1's and 0's string_as_array[string_as_array > 0] = 1 #Turn our array into a graph by treating it as an adjacency matrix string_as_graph = nx.from_numpy_array(string_as_array, create_using=nx.DiGraph) #Obfuscated string is a dictionary of dictionaries of this graph: return nx.to_dict_of_dicts(string_as_graph, edge_data=1)
Example #2
Source File: entity_discoverer.py From HarvestText with MIT License | 6 votes |
def clustering(self, threshold): """分不同词性的聚类 :return: partition: dict {word_id: cluster_id} """ print("Louvain clustering") partition = {} part_offset = 0 for etype, ners in self.type_entity_dict.items(): sub_id_mapping = [self.word2id[ner0] for ner0 in ners if ner0 in self.word2id] if len(sub_id_mapping) == 0: continue emb_mat_sub = self.emb_mat[sub_id_mapping, :] cos_sims = cosine_similarity(emb_mat_sub) cos_sims -= np.eye(len(emb_mat_sub)) adj_mat = (cos_sims > threshold).astype(int) G = nx.from_numpy_array(adj_mat) partition_sub = community.best_partition(G) for sub_id, main_id in enumerate(sub_id_mapping): sub_part_id = partition_sub[sub_id] partition[main_id] = sub_part_id + part_offset part_offset += max(partition_sub.values()) + 1 return partition
Example #3
Source File: test_convert_numpy.py From aws-kube-codesuite with Apache License 2.0 | 6 votes |
def test_from_numpy_array_type(self): A = np.array([[1]]) G = nx.from_numpy_array(A) assert_equal(type(G[0][0]['weight']), int) A = np.array([[1]]).astype(np.float) G = nx.from_numpy_array(A) assert_equal(type(G[0][0]['weight']), float) A = np.array([[1]]).astype(np.str) G = nx.from_numpy_array(A) assert_equal(type(G[0][0]['weight']), str) A = np.array([[1]]).astype(np.bool) G = nx.from_numpy_array(A) assert_equal(type(G[0][0]['weight']), bool) A = np.array([[1]]).astype(np.complex) G = nx.from_numpy_array(A) assert_equal(type(G[0][0]['weight']), complex) A = np.array([[1]]).astype(np.object) assert_raises(TypeError, nx.from_numpy_array, A)
Example #4
Source File: test_io.py From graspy with Apache License 2.0 | 6 votes |
def setup_class(self, tmpdir): n = 10 p = 0.5 wt = np.random.exponential wtargs = dict(scale=4) np.random.seed(1) self.A = gs.simulations.er_np(n, p) self.B = gs.simulations.er_np(n, p, wt=wt, wtargs=wtargs) G_A = nx.from_numpy_array(self.A) G_B = nx.from_numpy_array(self.B) G_B = nx.relabel_nodes(G_B, lambda x: x + 10) # relabel nodes to go from 10-19. self.A_path = str(tmpdir / "A_unweighted.edgelist") self.B_path = str(tmpdir / "B.edgelist") self.root = str(tmpdir) nx.write_edgelist(G_A, self.A_path, data=False) nx.write_weighted_edgelist(G_B, self.B_path)
Example #5
Source File: markov.py From striplog with Apache License 2.0 | 6 votes |
def as_graph(self, directed=True): if self.normalized_difference.ndim > 2: raise MarkovError("You can only graph one-step chains.") try: import networkx as nx except ImportError: nx = None if nx is None: print("Please install networkx with `pip install networkx`.") return if directed: alg = nx.DiGraph else: alg = nx.Graph G = nx.from_numpy_array(self.normalized_difference, create_using=alg) nx.set_node_attributes(G, self._state_dict, 'state') return G
Example #6
Source File: test_convert_numpy.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_from_numpy_array_type(self): A = np.array([[1]]) G = nx.from_numpy_array(A) assert_equal(type(G[0][0]['weight']), int) A = np.array([[1]]).astype(np.float) G = nx.from_numpy_array(A) assert_equal(type(G[0][0]['weight']), float) A = np.array([[1]]).astype(np.str) G = nx.from_numpy_array(A) assert_equal(type(G[0][0]['weight']), str) A = np.array([[1]]).astype(np.bool) G = nx.from_numpy_array(A) assert_equal(type(G[0][0]['weight']), bool) A = np.array([[1]]).astype(np.complex) G = nx.from_numpy_array(A) assert_equal(type(G[0][0]['weight']), complex) A = np.array([[1]]).astype(np.object) assert_raises(TypeError, nx.from_numpy_array, A)
Example #7
Source File: test_convert_numpy.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_from_numpy_matrix_type(self): A = np.matrix([[1]]) G = nx.from_numpy_matrix(A) assert_equal(type(G[0][0]['weight']), int) A = np.matrix([[1]]).astype(np.float) G = nx.from_numpy_matrix(A) assert_equal(type(G[0][0]['weight']), float) A = np.matrix([[1]]).astype(np.str) G = nx.from_numpy_matrix(A) assert_equal(type(G[0][0]['weight']), str) A = np.matrix([[1]]).astype(np.bool) G = nx.from_numpy_matrix(A) assert_equal(type(G[0][0]['weight']), bool) A = np.matrix([[1]]).astype(np.complex) G = nx.from_numpy_matrix(A) assert_equal(type(G[0][0]['weight']), complex) A = np.matrix([[1]]).astype(np.object) assert_raises(TypeError, nx.from_numpy_matrix, A) G = nx.cycle_graph(3) A = nx.adj_matrix(G).todense() H = nx.from_numpy_matrix(A) assert_true(all(type(m) == int and type(n) == int for m, n in H.edges())) H = nx.from_numpy_array(A) assert_true(all(type(m) == int and type(n) == int for m, n in H.edges()))
Example #8
Source File: util.py From yass with Apache License 2.0 | 5 votes |
def expand_rf(image, cluster_list): std = np.std(image) std_pixels = np.vstack(np.where(np.abs(image - np.mean(image))>std*2)) if(std_pixels.shape[0] ==0): np.asarray(std_pixels = []) return "poop", std_pixels std_pixels = np.array(std_pixels).T dists = scipy.spatial.distance.cdist(std_pixels, std_pixels) thresh = 1.5 upper=1 lower=0 bin_dists = np.where(dists<thresh, upper, lower) #print (bin_dists) #compute connected nodes and sum spikes over them G = nx.from_numpy_array(bin_dists) con = list(nx.connected_components(G)) test_elements = [element[0] for element in cluster_list] valid_list = [] for element in con: pixels = std_pixels[list(element)] indicator = [np.any([np.all(pixel == test_element) for pixel in pixels]) for test_element in test_elements] if np.any(indicator) == True: valid_list.append(element) return [std_pixels[list(element)] for element in valid_list] #wrapper for the 2 steps
Example #9
Source File: util.py From yass with Apache License 2.0 | 5 votes |
def get_seed(image, dim = 2): kernel = np.full((dim, dim), 1/(float(dim)**2)) smoothed_image = sig.convolve2d(image, kernel, 'same') seed = np.vstack(np.where(np.abs((smoothed_image - np.mean(smoothed_image))) > 4*np.std(smoothed_image))) std_pixels = np.array(seed).T dists = scipy.spatial.distance.cdist(std_pixels, std_pixels) thresh = 1.5 upper=1 lower=0 bin_dists = np.where(dists<thresh, upper, lower) #print (bin_dists) #compute connected nodes and sum spikes over them G = nx.from_numpy_array(bin_dists) con = list(nx.connected_components(G)) cluster_list = [std_pixels[list(con[i])] for i in range(len(con))] return cluster_list
Example #10
Source File: test_convert_numpy.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def test_from_numpy_array_parallel_edges(self): """Tests that the :func:`networkx.from_numpy_array` function interprets integer weights as the number of parallel edges when creating a multigraph. """ A = np.array([[1, 1], [1, 2]]) # First, with a simple graph, each integer entry in the adjacency # matrix is interpreted as the weight of a single edge in the graph. expected = nx.DiGraph() edges = [(0, 0), (0, 1), (1, 0)] expected.add_weighted_edges_from([(u, v, 1) for (u, v) in edges]) expected.add_edge(1, 1, weight=2) actual = nx.from_numpy_array(A, parallel_edges=True, create_using=nx.DiGraph()) assert_graphs_equal(actual, expected) actual = nx.from_numpy_array(A, parallel_edges=False, create_using=nx.DiGraph()) assert_graphs_equal(actual, expected) # Now each integer entry in the adjacency matrix is interpreted as the # number of parallel edges in the graph if the appropriate keyword # argument is specified. edges = [(0, 0), (0, 1), (1, 0), (1, 1), (1, 1)] expected = nx.MultiDiGraph() expected.add_weighted_edges_from([(u, v, 1) for (u, v) in edges]) actual = nx.from_numpy_array(A, parallel_edges=True, create_using=nx.MultiDiGraph()) assert_graphs_equal(actual, expected) expected = nx.MultiDiGraph() expected.add_edges_from(set(edges), weight=1) # The sole self-loop (edge 0) on vertex 1 should have weight 2. expected[1][1][0]['weight'] = 2 actual = nx.from_numpy_array(A, parallel_edges=False, create_using=nx.MultiDiGraph()) assert_graphs_equal(actual, expected)
Example #11
Source File: test_convert_numpy.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def test_from_numpy_array_dtype(self): dt = [('weight', float), ('cost', int)] A = np.array([[(1.0, 2)]], dtype=dt) G = nx.from_numpy_array(A) assert_equal(type(G[0][0]['weight']), float) assert_equal(type(G[0][0]['cost']), int) assert_equal(G[0][0]['cost'], 2) assert_equal(G[0][0]['weight'], 1.0)
Example #12
Source File: test_convert_numpy.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def test_shape(self): "Conversion from non-square array." A = np.array([[1, 2, 3], [4, 5, 6]]) assert_raises(nx.NetworkXError, nx.from_numpy_array, A)
Example #13
Source File: test_convert_numpy.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def identity_conversion(self, G, A, create_using): assert(A.sum() > 0) GG = nx.from_numpy_array(A, create_using=create_using) self.assert_equal(G, GG) GW = nx.to_networkx_graph(A, create_using=create_using) self.assert_equal(G, GW) GI = create_using.__class__(A) self.assert_equal(G, GI)
Example #14
Source File: test_convert_numpy.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_symmetric(self): """Tests that a symmetric array has edges added only once to an undirected multigraph when using :func:`networkx.from_numpy_array`. """ A = np.array([[0, 1], [1, 0]]) G = nx.from_numpy_array(A, create_using=nx.MultiGraph) expected = nx.MultiGraph() expected.add_edge(0, 1, weight=1) assert_graphs_equal(G, expected)
Example #15
Source File: test_convert_numpy.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_from_numpy_array_dtype(self): dt = [('weight', float), ('cost', int)] A = np.array([[(1.0, 2)]], dtype=dt) G = nx.from_numpy_array(A) assert_equal(type(G[0][0]['weight']), float) assert_equal(type(G[0][0]['cost']), int) assert_equal(G[0][0]['cost'], 2) assert_equal(G[0][0]['weight'], 1.0)
Example #16
Source File: test_convert_numpy.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_shape(self): "Conversion from non-square array." A = np.array([[1, 2, 3], [4, 5, 6]]) assert_raises(nx.NetworkXError, nx.from_numpy_array, A)
Example #17
Source File: test_convert_numpy.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def identity_conversion(self, G, A, create_using): assert(A.sum() > 0) GG = nx.from_numpy_array(A, create_using=create_using) self.assert_equal(G, GG) GW = nx.to_networkx_graph(A, create_using=create_using) self.assert_equal(G, GW) GI = nx.empty_graph(0, create_using).__class__(A) self.assert_equal(G, GI)
Example #18
Source File: test_utils.py From graspy with Apache License 2.0 | 5 votes |
def test_graphin(self): G = nx.from_numpy_array(self.A) np.testing.assert_array_equal(nx.to_numpy_array(G), gus.import_graph(G))
Example #19
Source File: test_io.py From graspy with Apache License 2.0 | 5 votes |
def test_graphin(self): G = nx.from_numpy_array(self.A) np.testing.assert_array_equal(nx.to_numpy_array(G), gs.utils.import_graph(G))
Example #20
Source File: kcenter.py From clusternet with MIT License | 5 votes |
def make_all_dists(bin_adj, dmax, use_weights=False): g = nx.from_numpy_array(bin_adj.detach().numpy()) if not use_weights: lengths = nx.shortest_path_length(g) else: lengths = nx.shortest_path_length(g, weight='weight') dist = torch.zeros_like(bin_adj) for u, lens_u in lengths: for v in range(bin_adj.shape[0]): if v in lens_u: dist[u,v] = lens_u[v] else: dist[u,v] = dmax return dist
Example #21
Source File: graph.py From netrd with MIT License | 5 votes |
def create_graph(A, create_using=None, remove_self_loops=True): """Flexibly creating a networkx graph from a numpy array. Parameters ---------- A (np.ndarray) A numpy array. create_using (nx.Graph or None) Create the graph using a specific networkx graph. Can be used for forcing an asymmetric matrix to create an undirected graph, for example. remove_self_loops (bool) If True, remove the diagonal of the matrix before creating the graph object. Returns ------- G A graph, typically a nx.Graph or nx.DiGraph. """ if remove_self_loops: np.fill_diagonal(A, 0) if create_using is None: if np.allclose(A, A.T): G = nx.from_numpy_array(A, create_using=nx.Graph()) else: G = nx.from_numpy_array(A, create_using=nx.DiGraph()) else: G = nx.from_numpy_array(A, create_using=create_using) return G
Example #22
Source File: kronecker_generator.py From GEM-Benchmark with BSD 3-Clause "New" or "Revised" License | 5 votes |
def convert(something): # use networkx conversion from numpy array # g = nx.from_numpy_matrix(someNPMat) # print(type(something)) g = nx.from_numpy_array(something) return g
Example #23
Source File: conversion.py From spektral with MIT License | 4 votes |
def numpy_to_nx(adj, node_features=None, edge_features=None, nf_name=None, ef_name=None): """ Converts graphs in numpy format to a list of nx.Graphs. :param adj: adjacency matrices of shape `(num_samples, num_nodes, num_nodes)`. If there is only one sample, the first dimension can be dropped. :param node_features: optional node attributes matrices of shape `(num_samples, num_nodes, node_features_dim)`. If there is only one sample, the first dimension can be dropped. :param edge_features: optional edge attributes matrices of shape `(num_samples, num_nodes, num_nodes, edge_features_dim)` If there is only one sample, the first dimension can be dropped. :param nf_name: optional name to assign to node attributes in the nx.Graphs :param ef_name: optional name to assign to edge attributes in the nx.Graphs :return: a list of nx.Graphs (or a single nx.Graph is there is only one sample) """ if adj.ndim == 2: adj = adj[None, ...] if node_features is not None: if nf_name is None: nf_name = 'node_features' node_features = node_features[None, ...] if node_features.ndim != 3: raise ValueError('node_features must have shape (batch, N, F) ' 'or (N, F).') if edge_features is not None: if ef_name is None: ef_name = 'edge_features' edge_features = edge_features[None, ...] if edge_features.ndim != 4: raise ValueError('edge_features must have shape (batch, N, N, S) ' 'or (N, N, S).') output = [] for i in range(adj.shape[0]): g = nx.from_numpy_array(adj[i]) g.remove_nodes_from(list(nx.isolates(g))) if node_features is not None: node_attrs = {n: {nf_name: node_features[i, n]} for n in g.nodes} nx.set_node_attributes(g, node_attrs, nf_name) if edge_features is not None: edge_attrs = {e: {ef_name: edge_features[i, e[0], e[1]]} for e in g.edges} nx.set_edge_attributes(g, edge_attrs, ef_name) output.append(g) if len(output) == 1: return output[0] else: return output
Example #24
Source File: utils.py From graspy with Apache License 2.0 | 4 votes |
def get_lcc(graph, return_inds=False): r""" Finds the largest connected component for the input graph. The largest connected component is the fully connected subgraph which has the most nodes. Parameters ---------- graph: nx.Graph, nx.DiGraph, nx.MultiDiGraph, nx.MultiGraph, np.ndarray Input graph in any of the above specified formats. If np.ndarray, interpreted as an :math:`n \times n` adjacency matrix return_inds: boolean, default: False Whether to return a np.ndarray containing the indices in the original adjacency matrix that were kept and are now in the returned graph. Ignored when input is networkx object Returns ------- graph: nx.Graph, nx.DiGraph, nx.MultiDiGraph, nx.MultiGraph, np.ndarray New graph of the largest connected component of the input parameter. inds: (optional) Indices from the original adjacency matrix that were kept after taking the largest connected component. """ input_ndarray = False if type(graph) is np.ndarray: input_ndarray = True if is_symmetric(graph): g_object = nx.Graph() else: g_object = nx.DiGraph() graph = nx.from_numpy_array(graph, create_using=g_object) if type(graph) in [nx.Graph, nx.MultiGraph]: lcc_nodes = max(nx.connected_components(graph), key=len) elif type(graph) in [nx.DiGraph, nx.MultiDiGraph]: lcc_nodes = max(nx.weakly_connected_components(graph), key=len) lcc = graph.subgraph(lcc_nodes).copy() lcc.remove_nodes_from([n for n in lcc if n not in lcc_nodes]) if return_inds: nodelist = np.array(list(lcc_nodes)) if input_ndarray: lcc = nx.to_numpy_array(lcc) if return_inds: return lcc, nodelist return lcc
Example #25
Source File: utils.py From graspy with Apache License 2.0 | 4 votes |
def is_fully_connected(graph): r""" Checks whether the input graph is fully connected in the undirected case or weakly connected in the directed case. Connected means one can get from any vertex u to vertex v by traversing the graph. For a directed graph, weakly connected means that the graph is connected after it is converted to an unweighted graph (ignore the direction of each edge) Parameters ---------- graph: nx.Graph, nx.DiGraph, nx.MultiDiGraph, nx.MultiGraph, np.ndarray Input graph in any of the above specified formats. If np.ndarray, interpreted as an :math:`n \times n` adjacency matrix Returns ------- boolean: True if the entire input graph is connected References ---------- http://mathworld.wolfram.com/ConnectedGraph.html http://mathworld.wolfram.com/WeaklyConnectedDigraph.html Examples -------- >>> a = np.array([ ... [0, 1, 0], ... [1, 0, 0], ... [0, 0, 0]]) >>> is_fully_connected(a) False """ if type(graph) is np.ndarray: if is_symmetric(graph): g_object = nx.Graph() else: g_object = nx.DiGraph() graph = nx.from_numpy_array(graph, create_using=g_object) if type(graph) in [nx.Graph, nx.MultiGraph]: return nx.is_connected(graph) elif type(graph) in [nx.DiGraph, nx.MultiDiGraph]: return nx.is_weakly_connected(graph)