Python networkx.adj_matrix() Examples
The following are 17
code examples of networkx.adj_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: PC.py From CausalDiscoveryToolbox with MIT License | 6 votes |
def orient_undirected_graph(self, data, graph, **kwargs): """Run PC on an undirected graph. Args: data (pandas.DataFrame): DataFrame containing the data graph (networkx.Graph): Skeleton of the graph to orient Returns: networkx.DiGraph: Solution given by PC on the given skeleton. """ # Building setup w/ arguments. self.arguments['{CITEST}'] = self.dir_CI_test[self.CI_test] self.arguments['{METHOD_INDEP}'] = self.dir_method_indep[self.CI_test] self.arguments['{DIRECTED}'] = 'TRUE' self.arguments['{ALPHA}'] = str(self.alpha) self.arguments['{NJOBS}'] = str(self.njobs) self.arguments['{VERBOSE}'] = str(self.verbose).upper() fe = DataFrame(nx.adj_matrix(graph, weight=None).todense()) fg = DataFrame(1 - fe.values) results = self._run_pc(data, fixedEdges=fe, fixedGaps=fg, verbose=self.verbose) return nx.relabel_nodes(nx.DiGraph(results), {idx: i for idx, i in enumerate(data.columns)})
Example #2
Source File: link_pred.py From nodevectors with MIT License | 6 votes |
def generate_neg_edges(G, testing_edges_num, seed=42): nnodes = len(G.nodes) # Make a full graph (matrix of 1) negG = np.ones((nnodes, nnodes)) np.fill_diagonal(negG, 0.) # Substract existing edges from full graph # generates negative graph original_graph = nx.adj_matrix(G).todense() negG = negG - original_graph # get negative edges (nonzero entries) neg_edges = np.where(negG > 0) random.seed(seed) # replicability! rng_edges = random.sample(range(neg_edges[0].size), testing_edges_num) # return edges in (src, dst) tuple format return list(zip( neg_edges[0][rng_edges], neg_edges[1][rng_edges] ))
Example #3
Source File: GES.py From CausalDiscoveryToolbox with MIT License | 6 votes |
def orient_undirected_graph(self, data, graph): """Run GES on an undirected graph. Args: data (pandas.DataFrame): DataFrame containing the data graph (networkx.Graph): Skeleton of the graph to orient Returns: networkx.DiGraph: Solution given by the GES algorithm. """ # Building setup w/ arguments. self.arguments['{VERBOSE}'] = str(self.verbose).upper() self.arguments['{SCORE}'] = self.scores[self.score] fe = DataFrame(nx.adj_matrix(graph, weight=None).todense()) fg = DataFrame(1 - fe.values) results = self._run_ges(data, fixedGaps=fg, verbose=self.verbose) return nx.relabel_nodes(nx.DiGraph(results), {idx: i for idx, i in enumerate(data.columns)})
Example #4
Source File: GIES.py From CausalDiscoveryToolbox with MIT License | 6 votes |
def orient_undirected_graph(self, data, graph): """Run GIES on an undirected graph. Args: data (pandas.DataFrame): DataFrame containing the data graph (networkx.Graph): Skeleton of the graph to orient Returns: networkx.DiGraph: Solution given by the GIES algorithm. """ # Building setup w/ arguments. self.arguments['{VERBOSE}'] = str(self.verbose).upper() self.arguments['{SCORE}'] = self.scores[self.score] fe = DataFrame(nx.adj_matrix(graph, weight=None).todense()) fg = DataFrame(1 - fe.values) results = self._run_gies(data, fixedGaps=fg, verbose=self.verbose) return nx.relabel_nodes(nx.DiGraph(results), {idx: i for idx, i in enumerate(data.columns)})
Example #5
Source File: test_graphmatrix.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def test_adjacency_matrix(self): "Conversion to adjacency matrix" assert_equal(nx.adj_matrix(self.G).todense(), self.A) assert_equal(nx.adj_matrix(self.MG).todense(), self.A) assert_equal(nx.adj_matrix(self.MG2).todense(), self.MG2A) assert_equal(nx.adj_matrix(self.G, nodelist=[0, 1]).todense(), self.A[:2, :2]) assert_equal(nx.adj_matrix(self.WG).todense(), self.WA) assert_equal(nx.adj_matrix(self.WG, weight=None).todense(), self.A) assert_equal(nx.adj_matrix(self.MG2, weight=None).todense(), self.MG2A) assert_equal(nx.adj_matrix(self.WG, weight='other').todense(), 0.6 * self.WA) assert_equal(nx.adj_matrix(self.no_edges_G, nodelist=[1, 3]).todense(), self.no_edges_A)
Example #6
Source File: test_graphmatrix.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_adjacency_matrix(self): "Conversion to adjacency matrix" assert_equal(nx.adj_matrix(self.G).todense(), self.A) assert_equal(nx.adj_matrix(self.MG).todense(), self.A) assert_equal(nx.adj_matrix(self.MG2).todense(), self.MG2A) assert_equal(nx.adj_matrix(self.G, nodelist=[0, 1]).todense(), self.A[:2, :2]) assert_equal(nx.adj_matrix(self.WG).todense(), self.WA) assert_equal(nx.adj_matrix(self.WG, weight=None).todense(), self.A) assert_equal(nx.adj_matrix(self.MG2, weight=None).todense(), self.MG2A) assert_equal(nx.adj_matrix(self.WG, weight='other').todense(), 0.6 * self.WA) assert_equal(nx.adj_matrix(self.no_edges_G, nodelist=[1, 3]).todense(), self.no_edges_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: test_graphmatrix.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def test_adjacency_matrix(self): "Conversion to adjacency matrix" assert_equal(nx.adj_matrix(self.G).todense(),self.A) assert_equal(nx.adj_matrix(self.MG).todense(),self.A) assert_equal(nx.adj_matrix(self.MG2).todense(),self.MG2A) assert_equal(nx.adj_matrix(self.G,nodelist=[0,1]).todense(),self.A[:2,:2]) assert_equal(nx.adj_matrix(self.WG).todense(),self.WA) assert_equal(nx.adj_matrix(self.WG,weight=None).todense(),self.A) assert_equal(nx.adj_matrix(self.MG2,weight=None).todense(),self.MG2A) assert_equal(nx.adj_matrix(self.WG,weight='other').todense(),0.6*self.WA)
Example #9
Source File: test_causality_graph.py From CausalDiscoveryToolbox with MIT License | 5 votes |
def test_directed(): for method in [GS, GIES, IAMB, Fast_IAMB, PC, GES, MMPC, Inter_IAMB]: print(method) m = method() output1 = m.predict(data_graph) print(nx.adj_matrix(output1).todense()) output2 = m.predict(data_graph, output1) assert isinstance(output2, nx.DiGraph) return 0
Example #10
Source File: test_pipeline_CGNN.py From CausalDiscoveryToolbox with MIT License | 5 votes |
def test_multiprocessing_ete_CGNN(): data = pd.read_csv('{}/../datasets/NUM_LUCAS.csv'.format(os.path.dirname(os.path.realpath(__file__)))).iloc[:50, :3] # Finding the structure of the graph # List results # print(nx.adj_matrix(ugraph).todense().shape) # Orient the edges of the graph SETTINGS.GPU = 0 Cgnn = CGNN(nruns=6, njobs=2, train_epochs=2, test_epochs=2) assert type(Cgnn.predict(data)) == nx.DiGraph return 0
Example #11
Source File: test_pipeline_CGNN.py From CausalDiscoveryToolbox with MIT License | 5 votes |
def test_multiprocessing_CGNN(): data = pd.read_csv('{}/../datasets/NUM_LUCAS.csv'.format(os.path.dirname(os.path.realpath(__file__)))).iloc[:50, :3] # Finding the structure of the graph Fsgnn = FSGNN(train_epochs=5, test_epochs=5, l1=0.006, njobs=2) ugraph = Fsgnn.predict(data, threshold=1e-2) # List results # print(nx.adj_matrix(ugraph).todense().shape) # Orient the edges of the graph Cgnn = CGNN(nruns=6, njobs=2, train_epochs=2, test_epochs=2) assert type(Cgnn.predict(data, graph=ugraph)) == nx.DiGraph return 0
Example #12
Source File: test_pipeline_CGNN.py From CausalDiscoveryToolbox with MIT License | 5 votes |
def test_pipeline_CGNN(): data = pd.read_csv('{}/../datasets/NUM_LUCAS.csv'.format(os.path.dirname(os.path.realpath(__file__)))).iloc[:50, :3] # Finding the structure of the graph Fsgnn = FSGNN(train_epochs=5, test_epochs=5, l1=0.006) ugraph = Fsgnn.predict(data, threshold=1e-2) # List results # print(nx.adj_matrix(ugraph).todense().shape) # Orient the edges of the graph Cgnn = CGNN(nruns=1, train_epochs=2, test_epochs=2) assert type(Cgnn.predict(data, graph=ugraph)) == nx.DiGraph return 0
Example #13
Source File: CGNN.py From CausalDiscoveryToolbox with MIT License | 5 votes |
def hill_climbing(data, graph, **kwargs): """Hill Climbing optimization: a greedy exploration algorithm.""" if isinstance(data, th.utils.data.Dataset): nodelist = data.get_names() elif isinstance(data, pd.DataFrame): nodelist = list(data.columns) else: raise TypeError('Data type not understood') tested_candidates = [nx.adj_matrix(graph, nodelist=nodelist, weight=None)] best_score = parallel_graph_evaluation(data, tested_candidates[0].todense(), ** kwargs) best_candidate = graph can_improve = True while can_improve: can_improve = False for (i, j) in best_candidate.edges(): test_graph = deepcopy(best_candidate) test_graph.add_edge(j, i, weight=test_graph[i][j]['weight']) test_graph.remove_edge(i, j) tadjmat = nx.adj_matrix(test_graph, nodelist=nodelist, weight=None) if (nx.is_directed_acyclic_graph(test_graph) and not any([(tadjmat != cand).nnz == 0 for cand in tested_candidates])): tested_candidates.append(tadjmat) score = parallel_graph_evaluation(data, tadjmat.todense(), **kwargs) if score < best_score: can_improve = True best_candidate = test_graph best_score = score break return best_candidate
Example #14
Source File: CGNN.py From CausalDiscoveryToolbox with MIT License | 5 votes |
def parallel_graph_evaluation(data, adj_matrix, nruns=16, njobs=None, gpus=None, **kwargs): """Parallelize the various runs of CGNN to evaluate a graph.""" njobs, gpus = SETTINGS.get_default(('njobs', njobs), ('gpu', gpus)) if gpus == 0: output = [graph_evaluation(data, adj_matrix, device=SETTINGS.default_device, **kwargs) for run in range(nruns)] else: output = parallel_run(graph_evaluation, data, adj_matrix, njobs=njobs, gpus=gpus, nruns=nruns, **kwargs) return np.mean(output)
Example #15
Source File: CGNN.py From CausalDiscoveryToolbox with MIT License | 5 votes |
def __init__(self, adj_matrix, batch_size, nh=20, device=None, confounding=False, initial_graph=None, **kwargs): """Init the model by creating the blocks and extracting the topological order.""" super(CGNN_model, self).__init__() self.topological_order = [i for i in nx.topological_sort(nx.DiGraph(adj_matrix))] self.adjacency_matrix = adj_matrix self.confounding = confounding if initial_graph is None: self.i_adj_matrix = self.adjacency_matrix else: self.i_adj_matrix = initial_graph self.blocks = th.nn.ModuleList() self.generated = [None for i in range(self.adjacency_matrix.shape[0])] self.register_buffer('noise', th.zeros(batch_size, self.adjacency_matrix.shape[0])) if self.confounding: corr_noises = [] for i, j in zip(*np.nonzero(self.i_adj_matrix)): if i < j: pname = 'cnoise_{}'.format(i) self.register_buffer(pname, th.FloatTensor(batch_size, 1)) corr_noises.append([(i, j), getattr(self, pname)]) self.corr_noise = dict(corr_noises) self.criterion = MMDloss(batch_size).to(device) self.register_buffer('score', th.FloatTensor([0])) self.batch_size = batch_size for i in range(self.adjacency_matrix.shape[0]): if not confounding: self.blocks.append(CGNN_block([int(self.adjacency_matrix[:, i].sum()) + 1, nh, 1])) else: self.blocks.append(CGNN_block([int(self.i_adj_matrix[:, i].sum()) + int(self.adjacency_matrix[:, i].sum()) + 1, nh, 1]))
Example #16
Source File: utils.py From pytorch-AGNN with MIT License | 4 votes |
def load_data(path="../data/cora/", dataset="cora"): """Load citation network dataset (cora only for now)""" print('Loading {} dataset...'.format(dataset)) if dataset == "cora": idx_features_labels = np.genfromtxt("{}{}.content".format(path, dataset), dtype=np.dtype(str)) features = sp.csr_matrix( idx_features_labels[:, 1:-1], dtype=np.float32) labels = encode_onehot(idx_features_labels[:, -1]) # build graph idx = np.array(idx_features_labels[:, 0], dtype=np.int32) idx_map = {j: i for i, j in enumerate(idx)} edges_unordered = np.genfromtxt("{}{}.cites".format(path, dataset), dtype=np.int32) edges = np.array(list(map(idx_map.get, edges_unordered.flatten())), dtype=np.int32).reshape(edges_unordered.shape) adj = sp.coo_matrix((np.ones(edges.shape[0]), (edges[:, 0], edges[:, 1])), shape=(labels.shape[0], labels.shape[0]), dtype=np.float32) elif dataset == "karate_club": g = nx.karate_club_graph() features = sp.csr_matrix(np.identity( g.number_of_nodes()), dtype=np.float32) labels = map(lambda x: x.get('club'), g.node.values()) labels = encode_onehot(labels).astype(np.float32) adj = nx.adj_matrix(g).astype(np.float32) else: raise Exception("dataset not defined!") # build symmetric adjacency matrix adj = adj + adj.T.multiply(adj.T > adj) - adj.multiply(adj.T > adj) # row-normalize input feature vectors features = normalize(features) # add self-loop adj = adj + sp.eye(adj.shape[0]) idx_train = range(140) idx_val = range(200, 500) idx_test = range(500, 1500) features = torch.FloatTensor(np.array(features.todense())) labels = torch.LongTensor(np.where(labels)[1]) adj = torch.FloatTensor(np.array(adj.todense())) idx_train = torch.LongTensor(idx_train) idx_val = torch.LongTensor(idx_val) idx_test = torch.LongTensor(idx_test) return adj, features, labels, idx_train, idx_val, idx_test
Example #17
Source File: bnlearn.py From CausalDiscoveryToolbox with MIT License | 4 votes |
def orient_undirected_graph(self, data, graph): """Run the algorithm on an undirected graph. Args: data (pandas.DataFrame): DataFrame containing the data graph (networkx.Graph): Skeleton of the graph to orient Returns: networkx.DiGraph: Solution on the given skeleton. """ # Building setup w/ arguments. self.arguments['{VERBOSE}'] = str(self.verbose).upper() self.arguments['{SCORE}'] = self.score self.arguments['{BETA}'] = str(self.beta) self.arguments['{OPTIM}'] = str(self.optim).upper() self.arguments['{ALPHA}'] = str(self.alpha) cols = list(data.columns) data.columns = [i for i in range(data.shape[1])] graph2 = nx.relabel_nodes(graph, {j: i for i, j in zip(['X' + str(i) for i in range(data.shape[1])], cols)}) whitelist = DataFrame(list(nx.edges(graph2)), columns=["from", "to"]) blacklist = DataFrame(list(nx.edges(nx.DiGraph(DataFrame(-nx.adj_matrix(graph2, weight=None).todense() + 1, columns=list(graph2.nodes()), index=list(graph2.nodes()))))), columns=["from", "to"]) results = self._run_bnlearn(data, whitelist=whitelist, blacklist=blacklist, verbose=self.verbose) try: return nx.relabel_nodes(nx.DiGraph(results), {idx: i for idx, i in enumerate(cols)}) except nx.exception.NetworkXError as e: if results.shape[1] == 2: output = nx.DiGraph() output.add_nodes_from(['X' + str(i) for i in range(data.shape[1])]) output.add_edges_from(results) return nx.relabel_nodes(output, {i: j for i, j in zip(['X' + str(i) for i in range(data.shape[1])], cols)}) else: raise e