Python networkx.set_node_attributes() Examples

The following are 30 code examples of networkx.set_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: test_cover.py    From dwave_networkx with Apache License 2.0 6 votes vote down vote up
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) 
Example #4
Source File: markov.py    From striplog with Apache License 2.0 6 votes vote down vote up
def as_graph(self, directed=True):

        if self.normalized_difference.ndim > 2:
            raise MarkovError("You can only graph one-step chains.")

        try:
            import networkx as nx
        except ImportError:
            nx = None

        if nx is None:
            print("Please install networkx with `pip install networkx`.")
            return

        if directed:
            alg = nx.DiGraph
        else:
            alg = nx.Graph

        G = nx.from_numpy_array(self.normalized_difference, create_using=alg)
        nx.set_node_attributes(G, self._state_dict, 'state')
        return G 
Example #5
Source File: mixin_viz.py    From ibeis with Apache License 2.0 6 votes vote down vote up
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 
Example #6
Source File: mixin_viz.py    From ibeis with Apache License 2.0 6 votes vote down vote up
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 
Example #7
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 #8
Source File: test_exact.py    From region with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_graph_str_multi_attr():
    nx.set_node_attributes(graph, attr_dict, attr_str)
    nx.set_node_attributes(
        graph, spatially_extensive_attr_dict, spatially_extensive_attr_str
    )
    cluster_object = MaxPRegionsExact()
    cluster_object.fit_from_networkx(
        graph,
        [attr_str] * 2,
        [spatially_extensive_attr_str] * 2,
        threshold=double_threshold,
    )
    result = region_list_from_array(cluster_object.labels_)
    compare_region_lists(result, optimal_clustering)


# test with W 
Example #9
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 #10
Source File: test_function.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_set_node_attributes():
    graphs = [nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()]
    for G in graphs:
        G = nx.path_graph(3, create_using=G)

        # Test single value
        attr = 'hello'
        vals = 100
        nx.set_node_attributes(G, attr, vals)
        assert_equal(G.node[0][attr], vals)
        assert_equal(G.node[1][attr], vals)
        assert_equal(G.node[2][attr], vals)

        # Test multiple values
        attr = 'hi'
        vals = dict(zip(sorted(G.nodes()), range(len(G))))
        nx.set_node_attributes(G, attr, vals)
        assert_equal(G.node[0][attr], 0)
        assert_equal(G.node[1][attr], 1)
        assert_equal(G.node[2][attr], 2) 
Example #11
Source File: nltk2graph.py    From ccg2lambda with Apache License 2.0 6 votes vote down vote up
def rename_nodes(graph, head_node=None, quant_active=None, quant_scope=None):
    """
    Traverses the graph, renaming those nodes that are either
    variable values or variable functions.
    """
    if head_node is None:
        head_node = graph.graph['head_node']
    # Get nodes and their scope information.
    scoped_nodes = get_scoped_nodes(graph, head_node)
    for nodes_to_relabel in scoped_nodes.values():
        for node, node_type in nodes_to_relabel:
            new_label = make_label(
                get_label(graph, node),
                node_type)
            nx.set_node_attributes(graph, {node : new_label}, 'label')
    return graph 
Example #12
Source File: MinDisagreeClusterByComponent.py    From SDA with MIT License 6 votes vote down vote up
def AddLayoutPreCC(g):
	pos = ABPUtils.BuildLayoutArray(g)
	if pos is None and len(g.nodes()) > 0:
		pos = nx.spring_layout(g, k=1/math.sqrt(len(g.nodes())), 
				weight=math.sqrt(len(g.nodes())), scale=100, iterations=1000)

	if pos is not None:
		nx.set_node_attributes(g, 'x', dict(zip(g.nodes(), [pos[n][0] for n in g.nodes()])))
		nx.set_node_attributes(g, 'y', dict(zip(g.nodes(), [pos[n][1] for n in g.nodes()])))
	


#starts = args.starts
#scores = {}
#scoreVals = []
#for idx in range(starts): 
Example #13
Source File: ABPUtils.py    From SDA with MIT License 6 votes vote down vote up
def DistanceMatrixToGraph(dm, nameLabels=None,colorLabels=None, scoreCutoff=10):
    g = nx.Graph()

    for i in range(0,dm.shape[1]):
        g.add_node(i)
    if (nameLabels is not None):
        nx.set_node_attributes(g, 'name', dict(zip(range(0,len(g)),nameLabels)))
    if (colorLabels is not None):
        nx.set_node_attributes(g, 'color', dict(zip(range(0,len(g)),colorLabels)))
    
    for i in range(0,len(dm)-1):
        for j in range(i+1,len(dm)):
            if (j == i):
                continue
            if (dm[i][j] >= scoreCutoff):
                g.add_edge(i,j,capacity=dm[i][j])
    return g 
Example #14
Source File: featgen.py    From gnn-model-explainer with Apache License 2.0 6 votes vote down vote up
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 
Example #15
Source File: zincbase.py    From zincbase with MIT License 6 votes vote down vote up
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}) 
Example #16
Source File: topology.py    From YAFS with MIT License 6 votes vote down vote up
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() 
Example #17
Source File: topology.py    From YAFS with MIT License 6 votes vote down vote up
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 
Example #18
Source File: test_all.py    From netwulf with MIT License 6 votes vote down vote up
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()) 
Example #19
Source File: test_independent_set.py    From dwave_networkx with Apache License 2.0 6 votes vote down vote up
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}) 
Example #20
Source File: test_compartment.py    From ndlib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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) 
Example #21
Source File: test_plotter.py    From pygraphistry with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #22
Source File: test_azp.py    From region with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_graph_str_multi_attr():
    nx.set_node_attributes(graph, attr_dict, attr_str)
    cluster_object = AZP(random_state=0)
    cluster_object.fit_from_networkx(graph, double_attr_str, n_regions=2)
    result = region_list_from_array(cluster_object.labels_)
    compare_region_lists(result, optimal_clustering)


# test with W 
Example #23
Source File: test_osmnx.py    From osmnx with MIT License 5 votes vote down vote up
def test_routing_folium():

    G = ox.graph_from_address(address=address, dist=500, dist_type="bbox", network_type="bike")

    # give each node a random elevation then calculate edge grades
    randm = np.random.random(size=len(G))
    elevs = {n: e for n, e in zip(G.nodes(), randm)}
    nx.set_node_attributes(G, name="elevation", values=elevs)
    G = ox.add_edge_grades(G, add_absolute=True)

    # give each edge speed and travel time attributes
    G = ox.add_edge_speeds(G)
    G = ox.add_edge_travel_times(G)

    orig_node = list(G.nodes())[5]
    dest_node = list(G.nodes())[-5]
    orig_pt = (G.nodes[orig_node]["y"], G.nodes[orig_node]["x"])
    dest_pt = (G.nodes[dest_node]["y"], G.nodes[dest_node]["x"])
    route = nx.shortest_path(G, orig_node, dest_node, weight="travel_time")

    attributes = ox.utils_graph.get_route_edge_attributes(G, route, "travel_time")

    fig, ax = ox.plot_graph_route(G, route, save=True)

    fig, ax = ox.plot_graph_route(G, route, save=True)

    # test multiple routes
    fig, ax = ox.plot_graph_routes(G, [route, route])

    # test folium
    gm = ox.plot_graph_folium(G, popup_attribute="name")
    rm = ox.plot_route_folium(G, route)

    # test calling folium plotters with FeatureGroup instead of Map, and extra kwargs
    fg = folium.FeatureGroup(name="legend name", show=True)
    gm = ox.plot_graph_folium(G, graph_map=fg)
    assert isinstance(gm, folium.FeatureGroup)

    rm = ox.plot_route_folium(G, route, route_color="g", route_map=fg, tooltip="x")
    assert isinstance(rm, folium.FeatureGroup) 
Example #24
Source File: add_load_gen_trafos_to_scigrid.py    From PyPSA with GNU General Public License v3.0 5 votes vote down vote up
def voronoi_partition(G, outline):
    """                                                                                                                                                   
    For 2D-embedded graph `G`, within the boundary given by the shapely polygon                                                                           
    `outline`, returns `G` with the Voronoi cell region as an additional node                                                                             
    attribute.                                                                                                                                            
    """
    #following line from vresutils.graph caused a bug
    #G = polygon_subgraph(G, outline, copy=False)
    points = list(vresutils.graph.get_node_attributes(G, 'pos').values())
    regions = vresutils.graph.voronoi_partition_pts(points, outline, no_multipolygons=True)
    nx.set_node_attributes(G, 'region', dict(zip(G.nodes(), regions)))

    return G 
Example #25
Source File: test_azp_simulated_annealing.py    From region with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_graph_str_basic():
    nx.set_node_attributes(graph, attr_dict, attr_str)
    cluster_object = AZPSimulatedAnnealing(
        init_temperature=1, max_iterations=2, random_state=0
    )
    cluster_object.fit_from_networkx(graph, attr_str, n_regions=2)
    result = region_list_from_array(cluster_object.labels_)
    compare_region_lists(result, optimal_clustering)


# test with W 
Example #26
Source File: test_azp.py    From region with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_graph_str_basic():
    nx.set_node_attributes(graph, attr_dict, attr_str)
    cluster_object = AZP(random_state=0)
    cluster_object.fit_from_networkx(graph, attr_str, n_regions=2)
    result = region_list_from_array(cluster_object.labels_)
    compare_region_lists(result, optimal_clustering)


# test with W 
Example #27
Source File: feat.py    From diffpool with MIT License 5 votes vote down vote up
def gen_node_features(self, G):
        feat = np.random.multivariate_normal(mu, sigma, G.number_of_nodes())
        feat_dict = {i:{'feat': feat[i]} for i in range(feat.shape[0])}
        nx.set_node_attributes(G, feat_dict) 
Example #28
Source File: test_heu.py    From region with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_graph_str_basic():
    nx.set_node_attributes(graph, attr_dict, attr_str)
    nx.set_node_attributes(
        graph, spatially_extensive_attr_dict, spatially_extensive_attr_str
    )
    cluster_object = MaxPRegionsHeu(random_state=0)
    cluster_object.fit_from_networkx(
        graph, attr_str, spatially_extensive_attr_str, threshold=threshold
    )
    result = region_list_from_array(cluster_object.labels_)
    compare_region_lists(result, optimal_clustering)


# test with W 
Example #29
Source File: feat.py    From diffpool with MIT License 5 votes vote down vote up
def gen_node_features(self, G):
        feat_dict = {i:{'feat': self.val} for i in G.nodes()}
        nx.set_node_attributes(G, feat_dict) 
Example #30
Source File: test_azp_simulated_annealing.py    From region with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_graph_str_multi_attr():
    nx.set_node_attributes(graph, attr_dict, attr_str)
    cluster_object = AZPSimulatedAnnealing(
        init_temperature=1, max_iterations=2, random_state=0
    )
    cluster_object.fit_from_networkx(graph, double_attr_str, n_regions=2)
    result = region_list_from_array(cluster_object.labels_)
    compare_region_lists(result, optimal_clustering)


# test with W