当前位置: 首页>>代码示例>>Python>>正文


Python networkx.set_node_attributes方法代码示例

本文整理汇总了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) 
开发者ID:graphistry,项目名称:pygraphistry,代码行数:26,代码来源:test_plotter.py

示例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") 
开发者ID:microsoft,项目名称:msticpy,代码行数:18,代码来源:security_alert_graph.py

示例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 
开发者ID:Erotemic,项目名称:ibeis,代码行数:18,代码来源:mixin_viz.py

示例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 
开发者ID:Erotemic,项目名称:ibeis,代码行数:20,代码来源:mixin_viz.py

示例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) 
开发者ID:Erotemic,项目名称:ibeis,代码行数:19,代码来源:viz_graph.py

示例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) 
开发者ID:GiulioRossetti,项目名称:ndlib,代码行数:21,代码来源:test_compartment.py

示例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 
开发者ID:RexYing,项目名称:gnn-model-explainer,代码行数:20,代码来源:featgen.py

示例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() 
开发者ID:acsicuib,项目名称:YAFS,代码行数:19,代码来源:topology.py

示例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 
开发者ID:acsicuib,项目名称:YAFS,代码行数:21,代码来源:topology.py

示例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()) 
开发者ID:benmaier,项目名称:netwulf,代码行数:20,代码来源:test_all.py

示例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}) 
开发者ID:dwavesystems,项目名称:dwave_networkx,代码行数:20,代码来源:test_independent_set.py

示例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) 
开发者ID:dwavesystems,项目名称:dwave_networkx,代码行数:26,代码来源:test_cover.py

示例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 
开发者ID:sparkandshine,项目名称:complex_network,代码行数:21,代码来源:buildupgraph.py

示例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 
开发者ID:sparkandshine,项目名称:complex_network,代码行数:21,代码来源:graphviz.py

示例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}) 
开发者ID:tomgrek,项目名称:zincbase,代码行数:18,代码来源:zincbase.py


注:本文中的networkx.set_node_attributes方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。