Example #1
0
    def test_multigraph_keys_max(self):
        """Tests that the maximum spanning edges of a multigraph
        preserves edge keys.

        """
        G = nx.MultiGraph()
        G.add_edge(0, 1, key="a", weight=2)
        G.add_edge(0, 1, key="b", weight=1)
        mst_edges = nx.maximum_spanning_edges(G, algorithm="kruskal", data=False)
        assert_equal([(0, 1, "a")], list(mst_edges))
        mst_edges = nx.maximum_spanning_edges(G, algorithm="prim", data=False)
        assert_equal([(0, 1, "a")], list(mst_edges))
Example #2
0
    def test_multigraph_keys_max(self):
        """Tests that the maximum spanning edges of a multigraph
        preserves edge keys.

        """
        G = nx.MultiGraph()
        G.add_edge(0, 1, key='a', weight=2)
        G.add_edge(0, 1, key='b', weight=1)
        mst_edges = nx.maximum_spanning_edges(G,
                                              algorithm='kruskal',
                                              data=False)
        assert_equal([(0, 1, 'a')], list(mst_edges))
        mst_edges = nx.maximum_spanning_edges(G, algorithm='prim', data=False)
        assert_equal([(0, 1, 'a')], list(mst_edges))
Example #3
0
def _get_n_best_paf_graphs(
    data,
    metadata,
    full_graph,
    n_graphs=10,
    root=None,
    which="best",
    ignore_inds=None,
    metric="auc",
):
    if which not in ("best", "worst"):
        raise ValueError('`which` must be either "best" or "worst"')

    (within_train, _), (between_train, _) = _calc_within_between_pafs(
        data,
        metadata,
        train_set_only=True,
    )
    # Handle unlabeled bodyparts...
    existing_edges = set(k for k, v in within_train.items() if v)
    if ignore_inds is not None:
        existing_edges = existing_edges.difference(ignore_inds)
    existing_edges = list(existing_edges)

    if not any(between_train.values()):
        # Only 1 animal, let us return the full graph indices only
        return ([existing_edges],
                dict(zip(existing_edges, [0] * len(existing_edges))))

    scores, _ = zip(*[
        _calc_separability(between_train[n], within_train[n], metric=metric)
        for n in existing_edges
    ])

    # Find minimal skeleton
    G = nx.Graph()
    for edge, score in zip(existing_edges, scores):
        if np.isfinite(score):
            G.add_edge(*full_graph[edge], weight=score)
    if which == "best":
        order = np.asarray(existing_edges)[np.argsort(scores)[::-1]]
        if root is None:
            root = []
            for edge in nx.maximum_spanning_edges(G, data=False):
                root.append(full_graph.index(sorted(edge)))
    else:
        order = np.asarray(existing_edges)[np.argsort(scores)]
        if root is None:
            root = []
            for edge in nx.minimum_spanning_edges(G, data=False):
                root.append(full_graph.index(sorted(edge)))

    n_edges = len(existing_edges) - len(root)
    lengths = np.linspace(0, n_edges, min(n_graphs, n_edges + 1),
                          dtype=int)[1:]
    order = order[np.isin(order, root, invert=True)]
    paf_inds = [root]
    for length in lengths:
        paf_inds.append(root + list(order[:length]))
    return paf_inds, dict(zip(existing_edges, scores))
Example #4
0
 def test_kruskal_maximum_spanning_edges(self):
     edgelist = sorted(nx.maximum_spanning_edges(self.G, algorithm="kruskal"))
     assert_equal(edgelist, self.maximum_spanning_edgelist)
Example #5
0
 def test_prim_maximum_spanning_edges(self):
     edgelist = sorted(nx.maximum_spanning_edges(self.G, algorithm="prim"))
     edgelist = sorted((sorted((u, v))[0], sorted((u, v))[1], d) for u, v, d in edgelist)
     assert_equal(edgelist, self.maximum_spanning_edgelist)
Example #6
0
 def test_maximum_edges(self):
     edges = nx.maximum_spanning_edges(self.G, algorithm=self.algo)
     # Edges from the spanning edges functions don't come in sorted
     # orientation, so we need to sort each edge individually.
     actual = sorted((min(u, v), max(u, v), d) for u, v, d in edges)
     assert_edges_equal(actual, self.maximum_spanning_edgelist)
Example #7
0
 def test_maximum_edges(self):
     edges = nx.maximum_spanning_edges(self.G, algorithm=self.algo)
     # Edges from the spanning edges functions don't come in sorted
     # orientation, so we need to sort each edge individually.
     actual = sorted((min(u, v), max(u, v), d) for u, v, d in edges)
     assert_edges_equal(actual, self.maximum_spanning_edgelist)
Example #8
0
 def test_kruskal_maximum_spanning_edges(self):
     edgelist = sorted(nx.maximum_spanning_edges(self.G, algorithm='kruskal'))
     assert_equal(edgelist, self.maximum_spanning_edgelist)
Example #9
0
 def test_prim_maximum_spanning_edges(self):
     edgelist = sorted(nx.maximum_spanning_edges(self.G, algorithm='prim'))
     edgelist = sorted((sorted((u, v))[0], sorted((u, v))[1], d)
                       for u, v, d in edgelist)
     assert_equal(edgelist, self.maximum_spanning_edgelist)
    #TIP: #TODO: Write your code here to calculate the required metrics, compute the
    #TIP: # thresholded network, maximal and minimal spanning tree, and visualize the networks
    #TIP: # Remember you can use the networkx functions
    print(f'Nnumber of nodes: {len(nx.nodes(net))}')
    print(f'Number of edges: {len(nx.edges(net))}')
    print(f'Density: {nx.density(net)}')
    print(f'Diameter: {nx.diameter(net)}')
    print(f'Average clustering coefficient: {nx.average_clustering(net)}')
    fig1 = plot_network_usa(net, xycoords, bg_figname)
    fig1[0].savefig('./full_network.png')
    min_st = list(nx.minimum_spanning_edges(net))
    fig2 = plot_network_usa(net, xycoords, bg_figname, min_st)
    plt.suptitle("Minimal spanning tree", size=20)
    fig2[0].savefig('./Minimal_spanning_tree.png')

    max_st = list(nx.maximum_spanning_edges(net))
    fig3 = plot_network_usa(net, xycoords, bg_figname, max_st)
    plt.suptitle("Maximal spanning tree", size=20)
    fig3[0].savefig('./Maximal_spanning_tree.png')

    # strongest M links
    max_m = len(max_st)
    edges_max_st = sorted(net.edges(data=True),
                          key=lambda x: x[2]['weight'],
                          reverse=True)
    fig4 = plot_network_usa(net, xycoords, bg_figname, edges_max_st[0:max_m])
    plt.suptitle(f'Strongest {max_m} links (maximal spanning tree)', size=20)
    fig4[0].savefig('./strongest_M_links_MST.png')

    count = 0
    for edge1 in edges_max_st[0:max_m]: