本文整理匯總了Python中networkx.set_edge_attributes方法的典型用法代碼示例。如果您正苦於以下問題:Python networkx.set_edge_attributes方法的具體用法?Python networkx.set_edge_attributes怎麽用?Python networkx.set_edge_attributes使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類networkx
的用法示例。
在下文中一共展示了networkx.set_edge_attributes方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_networkx2igraph
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_edge_attributes [as 別名]
def test_networkx2igraph(self):
import networkx as nx
ng = nx.complete_graph(3)
[x, y] = [int(x) for x in nx.__version__.split('.')]
if x == 1:
nx.set_node_attributes(ng, 'vattrib', 0)
nx.set_edge_attributes(ng, 'eattrib', 1)
else:
nx.set_node_attributes(ng, 0, 'vattrib')
nx.set_edge_attributes(ng, 1, 'eattrib')
(e, n) = graphistry.bind(source='src', destination='dst').networkx2pandas(ng)
edges = pd.DataFrame({
'dst': {0: 1, 1: 2, 2: 2},
'src': {0: 0, 1: 0, 2: 1},
'eattrib': {0: 1, 1: 1, 2: 1}
})
nodes = pd.DataFrame({
'__nodeid__': {0: 0, 1: 1, 2: 2},
'vattrib': {0: 0, 1: 0, 2: 0}
})
assertFrameEqual(e, edges)
assertFrameEqual(n, nodes)
示例2: ensure_names_are_connected
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_edge_attributes [as 別名]
def ensure_names_are_connected(graph, aids_list):
aug_graph = graph.copy().to_undirected()
orig_edges = aug_graph.edges()
unflat_edges = [list(itertools.product(aids, aids)) for aids in aids_list]
aid_pairs = [tup for tup in ut.iflatten(unflat_edges) if tup[0] != tup[1]]
new_edges = ut.setdiff_ordered(aid_pairs, aug_graph.edges())
preweighted_edges = nx.get_edge_attributes(aug_graph, 'weight')
if preweighted_edges:
orig_edges = ut.setdiff(orig_edges, list(preweighted_edges.keys()))
aug_graph.add_edges_from(new_edges)
# Ensure the largest possible set of original edges is in the MST
nx.set_edge_attributes(aug_graph, name='weight', values=dict([(edge, 1.0) for edge in new_edges]))
nx.set_edge_attributes(aug_graph, name='weight', values=dict([(edge, 0.1) for edge in orig_edges]))
for cc_sub_graph in nx.connected_component_subgraphs(aug_graph):
mst_sub_graph = nx.minimum_spanning_tree(cc_sub_graph)
for edge in mst_sub_graph.edges():
redge = edge[::-1]
if not (graph.has_edge(*edge) or graph.has_edge(*redge)):
graph.add_edge(*redge, attr_dict={})
示例3: test_edge_attribute
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_edge_attributes [as 別名]
def test_edge_attribute(self):
g = nx.karate_club_graph()
attr = {(u, v): {"even": int((u+v) % 2)} for (u, v) in g.edges()}
nx.set_edge_attributes(g, attr)
model = gc.CompositeModel(g)
model.add_status("Susceptible")
model.add_status("Infected")
c = cpm.EdgeCategoricalAttribute("even", "0", probability=0.6)
model.add_rule("Susceptible", "Infected", c)
config = mc.Configuration()
config.add_model_parameter('fraction_infected', 0.1)
model.set_initial_status(config)
iterations = model.iteration_bunch(10)
self.assertEqual(len(iterations), 10)
示例4: calculate_edge_lengths
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_edge_attributes [as 別名]
def calculate_edge_lengths(G, verbose=True):
# Calculate the lengths of the edges
if verbose:
print('Calculating edge lengths...')
x = np.matrix(G.nodes.data('x'))[:, 1]
y = np.matrix(G.nodes.data('y'))[:, 1]
node_coordinates = np.concatenate([x, y], axis=1)
node_distances = squareform(pdist(node_coordinates, 'euclidean'))
adjacency_matrix = np.array(nx.adjacency_matrix(G).todense())
adjacency_matrix = adjacency_matrix.astype('float')
adjacency_matrix[adjacency_matrix == 0] = np.nan
edge_lengths = np.multiply(node_distances, adjacency_matrix)
edge_attr_dict = {index: v for index, v in np.ndenumerate(edge_lengths) if ~np.isnan(v)}
nx.set_edge_attributes(G, edge_attr_dict, 'length')
return G
示例5: load_graphml
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_edge_attributes [as 別名]
def load_graphml(self,filename):
warnings.warn("The load_graphml function is deprecated and "
"will be removed in version 2.0.0. "
"Use NX.READ_GRAPHML function instead.",
FutureWarning,
stacklevel=8
)
self.G = nx.read_graphml(filename)
attEdges = {}
for k in self.G.edges():
attEdges[k] = {"BW": 1, "PR": 1}
nx.set_edge_attributes(self.G, values=attEdges)
attNodes = {}
for k in self.G.nodes():
attNodes[k] = {"IPT": 1}
nx.set_node_attributes(self.G, values=attNodes)
for k in self.G.nodes():
self.nodeAttributes[k] = self.G.node[k] #it has "id" att. TODO IMPROVE
示例6: test_typical_cases
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_edge_attributes [as 別名]
def test_typical_cases(self):
G = nx.complete_graph(10)
S = dnx.maximum_cut(G, ExactSolver())
self.assertTrue(len(S) == 5) # half of the nodes
with self.assertRaises(dnx.DWaveNetworkXException):
S = dnx.weighted_maximum_cut(G, ExactSolver())
nx.set_edge_attributes(G, 1, 'weight')
S = dnx.weighted_maximum_cut(G, ExactSolver())
self.assertTrue(len(S) == 5) # half of the nodes
G = nx.Graph()
G.add_edges_from([(0, 1), (0, 2), (1, 2), (1, 3), (3, 4), (2, 4)])
S = dnx.maximum_cut(G, ExactSolver())
self.assertTrue(len(S) in (2, 3))
# this needs another one for weight
示例7: test_weighted_input
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_edge_attributes [as 別名]
def test_weighted_input():
G1 = nx.karate_club_graph()
G2 = nx.karate_club_graph()
rand = np.random.RandomState(seed=42)
edge_weights = {e: rand.randint(0, 1000) for e in G2.edges}
nx.set_edge_attributes(G2, edge_weights, "weight")
assert nx.is_isomorphic(G1, G2)
for label, obj in distance.__dict__.items():
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
if isinstance(obj, type) and BaseDistance in obj.__bases__:
dist = obj().dist(G1, G2)
warning_triggered = False
for warning in w:
if "weighted" in str(warning.message):
warning_triggered = True
if not warning_triggered:
assert not np.isclose(dist, 0.0)
else:
assert np.isclose(dist, 0.0)
示例8: test_set_edge_attributes
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_edge_attributes [as 別名]
def test_set_edge_attributes():
graphs = [nx.Graph(), nx.DiGraph()]
for G in graphs:
G = nx.path_graph(3, create_using=G)
# Test single value
attr = 'hello'
vals = 3
nx.set_edge_attributes(G, attr, vals)
assert_equal(G[0][1][attr], vals)
assert_equal(G[1][2][attr], vals)
# Test multiple values
attr = 'hi'
edges = [(0,1), (1,2)]
vals = dict(zip(edges, range(len(edges))))
nx.set_edge_attributes(G, attr, vals)
assert_equal(G[0][1][attr], 0)
assert_equal(G[1][2][attr], 1)
示例9: test_set_edge_attributes_multi
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_edge_attributes [as 別名]
def test_set_edge_attributes_multi():
graphs = [nx.MultiGraph(), nx.MultiDiGraph()]
for G in graphs:
G = nx.path_graph(3, create_using=G)
# Test single value
attr = 'hello'
vals = 3
nx.set_edge_attributes(G, attr, vals)
assert_equal(G[0][1][0][attr], vals)
assert_equal(G[1][2][0][attr], vals)
# Test multiple values
attr = 'hi'
edges = [(0,1,0), (1,2,0)]
vals = dict(zip(edges, range(len(edges))))
nx.set_edge_attributes(G, attr, vals)
assert_equal(G[0][1][0][attr], 0)
assert_equal(G[1][2][0][attr], 1)
示例10: test_get_edge_attributes
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_edge_attributes [as 別名]
def test_get_edge_attributes():
graphs = [nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()]
for G in graphs:
G = nx.path_graph(3, create_using=G)
attr = 'hello'
vals = 100
nx.set_edge_attributes(G, attr, vals)
attrs = nx.get_edge_attributes(G, attr)
assert_equal(len(attrs), 2)
if G.is_multigraph():
keys = [(0,1,0), (1,2,0)]
else:
keys = [(0,1), (1,2)]
for key in keys:
assert_equal(attrs[key], 100)
示例11: test_get_edge_attributes
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_edge_attributes [as 別名]
def test_get_edge_attributes():
graphs = [nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()]
for G in graphs:
G = nx.path_graph(3, create_using=G)
attr = 'hello'
vals = 100
nx.set_edge_attributes(G, vals, attr)
attrs = nx.get_edge_attributes(G, attr)
assert_equal(len(attrs), 2)
if G.is_multigraph():
keys = [(0, 1, 0), (1, 2, 0)]
for u, v, k in keys:
try:
assert_equal(attrs[(u, v, k)], 100)
except KeyError:
assert_equal(attrs[(v, u, k)], 100)
else:
keys = [(0, 1), (1, 2)]
for u, v in keys:
try:
assert_equal(attrs[(u, v)], 100)
except KeyError:
assert_equal(attrs[(v, u)], 100)
示例12: create_star_graph
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_edge_attributes [as 別名]
def create_star_graph(n_nodes=10, ring=True):
"""
Create a star graph with the points connected by
Args:
n_nodes (int): number of nodes in graph (max 26)
ring (Boolean): add ring around the border with low (distance=2) weights
Returns:
networkx MultiGraoh in the shape of a star
"""
graph = nx.MultiGraph()
node_names = list(string.ascii_lowercase)[:n_nodes]
graph.add_star(node_names)
nx.set_edge_attributes(graph, 10, 'distance')
nx.set_edge_attributes(graph, 1, 'required')
nx.set_edge_attributes(graph, 'solid', 'style')
if ring:
for e in list(zip(node_names[1:-1] + [node_names[1]], node_names[2:] + [node_names[-1]])):
graph.add_edge(e[0], e[1], distance=2, required=0, style='dashed')
return graph
示例13: PyGGraph_to_nx
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_edge_attributes [as 別名]
def PyGGraph_to_nx(data):
edges = list(zip(data.edge_index[0, :].tolist(), data.edge_index[1, :].tolist()))
g = nx.from_edgelist(edges)
g.add_nodes_from(range(len(data.x))) # in case some nodes are isolated
# transform r back to rating label
edge_types = {(u, v): data.edge_type[i].item() for i, (u, v) in enumerate(edges)}
nx.set_edge_attributes(g, name='type', values=edge_types)
node_types = dict(zip(range(data.num_nodes), torch.argmax(data.x, 1).tolist()))
nx.set_node_attributes(g, name='type', values=node_types)
g.graph['rating'] = data.y.item()
return g
示例14: add_edge_lengths
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_edge_attributes [as 別名]
def add_edge_lengths(G):
"""
https://github.com/gboeing/osmnx/blob/master/osmnx/core.py
Add length (meters) attribute to each edge by great circle distance between
nodes u and v.
Parameters
----------
G : networkx multidigraph
Returns
-------
G : networkx multidigraph
"""
start_time = time.time()
# first load all the edges' origin and destination coordinates as a
# dataframe indexed by u, v, key
coords = np.array([[u, v, k, G.nodes[u]['y'], G.nodes[u]['x'], G.nodes[v]['y'], G.nodes[v]['x']] for u, v, k in G.edges(keys=True)])
df_coords = pd.DataFrame(coords, columns=['u', 'v', 'k', 'u_y', 'u_x', 'v_y', 'v_x'])
df_coords[['u', 'v', 'k']] = df_coords[['u', 'v', 'k']].astype(np.int64)
df_coords = df_coords.set_index(['u', 'v', 'k'])
# then calculate the great circle distance with the vectorized function
gc_distances = great_circle_vec(lat1=df_coords['u_y'],
lng1=df_coords['u_x'],
lat2=df_coords['v_y'],
lng2=df_coords['v_x'])
# fill nulls with zeros and round to the millimeter
gc_distances = gc_distances.fillna(value=0).round(3)
nx.set_edge_attributes(G, name='length', values=gc_distances.to_dict())
print('Added edge lengths to graph in {:,.2f} seconds'.format(time.time()-start_time))
return G
示例15: build_graph
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_edge_attributes [as 別名]
def build_graph(uvw_list):
_edges = [(u, v, {'weight': w}) for (u, v, w) in uvw_list]
G = nx.Graph()
G.add_edges_from(_edges)
node_to_label = {e: '%s,%s\n%s' % (e + (d,)) for e, d in nx.get_edge_attributes(G, 'weight').items()}
nx.set_edge_attributes(G, name='label', values=node_to_label)
return G