Python networkx.get_edge_attributes() Examples

The following are 30 code examples of networkx.get_edge_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: svm_utils.py    From ilf with Apache License 2.0 9 votes vote down vote up
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() 
Example #2
Source File: network.py    From ditto with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #3
Source File: test_function.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
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) 
Example #4
Source File: transaction_generator.py    From AMLSim with Apache License 2.0 6 votes vote down vote up
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)) 
Example #5
Source File: plot_alert_pattern_subgraphs.py    From AMLSim with Apache License 2.0 6 votes vote down vote up
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) 
Example #6
Source File: test_function.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #7
Source File: fast_consensus.py    From fastconsensus with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #8
Source File: test_function.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #9
Source File: Planner.py    From GOApy with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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) 
Example #10
Source File: mixin_helpers.py    From ibeis with Apache License 2.0 6 votes vote down vote up
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 
Example #11
Source File: utilities.py    From entropica_qaoa with Apache License 2.0 6 votes vote down vote up
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
############################################################################# 
Example #12
Source File: test_FormanRicci.py    From GraphRicciCurvature with Apache License 2.0 5 votes vote down vote up
def test_compute_ricci_curvature():
    Gd = nx.DiGraph()
    Gd.add_edges_from([(1, 2), (2, 3), (3, 4), (2, 4), (4, 2)])
    orc_directed = FormanRicci(Gd)
    orc_directed.compute_ricci_curvature()

    frc = nx.get_edge_attributes(orc_directed.G, "formanCurvature")

    assert frc == {(1, 2): -2, (2, 3): 0, (2, 4): 0, (3, 4): 1, (4, 2): 0} 
Example #13
Source File: graphing.py    From orquesta with Apache License 2.0 5 votes vote down vote up
def get_transition_attributes(self, attribute):
        return nx.get_edge_attributes(self._graph, attribute) 
Example #14
Source File: plot.py    From osmnx with MIT License 5 votes vote down vote up
def get_edge_colors_by_attr(
    G, attr, num_bins=None, cmap="viridis", start=0, stop=1, na_color="none", equal_size=False
):
    """
    Get colors based on edge attribute values.

    Parameters
    ----------
    G : networkx.MultiDiGraph
        input graph
    attr : string
        name of a numerical edge 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 edges 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
    -------
    edge_colors : pandas.Series
        series labels are edge IDs (u, v, k) and values are colors
    """
    vals = pd.Series(nx.get_edge_attributes(G, attr))
    return _get_colors_by_value(vals, num_bins, cmap, start, stop, na_color, equal_size) 
Example #15
Source File: my_surgery.py    From GraphRicciCurvature with Apache License 2.0 5 votes vote down vote up
def my_surgery(G_origin: nx.Graph(), weight="weight", cut=0):
    """
    A simple surgery function that remove the edges with weight above a threshold
    :param G: A weighted networkx graph
    :param weight: Name of edge weight to cut
    :param cut: Manually assign cut point
    :return: A weighted networkx graph after surgery
    """
    G = G_origin.copy()
    w = nx.get_edge_attributes(G, weight)

    assert cut >= 0, "Cut value should be greater than 0."
    if not cut:
        cut = (max(w.values()) - 1.0) * 0.6 + 1.0  # Guess a cut point as default

    to_cut = []
    for n1, n2 in G.edges():
        if G[n1][n2][weight] > cut:
            to_cut.append((n1, n2))
    print("*************** Surgery time ****************")
    print("* Cut %d edges." % len(to_cut))
    G.remove_edges_from(to_cut)
    print("* Number of nodes now: %d" % G.number_of_nodes())
    print("* Number of edges now: %d" % G.number_of_edges())
    cc = list(nx.connected_components(G))
    print("* Modularity now: %f " % nx.algorithms.community.quality.modularity(G, cc))

    print("* ARI now: %f " % ARI(G, cc))
    print("*********************************************")

    return G 
Example #16
Source File: test_OllivierRicci.py    From GraphRicciCurvature with Apache License 2.0 5 votes vote down vote up
def test_compute_ricci_curvature():
    G = nx.karate_club_graph()
    orc = OllivierRicci(G, alpha=0.5)
    Gout = orc.compute_ricci_curvature()
    rc = list(nx.get_edge_attributes(Gout, "ricciCurvature").values())
    ans = [0.111111, -0.143750, 0.041667, -0.114583, -0.281250, -0.281250, 0.062500, -0.200000, -0.114583, 0.062500,
           -0.000000, 0.062500, 0.062500, -0.031250, 0.062500, -0.427083, 0.044444, 0.166667, 0.194444, 0.244444,
           0.166667, 0.111111, 0.166667, -0.041667, 0.050000, 0.125000, 0.100000, 0.100000, 0.200000, -0.175000,
           0.033333, -0.233333, 0.416667, 0.250000, 0.216667, 0.291667, 0.500000, 0.500000, 0.291667, 0.375000,
           0.375000, 0.375000, -0.025000, 0.011765, -0.044118, -0.288235, 0.125000, 0.088235, 0.125000, 0.088235,
           0.125000, 0.088235, -0.254902, 0.125000, 0.088235, 0.125000, 0.088235, 0.100000, 0.225000, 0.200000,
           -0.066667, -0.076471, 0.500000, 0.125000, 0.083333, 0.166667, 0.375000, -0.073529, -0.147059, 0.166667,
           -0.068627, -0.041667, -0.014706, -0.041667, -0.044118, -0.166667, -0.122549, 0.267157]

    npt.assert_array_almost_equal(rc, ans) 
Example #17
Source File: test_OllivierRicci.py    From GraphRicciCurvature with Apache License 2.0 5 votes vote down vote up
def test_compute_ricci_flow():
    G = nx.karate_club_graph()
    orc = OllivierRicci(G, alpha=0.5)
    Gout = orc.compute_ricci_flow(iterations=3)
    rf = list(nx.get_edge_attributes(Gout, "weight").values())
    ans = [0.584642, 1.222957, 0.828566, 1.893597, 2.179315, 2.179315, 0.814135, 1.647656, 1.893597, 0.906430,
           0.916791, 0.798319, 0.760511, 0.829311, 0.760511, 2.477847, 0.937765, 0.681481, 0.612859, 0.568307,
           0.675702, 0.702774, 0.675702, 1.484889, 0.843498, 0.753397, 1.098413, 0.868616, 0.646627, 2.061065,
           1.425968, 1.924123, 0.292387, 0.487378, 0.446435, 0.509673, 0.101477, 0.108645, 0.509673, 0.246037,
           0.246037, 0.228701, 1.309931, 1.213249, 1.317511, 2.149341, 0.712759, 0.811386, 0.712759, 0.811386,
           0.712759, 0.811386, 2.245314, 0.712759, 0.811386, 0.712759, 0.811386, 0.947310, 0.518039, 0.857636,
           1.525740, 1.429449, 0.180896, 0.692919, 0.724545, 0.639637, 0.281116, 1.427853, 1.622385, 0.807457,
           1.386869, 1.372091, 1.320579, 1.324087, 1.276729, 1.843012, 1.721982, 0.412472]

    npt.assert_array_almost_equal(rf, ans) 
Example #18
Source File: util_functions.py    From IGMC with MIT License 5 votes vote down vote up
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 
Example #19
Source File: function.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def get_edge_attributes(G, name):
    """Get edge attributes from graph

    Parameters
    ----------
    G : NetworkX Graph

    name : string
       Attribute name

    Returns
    -------
    Dictionary of attributes keyed by edge. For (di)graphs, the keys are
    2-tuples of the form: (u,v). For multi(di)graphs, the keys are 3-tuples of
    the form: (u, v, key).

    Examples
    --------
    >>> G=nx.Graph()
    >>> G.add_path([1,2,3],color='red')
    >>> color=nx.get_edge_attributes(G,'color')
    >>> color[(1,2)]
    'red'
    """
    if G.is_multigraph():
        edges = G.edges(keys=True, data=True)
    else:
        edges = G.edges(data=True)
    return dict( (x[:-1], x[-1][name]) for x in edges if name in x[-1] ) 
Example #20
Source File: function.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_edge_attributes(G, name):
    """Get edge attributes from graph

    Parameters
    ----------
    G : NetworkX Graph

    name : string
       Attribute name

    Returns
    -------
    Dictionary of attributes keyed by edge. For (di)graphs, the keys are
    2-tuples of the form: (u, v). For multi(di)graphs, the keys are 3-tuples of
    the form: (u, v, key).

    Examples
    --------
    >>> G = nx.Graph()
    >>> nx.add_path(G, [1, 2, 3], color='red')
    >>> color = nx.get_edge_attributes(G, 'color')
    >>> color[(1, 2)]
    'red'
    """
    if G.is_multigraph():
        edges = G.edges(keys=True, data=True)
    else:
        edges = G.edges(data=True)
    return {x[:-1]: x[-1][name] for x in edges if name in x[-1]} 
Example #21
Source File: edge_kcomponents.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def k_edge_components(self, k):
        """Queries the auxiliary graph for k-edge-connected components.

        Parameters
        ----------
        k : Integer
            Desired edge connectivity

        Returns
        -------
        k_edge_components : a generator of k-edge-ccs

        Notes
        -----
        Given the auxiliary graph, the k-edge-connected components can be
        determined in linear time by removing all edges with weights less than
        k from the auxiliary graph.  The resulting connected components are the
        k-edge-ccs in the original graph.
        """
        if k < 1:
            raise ValueError('k cannot be less than 1')
        A = self.A
        # "traverse the auxiliary graph A and delete all edges with weights less
        # than k"
        aux_weights = nx.get_edge_attributes(A, 'weight')
        # Create a relevant graph with the auxiliary edges with weights >= k
        R = nx.Graph()
        R.add_nodes_from(A.nodes())
        R.add_edges_from(e for e, w in aux_weights.items() if w >= k)

        # Return the nodes that are k-edge-connected in the original graph
        for cc in nx.connected_components(R):
            yield cc 
Example #22
Source File: function.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def get_edge_attributes(G, name):
    """Get edge attributes from graph

    Parameters
    ----------
    G : NetworkX Graph

    name : string
       Attribute name

    Returns
    -------
    Dictionary of attributes keyed by edge. For (di)graphs, the keys are
    2-tuples of the form: (u, v). For multi(di)graphs, the keys are 3-tuples of
    the form: (u, v, key).

    Examples
    --------
    >>> G = nx.Graph()
    >>> nx.add_path(G, [1, 2, 3], color='red')
    >>> color = nx.get_edge_attributes(G, 'color')
    >>> color[(1, 2)]
    'red'
    """
    if G.is_multigraph():
        edges = G.edges(keys=True, data=True)
    else:
        edges = G.edges(data=True)
    return {x[:-1]: x[-1][name] for x in edges if name in x[-1]} 
Example #23
Source File: edge_kcomponents.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def k_edge_components(self, k):
        """Queries the auxillary graph for k-edge-connected components.

        Parameters
        ----------
        k : Integer
            Desired edge connectivity

        Returns
        -------
        k_edge_components : a generator of k-edge-ccs

        Notes
        -----
        Given the auxillary graph, the k-edge-connected components can be
        determined in linear time by removing all edges with weights less than
        k from the auxillary graph.  The resulting connected components are the
        k-edge-ccs in the original graph.
        """
        if k < 1:
            raise ValueError('k cannot be less than 1')
        A = self.A
        # "traverse the auxiliary graph A and delete all edges with weights less
        # than k"
        aux_weights = nx.get_edge_attributes(A, 'weight')
        # Create a relevant graph with the auxillary edges with weights >= k
        R = nx.Graph()
        R.add_nodes_from(A.nodes())
        R.add_edges_from(e for e, w in aux_weights.items() if w >= k)

        # Return the nodes that are k-edge-connected in the original graph
        for cc in nx.connected_components(R):
            yield cc 
Example #24
Source File: network_analysis.py    From ditto with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def provide_network(self, network):
        """TODO"""
        if not isinstance(network, Network):
            raise TypeError(
                "provide_network expects a Network instance. A {t} was provided.".format(
                    t=type(network)
                )
            )
        self.G = network
        self.G.set_attributes(self.model)
        self.edge_equipment = nx.get_edge_attributes(self.G.graph, "equipment")
        self.edge_equipment_name = nx.get_edge_attributes(
            self.G.graph, "equipment_name"
        ) 
Example #25
Source File: good_structure.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
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') 
Example #26
Source File: network.py    From ditto with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_upstream_transformer(self, model, node):

        curr_node = node
        curr = list(self.digraph.predecessors(node))
        edge_equipment = nx.get_edge_attributes(self.digraph, "equipment")
        edge_equipment_name = nx.get_edge_attributes(self.digraph, "equipment_name")
        # import pdb; pdb.set_trace()
        while curr != []:
            edge_type = edge_equipment[(curr[0], curr_node)]
            if edge_type == "PowerTransformer":
                return edge_equipment_name[(curr[0], curr_node)]
            curr_node = curr[0]  # assuming that the network is a DAG
            curr = list(self.digraph.predecessors(curr_node))
        return None 
Example #27
Source File: show_task.py    From costar_plan with Apache License 2.0 5 votes vote down vote up
def showTask(task, root="ROOT()", filename="task.dot"):
    import matplotlib.pyplot as plt

    g = nx.DiGraph()

    nodes = [root]
    visited = set()
    nodelist = []

    print(root)
    print(task.nodeSummary())

    while len(nodes) > 0:
        node = nodes.pop()
        visited.add(node)
        children = task.children[node]
        print("NODE =", node, "CHILDREN =")
        weights = task.weights[node]
        if len(weights) > 0:
            for child, wt in zip(children, weights):
                print("\t",child,"weight =", wt)
                g.add_edge(node, child, weight=int(wt))
                nodelist.append(child)
                if child not in visited:
                    print("\t\tadding", child)
                    nodes.append(child)
        elif len(children) > 0:
            raise RuntimeError('weights not initialized')

    pos = nx.nx_agraph.graphviz_layout(g, prog="dot")
    nx.draw_networkx_edges(g, pos, width=1.0, alpha=1., arrows=False)
    nx.draw(g, pos, prog='dot', node_size=1000, nodelist=nodelist,
            width=1.0, alpha=1., arrows=True, with_labels=True,)
    labels = nx.get_edge_attributes(g,'weight')
    nx.draw_networkx_edge_labels(g,pos,edge_labels=labels)
    #a = nx.nx_agraph.to_agraph(g)
    #a.draw('ex.png', prog='dot')
    plt.axis('off')
    plt.show() 
Example #28
Source File: transaction_graph_generator.py    From AMLSim with Apache License 2.0 5 votes vote down vote up
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)) 
Example #29
Source File: visualise_graph.py    From IDTxl with GNU General Public License v3.0 5 votes vote down vote up
def _plot_graph(graph, axis, weights=None, display_edge_labels=True):
    """Plot graph using networkx."""
    pos = nx.circular_layout(graph)
    nx.draw_circular(graph, with_labels=True, node_size=600, alpha=1.0,
                     ax=axis, node_color='Gainsboro', hold=True, font_size=14,
                     font_weight='bold')
    if display_edge_labels:
        edge_labels = nx.get_edge_attributes(graph, weights)
        nx.draw_networkx_edge_labels(graph, pos, edge_labels=edge_labels,
                                     font_size=13)  # font_weight='bold' 
Example #30
Source File: utilities.py    From entropica_qaoa with Apache License 2.0 5 votes vote down vote up
def hamiltonian_from_graph(G: nx.Graph) -> PauliSum:
    """
    Builds a cost Hamiltonian as a PauliSum from a specified networkx graph,
    extracting any node biases and edge weights.

    Parameters
    ----------
    G:
        The networkx graph of interest.

    Returns
    -------
    PauliSum:
        The PauliSum representation of the networkx graph.

    """

    hamiltonian = []

    # Node bias terms
    bias_nodes = [*nx.get_node_attributes(G, 'weight')]
    biases = [*nx.get_node_attributes(G, 'weight').values()]

    for node, bias in zip(bias_nodes, biases):
        hamiltonian.append(PauliTerm("Z", node, bias))

    # Edge terms
    edges = list(G.edges)
    edge_weights = [*nx.get_edge_attributes(G, 'weight').values()]

    for edge, weight in zip(edges, edge_weights):
        hamiltonian.append(PauliTerm("Z", edge[0], weight) *
                           PauliTerm("Z", edge[1]))

    return PauliSum(hamiltonian)