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


Python networkx.get_edge_attributes方法代码示例

本文整理汇总了Python中networkx.get_edge_attributes方法的典型用法代码示例。如果您正苦于以下问题:Python networkx.get_edge_attributes方法的具体用法?Python networkx.get_edge_attributes怎么用?Python networkx.get_edge_attributes使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在networkx的用法示例。


在下文中一共展示了networkx.get_edge_attributes方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: write_alert_members_list

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import get_edge_attributes [as 别名]
def write_alert_members_list(self):

    def get_outEdge_attrs(g, vid, name):
      return [v for k, v in nx.get_edge_attributes(g, name).iteritems() if (k[0] == vid or k[1] == vid)]

    fname = os.path.join(self.output_dir, self.conf.get("OutputFile", "alert_members"))
    with open(fname, "w") as wf:
      writer = csv.writer(wf)
      writer.writerow(["alertID", "clientID", "isSubject", "modelID", "minAmount", "maxAmount", "startStep", "endStep"])
      for gid, sub_g in self.fraudgroups.iteritems():
        modelID = sub_g.graph["modelID"]
        for n in sub_g.nodes():
          isSubject = "true" if (sub_g.graph["subject"] == n) else "false"
          minAmount = '{:.2f}'.format(min(get_outEdge_attrs(sub_g, n, "amount")))
          maxAmount = '{:.2f}'.format(max(get_outEdge_attrs(sub_g, n, "amount")))
          minStep = min(get_outEdge_attrs(sub_g, n, "date"))
          maxStep = max(get_outEdge_attrs(sub_g, n, "date"))
          writer.writerow([gid, n, isSubject, modelID, minAmount, maxAmount, minStep, maxStep])

    print("Exported %d alert groups." % len(self.fraudgroups)) 
开发者ID:IBM,项目名称:AMLSim,代码行数:22,代码来源:transaction_generator.py

示例2: plot_alerts

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import get_edge_attributes [as 别名]
def plot_alerts(_g, _bank_accts, _output_png):
    bank_ids = _bank_accts.keys()
    cmap = plt.get_cmap("tab10")
    pos = nx.nx_agraph.graphviz_layout(_g)

    plt.figure(figsize=(12.0, 8.0))
    plt.axis('off')

    for i, bank_id in enumerate(bank_ids):
        color = cmap(i)
        members = _bank_accts[bank_id]
        nx.draw_networkx_nodes(_g, pos, members, node_size=300, node_color=color, label=bank_id)
        nx.draw_networkx_labels(_g, pos, {n: n for n in members}, font_size=10)

    edge_labels = nx.get_edge_attributes(_g, "label")
    nx.draw_networkx_edges(_g, pos)
    nx.draw_networkx_edge_labels(_g, pos, edge_labels, font_size=6)

    plt.legend(numpoints=1)
    plt.subplots_adjust(left=0, right=1, bottom=0, top=1)
    plt.savefig(_output_png, dpi=120) 
开发者ID:IBM,项目名称:AMLSim,代码行数:23,代码来源:plot_alert_pattern_subgraphs.py

示例3: assert_neg_metagraph

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import get_edge_attributes [as 别名]
def assert_neg_metagraph(infr):
        """
        Checks that the negative metgraph is correctly book-kept.
        """
        # The total weight of all edges in the negative metagraph should equal
        # the total number of negative edges.
        neg_weight = sum(nx.get_edge_attributes(
            infr.neg_metagraph, 'weight').values())
        n_neg_edges = infr.neg_graph.number_of_edges()
        assert neg_weight == n_neg_edges

        # Self loops should correspond to the number of inconsistent components
        neg_self_loop_nids = sorted([
            ne[0] for ne in list(infr.neg_metagraph.selfloop_edges())])
        incon_nids = sorted(infr.nid_to_errors.keys())
        assert neg_self_loop_nids == incon_nids 
开发者ID:Erotemic,项目名称:ibeis,代码行数:18,代码来源:mixin_helpers.py

示例4: plot_graph

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import get_edge_attributes [as 别名]
def plot_graph(G, ax=None):
    """
    Plots a networkx graph.

    Parameters
    ----------
    G:
        The networkx graph of interest.
    ax: Matplotlib axes object
        Defaults to None. Matplotlib axes to plot on.
    """

    weights = np.real([*nx.get_edge_attributes(G, 'weight').values()])
    pos = nx.shell_layout(G)

    nx.draw(G, pos, node_color='#A0CBE2', with_labels=True, edge_color=weights,
            width=4, edge_cmap=plt.cm.Blues, ax=ax)
    plt.show()


#############################################################################
# HAMILTONIANS AND DATA
############################################################################# 
开发者ID:entropicalabs,项目名称:entropica_qaoa,代码行数:25,代码来源:utilities.py

示例5: plot

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import get_edge_attributes [as 别名]
def plot(self, file_path: str):
        try:
            import matplotlib.pyplot as plt
        except ImportError as err:
            raise('matplotlib not installed. Failed at: {}', err)

        try:
            pos = nx.nx_agraph.graphviz_layout(self.directed)
            nx.draw(
                self.directed,
                pos=pos,
                node_size=1200,
                node_color='lightblue',
                linewidths=0.25,
                font_size=8,
                font_weight='bold',
                with_labels=True,
                dpi=5000
            )
            # edge_labels = nx.get_edge_attributes(self.directed, name='attr_dict')
            # nx.draw_networkx_edge_labels(self.directed, pos=pos, edge_labels=edge_labels)
            plt.savefig(file_path)
        except IOError as err:
            raise('Could not create plot image: {}', err) 
开发者ID:leopepe,项目名称:GOApy,代码行数:26,代码来源:Planner.py

示例6: draw_wstate_tree

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import get_edge_attributes [as 别名]
def draw_wstate_tree(svm):
    import matplotlib.pyplot as plt
    import networkx as nx
    from networkx.drawing.nx_agraph import write_dot, graphviz_layout

    G = nx.DiGraph()
    pending_list = [svm.root_wstate]
    while len(pending_list):
        root = pending_list.pop()
        for trace, children in root.trace_to_children.items():
            for c in children:
                G.add_edge(repr(root), repr(c), label=trace)
                pending_list.append(c)
    # pos = nx.spring_layout(G)
    pos = graphviz_layout(G, prog='dot')
    edge_labels = nx.get_edge_attributes(G, 'label')
    nx.draw(G, pos)
    nx.draw_networkx_edge_labels(G, pos, edge_labels, font_size=8)
    nx.draw_networkx_labels(G, pos, font_size=10)
    plt.show() 
开发者ID:eth-sri,项目名称:ilf,代码行数:22,代码来源:svm_utils.py

示例7: find_internal_edges

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import get_edge_attributes [as 别名]
def find_internal_edges(self, nodeset):
        """Find all edges that have both edges in the set of provided nodes"""
        internal_edges = set()
        all_edges = set()
        names = nx.get_edge_attributes(self.graph, "equipment_name")
        for node in nodeset:
            linked_edges = self.graph.edges([node])
            for edge in linked_edges:
                all_edges.add(edge)

        for edge in all_edges:
            if edge[0] in nodeset and edge[1] in nodeset:
                if (edge[0], edge[1]) in names:
                    internal_edges.add(names[(edge[0], edge[1])])
                elif (edge[1], edge[0]) in names:
                    internal_edges.add(names[(edge[1], edge[0])])

        return internal_edges 
开发者ID:NREL,项目名称:ditto,代码行数:20,代码来源:network.py

示例8: check_consensus_graph

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import get_edge_attributes [as 别名]
def check_consensus_graph(G, n_p, delta):
    '''
    This function checks if the networkx graph has converged. 
    Input:
    G: networkx graph
    n_p: number of partitions while creating G
    delta: if more than delta fraction of the edges have weight != n_p then returns False, else True
    '''



    count = 0
    
    for wt in nx.get_edge_attributes(G, 'weight').values():
        if wt != 0 and wt != n_p:
            count += 1

    if count > delta*G.number_of_edges():
        return False

    return True 
开发者ID:adityat,项目名称:fastconsensus,代码行数:23,代码来源:fast_consensus.py

示例9: test_get_edge_attributes

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import get_edge_attributes [as 别名]
def test_get_edge_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_edge_attributes(G, attr, vals)
        attrs = nx.get_edge_attributes(G, attr)

        assert_equal(len(attrs), 2)
        if G.is_multigraph():
            keys = [(0,1,0), (1,2,0)]
        else:
            keys = [(0,1), (1,2)]
        for key in keys:
            assert_equal(attrs[key], 100) 
开发者ID:SpaceGroupUCL,项目名称:qgisSpaceSyntaxToolkit,代码行数:18,代码来源:test_function.py

示例10: test_get_edge_attributes

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import get_edge_attributes [as 别名]
def test_get_edge_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_edge_attributes(G, vals, attr)
        attrs = nx.get_edge_attributes(G, attr)

        assert_equal(len(attrs), 2)
        if G.is_multigraph():
            keys = [(0, 1, 0), (1, 2, 0)]
            for u, v, k in keys:
                try:
                    assert_equal(attrs[(u, v, k)], 100)
                except KeyError:
                    assert_equal(attrs[(v, u, k)], 100)
        else:
            keys = [(0, 1), (1, 2)]
            for u, v in keys:
                try:
                    assert_equal(attrs[(u, v)], 100)
                except KeyError:
                    assert_equal(attrs[(v, u)], 100) 
开发者ID:holzschu,项目名称:Carnets,代码行数:26,代码来源:test_function.py

示例11: draw_graph

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import get_edge_attributes [as 别名]
def draw_graph(self):
        nx.draw_shell(self.G, with_labels=True, font_weight='bold')

        # pos = graphviz_layout(self.G)
        # plt.axis('off')
        # nx.draw_networkx_nodes(self.G,pos,node_color='g',alpha = 0.8)
        # nx.draw_networkx_edges(self.G,pos,edge_color='b',alpha = 0.6)
        # nx.draw_networkx_edge_labels(self.G,pos,edge_labels = \
        # nx.get_edge_attributes(self.G,'weight'))
        # nx.draw_networkx_labels(self.G,pos) # node lables

        plt.savefig('graph.png') 
开发者ID:gcallah,项目名称:indras_net,代码行数:14,代码来源:good_structure.py

示例12: nx_to_PyGGraph

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import get_edge_attributes [as 别名]
def nx_to_PyGGraph(g, graph_label, node_labels, node_features, max_node_label, class_values):
    # convert networkx graph to pytorch_geometric data format
    y = torch.FloatTensor([class_values[graph_label]])
    if len(g.edges()) == 0:
        i, j = [], []
    else:
        i, j = zip(*g.edges())
    edge_index = torch.LongTensor([i+j, j+i])
    edge_type_dict = nx.get_edge_attributes(g, 'type')
    edge_type = torch.LongTensor([edge_type_dict[(ii, jj)] for ii, jj in zip(i, j)])
    edge_type = torch.cat([edge_type, edge_type], 0)
    edge_attr = torch.FloatTensor(
        class_values[edge_type]
    ).unsqueeze(1)  # continuous ratings, num_edges * 1
    x = torch.FloatTensor(one_hot(node_labels, max_node_label+1))
    if node_features is not None:
        if type(node_features) == list:
            # node features are only provided for target user and item
            u_feature, v_feature = node_features
        else:
            # node features are provided for all nodes
            x2 = torch.FloatTensor(node_features)
            x = torch.cat([x, x2], 1)

    data = Data(x, edge_index, edge_attr=edge_attr, y=y)
    data.edge_type = edge_type
    if type(node_features) == list:
        data.u_feature = torch.FloatTensor(u_feature).unsqueeze(0)
        data.v_feature = torch.FloatTensor(v_feature).unsqueeze(0)
    return data 
开发者ID:muhanzhang,项目名称:IGMC,代码行数:32,代码来源:util_functions.py

示例13: write_alert_account_list

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import get_edge_attributes [as 别名]
def write_alert_account_list(self):
        def get_out_edge_attrs(g, vid, name):
            return [v for k, v in nx.get_edge_attributes(g, name).items() if (k[0] == vid or k[1] == vid)]

        acct_count = 0
        alert_member_file = os.path.join(self.output_dir, self.out_alert_member_file)
        logger.info("Output alert member list to: " + alert_member_file)
        with open(alert_member_file, "w") as wf:
            writer = csv.writer(wf)
            base_attrs = ["alertID", "reason", "accountID", "isMain", "isSAR", "modelID",
                          "minAmount", "maxAmount", "startStep", "endStep", "scheduleID", "bankID"]
            writer.writerow(base_attrs + self.attr_names)
            for gid, sub_g in self.alert_groups.items():
                main_id = sub_g.graph[MAIN_ACCT_KEY]
                model_id = sub_g.graph["model_id"]
                schedule_id = sub_g.graph["scheduleID"]
                reason = sub_g.graph["reason"]
                start = sub_g.graph["start"]
                end = sub_g.graph["end"]
                for n in sub_g.nodes():
                    is_main = "true" if n == main_id else "false"
                    is_sar = "true" if sub_g.graph[IS_SAR_KEY] else "false"
                    min_amt = '{:.2f}'.format(min(get_out_edge_attrs(sub_g, n, "amount")))
                    max_amt = '{:.2f}'.format(max(get_out_edge_attrs(sub_g, n, "amount")))
                    min_step = start
                    max_step = end
                    bank_id = sub_g.node[n]["bank_id"]
                    values = [gid, reason, n, is_main, is_sar, model_id, min_amt, max_amt,
                              min_step, max_step, schedule_id, bank_id]
                    prop = self.g.node[n]
                    for attr_name in self.attr_names:
                        values.append(prop[attr_name])
                    writer.writerow(values)
                    acct_count += 1

        logger.info("Exported %d members for %d AML typologies to %s" %
                    (acct_count, len(self.alert_groups), alert_member_file)) 
开发者ID:IBM,项目名称:AMLSim,代码行数:39,代码来源:transaction_graph_generator.py

示例14: get_date_list

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import get_edge_attributes [as 别名]
def get_date_list(_g):
    all_dates = list(nx.get_edge_attributes(_g, "date").values())
    start_date = min(all_dates)
    end_date = max(all_dates)
    days = (end_date - start_date).days + 1
    date_list = [start_date + timedelta(days=n) for n in range(days)]
    return date_list 
开发者ID:IBM,项目名称:AMLSim,代码行数:9,代码来源:plot_distributions.py

示例15: plot_clustering_coefficient

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import get_edge_attributes [as 别名]
def plot_clustering_coefficient(_g, _plot_img, interval=30):
    """Plot the clustering coefficient transition
    :param _g: Transaction graph
    :param _plot_img: Output image file
    :param interval: Simulation step interval for plotting
    (it takes too much time to compute clustering coefficient)
    :return:
    """
    date_list = get_date_list(_g)

    gg = nx.Graph()
    edges = defaultdict(list)
    for k, v in nx.get_edge_attributes(_g, "date").items():
        e = (k[0], k[1])
        edges[v].append(e)

    sample_dates = list()
    values = list()
    for i, t in enumerate(date_list):
        gg.add_edges_from(edges[t])
        if i % interval == 0:
            v = nx.average_clustering(gg) if gg.number_of_nodes() else 0.0
            sample_dates.append(t)
            values.append(v)
            print("Clustering coefficient at %s: %f" % (str(t), v))

    plt.figure(figsize=(16, 12))
    plt.clf()
    plt.plot(sample_dates, values, 'bo-')
    plt.title("Clustering Coefficient Transition")
    plt.xlabel("date")
    plt.ylabel("Clustering Coefficient")
    plt.savefig(_plot_img) 
开发者ID:IBM,项目名称:AMLSim,代码行数:35,代码来源:plot_distributions.py


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