當前位置: 首頁>>代碼示例>>Python>>正文


Python networkx.get_node_attributes方法代碼示例

本文整理匯總了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) 
開發者ID:IBM,項目名稱:AMLSim,代碼行數:23,代碼來源:transaction_graph_generator.py

示例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") 
開發者ID:microsoft,項目名稱:msticpy,代碼行數:18,代碼來源:security_alert_graph.py

示例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. 
開發者ID:PythonOT,項目名稱:POT,代碼行數:21,代碼來源:plot_barycenter_fgw.py

示例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 
開發者ID:Erotemic,項目名稱:ibeis,代碼行數:22,代碼來源:script_bp_cut.py

示例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) 
開發者ID:Erotemic,項目名稱:ibeis,代碼行數:19,代碼來源:viz_graph.py

示例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 
開發者ID:GiulioRossetti,項目名稱:ndlib,代碼行數:19,代碼來源:NodeNumericalAttribute.py

示例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) 
開發者ID:baryshnikova-lab,項目名稱:safepy,代碼行數:20,代碼來源:safe.py

示例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 
開發者ID:sparkandshine,項目名稱:complex_network,代碼行數:21,代碼來源:buildupgraph.py

示例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 
開發者ID:sparkandshine,項目名稱:complex_network,代碼行數:21,代碼來源:graphviz.py

示例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 
開發者ID:sonata-nfv,項目名稱:son-emu,代碼行數:25,代碼來源:network.py

示例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) 
開發者ID:SpaceGroupUCL,項目名稱:qgisSpaceSyntaxToolkit,代碼行數:25,代碼來源:function.py

示例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() 
開發者ID:djordon,項目名稱:queueing-tool,代碼行數:21,代碼來源:graph_wrapper.py

示例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} 
開發者ID:holzschu,項目名稱:Carnets,代碼行數:25,代碼來源:function.py

示例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]) 
開發者ID:IBM,項目名稱:AMLSim,代碼行數:17,代碼來源:network_analytics.py

示例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 
開發者ID:bowenliu16,項目名稱:rl_graph_generation,代碼行數:31,代碼來源:dataset_utils.py


注:本文中的networkx.get_node_attributes方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。