Python networkx.from_numpy_matrix() Examples
The following are 30
code examples of networkx.from_numpy_matrix().
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: analyse_meg_epilepsy_clips.py From mmvt with GNU General Public License v3.0 | 8 votes |
def _calc_graph_func(p): con, times_chunk, graph_func = p vals = [] now = time.time() for run, t in enumerate(times_chunk): utils.time_to_go(now, run, len(times_chunk), 10) con_t = con[:, :, t] g = nx.from_numpy_matrix(con_t) if graph_func == 'closeness_centrality': x = nx.closeness_centrality(g) elif graph_func == 'degree_centrality': x = nx.degree_centrality(g) elif graph_func == 'eigenvector_centrality': x = nx.eigenvector_centrality(g, max_iter=10000) elif graph_func == 'katz_centrality': x = nx.katz_centrality(g, max_iter=100000) else: raise Exception('Wrong graph func!') vals.append([x[k] for k in range(len(x))]) vals = np.array(vals) return vals, times_chunk
Example #2
Source File: time_align.py From scanorama with MIT License | 7 votes |
def time_align_visualize(alignments, time, y, namespace='time_align'): plt.figure() heat = np.flip(alignments + alignments.T + np.eye(alignments.shape[0]), axis=0) sns.heatmap(heat, cmap="YlGnBu", vmin=0, vmax=1) plt.savefig(namespace + '_heatmap.svg') G = nx.from_numpy_matrix(alignments) G = nx.maximum_spanning_tree(G) pos = {} for i in range(len(G.nodes)): pos[i] = np.array([time[i], y[i]]) mst_edges = set(nx.maximum_spanning_tree(G).edges()) weights = [ G[u][v]['weight'] if (not (u, v) in mst_edges) else 8 for u, v in G.edges() ] plt.figure() nx.draw(G, pos, edges=G.edges(), width=10) plt.ylim([-1, 1]) plt.savefig(namespace + '.svg')
Example #3
Source File: utils.py From GraphRNN with MIT License | 7 votes |
def decode_graph(adj, prefix): adj = np.asmatrix(adj) G = nx.from_numpy_matrix(adj) # G.remove_nodes_from(nx.isolates(G)) print('num of nodes: {}'.format(G.number_of_nodes())) print('num of edges: {}'.format(G.number_of_edges())) G_deg = nx.degree_histogram(G) G_deg_sum = [a * b for a, b in zip(G_deg, range(0, len(G_deg)))] print('average degree: {}'.format(sum(G_deg_sum) / G.number_of_nodes())) if nx.is_connected(G): print('average path length: {}'.format(nx.average_shortest_path_length(G))) print('average diameter: {}'.format(nx.diameter(G))) G_cluster = sorted(list(nx.clustering(G).values())) print('average clustering coefficient: {}'.format(sum(G_cluster) / len(G_cluster))) cycle_len = [] cycle_all = nx.cycle_basis(G, 0) for item in cycle_all: cycle_len.append(len(item)) print('cycles', cycle_len) print('cycle count', len(cycle_len)) draw_graph(G, prefix=prefix)
Example #4
Source File: test_branchings.py From aws-kube-codesuite with Apache License 2.0 | 6 votes |
def test_edmonds1_minbranch(): # Using -G_array and min should give the same as optimal_arborescence_1, # but with all edges negative. edges = [(u, v, -w) for (u, v, w) in optimal_arborescence_1] G = nx.DiGraph() G = nx.from_numpy_matrix(-G_array, create_using=G) # Quickly make sure max branching is empty. x = branchings.maximum_branching(G) x_ = build_branching([]) assert_equal_branchings(x, x_) # Now test the min branching. x = branchings.minimum_branching(G) x_ = build_branching(edges) assert_equal_branchings(x, x_)
Example #5
Source File: test_branchings.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 6 votes |
def test_edmonds1_minbranch(): # Using -G_array and min should give the same as optimal_arborescence_1, # but with all edges negative. edges = [ (u, v, -w) for (u, v, w) in optimal_arborescence_1 ] G = nx.DiGraph() G = nx.from_numpy_matrix(-G_array, create_using=G) # Quickly make sure max branching is empty. x = branchings.maximum_branching(G) x_ = build_branching([]) assert_equal_branchings(x, x_) # Now test the min branching. x = branchings.minimum_branching(G) x_ = build_branching(edges) assert_equal_branchings(x, x_)
Example #6
Source File: data.py From graph-generation with MIT License | 6 votes |
def __getitem__(self, idx): adj_copy = self.adj_all[idx].copy() x_batch = np.zeros((self.n, self.max_prev_node)) # here zeros are padded for small graph x_batch[0,:] = 1 # the first input token is all ones y_batch = np.zeros((self.n, self.max_prev_node)) # here zeros are padded for small graph # generate input x, y pairs len_batch = adj_copy.shape[0] # adj_copy_matrix = np.asmatrix(adj_copy) # G = nx.from_numpy_matrix(adj_copy_matrix) # then do bfs in the permuted G # start_idx = G.number_of_nodes()-1 # x_idx = np.array(bfs_seq(G, start_idx)) # adj_copy = adj_copy[np.ix_(x_idx, x_idx)] adj_encoded = encode_adj(adj_copy, max_prev_node=self.max_prev_node) # get x and y and adj # for small graph the rest are zero padded y_batch[0:adj_encoded.shape[0], :] = adj_encoded x_batch[1:adj_encoded.shape[0] + 1, :] = adj_encoded return {'x':x_batch,'y':y_batch, 'len':len_batch}
Example #7
Source File: test_convert_numpy.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 6 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)
Example #8
Source File: data.py From graph-generation with MIT License | 6 votes |
def __getitem__(self, idx): adj_copy = self.adj_all[idx].copy() x_batch = np.zeros((self.n, self.max_prev_node)) # here zeros are padded for small graph x_batch[0,:] = 1 # the first input token is all ones y_batch = np.zeros((self.n, self.max_prev_node)) # here zeros are padded for small graph # generate input x, y pairs len_batch = adj_copy.shape[0] # adj_copy_matrix = np.asmatrix(adj_copy) # G = nx.from_numpy_matrix(adj_copy_matrix) # then do bfs in the permuted G # start_idx = G.number_of_nodes()-1 # x_idx = np.array(bfs_seq(G, start_idx)) # adj_copy = adj_copy[np.ix_(x_idx, x_idx)] adj_encoded = encode_adj(adj_copy, max_prev_node=self.max_prev_node) # get x and y and adj # for small graph the rest are zero padded y_batch[0:adj_encoded.shape[0], :] = adj_encoded x_batch[1:adj_encoded.shape[0] + 1, :] = adj_encoded return {'x':x_batch,'y':y_batch, 'len':len_batch}
Example #9
Source File: data.py From graph-generation with MIT License | 6 votes |
def __getitem__(self, idx): adj_copy = self.adj_all[idx].copy() x_batch = np.zeros((self.n, self.max_prev_node)) # here zeros are padded for small graph x_batch[0,:] = 1 # the first input token is all ones y_batch = np.zeros((self.n, self.max_prev_node)) # here zeros are padded for small graph # generate input x, y pairs len_batch = adj_copy.shape[0] x_idx = np.random.permutation(adj_copy.shape[0]) adj_copy = adj_copy[np.ix_(x_idx, x_idx)] adj_copy_matrix = np.asmatrix(adj_copy) G = nx.from_numpy_matrix(adj_copy_matrix) # then do bfs in the permuted G start_idx = np.random.randint(adj_copy.shape[0]) x_idx = np.array(bfs_seq(G, start_idx)) adj_copy = adj_copy[np.ix_(x_idx, x_idx)] adj_encoded = encode_adj(adj_copy.copy(), max_prev_node=self.max_prev_node) # get x and y and adj # for small graph the rest are zero padded y_batch[0:adj_encoded.shape[0], :] = adj_encoded x_batch[1:adj_encoded.shape[0] + 1, :] = adj_encoded return {'x':x_batch,'y':y_batch, 'len':len_batch}
Example #10
Source File: data.py From GraphRNN with MIT License | 6 votes |
def __getitem__(self, idx): adj_copy = self.adj_all[idx].copy() x_batch = np.zeros((self.n, self.max_prev_node)) # here zeros are padded for small graph x_batch[0,:] = 1 # the first input token is all ones y_batch = np.zeros((self.n, self.max_prev_node)) # here zeros are padded for small graph # generate input x, y pairs len_batch = adj_copy.shape[0] x_idx = np.random.permutation(adj_copy.shape[0]) adj_copy = adj_copy[np.ix_(x_idx, x_idx)] adj_copy_matrix = np.asmatrix(adj_copy) G = nx.from_numpy_matrix(adj_copy_matrix) # then do bfs in the permuted G start_idx = np.random.randint(adj_copy.shape[0]) x_idx = np.array(bfs_seq(G, start_idx)) adj_copy = adj_copy[np.ix_(x_idx, x_idx)] adj_encoded = encode_adj(adj_copy.copy(), max_prev_node=self.max_prev_node) # get x and y and adj # for small graph the rest are zero padded y_batch[0:adj_encoded.shape[0], :] = adj_encoded x_batch[1:adj_encoded.shape[0] + 1, :] = adj_encoded return {'x':x_batch,'y':y_batch, 'len':len_batch}
Example #11
Source File: data.py From GraphRNN with MIT License | 6 votes |
def __getitem__(self, idx): adj_copy = self.adj_all[idx].copy() x_batch = np.zeros((self.n, self.max_prev_node)) # here zeros are padded for small graph x_batch[0,:] = 1 # the first input token is all ones y_batch = np.zeros((self.n, self.max_prev_node)) # here zeros are padded for small graph # generate input x, y pairs len_batch = adj_copy.shape[0] # adj_copy_matrix = np.asmatrix(adj_copy) # G = nx.from_numpy_matrix(adj_copy_matrix) # then do bfs in the permuted G # start_idx = G.number_of_nodes()-1 # x_idx = np.array(bfs_seq(G, start_idx)) # adj_copy = adj_copy[np.ix_(x_idx, x_idx)] adj_encoded = encode_adj(adj_copy, max_prev_node=self.max_prev_node) # get x and y and adj # for small graph the rest are zero padded y_batch[0:adj_encoded.shape[0], :] = adj_encoded x_batch[1:adj_encoded.shape[0] + 1, :] = adj_encoded return {'x':x_batch,'y':y_batch, 'len':len_batch}
Example #12
Source File: utils.py From graph-generation with MIT License | 6 votes |
def decode_graph(adj, prefix): adj = np.asmatrix(adj) G = nx.from_numpy_matrix(adj) # G.remove_nodes_from(nx.isolates(G)) print('num of nodes: {}'.format(G.number_of_nodes())) print('num of edges: {}'.format(G.number_of_edges())) G_deg = nx.degree_histogram(G) G_deg_sum = [a * b for a, b in zip(G_deg, range(0, len(G_deg)))] print('average degree: {}'.format(sum(G_deg_sum) / G.number_of_nodes())) if nx.is_connected(G): print('average path length: {}'.format(nx.average_shortest_path_length(G))) print('average diameter: {}'.format(nx.diameter(G))) G_cluster = sorted(list(nx.clustering(G).values())) print('average clustering coefficient: {}'.format(sum(G_cluster) / len(G_cluster))) cycle_len = [] cycle_all = nx.cycle_basis(G, 0) for item in cycle_all: cycle_len.append(len(item)) print('cycles', cycle_len) print('cycle count', len(cycle_len)) draw_graph(G, prefix=prefix)
Example #13
Source File: test_branchings.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_edmonds1_minbranch(): # Using -G_array and min should give the same as optimal_arborescence_1, # but with all edges negative. edges = [(u, v, -w) for (u, v, w) in optimal_arborescence_1] G = nx.DiGraph() G = nx.from_numpy_matrix(-G_array, create_using=G) # Quickly make sure max branching is empty. x = branchings.maximum_branching(G) x_ = build_branching([]) assert_equal_branchings(x, x_) # Now test the min branching. x = branchings.minimum_branching(G) x_ = build_branching(edges) assert_equal_branchings(x, x_)
Example #14
Source File: data.py From GraphRNN with MIT License | 6 votes |
def __getitem__(self, idx): adj_copy = self.adj_all[idx].copy() x_batch = np.zeros((self.n, self.max_prev_node)) # here zeros are padded for small graph x_batch[0,:] = 1 # the first input token is all ones y_batch = np.zeros((self.n, self.max_prev_node)) # here zeros are padded for small graph # generate input x, y pairs len_batch = adj_copy.shape[0] # adj_copy_matrix = np.asmatrix(adj_copy) # G = nx.from_numpy_matrix(adj_copy_matrix) # then do bfs in the permuted G # start_idx = G.number_of_nodes()-1 # x_idx = np.array(bfs_seq(G, start_idx)) # adj_copy = adj_copy[np.ix_(x_idx, x_idx)] adj_encoded = encode_adj(adj_copy, max_prev_node=self.max_prev_node) # get x and y and adj # for small graph the rest are zero padded y_batch[0:adj_encoded.shape[0], :] = adj_encoded x_batch[1:adj_encoded.shape[0] + 1, :] = adj_encoded return {'x':x_batch,'y':y_batch, 'len':len_batch}
Example #15
Source File: neighborhood_assembly.py From graph-based-image-classification with MIT License | 6 votes |
def neighborhoods_weights_to_root(adjacency, sequence, size): def _neighborhoods_weights_to_root(adjacency, sequence): graph = nx.from_numpy_matrix(adjacency) neighborhoods = np.zeros((sequence.shape[0], size), dtype=np.int32) neighborhoods.fill(-1) for i in xrange(0, sequence.shape[0]): n = sequence[i] if n < 0: break shortest = nx.single_source_dijkstra_path_length(graph, n).items() shortest = sorted(shortest, key=lambda v: v[1]) shortest = shortest[:size] for j in xrange(0, min(size, len(shortest))): neighborhoods[i][j] = shortest[j][0] return neighborhoods return tf.py_func(_neighborhoods_weights_to_root, [adjacency, sequence], tf.int32, stateful=False, name='neighborhoods_weights_to_root')
Example #16
Source File: test_convert_numpy.py From aws-kube-codesuite with Apache License 2.0 | 6 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)
Example #17
Source File: connectivity.py From pycog with MIT License | 6 votes |
def is_connected(C): """ Return `True` if the square connection matrix `C` is connected, i.e., every unit is reachable from every other unit, otherwise `False`. Note ---- This function only performs the check if the NetworkX package is available: https://networkx.github.io/ """ if nx is None: return True G = nx.from_numpy_matrix(C, create_using=nx.DiGraph()) return nx.is_strongly_connected(G)
Example #18
Source File: test_convert_numpy.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def test_from_numpy_matrix_dtype(self): dt = [('weight', float), ('cost', int)] A = np.matrix([[(1.0, 2)]], dtype=dt) G = nx.from_numpy_matrix(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 #19
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_matrix, A)
Example #20
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_matrix(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 #21
Source File: test_branchings.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def G1(): G = nx.DiGraph() G = nx.from_numpy_matrix(G_array, create_using=G) G = nx.MultiDiGraph(G) return G
Example #22
Source File: statistics.py From generative-graph-transformer with MIT License | 5 votes |
def get_diameters(graph): r""" Compute histogram of connected components diameters for a graph. :param graph: graph representation in networkx format: nx.from_numpy_matrix(A) :return: list of connected components diameters """ diams = [] for g in nx.connected_component_subgraphs(graph): diams.append(nx.diameter(g)) diams = list(filter(lambda a: a != 0, diams)) return np.array(diams)
Example #23
Source File: statistics.py From generative-graph-transformer with MIT License | 5 votes |
def compute_statistics_MLP(y_A, y_nodes, output_A, output_nodes, y_seq_len, output_seq_len): r""" Compute statistics for the current data point, based on the one-shot output from the MLP decoder. :param output_adj: predicted A :param output_coord: predicted X :param output_seq_len: predicted |V| :param y_adj: target A :param y_coord: target X :param y_seq_len: target |V| :param lamb: lambda parameter for the loss in this experiment :return: streetmover, acc_A, delta_n_edges, delta_n_nodes, dist_degree, dist_diam """ output_graph = nx.from_numpy_matrix(output_A) y_graph = nx.from_numpy_matrix(y_A) output_degree = get_degree_hist(output_graph) y_degree = get_degree_hist(y_graph) dist_degree = wasserstein_distance(output_degree, y_degree) output_diam = get_diameters(output_graph) y_diam = get_diameters(y_graph) dist_diam = wasserstein_distance(output_diam, y_diam) if len(output_diam) > 0 else 1 delta_n_nodes = int(output_seq_len - y_seq_len) delta_n_edges = output_A.sum() - y_A.sum() acc_A = get_accuracy_A(output_A, y_A) (y_pc, output_pc), (streetmover, P, C) = streetmover_distance(y_A, y_nodes, output_A, output_nodes, n_points=100) # print("Streetmover distance: {:.3f}".format(streetmover.item())) return streetmover.item(), acc_A, delta_n_edges, delta_n_nodes, dist_degree, dist_diam
Example #24
Source File: util.py From JustCopy with MIT License | 5 votes |
def sort_sentences(sentences, words, sim_func = get_similarity, pagerank_config = {'alpha': 0.85,}): """将句子按照关键程度从大到小排序 Keyword arguments: sentences -- 列表,元素是句子 words -- 二维列表,子列表和sentences中的句子对应,子列表由单词组成 sim_func -- 计算两个句子的相似性,参数是两个由单词组成的列表 pagerank_config -- pagerank的设置 """ sorted_sentences = [] _source = words sentences_num = len(_source) graph = np.zeros((sentences_num, sentences_num)) for x in xrange(sentences_num): for y in xrange(x, sentences_num): similarity = sim_func( _source[x], _source[y] ) graph[x, y] = similarity graph[y, x] = similarity nx_graph = nx.from_numpy_matrix(graph) scores = nx.pagerank(nx_graph, **pagerank_config) # this is a dict sorted_scores = sorted(scores.items(), key = lambda item: item[1], reverse=True) for index, score in sorted_scores: item = AttrDict(index=index, sentence=sentences[index], weight=score) sorted_sentences.append(item) return sorted_sentences
Example #25
Source File: test_convert_numpy.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def test_from_numpy_matrix_parallel_edges(self): """Tests that the :func:`networkx.from_numpy_matrix` function interprets integer weights as the number of parallel edges when creating a multigraph. """ A = np.matrix([[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_matrix(A, parallel_edges=True, create_using=nx.DiGraph()) assert_graphs_equal(actual, expected) actual = nx.from_numpy_matrix(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_matrix(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_matrix(A, parallel_edges=False, create_using=nx.MultiDiGraph()) assert_graphs_equal(actual, expected)
Example #26
Source File: test_convert_numpy.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def test_from_numpy_matrix_dtype(self): dt=[('weight',float),('cost',int)] A=np.matrix([[(1.0,2)]],dtype=dt) G=nx.from_numpy_matrix(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 #27
Source File: plot_utils.py From graph-convnet-tsp with MIT License | 5 votes |
def plot_tsp(p, x_coord, W, W_val, W_target, title="default"): """ Helper function to plot TSP tours. Args: p: Matplotlib figure/subplot x_coord: Coordinates of nodes W: Edge adjacency matrix W_val: Edge values (distance) matrix W_target: One-hot matrix with 1s on groundtruth/predicted edges title: Title of figure/subplot Returns: p: Updated figure/subplot """ def _edges_to_node_pairs(W): """Helper function to convert edge matrix into pairs of adjacent nodes. """ pairs = [] for r in range(len(W)): for c in range(len(W)): if W[r][c] == 1: pairs.append((r, c)) return pairs G = nx.from_numpy_matrix(W_val) pos = dict(zip(range(len(x_coord)), x_coord.tolist())) adj_pairs = _edges_to_node_pairs(W) target_pairs = _edges_to_node_pairs(W_target) colors = ['g'] + ['b'] * (len(x_coord) - 1) # Green for 0th node, blue for others nx.draw_networkx_nodes(G, pos, node_color=colors, node_size=50) nx.draw_networkx_edges(G, pos, edgelist=adj_pairs, alpha=0.3, width=0.5) nx.draw_networkx_edges(G, pos, edgelist=target_pairs, alpha=1, width=1, edge_color='r') p.set_title(title) return p
Example #28
Source File: plot_utils.py From graph-convnet-tsp with MIT License | 5 votes |
def plot_tsp_heatmap(p, x_coord, W_val, W_pred, title="default"): """ Helper function to plot predicted TSP tours with edge strength denoting confidence of prediction. Args: p: Matplotlib figure/subplot x_coord: Coordinates of nodes W_val: Edge values (distance) matrix W_pred: Edge predictions matrix title: Title of figure/subplot Returns: p: Updated figure/subplot """ def _edges_to_node_pairs(W): """Helper function to convert edge matrix into pairs of adjacent nodes. """ pairs = [] edge_preds = [] for r in range(len(W)): for c in range(len(W)): if W[r][c] > 0.25: pairs.append((r, c)) edge_preds.append(W[r][c]) return pairs, edge_preds G = nx.from_numpy_matrix(W_val) pos = dict(zip(range(len(x_coord)), x_coord.tolist())) node_pairs, edge_color = _edges_to_node_pairs(W_pred) node_color = ['g'] + ['b'] * (len(x_coord) - 1) # Green for 0th node, blue for others nx.draw_networkx_nodes(G, pos, node_color=node_color, node_size=50) nx.draw_networkx_edges(G, pos, edgelist=node_pairs, edge_color=edge_color, edge_cmap=plt.cm.Reds, width=0.75) p.set_title(title) return p
Example #29
Source File: test_convert_numpy.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def identity_conversion(self, G, A, create_using): GG = nx.from_numpy_matrix(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 #30
Source File: test_convert_numpy.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.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_matrix, A)