本文整理匯總了Python中networkx.get_node_attributes方法的典型用法代碼示例。如果您正苦於以下問題:Python networkx.get_node_attributes方法的具體用法?Python networkx.get_node_attributes怎麽用?Python networkx.get_node_attributes使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類networkx
的用法示例。
在下文中一共展示了networkx.get_node_attributes方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: add_normal_sar_edges
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import get_node_attributes [as 別名]
def add_normal_sar_edges(self, ratio=1.0):
"""Add extra edges from normal accounts to SAR accounts to adjust transaction graph features
:param ratio: Ratio of the number of edges to be added from normal accounts to SAR accounts
compared to the number of total SAR accounts
"""
sar_flags = nx.get_node_attributes(self.g, IS_SAR_KEY)
orig_candidates = [n for n in self.hubs if not sar_flags.get(n, False)] # Normal
bene_candidates = [n for n, sar in sar_flags.items() if sar] # SAR
num = int(len(bene_candidates) * ratio)
if num <= 0:
return
num_origs = len(orig_candidates)
print("Number of orig/bene candidates: %d/%d" % (num_origs, len(bene_candidates)))
orig_list = random.choices(orig_candidates, k=num)
bene_list = random.choices(bene_candidates, k=num)
for i in range(num):
_orig = orig_list[i]
_bene = bene_list[i]
self.add_transaction(_orig, _bene)
logger.info("Added %d edges from normal accounts to sar accounts" % num)
示例2: _add_related_alert_edge
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import get_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: graph_colors
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import get_node_attributes [as 別名]
def graph_colors(nx_graph, vmin=0, vmax=7):
cnorm = mcol.Normalize(vmin=vmin, vmax=vmax)
cpick = cm.ScalarMappable(norm=cnorm, cmap='viridis')
cpick.set_array([])
val_map = {}
for k, v in nx.get_node_attributes(nx_graph, 'attr_name').items():
val_map[k] = cpick.to_rgba(v)
colors = []
for node in nx_graph.nodes():
colors.append(val_map[node])
return colors
##############################################################################
# Generate data
# -------------
#%% circular dataset
# We build a dataset of noisy circular graphs.
# Noise is added on the structures by random connections and on the features by gaussian noise.
示例4: rectify_labels
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import get_node_attributes [as 別名]
def rectify_labels(G, labels):
# Ensure labels are rebased and
# are different between different connected compoments
graph = G.copy()
node_to_annot_idx = nx.get_node_attributes(graph, 'annot_idx')
cut_edges = []
for u, v in graph.edges():
idx1 = node_to_annot_idx[u]
idx2 = node_to_annot_idx[v]
if labels[idx1] != labels[idx2]:
cut_edges.append((u, v))
graph.remove_edges_from(cut_edges)
ccs_nodes = list(nx.connected_components(graph))
ccs_idxs = ut.unflat_take(node_to_annot_idx, ccs_nodes)
# Make consistent sorting
ccs_idxs = [sorted(idxs) for idxs in ccs_idxs]
ccs_idxs = ut.sortedby(ccs_idxs, ut.take_column(ccs_idxs, 0))
labels = ut.ungroup([[c] * len(x) for c, x in enumerate(ccs_idxs)], ccs_idxs)
labels = np.array(labels)
return labels
示例5: __init__
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import get_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: execute
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import get_node_attributes [as 別名]
def execute(self, node, graph, status, status_map, *args, **kwargs):
val = nx.get_node_attributes(graph, self.attribute)[node]
p = np.random.random_sample()
if self.operator == "IN":
condition = self.__available_operators[self.operator][0](val, self.attribute_range[0]) and \
self.__available_operators[self.operator][1](val, self.attribute_range[1])
else:
condition = self.__available_operators[self.operator](val, self.attribute_range)
test = condition and p <= self.probability
if test:
return self.compose(node, graph, status, status_map, kwargs)
return False
示例7: load_attributes
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import get_node_attributes [as 別名]
def load_attributes(self, **kwargs):
# Overwrite the global settings, if required
if 'attribute_file' in kwargs:
self.path_to_attribute_file = kwargs['attribute_file']
else:
kwargs['attribute_file'] = self.path_to_attribute_file
# Make sure that the settings are still valid
self.validate_config()
node_label_order = list(nx.get_node_attributes(self.graph, self.node_key_attribute).values())
if self.verbose and isinstance(self.path_to_attribute_file, str):
print('Loading attributes from %s' % self.path_to_attribute_file)
[self.attributes, _, self.node2attribute] = load_attributes(node_label_order=node_label_order,
verbose=self.verbose, **kwargs)
示例8: read_graphml_with_position
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import get_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
示例9: read_graphml_with_position
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import get_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
示例10: get
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import get_node_attributes [as 別名]
def get(self):
nodes = list()
nodes2 = list()
links = list()
# add all DCs
node_attr = networkx.get_node_attributes(net.DCNetwork_graph, 'type')
for node_name in net.DCNetwork_graph.nodes():
nodes2.append(node_name)
type = node_attr[node_name]
node_dict = {"name": node_name, "group": type}
nodes.append(node_dict)
# add links between other DCs
for node1_name in net.DCNetwork_graph.nodes():
node1_index = nodes2.index(node1_name)
for node2_name in net.DCNetwork_graph.neighbors(node1_name):
node2_index = nodes2.index(node2_name)
edge_dict = {"source": node1_index,
"target": node2_index, "value": 10}
links.append(edge_dict)
json = {"nodes": nodes, "links": links}
return json, 200, CORS_HEADER
示例11: get_node_attributes
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import get_node_attributes [as 別名]
def get_node_attributes(G, name):
"""Get node attributes from graph
Parameters
----------
G : NetworkX Graph
name : string
Attribute name
Returns
-------
Dictionary of attributes keyed by node.
Examples
--------
>>> G=nx.Graph()
>>> G.add_nodes_from([1,2,3],color='red')
>>> color=nx.get_node_attributes(G,'color')
>>> color[1]
'red'
"""
return dict( (n,d[name]) for n,d in G.node.items() if name in d)
示例12: __init__
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import get_node_attributes [as 別名]
def __init__(self, data=None, **kwargs):
if isinstance(data, dict):
data = adjacency2graph(data, **kwargs)
super(QueueNetworkDiGraph, self).__init__(data, **kwargs)
edges = sorted(self.edges())
self.edge_index = {e: k for k, e in enumerate(edges)}
pos = nx.get_node_attributes(self, name='pos')
if len(pos) == self.number_of_nodes():
self.pos = np.array([pos[v] for v in self.nodes()])
else:
self.pos = None
self.edge_color = None
self.vertex_color = None
self.vertex_fill_color = None
self._nE = self.number_of_edges()
示例13: get_node_attributes
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import get_node_attributes [as 別名]
def get_node_attributes(G, name):
"""Get node attributes from graph
Parameters
----------
G : NetworkX Graph
name : string
Attribute name
Returns
-------
Dictionary of attributes keyed by node.
Examples
--------
>>> G = nx.Graph()
>>> G.add_nodes_from([1, 2, 3], color='red')
>>> color = nx.get_node_attributes(G, 'color')
>>> color[1]
'red'
"""
return {n: d[name] for n, d in G.nodes.items() if name in d}
示例14: __init__
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import get_node_attributes [as 別名]
def __init__(self, _conf_json):
super(ResultGraphLoader, self).__init__(_conf_json)
# Create a transaction graph from output files
output_dir = os.path.join(self.output_conf["directory"], self.sim_name)
acct_file = self.output_conf["accounts"]
tx_file = self.output_conf["transactions"]
alert_acct_file = self.output_conf["alert_members"]
alert_tx_file = self.output_conf["alert_transactions"]
acct_path = os.path.join(output_dir, acct_file)
tx_path = os.path.join(output_dir, tx_file)
self.g = load_result_csv(acct_path, tx_path, self.schema)
self.num_normal_accts = len([n for n, flag in nx.get_node_attributes(self.g, ACCT_SAR).items() if not flag])
self.num_sar_accts = len([n for n, flag in nx.get_node_attributes(self.g, ACCT_SAR).items() if flag])
示例15: nx_to_mol
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import get_node_attributes [as 別名]
def nx_to_mol(G):
mol = Chem.RWMol()
atomic_nums = nx.get_node_attributes(G, 'atomic_num')
chiral_tags = nx.get_node_attributes(G, 'chiral_tag')
formal_charges = nx.get_node_attributes(G, 'formal_charge')
node_is_aromatics = nx.get_node_attributes(G, 'is_aromatic')
node_hybridizations = nx.get_node_attributes(G, 'hybridization')
num_explicit_hss = nx.get_node_attributes(G, 'num_explicit_hs')
node_to_idx = {}
for node in G.nodes():
a=Chem.Atom(atomic_nums[node])
a.SetChiralTag(chiral_tags[node])
a.SetFormalCharge(formal_charges[node])
a.SetIsAromatic(node_is_aromatics[node])
a.SetHybridization(node_hybridizations[node])
a.SetNumExplicitHs(num_explicit_hss[node])
idx = mol.AddAtom(a)
node_to_idx[node] = idx
bond_types = nx.get_edge_attributes(G, 'bond_type')
for edge in G.edges():
first, second = edge
ifirst = node_to_idx[first]
isecond = node_to_idx[second]
bond_type = bond_types[first, second]
mol.AddBond(ifirst, isecond, bond_type)
Chem.SanitizeMol(mol)
return mol