本文整理汇总了Python中networkx.convert_node_labels_to_integers方法的典型用法代码示例。如果您正苦于以下问题:Python networkx.convert_node_labels_to_integers方法的具体用法?Python networkx.convert_node_labels_to_integers怎么用?Python networkx.convert_node_labels_to_integers使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx
的用法示例。
在下文中一共展示了networkx.convert_node_labels_to_integers方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __getitem__
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import convert_node_labels_to_integers [as 别名]
def __getitem__(self, item):
"""
Returns an rdkit mol object
:param item:
:return:
"""
smiles = self.df['smiles'][item]
mol = Chem.MolFromSmiles(smiles)
return mol
# # TESTS
# path = 'gdb13.rand1M.smi.gz'
# dataset = gdb_dataset(path)
#
# print(len(dataset))
# mol,_ = dataset[0]
# graph = mol_to_nx(mol)
# graph_sub = graph.subgraph([0,3,5,7,9])
# graph_sub_new = nx.convert_node_labels_to_integers(graph_sub,label_attribute='old')
# graph_sub_node = graph_sub.nodes()
# graph_sub_new_node = graph_sub_new.nodes()
# matrix = nx.adjacency_matrix(graph_sub)
# np_matrix = matrix.toarray()
# print(np_matrix)
# print('end')
示例2: _get_9q_square_qvm
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import convert_node_labels_to_integers [as 别名]
def _get_9q_square_qvm(
name: str, noisy: bool, connection: Optional[ForestConnection] = None, qvm_type: str = "qvm"
) -> QuantumComputer:
"""
A nine-qubit 3x3 square lattice.
This uses a "generic" lattice not tied to any specific device. 9 qubits is large enough
to do vaguely interesting algorithms and small enough to simulate quickly.
:param name: The name of this QVM
:param connection: The connection to use to talk to external services
:param noisy: Whether to construct a noisy quantum computer
:param qvm_type: The type of QVM. Either 'qvm' or 'pyqvm'.
:return: A pre-configured QuantumComputer
"""
topology = nx.convert_node_labels_to_integers(nx.grid_2d_graph(3, 3))
return _get_qvm_with_topology(
name=name,
connection=connection,
topology=topology,
noisy=noisy,
requires_executable=True,
qvm_type=qvm_type,
)
示例3: load_nofeatures
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import convert_node_labels_to_integers [as 别名]
def load_nofeatures(dataset, version, n = None):
'''
Loads a dataset that is just an edgelist, creating sparse one-hot features.
n: total number of nodes in the graph. This is the number of nodes present
in the edgelist unless otherwise specified
'''
# g = nx.read_edgelist('data/{}/{}{}.txt'.format(dataset, dataset, version))
# g = nx.convert_node_labels_to_integers(g)
# edges = np.array([(x[0], x[1]) for x in nx.to_edgelist(g)])
edges = np.loadtxt('data/{}/{}{}.cites'.format(dataset, dataset, version), dtype=np.int)
if n == None:
n = int(edges.max()) + 1
adj = make_normalized_adj(torch.tensor(edges).long(), n)
features = torch.eye(n).to_sparse()
return adj, features, None
示例4: tensorize_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import convert_node_labels_to_integers [as 别名]
def tensorize_graph(graph_batch, vocab):
fnode,fmess = [None],[(0,0,0,0)]
agraph,bgraph = [[]], [[]]
scope = []
edge_dict = {}
all_G = []
for bid,G in enumerate(graph_batch):
offset = len(fnode)
scope.append( (offset, len(G)) )
G = nx.convert_node_labels_to_integers(G, first_label=offset)
all_G.append(G)
fnode.extend( [None for v in G.nodes] )
for v, attr in G.nodes(data='label'):
G.nodes[v]['batch_id'] = bid
fnode[v] = vocab[attr]
agraph.append([])
for u, v, attr in G.edges(data='label'):
if type(attr) is tuple:
fmess.append( (u, v, attr[0], attr[1]) )
else:
fmess.append( (u, v, attr, 0) )
edge_dict[(u, v)] = eid = len(edge_dict) + 1
G[u][v]['mess_idx'] = eid
agraph[v].append(eid)
bgraph.append([])
for u, v in G.edges:
eid = edge_dict[(u, v)]
for w in G.predecessors(u):
if w == v: continue
bgraph[eid].append( edge_dict[(w, u)] )
fnode[0] = fnode[1]
fnode = torch.IntTensor(fnode)
fmess = torch.IntTensor(fmess)
agraph = create_pad_tensor(agraph)
bgraph = create_pad_tensor(bgraph)
return (fnode, fmess, agraph, bgraph, scope), nx.union_all(all_G)
示例5: __getitem__
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import convert_node_labels_to_integers [as 别名]
def __getitem__(self, index):
#TODO: Manually have to check the convert_node_labels_to_integers function
g = nx.convert_node_labels_to_integers(nx.read_graphml(os.path.join(self.root, self.ids[index])))
target = self.classes[index]
h = self.vertex_transform(g)
g, e = self.edge_transform(g)
target = self.target_transform(target)
return (g, h, e), target
示例6: from_networkx
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import convert_node_labels_to_integers [as 别名]
def from_networkx(G):
r"""Converts a :obj:`networkx.Graph` or :obj:`networkx.DiGraph` to a
:class:`torch_geometric.data.Data` instance.
Args:
G (networkx.Graph or networkx.DiGraph): A networkx graph.
"""
G = nx.convert_node_labels_to_integers(G)
G = G.to_directed() if not nx.is_directed(G) else G
edge_index = torch.tensor(list(G.edges)).t().contiguous()
data = {}
for i, (_, feat_dict) in enumerate(G.nodes(data=True)):
for key, value in feat_dict.items():
data[key] = [value] if i == 0 else data[key] + [value]
for i, (_, _, feat_dict) in enumerate(G.edges(data=True)):
for key, value in feat_dict.items():
data[key] = [value] if i == 0 else data[key] + [value]
for key, item in data.items():
try:
data[key] = torch.tensor(item)
except ValueError:
pass
data['edge_index'] = edge_index.view(2, -1)
data = torch_geometric.data.Data.from_dict(data)
data.num_nodes = G.number_of_nodes()
return data
示例7: _gen_hypercube
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import convert_node_labels_to_integers [as 别名]
def _gen_hypercube(self, n):
for _ in range(n):
num_v = np.random.randint(self.min_num_v, self.max_num_v)
g = nx.hypercube_graph(int(math.log(num_v, 2)))
g = nx.convert_node_labels_to_integers(g)
self.graphs.append(g)
self.labels.append(4)
示例8: _gen_grid
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import convert_node_labels_to_integers [as 别名]
def _gen_grid(self, n):
for _ in range(n):
num_v = np.random.randint(self.min_num_v, self.max_num_v)
assert num_v >= 4, 'We require a grid graph to contain at least two ' \
'rows and two columns, thus 4 nodes, got {:d} ' \
'nodes'.format(num_v)
n_rows = np.random.randint(2, num_v // 2)
n_cols = num_v // n_rows
g = nx.grid_graph([n_rows, n_cols])
g = nx.convert_node_labels_to_integers(g)
self.graphs.append(g)
self.labels.append(5)
示例9: compile
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import convert_node_labels_to_integers [as 别名]
def compile(self, seq, registers):
"""Class-specific circuit compilation method.
If additional compilation logic is required, child classes can redefine this method.
Args:
seq (Sequence[Command]): quantum circuit to modify
registers (Sequence[RegRefs]): quantum registers
Returns:
List[Command]: modified circuit
Raises:
CircuitError: the given circuit cannot be validated to belong to this circuit class
"""
# registers is not used here, but may be used if the method is overwritten pylint: disable=unused-argument
if self.graph is not None:
# check topology
DAG = pu.list_to_DAG(seq)
# relabel the DAG nodes to integers, with attributes
# specifying the operation name. This allows them to be
# compared, rather than using Command objects.
mapping = {i: n.op.__class__.__name__ for i, n in enumerate(DAG.nodes())}
circuit = nx.convert_node_labels_to_integers(DAG)
nx.set_node_attributes(circuit, mapping, name="name")
def node_match(n1, n2):
"""Returns True if both nodes have the same name"""
return n1["name"] == n2["name"]
# check if topology matches
if not nx.is_isomorphic(circuit, self.graph, node_match):
# TODO: try and compile the program to match the topology
# TODO: add support for parameter range matching/compilation
raise pu.CircuitError(
"Program cannot be used with the CircuitSpec '{}' "
"due to incompatible topology.".format(self.short_name)
)
return seq
示例10: citeseer_ego
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import convert_node_labels_to_integers [as 别名]
def citeseer_ego():
_, _, G = data.Graph_load(dataset='citeseer')
G = max(nx.connected_component_subgraphs(G), key=len)
G = nx.convert_node_labels_to_integers(G)
graphs = []
for i in range(G.number_of_nodes()):
G_ego = nx.ego_graph(G, i, radius=3)
if G_ego.number_of_nodes() >= 50 and (G_ego.number_of_nodes() <= 400):
graphs.append(G_ego)
return graphs
示例11: load_graph_list
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import convert_node_labels_to_integers [as 别名]
def load_graph_list(fname,is_real=True):
with open(fname, "rb") as f:
graph_list = pickle.load(f)
for i in range(len(graph_list)):
edges_with_selfloops = graph_list[i].selfloop_edges()
if len(edges_with_selfloops)>0:
graph_list[i].remove_edges_from(edges_with_selfloops)
if is_real:
graph_list[i] = max(nx.connected_component_subgraphs(graph_list[i]), key=len)
graph_list[i] = nx.convert_node_labels_to_integers(graph_list[i])
else:
graph_list[i] = pick_connected_component_new(graph_list[i])
return graph_list
示例12: grid
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import convert_node_labels_to_integers [as 别名]
def grid(start, dim=2, role_start=0):
""" Builds a 2by2 grid
"""
grid_G = nx.grid_graph([dim, dim])
grid_G = nx.convert_node_labels_to_integers(grid_G, first_label=start)
roles = [role_start for i in grid_G.nodes()]
return grid_G, roles
示例13: plain_graph_generation
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import convert_node_labels_to_integers [as 别名]
def plain_graph_generation(qcs, acs, paths, rels):
global cpnet, concept2id, relation2id, id2relation, id2concept, cpnet_simple
# print("qcs", qcs)
# print("acs", acs)
# print("paths", paths)
# print("rels", rels)
graph = nx.Graph()
for index, p in enumerate(paths):
for c_index in range(len(p)-1):
h = p[c_index]
t = p[c_index+1]
# TODO: the weight can computed by concept embeddings and relation embeddings of TransE
graph.add_edge(h,t, weight=1.0)
for qc1, qc2 in list(itertools.combinations(qcs, 2)):
if cpnet_simple.has_edge(qc1, qc2):
graph.add_edge(qc1, qc2, weight=1.0)
for ac1, ac2 in list(itertools.combinations(acs, 2)):
if cpnet_simple.has_edge(ac1, ac2):
graph.add_edge(ac1, ac2, weight=1.0)
if len(qcs) == 0:
qcs.append(-1)
if len(acs) == 0:
acs.append(-1)
if len(paths) == 0:
for qc in qcs:
for ac in acs:
graph.add_edge(qc,ac, rel=-1, weight=0.1)
g = nx.convert_node_labels_to_integers(graph, label_attribute='cid') # re-index
g_str = json.dumps(nx.node_link_data(g))
return g_str
# relational graph generation
示例14: reddit_to_networkx
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import convert_node_labels_to_integers [as 别名]
def reddit_to_networkx(dirpath):
print("Loading graph data")
coo_adj = scipy.sparse.load_npz(os.path.join(dirpath, edge_file_name))
G = nx.from_scipy_sparse_matrix(coo_adj)
print("Loading node feature and label")
# node feature, edge label
reddit_data = numpy.load(os.path.join(dirpath, feat_file_name))
G.graph['x'] = reddit_data['feature'].astype(numpy.float32)
G.graph['y'] = reddit_data['label'].astype(numpy.int32)
G.graph['label_num'] = 41
# G = nx.convert_node_labels_to_integers(G)
print("Finish loading graph: {}".format(dirpath))
return G
示例15: citation_to_networkx
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import convert_node_labels_to_integers [as 别名]
def citation_to_networkx(dirpath, name):
G = nx.Graph()
# node feature, node label
with open(os.path.join(dirpath, "{}.content".format(name))) as f:
lines = f.readlines()
compressor = {}
acc = 0
for line in tqdm(lines):
lis = line.split()
key, val = lis[0], lis[-1]
if val in compressor:
val = compressor[val]
else:
compressor[val] = acc
val = acc
acc += 1
G.add_node(key,
x=numpy.array(lis[1:-1], dtype=numpy.float32),
y=val)
G.graph['label_num'] = acc
# edge
with open(os.path.join(dirpath, "{}.cites".format(name))) as f:
lines = f.readlines()
for line in tqdm(lines):
u, v = line.split()
if u not in G.nodes.keys():
print("Warning: {} does not appear in {}{}.content".format(
u, dirpath, name))
elif v not in G.nodes.keys():
print("Warning: {} does not appear in {}{}.content".format(
v, dirpath, name))
else:
G.add_edge(u, v)
G = nx.convert_node_labels_to_integers(G)
print("Finished loading graph: {}".format(dirpath))
print("number of nodes: {}, number of edges: {}".format(
G.number_of_nodes(), G.number_of_edges()
))
return G