Python networkx.get_node_attributes() Examples

The following are 30 code examples of networkx.get_node_attributes(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module networkx , or try the search function .
Example #1
Source File: buildupgraph.py    From complex_network with GNU General Public License v2.0 7 votes vote down vote up
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 
Example #2
Source File: graphviz.py    From complex_network with GNU General Public License v2.0 7 votes vote down vote up
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 
Example #3
Source File: transaction_graph_generator.py    From AMLSim with Apache License 2.0 6 votes vote down vote up
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) 
Example #4
Source File: security_alert_graph.py    From msticpy with MIT License 6 votes vote down vote up
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") 
Example #5
Source File: plot_barycenter_fgw.py    From POT with MIT License 6 votes vote down vote up
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. 
Example #6
Source File: function.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
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} 
Example #7
Source File: script_bp_cut.py    From ibeis with Apache License 2.0 6 votes vote down vote up
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 
Example #8
Source File: viz_graph.py    From ibeis with Apache License 2.0 6 votes vote down vote up
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) 
Example #9
Source File: NodeNumericalAttribute.py    From ndlib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 
Example #10
Source File: function.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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} 
Example #11
Source File: graph_wrapper.py    From queueing-tool with MIT License 6 votes vote down vote up
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() 
Example #12
Source File: safe.py    From safepy with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #13
Source File: function.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #14
Source File: network.py    From son-emu with Apache License 2.0 6 votes vote down vote up
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 
Example #15
Source File: test_function.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_get_node_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_node_attributes(G, vals, attr)
        attrs = nx.get_node_attributes(G, attr)
        assert_equal(attrs[0], vals)
        assert_equal(attrs[1], vals)
        assert_equal(attrs[2], vals) 
Example #16
Source File: circuit.py    From GridCal with GNU General Public License v3.0 5 votes vote down vote up
def plot(self):
        """
        Plot the circuit layout
        :return:
        """
        # from networkx.drawing.nx_pylab import draw_networkx
        # fig = plt.Figure(figsize=(16, 12))
        # ax = fig.add_subplot(111)
        pos = nx.get_node_attributes(self.graph, 'pos')
        nx.draw(self.graph, pos,  with_labels=True, figsize=(16, 12))
        plt.show() 
Example #17
Source File: nltk2graph_test.py    From ccg2lambda with Apache License 2.0 5 votes vote down vote up
def assert_graphs_are_equal(self, expected_graph, output_graph):
        expected_graph = nx.convert_node_labels_to_integers(expected_graph)
        output_graph = nx.convert_node_labels_to_integers(output_graph)
        self.assertTrue(
            are_graphs_equal(expected_graph, output_graph),
            msg='\nexpected: {0}\n          {1}\nvs.\noutput:   {2}\n          {3}'.format(
                expected_graph.adj, nx.get_node_attributes(expected_graph, 'label'),
                output_graph.adj, nx.get_node_attributes(output_graph, 'label')))
        return 
Example #18
Source File: nltk2graph_test.py    From ccg2lambda with Apache License 2.0 5 votes vote down vote up
def assert_graphs_are_equal(self, expected_graph, output_graph):
        self.assertTrue(
            are_graphs_equal(expected_graph, output_graph),
            msg='\nexpected: {0}\n          {1}\nvs.\noutput:   {2}\n          {3}'.format(
                expected_graph.adj, nx.get_node_attributes(expected_graph, 'label'),
                output_graph.adj, nx.get_node_attributes(output_graph, 'label')))
        return 
Example #19
Source File: nltk2graph_test.py    From ccg2lambda with Apache License 2.0 5 votes vote down vote up
def are_graphs_equal(g1, g2):
    g1_n2a = nx.get_node_attributes(g1, 'label')
    g1_label_adj = sorted([(g1_n2a[src], frozenset(g1_n2a[trg] for trg in g1.succ[src])) for src in g1.nodes()])
    g2_n2a = nx.get_node_attributes(g2, 'label')
    g2_label_adj = sorted([(g2_n2a[src], frozenset(g2_n2a[trg] for trg in g2.succ[src])) for src in g2.nodes()])

    return g1_label_adj == g2_label_adj 
Example #20
Source File: my_surgery.py    From GraphRicciCurvature with Apache License 2.0 5 votes vote down vote up
def ARI(G, cc, clustering_label="club"):
    """
    Computer the Adjust Rand Index (clustering accuray) of clustering "cc" with clustering_label as ground truth.
    :param G: A networkx graph
    :param cc: A clustering result as list of connected components list
    :param clustering_label: Node label for clustering groundtruth
    """

    if importlib.util.find_spec("sklearn") is not None:
        from sklearn import preprocessing, metrics
    else:
        print("scikit-learn not installed...")
        return -1

    complexlist = nx.get_node_attributes(G, clustering_label)

    le = preprocessing.LabelEncoder()
    y_true = le.fit_transform(list(complexlist.values()))

    predict_dict = {}
    for idx, comp in enumerate(cc):
        for c in list(comp):
            predict_dict[c] = idx
    y_pred = []
    for v in complexlist.keys():
        y_pred.append(predict_dict[v])
    y_pred = np.array(y_pred)

    return metrics.adjusted_rand_score(y_true, y_pred) 
Example #21
Source File: graph_network.py    From network_traffic_modeler_py3 with Apache License 2.0 5 votes vote down vote up
def _draw_node_labels(G):
  # Given networkx graph G, draw node labels
  nx.draw_networkx_labels(G, pos=nx.get_node_attributes(G, 'pos'),
                          labels={data['name']: data['name']
                                  for data in G.nodes.values()}) 
Example #22
Source File: test_clique_merge_operation.py    From kgx with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_clique_merge():
    """
    Test for clique merge (lenient)
    """
    t = PandasTransformer()
    os.makedirs(target_dir, exist_ok=True)
    t.parse(os.path.join(resource_dir, 'cm_nodes.csv'))
    t.parse(os.path.join(resource_dir, 'cm_edges.csv'))
    t.report()
    cm = CliqueMerge(prefix_prioritization_map)
    cm.build_cliques(t.graph)
    cm.elect_leader()
    updated_graph = cm.consolidate_edges()
    leaders = nx.get_node_attributes(updated_graph, 'clique_leader')
    leader_list = list(leaders.keys())
    leader_list.sort()
    assert len(leader_list) == 2
    n1 = updated_graph.nodes[leader_list[0]]
    assert n1['election_strategy'] == 'PREFIX_PRIORITIZATION'
    assert 'NCBIGene:100302240' in n1['aliases']
    assert 'ENSEMBL:ENSG00000284458' in n1['aliases']
    n2 = updated_graph.nodes[leader_list[1]]
    assert n2['election_strategy'] == 'PREFIX_PRIORITIZATION'
    assert 'NCBIGene:8202' in n2['aliases']
    assert 'OMIM:601937' in n2['aliases']
    assert 'ENSEMBL:ENSG00000124151' not in n2['aliases'] 
Example #23
Source File: test_kcomponents.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def graph_example_1():
    G = nx.convert_node_labels_to_integers(nx.grid_graph([5,5]),
                                            label_attribute='labels')
    rlabels = nx.get_node_attributes(G, 'labels')
    labels = dict((v, k) for k, v in rlabels.items())

    for nodes in [(labels[(0,0)], labels[(1,0)]),
                    (labels[(0,4)], labels[(1,4)]),
                    (labels[(3,0)], labels[(4,0)]),
                    (labels[(3,4)], labels[(4,4)]) ]:
        new_node = G.order()+1
        # Petersen graph is triconnected
        P = nx.petersen_graph()
        G = nx.disjoint_union(G,P)
        # Add two edges between the grid and P
        G.add_edge(new_node+1, nodes[0])
        G.add_edge(new_node, nodes[1])
        # K5 is 4-connected
        K = nx.complete_graph(5)
        G = nx.disjoint_union(G,K)
        # Add three edges between P and K5
        G.add_edge(new_node+2,new_node+11)
        G.add_edge(new_node+3,new_node+12)
        G.add_edge(new_node+4,new_node+13)
        # Add another K5 sharing a node
        G = nx.disjoint_union(G,K)
        nbrs = G[new_node+10]
        G.remove_node(new_node+10)
        for nbr in nbrs:
            G.add_edge(new_node+17, nbr)
        G.add_edge(new_node+16, new_node+5)

    G.name = 'Example graph for connectivity'
    return G 
Example #24
Source File: plot.py    From osmnx with MIT License 5 votes vote down vote up
def get_node_colors_by_attr(
    G, attr, num_bins=None, cmap="viridis", start=0, stop=1, na_color="none", equal_size=False
):
    """
    Get colors based on node attribute values.

    Parameters
    ----------
    G : networkx.MultiDiGraph
        input graph
    attr : string
        name of a numerical node attribute
    num_bins : int
        if None, linearly map a color to each value. otherwise, assign values
        to this many bins then assign a color to each bin.
    cmap : string
        name of a matplotlib colormap
    start : float
        where to start in the colorspace
    stop : float
        where to end in the colorspace
    na_color : string
        what color to assign nodes with missing attr values
    equal_size : bool
        ignored if num_bins is None. if True, bin into equal-sized quantiles
        (requires unique bin edges). if False, bin into equal-spaced bins.

    Returns
    -------
    node_colors : pandas.Series
        series labels are node IDs and values are colors
    """
    vals = pd.Series(nx.get_node_attributes(G, attr))
    return _get_colors_by_value(vals, num_bins, cmap, start, stop, na_color, equal_size) 
Example #25
Source File: graphing.py    From orquesta with Apache License 2.0 5 votes vote down vote up
def get_task_attributes(self, attribute):
        return dict_util.merge_dicts(
            {n: None for n in self._graph.nodes()},
            nx.get_node_attributes(self._graph, attribute),
            overwrite=True,
        ) 
Example #26
Source File: reference_network.py    From deep500 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def inference(self, input_dict: Dict[str, np.ndarray]) -> Dict[str, np.ndarray]:
        self.setup()

        self.variables.update(input_dict)

        nodes_custom_op = nx.get_node_attributes(self.graph, 'custom_op')
        nodes_operator = nx.get_node_attributes(self.graph, 'operator')
        
        for node_name in self.nodes_sorted_fwd:
            op = nodes_operator[node_name]
            custom_operator = nodes_custom_op[node_name]

            inputs = [self.variables[input_name] for input_name in op.input]

            print('start: forward computation of ' + str(node_name))
            if isinstance(custom_operator, CustomPythonOp):
                self.variables[op.output[0]] = custom_operator.forward(*inputs)
            elif isinstance(custom_operator, CustomCPPOp):
                custom_operator.forward(*inputs, self.variables[op.output[0]])
            else:
                raise ValueError('type of custom_operator is not supported')
            print('end: forward computation of ' + str(node_name))

        out_dict = {}
        for name in self.output_names:
            out_dict[name] = self.variables[name]
        return out_dict 
Example #27
Source File: network_analytics.py    From AMLSim with Apache License 2.0 5 votes vote down vote up
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]) 
Example #28
Source File: plotnxgraph.py    From complex_network with GNU General Public License v2.0 5 votes vote down vote up
def plot_graph(G, out_file=None, node_size=1500, font_size=10,
				node_and_labels=None, edge_and_labels=None):
	"""
	plot a graph
	"""

	pos = nx.get_node_attributes(G, 'pos')
	if not pos:
		pos = nx.spring_layout(G)

	nx.draw_networkx(G, pos, node_size=node_size, 
						node_color='w', 
						edge_color='k', 
						labels = node_and_labels,
						font_size=font_size,
						font_color='r',
						arrows=True,
						with_labels=True)

	plt.axis('off')	

	if edge_and_labels:
		nx.draw_networkx_edge_labels(G, pos, 
										edge_labels=edge_and_labels, 
										font_color='r',
										label_pos=0.4, 
										alpha=0.0)

	if out_file:
		plt.savefig(out_file, bbox_inches='tight')

	plt.show() 
Example #29
Source File: geometric.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def _fast_construct_edges(G, radius, p):
    """Construct edges for random geometric graph.

    Requires scipy to be installed.
    """
    pos = nx.get_node_attributes(G, 'pos')
    nodes, coords = list(zip(*pos.items()))
    kdtree = KDTree(coords)  # Cannot provide generator.
    edge_indexes = kdtree.query_pairs(radius, p)
    edges = ((nodes[u], nodes[v]) for u, v in edge_indexes)
    G.add_edges_from(edges) 
Example #30
Source File: nltk2graph_test.py    From ccg2lambda with Apache License 2.0 5 votes vote down vote up
def assert_graphs_are_equal(self, expected_graph, output_graph):
        self.assertTrue(
            are_graphs_equal(expected_graph, output_graph),
            msg='\nexpected: {0}\n          {1}\nvs.\noutput:   {2}\n          {3}'.format(
                expected_graph.adj, nx.get_node_attributes(expected_graph, 'label'),
                output_graph.adj, nx.get_node_attributes(output_graph, 'label')))
        return