Python networkx.from_edgelist() Examples
The following are 30
code examples of networkx.from_edgelist().
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: test_quantum_computer.py From pyquil with Apache License 2.0 | 6 votes |
def test_device_stuff(): topo = nx.from_edgelist([(0, 4), (0, 99)]) qc = QuantumComputer( name="testy!", qam=None, # not necessary for this test device=NxDevice(topo), compiler=DummyCompiler(), ) assert nx.is_isomorphic(qc.qubit_topology(), topo) isa = qc.get_isa(twoq_type="CPHASE") assert isa.edges[0].type == "CPHASE" assert isa.edges[0].targets == (0, 4) # We sometimes narrowly miss the np.mean(parity) < 0.15 assertion, below. Alternatively, that upper # bound could be relaxed.
Example #2
Source File: utils.py From GraRep with GNU General Public License v3.0 | 6 votes |
def create_inverse_degree_matrix(edges): """ Creating an inverse degree matrix from an edge list. :param edges: Edge list. :return D_1: Inverse degree matrix. """ graph = nx.from_edgelist(edges) ind = range(len(graph.nodes())) degs = [1.0/graph.degree(node) for node in range(graph.number_of_nodes())] D_1 = sparse.coo_matrix((degs, (ind, ind)), shape=(graph.number_of_nodes(), graph.number_of_nodes()), dtype=np.float32) return D_1
Example #3
Source File: convert.py From aws-kube-codesuite with Apache License 2.0 | 6 votes |
def from_edgelist(edgelist, create_using=None): """Return a graph from a list of edges. Parameters ---------- edgelist : list or iterator Edge tuples create_using : NetworkX graph Use specified graph for result. Otherwise a new graph is created. Examples -------- >>> edgelist = [(0, 1)] # single edge (0,1) >>> G = nx.from_edgelist(edgelist) or >>> G = nx.Graph(edgelist) # use Graph constructor """ G = _prep_create_using(create_using) G.add_edges_from(edgelist) return G
Example #4
Source File: convert.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def from_edgelist(edgelist, create_using=None): """Returns a graph from a list of edges. Parameters ---------- edgelist : list or iterator Edge tuples create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Examples -------- >>> edgelist = [(0, 1)] # single edge (0,1) >>> G = nx.from_edgelist(edgelist) or >>> G = nx.Graph(edgelist) # use Graph constructor """ G = nx.empty_graph(0, create_using) G.add_edges_from(edgelist) return G
Example #5
Source File: helpers.py From TADW with GNU General Public License v3.0 | 6 votes |
def read_graph(edge_path, order): """ Method to read graph and create a target matrix by summing adjacency matrix powers. :param edge_path: Path to the ege list. :param order: Order of approximations. :return out_A: Target matrix. """ print("Target matrix creation started.") graph = nx.from_edgelist(pd.read_csv(edge_path).values.tolist()) A = normalize_adjacency(graph) if order > 1: powered_A, out_A = A, A for _ in tqdm(range(order-1)): powered_A = powered_A.dot(A) out_A = out_A + powered_A else: out_A = A print("Factorization started.") return out_A
Example #6
Source File: helpers.py From TENE with GNU General Public License v3.0 | 6 votes |
def read_graph(edge_path, order): """ Method to read graph and create a target matrix with pooled adjacency matrix powers up to the order. :param edge_path: Path to the ege list. :param order: Order of approximations. :return out_A: Target matrix. """ print("Target matrix creation started.") graph = nx.from_edgelist(pd.read_csv(edge_path).values.tolist()) A = normalize_adjacency(graph) if order > 1: powered_A, out_A = A, A for _ in tqdm(range(order-1)): powered_A = powered_A.dot(A) out_A = out_A + powered_A else: out_A = A print("Factorization started.") return out_A
Example #7
Source File: helpers.py From FSCNMF with GNU General Public License v3.0 | 6 votes |
def read_graph(edge_path, order): """ Method to read graph and create a target matrix by summing adjacency matrix powers. :param edge_path: Path to the ege list. :param order: Order of approximations. :return out_A: Target matrix. """ print("Target matrix creation started.") graph = nx.from_edgelist(pd.read_csv(edge_path).values.tolist()) A = normalize_adjacency(graph) if order > 1: powered_A, out_A = A, A for _ in tqdm(range(order-1)): powered_A = powered_A.dot(A) out_A = out_A + powered_A else: out_A = A print("Factorization started.") return out_A
Example #8
Source File: graph2vec.py From graph2vec with GNU General Public License v3.0 | 6 votes |
def dataset_reader(path): """ Function to read the graph and features from a json file. :param path: The path to the graph json. :return graph: The graph object. :return features: Features hash table. :return name: Name of the graph. """ name = path.strip(".json").split("/")[-1] data = json.load(open(path)) graph = nx.from_edgelist(data["edges"]) if "features" in data.keys(): features = data["features"] else: features = nx.degree(graph) features = {int(k): v for k, v in features.items()} return graph, features, name
Example #9
Source File: convert.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 6 votes |
def from_edgelist(edgelist,create_using=None): """Return a graph from a list of edges. Parameters ---------- edgelist : list or iterator Edge tuples create_using : NetworkX graph Use specified graph for result. Otherwise a new graph is created. Examples -------- >>> edgelist= [(0,1)] # single edge (0,1) >>> G=nx.from_edgelist(edgelist) or >>> G=nx.Graph(edgelist) # use Graph constructor """ G=_prep_create_using(create_using) G.add_edges_from(edgelist) return G
Example #10
Source File: dgk.py From cogdl with MIT License | 5 votes |
def feature_extractor(data, rounds, name): graph = nx.from_edgelist(np.array(data.edge_index.T.cpu(), dtype=int)) if data.x is not None: feature = {int(key): str(val.argmax(axis=0)) for key, val in enumerate(np.array(data.x.cpu()))} else: feature = dict(nx.degree(graph)) graph_wl_features = DeepGraphKernel.wl_iterations(graph, feature, rounds) return graph_wl_features
Example #11
Source File: calculation_helper.py From M-NMF with GNU General Public License v3.0 | 5 votes |
def graph_reader(input_path): """ Function to read a csv edge list and transform it to a networkx graph object. :param input_path: Path to the edge list csv. :return graph: NetworkX grapg object. """ edges = pd.read_csv(input_path) graph = nx.from_edgelist(edges.values.tolist()) return graph
Example #12
Source File: graph2vec.py From cogdl with MIT License | 5 votes |
def feature_extractor(data, rounds, name): graph = nx.from_edgelist(np.array(data.edge_index.T.cpu(), dtype=int)) if data.x is not None: feature = {int(key): str(val) for key, val in enumerate(np.array(data.x.cpu()))} else: feature = dict(nx.degree(graph)) graph_wl_features = Graph2Vec.wl_iterations(graph, feature, rounds) doc = TaggedDocument(words=graph_wl_features, tags=["g_" + name]) return doc
Example #13
Source File: TADClassifier.py From Topological-Anomaly-Detection with BSD 3-Clause "New" or "Revised" License | 5 votes |
def construct_constrained_graph(adj, r, n): """ given an adjacency matrix adj in the form of a condensed distance matrix (of the kind returned by pdist) for n observations, returns the similarity graph for all distances less than or equal to r. """ ij = row_col_from_condensed_index(n, np.where(adj<=r)[0]) g = nx.from_edgelist(zip(*ij)) g.add_nodes_from(range(n)) return g
Example #14
Source File: utils.py From APPNP with GNU General Public License v3.0 | 5 votes |
def graph_reader(path): """ Function to read the graph from the path. :param path: Path to the edge list. :return graph: NetworkX object returned. """ graph = nx.from_edgelist(pd.read_csv(path).values.tolist()) graph.remove_edges_from(nx.selfloop_edges(graph)) return graph
Example #15
Source File: utils.py From MixHop-and-N-GCN with GNU General Public License v3.0 | 5 votes |
def graph_reader(path): """ Function to read the graph from the path. :param path: Path to the edge list. :return graph: NetworkX object returned. """ graph = nx.from_edgelist(pd.read_csv(path).values.tolist()) graph.remove_edges_from(list(nx.selfloop_edges(graph))) return graph
Example #16
Source File: utils.py From GraphWaveletNeuralNetwork with GNU General Public License v3.0 | 5 votes |
def graph_reader(path): """ Function to create an NX graph object. :param path: Path to the edge list csv. :return graph: NetworkX graph. """ graph = nx.from_edgelist(pd.read_csv(path).values.tolist()) graph.remove_edges_from(nx.selfloop_edges(graph)) return graph
Example #17
Source File: device_test.py From Cirq with Apache License 2.0 | 5 votes |
def test_nx_qubit_layout_3(): g = nx.from_edgelist([ (cirq.NamedQubit('a'), cirq.NamedQubit('b')), (cirq.NamedQubit('b'), cirq.NamedQubit('c')), ]) node_to_i = { cirq.NamedQubit('a'): 0, cirq.NamedQubit('b'): 1, cirq.NamedQubit('c'): 2, } pos = ccr.nx_qubit_layout(g) for k, (x, y) in pos.items(): assert x == 0.5 assert y == node_to_i[k] + 1
Example #18
Source File: device_test.py From Cirq with Apache License 2.0 | 5 votes |
def test_nx_qubit_layout_2(): g = nx.from_edgelist([ (cirq.LineQubit(0), cirq.LineQubit(1)), (cirq.LineQubit(1), cirq.LineQubit(2)), ]) pos = ccr.nx_qubit_layout(g) for k, (x, y) in pos.items(): assert x == k.x assert y == 0.5
Example #19
Source File: graphs.py From holoviews with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _process(self, element, key=None): if self.p.layout and isinstance(self.p.layout, FunctionType): import networkx as nx edges = element.array([0, 1]) graph = nx.from_edgelist(edges) if 'weight' in self.p.kwargs: weight = self.p.kwargs['weight'] for (s, t), w in zip(edges, element[weight]): graph.edges[s, t][weight] = w positions = self.p.layout(graph, **self.p.kwargs) nodes = [tuple(pos)+(idx,) for idx, pos in sorted(positions.items())] else: source = element.dimension_values(0, expanded=False) target = element.dimension_values(1, expanded=False) nodes = np.unique(np.concatenate([source, target])) if self.p.layout: import pandas as pd df = pd.DataFrame({'index': nodes}) nodes = self.p.layout(df, element.dframe(), **self.p.kwargs) nodes = nodes[['x', 'y', 'index']] else: nodes = circular_layout(nodes) nodes = element.node_type(nodes) if element._nodes: for d in element.nodes.vdims: vals = element.nodes.dimension_values(d) nodes = nodes.add_dimension(d, len(nodes.vdims), vals, vdim=True) if self.p.only_nodes: return nodes return element.clone((element.data, nodes))
Example #20
Source File: main.py From GraphWaveMachine with GNU General Public License v3.0 | 5 votes |
def read_graph(settings): """ Reading the edge list from the path and returning the networkx graph object. :param path: Path to the edge list. :return graph: Graph from edge list. """ if settings.edgelist_input: graph = nx.read_edgelist(settings.input) else: edge_list = pd.read_csv(settings.input).values.tolist() graph = nx.from_edgelist(edge_list) graph.remove_edges_from(nx.selfloop_edges(graph)) return graph
Example #21
Source File: print_and_read.py From LabelPropagation with GNU General Public License v3.0 | 5 votes |
def graph_reader(input_path): """ Function to read graph from input path. :param input_path: Graph read into memory. :return graph: Networkx graph. """ edges = pd.read_csv(input_path) graph = nx.from_edgelist(edges.values.tolist()) return graph
Example #22
Source File: test_device.py From pyquil with Apache License 2.0 | 5 votes |
def test_isa_to_graph(isa_dict): graph = isa_to_graph(ISA.from_dict(isa_dict)) should_be = nx.from_edgelist([(0, 1), (1, 2), (0, 2)]) assert nx.is_isomorphic(graph, should_be)
Example #23
Source File: test_entangled_states.py From forest-benchmarking with Apache License 2.0 | 5 votes |
def test_create_ghz_program(wfn): tree = nx.from_edgelist([(0, 1), (0, 2)], create_using=nx.DiGraph()) prog = create_ghz_program(tree) for _ in tree.nodes: prog.pop() # remove measurements prog = address_qubits(prog) wf = wfn.wavefunction(prog) should_be = [0.5] + [0] * (2 ** tree.number_of_nodes() - 2) + [0.5] np.testing.assert_allclose(should_be, wf.probabilities())
Example #24
Source File: test_entangled_states.py From forest-benchmarking with Apache License 2.0 | 5 votes |
def test_create_bad_ghz_program(): tree = nx.from_edgelist([(0, 1), (1, 2), (2, 0)], create_using=nx.DiGraph()) with pytest.raises(AssertionError) as e: prog = create_ghz_program(tree) assert e.match(r'Needs to be a tree')
Example #25
Source File: utils.py From SEAL-CI with GNU General Public License v3.0 | 5 votes |
def hierarchical_graph_reader(path): """ Reading the macro-level graph from disk. :param path: Path to the edge list. :return graph: Hierarchical graph as a NetworkX object. """ edges = pd.read_csv(path).values.tolist() graph = nx.from_edgelist(edges) return graph
Example #26
Source File: utils.py From BioNEV with MIT License | 5 votes |
def read_for_gae(filename, weighted=False): print("Loading training graph for learning embedding...") edgelist = np.loadtxt(filename, dtype='float') if weighted: edgelist = [(int(edgelist[idx, 0]), int(edgelist[idx, 1])) for idx in range(edgelist.shape[0]) if edgelist[idx, 2] > 0] else: edgelist = [(int(edgelist[idx, 0]), int(edgelist[idx, 1])) for idx in range(edgelist.shape[0])] G=nx.from_edgelist(edgelist) node_list=list(G.nodes) adj = nx.adjacency_matrix(G, nodelist=node_list) print("Graph Loaded...") return (adj,node_list)
Example #27
Source File: test_euler.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_disconnected(self): G = nx.from_edgelist([(0, 1), (2, 3)]) nx.eulerize(G)
Example #28
Source File: refex.py From RolX with GNU General Public License v3.0 | 5 votes |
def dataset_reader(path): edges = pd.read_csv(path).values.tolist() graph = nx.from_edgelist(edges) return graph
Example #29
Source File: utils.py From role2vec with GNU General Public License v3.0 | 5 votes |
def load_graph(graph_path): """ Reading an edge list csv to an NX graph object. :param graph_path: Path to the edhe list csv. :return graph: NetworkX object. """ graph = nx.from_edgelist(pd.read_csv(graph_path).values.tolist()) graph.remove_edges_from(nx.selfloop_edges(graph)) return graph
Example #30
Source File: utils.py From EdMot with GNU General Public License v3.0 | 5 votes |
def graph_reader(path): """ Function to read the graph from the path. :param path: Path to the edge list. :return graph: NetworkX object returned. """ graph = nx.from_edgelist(pd.read_csv(path).values.tolist()) graph.remove_edges_from(nx.selfloop_edges(graph)) return graph