本文整理匯總了Python中networkx.set_node_attributes方法的典型用法代碼示例。如果您正苦於以下問題:Python networkx.set_node_attributes方法的具體用法?Python networkx.set_node_attributes怎麽用?Python networkx.set_node_attributes使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類networkx
的用法示例。
在下文中一共展示了networkx.set_node_attributes方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_networkx2igraph
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_node_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: _add_related_alert_edge
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_node_attributes [as 別名]
def _add_related_alert_edge(nx_graph, source, target):
"""Add related alert to an existing graph."""
count_attrs = nx.get_node_attributes(nx_graph, "count")
target_node = target["AlertType"] + "(R)"
if target_node in count_attrs:
current_count = count_attrs[target_node]
else:
current_count = 0
current_count += 1
description = "Related alert: {} Count:{}".format(
target["AlertType"], current_count
)
node_attrs = {target_node: {"count": current_count, "description": description}}
nx.set_node_attributes(nx_graph, node_attrs)
nx_graph.add_edge(source, target_node, weight=0.7, description="Related Alert")
示例3: initialize_visual_node_attrs
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_node_attributes [as 別名]
def initialize_visual_node_attrs(infr, graph=None):
infr.print('initialize_visual_node_attrs!!!')
infr.print('initialize_visual_node_attrs', 3)
# import networkx as nx
if graph is None:
graph = infr.graph
# nx.set_node_attributes(graph, name='framewidth', values=3.0)
# nx.set_node_attributes(graph, name='shape', values=ut.dzip(annot_nodes, ['rect']))
ut.nx_delete_node_attr(graph, 'size')
ut.nx_delete_node_attr(graph, 'width')
ut.nx_delete_node_attr(graph, 'height')
ut.nx_delete_node_attr(graph, 'radius')
infr._viz_init_nodes = True
infr._viz_image_config_dirty = False
示例4: update_node_image_attribute
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_node_attributes [as 別名]
def update_node_image_attribute(infr, use_image=False, graph=None):
if graph is None:
graph = infr.graph
if not hasattr(infr, '_viz_image_config_dirty'):
infr.initialize_visual_node_attrs()
aid_list = list(graph.nodes())
if infr.ibs is not None:
nx.set_node_attributes(graph, name='framewidth', values=3.0)
nx.set_node_attributes(graph, name='shape', values=ut.dzip(aid_list, ['rect']))
if infr.ibs is None:
raise ValueError('Cannot show images when ibs is None')
imgpath_list = infr.ibs.depc_annot.get('chipthumb', aid_list, 'img',
config=infr._viz_image_config,
read_extern=False)
nx.set_node_attributes(graph, name='image', values=ut.dzip(aid_list, imgpath_list))
if graph is infr.graph:
infr._viz_image_config_dirty = False
示例5: __init__
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_node_attributes [as 別名]
def __init__(self, infr, selected_aids=[],
use_image=False, temp_nids=None):
super(AnnotGraphInteraction, self).__init__()
self.infr = infr
self.selected_aids = selected_aids
self.node2_aid = nx.get_node_attributes(self.infr.graph, 'aid')
self.aid2_node = ut.invert_dict(self.node2_aid)
node2_label = {
#node: '%d:aid=%r' % (node, aid)
node: 'aid=%r' % (aid)
for node, aid in self.node2_aid.items()
}
#self.show_cuts = False
self.use_image = use_image
self.show_cuts = False
self.config = InferenceConfig()
nx.set_node_attributes(self.infr.graph, name='label', values=node2_label)
示例6: test_node_attribute
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_node_attributes [as 別名]
def test_node_attribute(self):
g = nx.karate_club_graph()
attr = {n: {"even": int(n % 2)} for n in g.nodes()}
nx.set_node_attributes(g, attr)
model = gc.CompositeModel(g)
model.add_status("Susceptible")
model.add_status("Infected")
c = cpm.NodeCategoricalAttribute("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)
示例7: gen_node_features
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_node_attributes [as 別名]
def gen_node_features(self, G):
# Generate community assignment
community_dict = {
n: self.com_choices[0] if G.degree(n) < 4 else self.com_choices[1]
for n in G.nodes()
}
# Generate random variable
s = np.random.normal(self.mu, self.sigma, G.number_of_nodes())
# Generate features
feat_dict = {
n: {"feat": np.asarray([community_dict[n], s[i]])}
for i, n in enumerate(G.nodes())
}
nx.set_node_attributes(G, feat_dict)
return community_dict
示例8: load_all_node_attr
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_node_attributes [as 別名]
def load_all_node_attr(self,data):
self.G = nx.Graph()
for edge in data["link"]:
self.G.add_edge(edge["s"], edge["d"], BW=edge[self.LINK_BW], PR=edge[self.LINK_PR])
dc = {str(x): {} for x in data["entity"][0].keys()}
for ent in data["entity"]:
for key in ent.keys():
dc[key][ent["id"]] = ent[key]
for x in data["entity"][0].keys():
nx.set_node_attributes(self.G, values=dc[x], name=str(x))
for node in data["entity"]:
self.nodeAttributes[node["id"]] = node
self.__idNode = len(self.G.nodes)
self.__init_uptimes()
示例9: load_graphml
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_node_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
示例10: test_filtering
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_node_attributes [as 別名]
def test_filtering(self):
"""Test whether filtering works the way it should."""
G = _get_test_network()
weights = [10,100]
for e, (u, v) in enumerate(G.edges()):
G[u][v]['foo'] = weights[e]
G[u][v]['bar'] = weights[(e+1)%2]
grp = {u: 'AB'[i%2] for i, u in enumerate(G.nodes()) }
new_G = get_filtered_network(G,edge_weight_key='foo')
visualize(new_G,is_test=True,config=_get_test_config())
nx.set_node_attributes(G, grp, 'wum')
new_G = get_filtered_network(G,edge_weight_key='bar',node_group_key='wum')
visualize(new_G,is_test=True,config=_get_test_config())
示例11: test_maximum_independent_set_weighted
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_node_attributes [as 別名]
def test_maximum_independent_set_weighted(self):
weight = 'weight'
G = nx.path_graph(6)
# favor odd nodes
nx.set_node_attributes(G, {node: node % 2 + 1 for node in G}, weight)
indep_set = dnx.maximum_weighted_independent_set(G, weight, dimod.ExactSolver())
self.assertEqual(set(indep_set), {1, 3, 5})
# favor even nodes
nx.set_node_attributes(G, {node: (node + 1) % 2 + 1 for node in G}, weight)
indep_set = dnx.maximum_weighted_independent_set(G, weight, dimod.ExactSolver())
self.assertEqual(set(indep_set), {0, 2, 4})
# make nodes 1 and 4 likely
nx.set_node_attributes(G, {0: 1, 1: 3, 2: 1, 3: 1, 4: 3, 5: 1}, weight)
indep_set = dnx.maximum_weighted_independent_set(G, weight, dimod.ExactSolver())
self.assertEqual(set(indep_set), {1, 4})
示例12: test_vertex_cover_weighted
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_node_attributes [as 別名]
def test_vertex_cover_weighted(self):
weight = 'weight'
G = nx.path_graph(6)
# favor even nodes
nx.set_node_attributes(G, {node: node % 2 + 1 for node in G}, weight)
cover = dnx.min_weighted_vertex_cover(G, weight, ExactSolver())
self.assertEqual(set(cover), {0, 2, 4})
# favor odd nodes
nx.set_node_attributes(G, {node: (node + 1) % 2 + 1 for node in G}, weight)
cover = dnx.min_weighted_vertex_cover(G, weight, ExactSolver())
self.assertEqual(set(cover), {1, 3, 5})
# make nodes 1 and 4 unlikely
nx.set_node_attributes(G, {0: 1, 1: 3, 2: 1, 3: 1, 4: 3, 5: 1}, weight)
cover = dnx.min_weighted_vertex_cover(G, weight, ExactSolver())
self.assertEqual(set(cover), {0, 2, 3, 5})
for __ in range(10):
G = nx.gnp_random_graph(5, .5)
nx.set_node_attributes(G, {node: random.random() for node in G}, weight)
cover = dnx.min_weighted_vertex_cover(G, weight, ExactSolver())
self.vertex_cover_check(G, cover)
示例13: read_graphml_with_position
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_node_attributes [as 別名]
def read_graphml_with_position(filename):
"""Read a graph in GraphML format with position
"""
G = nx.read_graphml(filename)
# rearrage node attributes x, y as position for networkx
pos = dict() # A dictionary with nodes as keys and positions as values. Positions should be sequences of length 2.
node_and_x = nx.get_node_attributes(G, 'x')
node_and_y = nx.get_node_attributes(G, 'y')
for node in node_and_x:
x = node_and_x[node]
y = node_and_y[node]
pos[node] = (x, y)
# add node attribute `pos` to G
nx.set_node_attributes(G, 'pos', pos)
return G
示例14: read_graphml_with_position
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_node_attributes [as 別名]
def read_graphml_with_position(cls, filename):
"""Read a graph in GraphML format with position
"""
G = nx.read_graphml(filename)
# rearrage node attributes x, y as position for networkx
pos = dict() # A dictionary with nodes as keys and positions as values. Positions should be sequences of length 2.
node_and_x = nx.get_node_attributes(G, 'x')
node_and_y = nx.get_node_attributes(G, 'y')
for node in node_and_x:
x = node_and_x[node]
y = node_and_y[node]
pos[node] = (x, y)
# add node attribute `pos` to G
nx.set_node_attributes(G, 'pos', pos)
return G
示例15: attr
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import set_node_attributes [as 別名]
def attr(self, node_name, attributes):
"""Set attributes on an existing graph node.
:param str node_name: Name of the node
:param dict attributes: Dictionary of attributes to set
:Example:
>>> kb = KB()
>>> kb.store('eats(tom, rice)')
0
>>> kb.attr('tom', {'is_person': True})
>>> kb.node('tom')
{'is_person': True}"""
nx.set_node_attributes(self.G, {node_name: attributes})