Python scipy.sparse.csgraph.minimum_spanning_tree() Examples

The following are code examples for showing how to use scipy.sparse.csgraph.minimum_spanning_tree(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 6 votes vote down vote up
def mst_edges(V, k):
    """
    Construct the approximate minimum spanning tree from vectors V

    :param: V: 2D array, sequence of vectors
    :param: k: int the number of neighbor to consider for each vector
    :return: V ndarray of edges forming the MST
    """

    # k = len(X)-1 gives the exact MST
    k = min(len(V) - 1, k)

    # generate a sparse graph using the k nearest neighbors of each point
    G = kneighbors_graph(V, n_neighbors=k, mode='distance')

    # Compute the minimum spanning tree of this graph
    full_tree = minimum_spanning_tree(G, overwrite=True)

    return np.array(full_tree.nonzero()).T 
Example 2
Project: DBCV   Author: christopherjenness   File: DBCV.py    MIT License 6 votes vote down vote up
def _mutual_reach_dist_MST(dist_tree):
    """
    Computes minimum spanning tree of the mutual reach distance complete graph

    Args:
        dist_tree (np.ndarray): array of dimensions (n_samples, n_samples)
            Graph of all pair-wise mutual reachability distances
            between points.

    Returns: minimum_spanning_tree (np.ndarray)
        array of dimensions (n_samples, n_samples)
        minimum spanning tree of all pair-wise mutual reachability
            distances between points.
    """
    mst = minimum_spanning_tree(dist_tree).toarray()
    return mst + np.transpose(mst) 
Example 3
Project: HashCode   Author: sbrodehl   File: best_solution_in_the_wuuuuuuurld.py    Apache License 2.0 6 votes vote down vote up
def _place_mst_paths(d, routers, idx, idy, dists):
    # calc mst
    mat = csr_matrix((dists, (idx, idy)), shape=(len(routers), len(routers)))
    Tmat = minimum_spanning_tree(mat).toarray()

    # place cabels
    for i, r in enumerate(Tmat):
        for j, c in enumerate(r):
            if Tmat[i, j] > 0:
                cables = find_chess_connection(routers[i], routers[j])
                for cable in cables:
                    if cable == d['backbone']:
                        continue
                    if d['graph'][cable] == Cell.Router:
                        d['graph'][cable] = Cell.ConnectedRouter
                    else:
                        d['graph'][cable] = Cell.Cable

    for router in routers:
        if router == d['backbone']:
            continue
        d['graph'][router] = Cell.ConnectedRouter

    return d 
Example 4
Project: treecat   Author: posterior   File: structure.py    Apache License 2.0 6 votes vote down vote up
def estimate_tree(grid, edge_logits):
    """Compute a maximum likelihood spanning tree of a dense weighted graph.

    Args:
        grid: A 3 x K array as returned by make_complete_graph().
        edge_logits: A length-K array of nonnormalized log probabilities.

    Returns:
        A list of (vertex, vertex) pairs.
    """
    K = len(edge_logits)
    assert grid.shape == (3, K)
    weights = triangular_to_square(grid, edge_logits)
    weights *= -1
    weights -= weights.min()
    weights += 1.0
    csr = minimum_spanning_tree(weights, overwrite=True)
    coo = csr.tocoo()
    edges = zip(coo.row, coo.col)
    edges = sorted(tuple(sorted(pair)) for pair in edges)
    assert len(edges) == weights.shape[0] - 1
    return edges 
Example 5
Project: netviewP   Author: esteinig   File: netview.py    GNU General Public License v2.0 5 votes vote down vote up
def runNetView(self, tree=True, start=10, stop=40, step=10, algorithm='auto', edges=False, html=True):

        print(get_time() + "\t" + "Minimum Spanning Tree = " + str(tree).upper())
        print(get_time() + "\t" + "Nearest Neighbour = " + algorithm.upper())
        print(get_time() + "\t" + "k = " + str(start) + " - " + str(stop) + ' (by ' + str(step) + ')')
        print(get_time() + "\t" + "---------------------------------")

        self.data.netview_runs += 1
        
        matrix = self.data.matrix

        if tree:
            mst = csg.minimum_spanning_tree(matrix)
            mst = mst.toarray()
            #self.data.networks[self.data.prefix + 'mst_' + str(self.data.netview_runs)] = mst
            mst = mst + mst.T
        else:
            mst = None

        pool = mp.Pool()
        networks = [pool.apply_async(netview, args=(matrix, k, mst, algorithm, tree,), callback=netview_callback)
                    for k in range(start, stop+1, step)]
        pool.close()
        pool.join()

        for item in networks:
            result = item.get()
            self.data.networks['netview_k' + str(result[0]) + '_' + str(self.data.netview_runs)] = result
        print(get_time() + "\t" + "---------------------------------")

        if html:
            print(get_time() + "\t" + "Out = JSON")
            self.data.writeData(f='json')
        if edges:
            self.data.writeData(f='edges')
            print(get_time() + "\t" + "Out = Edges") 
Example 6
Project: netviewP   Author: esteinig   File: netview.py    GNU General Public License v2.0 5 votes vote down vote up
def runNetView(self, tree=True, start=10, stop=40, step=10, algorithm='auto', edges=False, html=True):

        print(get_time() + "\t" + "Minimum Spanning Tree = " + str(tree).upper())
        print(get_time() + "\t" + "Nearest Neighbour = " + algorithm.upper())
        print(get_time() + "\t" + "k = " + str(start) + " - " + str(stop) + ' (by ' + str(step) + ')')
        print(get_time() + "\t" + "---------------------------------")

        self.data.netview_runs += 1
        
        matrix = self.data.matrix

        if tree:
            mst = csg.minimum_spanning_tree(matrix)
            mst = mst.toarray()
            #self.data.networks[self.data.prefix + 'mst_' + str(self.data.netview_runs)] = mst
            mst = mst + mst.T
        else:
            mst = None

        pool = mp.Pool()
        networks = [pool.apply_async(netview, args=(matrix, k, mst, algorithm, tree,), callback=netview_callback)
                    for k in range(start, stop+1, step)]
        pool.close()
        pool.join()

        for item in networks:
            result = item.get()
            self.data.networks['netview_k' + str(result[0]) + '_' + str(self.data.netview_runs)] = result
        print(get_time() + "\t" + "---------------------------------")

        if html:
            print(get_time() + "\t" + "Out = JSON")
            self.data.writeData(f='json')
        if edges:
            self.data.writeData(f='edges')
            print(get_time() + "\t" + "Out = Edges") 
Example 7
Project: viznet   Author: GiggleLiu   File: logo.py    MIT License 5 votes vote down vote up
def logo3():
    viznet.setting.node_setting['inner_lw'] = 0
    viznet.setting.node_setting['lw'] = 0
    npoint = 60
    nedge = 50
    angle = random(npoint)*2*np.pi
    #r = np.exp(randn(npoint)*0.4)
    r = np.sqrt(randn(npoint))
    xy = np.array([r*np.cos(angle), r*np.sin(angle)]).T
    #xy = randn(npoint, 2)*0.5
    with viznet.DynamicShow(figsize=(4,4), filename='_logo3.png') as ds:
        #body = viznet.NodeBrush('tn.mps', size='huge', color='#AACCFF') >> (0, 0)
        dot = viznet.NodeBrush('tn.mps', size='tiny')
        node_list = []
        for i, p in enumerate(xy):
            dot.color = random(3)*0.5+0.5
            dot.zorder = 100+i*2
            dot.size = 0.05+0.08*random()
            node_list.append(dot >> p)
        dis_mat = np.linalg.norm(xy-xy[:,None,:], axis=-1)
        tree = minimum_spanning_tree(dis_mat).tocoo()
        for i, j in zip(tree.row, tree.col):
            n1,n2=node_list[i],node_list[j]
            viznet.EdgeBrush(choice(['.>.', '.>.']), lw=1, color=random([3])*0.4, zorder=(n1.obj.zorder+n2.obj.zorder)/2) >> (n1,n2)
        #for i in range(nedge):
        #    n1, n2 =choice(node_list),choice(node_list)
         #   viznet.EdgeBrush(choice(['.>.', '->-']), lw=1, color=random([3])*0.4, zorder=(n1.obj.zorder+n2.obj.zorder)/2) >> (n1,n2) 
Example 8
Project: scanpy   Author: theislab   File: _paga.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_connectivities_tree_v1_2(self):
        inverse_connectivities = self.connectivities.copy()
        inverse_connectivities.data = 1./inverse_connectivities.data
        connectivities_tree = minimum_spanning_tree(inverse_connectivities)
        connectivities_tree_indices = [
            connectivities_tree[i].nonzero()[1]
            for i in range(connectivities_tree.shape[0])]
        connectivities_tree = sp.sparse.lil_matrix(self.connectivities.shape, dtype=float)
        for i, neighbors in enumerate(connectivities_tree_indices):
            if len(neighbors) > 0:
                connectivities_tree[i, neighbors] = self.connectivities[i, neighbors]
        return connectivities_tree.tocsr() 
Example 9
Project: scanpy   Author: theislab   File: _paga.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_connectivities_tree_v1_0(self, inter_es):
        inverse_inter_es = inter_es.copy()
        inverse_inter_es.data = 1./inverse_inter_es.data
        connectivities_tree = minimum_spanning_tree(inverse_inter_es)
        connectivities_tree_indices = [
            connectivities_tree[i].nonzero()[1]
            for i in range(connectivities_tree.shape[0])]
        connectivities_tree = sp.sparse.lil_matrix(inter_es.shape, dtype=float)
        for i, neighbors in enumerate(connectivities_tree_indices):
            if len(neighbors) > 0:
                connectivities_tree[i, neighbors] = self.connectivities[i, neighbors]
        return connectivities_tree.tocsr() 
Example 10
Project: 2019-ICML-COMIC   Author: limit-scu   File: comic.py    MIT License 5 votes vote down vote up
def m_knn(X, k, measure='cosine'):
       
        samples = X.shape[0]
        batch_size = 10000
        b = np.arange(k+1)
        b = tuple(b[1:].ravel())

        z = np.zeros((samples, k))
        weigh = np.zeros_like(z)

        for x in np.arange(0, samples, batch_size):
            start = x
            end = min(x+batch_size, samples)

            w = distance.cdist(X[start:end], X, measure)

            y = np.argpartition(w, b, axis=1)

            z[start:end, :] = y[:, 1:k + 1]
            weigh[start:end, :] = np.reshape(w[tuple(np.repeat(np.arange(end-start), k)),
                                               tuple(y[:, 1:k+1].ravel())], (end-start, k))
            del w

        ind = np.repeat(np.arange(samples), k)

        P = csr_matrix((np.ones((samples*k)), (ind.ravel(), z.ravel())), shape=(samples, samples))
        Q = csr_matrix((weigh.ravel(), (ind.ravel(), z.ravel())), shape=(samples, samples))

        Tcsr = minimum_spanning_tree(Q)
        P = P.minimum(P.transpose()) + Tcsr.maximum(Tcsr.transpose())
        P = triu(P, k=1)

        V = np.asarray(find(P)).T
        return V[:, :2].astype(np.int32) 
Example 11
Project: HashCode   Author: sbrodehl   File: best_solution_in_the_wuuuuuuurld.py    Apache License 2.0 5 votes vote down vote up
def _mst(d, new_router, routers=[], idx=[], idy=[], dists=[]):

    new_id = len(routers)

    # calc new router dists
    for i, a in enumerate(routers):
        dist = chessboard_dist(a, new_router)
        if dist > 0:
            idx.append(i)
            idy.append(new_id)
            dists.append(dist)

    # add new router
    routers.append(new_router)
    # create matrix
    mat = csr_matrix((dists, (idx, idy)), shape=(len(routers), len(routers)))

    # minimal spanning tree
    Tmat = minimum_spanning_tree(mat)

    # check costs
    cost = np.sum(Tmat) * d['price_backbone'] + (len(routers) - 1) * d['price_router']
    succ = cost <= d['original_budget']

    # return
    return succ, cost, routers, idx, idy, dists 
Example 12
Project: LaserTOF   Author: kyleuckert   File: test_spanning_tree.py    MIT License 4 votes vote down vote up
def test_minimum_spanning_tree():

    # Create a graph with two connected components.
    graph = [[0,1,0,0,0],
             [1,0,0,0,0],
             [0,0,0,8,5],
             [0,0,8,0,1],
             [0,0,5,1,0]]
    graph = np.asarray(graph)

    # Create the expected spanning tree.
    expected = [[0,1,0,0,0],
                [0,0,0,0,0],
                [0,0,0,0,5],
                [0,0,0,0,1],
                [0,0,0,0,0]]
    expected = np.asarray(expected)

    # Ensure minimum spanning tree code gives this expected output.
    csgraph = csr_matrix(graph)
    mintree = minimum_spanning_tree(csgraph)
    npt.assert_array_equal(mintree.todense(), expected,
        'Incorrect spanning tree found.')

    # Ensure that the original graph was not modified.
    npt.assert_array_equal(csgraph.todense(), graph,
        'Original graph was modified.')

    # Now let the algorithm modify the csgraph in place.
    mintree = minimum_spanning_tree(csgraph, overwrite=True)
    npt.assert_array_equal(mintree.todense(), expected,
        'Graph was not properly modified to contain MST.')

    np.random.seed(1234)
    for N in (5, 10, 15, 20):

        # Create a random graph.
        graph = 3 + np.random.random((N, N))
        csgraph = csr_matrix(graph)

        # The spanning tree has at most N - 1 edges.
        mintree = minimum_spanning_tree(csgraph)
        assert_(mintree.nnz < N)

        # Set the sub diagonal to 1 to create a known spanning tree.
        idx = np.arange(N-1)
        graph[idx,idx+1] = 1
        csgraph = csr_matrix(graph)
        mintree = minimum_spanning_tree(csgraph)

        # We expect to see this pattern in the spanning tree and otherwise
        # have this zero.
        expected = np.zeros((N, N))
        expected[idx, idx+1] = 1

        npt.assert_array_equal(mintree.todense(), expected,
            'Incorrect spanning tree found.') 
Example 13
Project: netviewP   Author: esteinig   File: netview.py    GNU General Public License v2.0 4 votes vote down vote up
def runNetView(self, tree=True, start=10, stop=40, step=10, algorithm='auto'):

        print(get_time() + "\t" + "Minimum Spanning Tree = " + str(tree).upper())
        print(get_time() + "\t" + "Nearest Neighbour = " + algorithm.upper())
        print(get_time() + "\t" + "k = " + str(start) + " - " + str(stop) + ' (by ' + str(step) + ')')
        print(get_time() + "\t" + "---------------------------------")

        self.data.netview_runs += 1
        
        matrix = self.data.matrix

        if tree:
            mst = csg.minimum_spanning_tree(matrix)
            mst = mst.toarray()
            self.data.networks['mst_' + str(self.data.netview_runs)] = mst
            mst = mst + mst.T
        else:
            mst = None

        pool = mp.Pool()
        networks = [pool.apply_async(netview, args=(matrix, k, mst, algorithm, tree,), callback=netview_callback)
                    for k in range(start, stop+1, step)]
        pool.close()
        pool.join()

        for item in networks:
            result = item.get()
            edges_array = result[1]
            edges = result[1].tolist()
            mst_edges = result[4].tolist()

            self.data.networks['netview_k' + str(result[0]) + '_' + str(self.data.netview_runs)] = result[1:]

            filename = self.data.prefix + '_netview_k'  + str(result[0]) +\
                       "_" + str(self.data.netview_runs) + '.edges'

            out = open(filename, "w")
            out.write('Source\tTarget\tDistance\tMST\n')
            for i in range(len(edges)):
                out.write(str(self.data.ids[edges[i][0]]) + "\t" + str(self.data.ids[edges[i][1]]) +
                          "\t" + str(matrix[edges[i][0], edges[i][1]]))
                if tree:
                    if edges[i] in mst_edges:
                        out.write('\t' + 'red\n')
                    else:
                        out.write('\t' + 'grey\n')
                else:
                    out.write("\n")

            if not tree:
                singletons = np.setdiff1d(np.arange(self.data.n), edges_array.flatten()).tolist()
                if singletons:
                    for node in singletons:
                        out.write(str(node) + '\n')
            out.close() 
Example 14
Project: netviewP   Author: esteinig   File: netview.py    GNU General Public License v2.0 4 votes vote down vote up
def runNetView(self, tree=True, start=10, stop=40, step=10, algorithm='auto'):

        print(get_time() + "\t" + "Minimum Spanning Tree = " + str(tree).upper())
        print(get_time() + "\t" + "Nearest Neighbour = " + algorithm.upper())
        print(get_time() + "\t" + "k = " + str(start) + " - " + str(stop) + ' (by ' + str(step) + ')')
        print(get_time() + "\t" + "---------------------------------")

        self.data.netview_runs += 1
        
        matrix = self.data.matrix

        if tree:
            mst = csg.minimum_spanning_tree(matrix)
            mst = mst.toarray()
            self.data.networks['mst_' + str(self.data.netview_runs)] = mst
            mst = mst + mst.T
        else:
            mst = None

        pool = mp.Pool()
        networks = [pool.apply_async(netview, args=(matrix, k, mst, algorithm, tree,), callback=netview_callback)
                    for k in range(start, stop+1, step)]
        pool.close()
        pool.join()

        for item in networks:
            result = item.get()
            edges_array = result[1]
            edges = result[1].tolist()
            mst_edges = result[4].tolist()

            self.data.networks['netview_k' + str(result[0]) + '_' + str(self.data.netview_runs)] = result[1:]

            filename = self.data.prefix + '_netview_k'  + str(result[0]) +\
                       "_" + str(self.data.netview_runs) + '.edges'

            out = open(filename, "w")
            out.write('Source\tTarget\tDistance\tMST\n')
            for i in range(len(edges)):
                out.write(str(self.data.ids[edges[i][0]]) + "\t" + str(self.data.ids[edges[i][1]]) +
                          "\t" + str(matrix[edges[i][0], edges[i][1]]))
                if tree:
                    if edges[i] in mst_edges:
                        out.write('\t' + 'red\n')
                    else:
                        out.write('\t' + 'grey\n')
                else:
                    out.write("\n")

            if not tree:
                singletons = np.setdiff1d(np.arange(self.data.n), edges_array.flatten()).tolist()
                if singletons:
                    for node in singletons:
                        out.write(str(node) + '\n')
            out.close() 
Example 15
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_spanning_tree.py    MIT License 4 votes vote down vote up
def test_minimum_spanning_tree():

    # Create a graph with two connected components.
    graph = [[0,1,0,0,0],
             [1,0,0,0,0],
             [0,0,0,8,5],
             [0,0,8,0,1],
             [0,0,5,1,0]]
    graph = np.asarray(graph)

    # Create the expected spanning tree.
    expected = [[0,1,0,0,0],
                [0,0,0,0,0],
                [0,0,0,0,5],
                [0,0,0,0,1],
                [0,0,0,0,0]]
    expected = np.asarray(expected)

    # Ensure minimum spanning tree code gives this expected output.
    csgraph = csr_matrix(graph)
    mintree = minimum_spanning_tree(csgraph)
    npt.assert_array_equal(mintree.todense(), expected,
        'Incorrect spanning tree found.')

    # Ensure that the original graph was not modified.
    npt.assert_array_equal(csgraph.todense(), graph,
        'Original graph was modified.')

    # Now let the algorithm modify the csgraph in place.
    mintree = minimum_spanning_tree(csgraph, overwrite=True)
    npt.assert_array_equal(mintree.todense(), expected,
        'Graph was not properly modified to contain MST.')

    np.random.seed(1234)
    for N in (5, 10, 15, 20):

        # Create a random graph.
        graph = 3 + np.random.random((N, N))
        csgraph = csr_matrix(graph)

        # The spanning tree has at most N - 1 edges.
        mintree = minimum_spanning_tree(csgraph)
        assert_(mintree.nnz < N)

        # Set the sub diagonal to 1 to create a known spanning tree.
        idx = np.arange(N-1)
        graph[idx,idx+1] = 1
        csgraph = csr_matrix(graph)
        mintree = minimum_spanning_tree(csgraph)

        # We expect to see this pattern in the spanning tree and otherwise
        # have this zero.
        expected = np.zeros((N, N))
        expected[idx, idx+1] = 1

        npt.assert_array_equal(mintree.todense(), expected,
            'Incorrect spanning tree found.') 
Example 16
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_spanning_tree.py    GNU General Public License v3.0 4 votes vote down vote up
def test_minimum_spanning_tree():

    # Create a graph with two connected components.
    graph = [[0,1,0,0,0],
             [1,0,0,0,0],
             [0,0,0,8,5],
             [0,0,8,0,1],
             [0,0,5,1,0]]
    graph = np.asarray(graph)

    # Create the expected spanning tree.
    expected = [[0,1,0,0,0],
                [0,0,0,0,0],
                [0,0,0,0,5],
                [0,0,0,0,1],
                [0,0,0,0,0]]
    expected = np.asarray(expected)

    # Ensure minimum spanning tree code gives this expected output.
    csgraph = csr_matrix(graph)
    mintree = minimum_spanning_tree(csgraph)
    npt.assert_array_equal(mintree.todense(), expected,
        'Incorrect spanning tree found.')

    # Ensure that the original graph was not modified.
    npt.assert_array_equal(csgraph.todense(), graph,
        'Original graph was modified.')

    # Now let the algorithm modify the csgraph in place.
    mintree = minimum_spanning_tree(csgraph, overwrite=True)
    npt.assert_array_equal(mintree.todense(), expected,
        'Graph was not properly modified to contain MST.')

    np.random.seed(1234)
    for N in (5, 10, 15, 20):

        # Create a random graph.
        graph = 3 + np.random.random((N, N))
        csgraph = csr_matrix(graph)

        # The spanning tree has at most N - 1 edges.
        mintree = minimum_spanning_tree(csgraph)
        assert_(mintree.nnz < N)

        # Set the sub diagonal to 1 to create a known spanning tree.
        idx = np.arange(N-1)
        graph[idx,idx+1] = 1
        csgraph = csr_matrix(graph)
        mintree = minimum_spanning_tree(csgraph)

        # We expect to see this pattern in the spanning tree and otherwise
        # have this zero.
        expected = np.zeros((N, N))
        expected[idx, idx+1] = 1

        npt.assert_array_equal(mintree.todense(), expected,
            'Incorrect spanning tree found.') 
Example 17
Project: DCC   Author: shahsohil   File: edgeConstruction.py    MIT License 4 votes vote down vote up
def mkNN(X, k, measure='euclidean'):
    """
    Construct mutual_kNN for large scale dataset

    If j is one of i's closest neighbors and i is also one of j's closest members,
    the edge will appear once with (i,j) where i < j.

    Parameters
    ----------
    X : [n_samples, n_dim] array
    k : int
      number of neighbors for each sample in X
    """
    from scipy.spatial import distance
    from scipy.sparse import csr_matrix, triu, find
    from scipy.sparse.csgraph import minimum_spanning_tree

    samples = X.shape[0]
    batchsize = 10000
    b = np.arange(k + 1)
    b = tuple(b[1:].ravel())

    z = np.zeros((samples, k))
    weigh = np.zeros_like(z)

    # This loop speeds up the computation by operating in batches
    # This can be parallelized to further utilize CPU/GPU resource
    for x in np.arange(0, samples, batchsize):
        start = x
        end = min(x + batchsize, samples)

        w = distance.cdist(X[start:end], X, measure)

        y = np.argpartition(w, b, axis=1)

        z[start:end, :] = y[:, 1:k + 1]
        weigh[start:end, :] = np.reshape(w[tuple(np.repeat(np.arange(end - start), k)), tuple(y[:, 1:k + 1].ravel())],
                                         (end - start, k))
        del (w)

    ind = np.repeat(np.arange(samples), k)

    P = csr_matrix((np.ones((samples * k)), (ind.ravel(), z.ravel())), shape=(samples, samples))
    Q = csr_matrix((weigh.ravel(), (ind.ravel(), z.ravel())), shape=(samples, samples))

    Tcsr = minimum_spanning_tree(Q)
    P = P.minimum(P.transpose()) + Tcsr.maximum(Tcsr.transpose())
    P = triu(P, k=1)

    return np.asarray(find(P)).T 
Example 18
Project: ble5-nrf52-mac   Author: tomasero   File: test_spanning_tree.py    MIT License 4 votes vote down vote up
def test_minimum_spanning_tree():

    # Create a graph with two connected components.
    graph = [[0,1,0,0,0],
             [1,0,0,0,0],
             [0,0,0,8,5],
             [0,0,8,0,1],
             [0,0,5,1,0]]
    graph = np.asarray(graph)

    # Create the expected spanning tree.
    expected = [[0,1,0,0,0],
                [0,0,0,0,0],
                [0,0,0,0,5],
                [0,0,0,0,1],
                [0,0,0,0,0]]
    expected = np.asarray(expected)

    # Ensure minimum spanning tree code gives this expected output.
    csgraph = csr_matrix(graph)
    mintree = minimum_spanning_tree(csgraph)
    npt.assert_array_equal(mintree.todense(), expected,
        'Incorrect spanning tree found.')

    # Ensure that the original graph was not modified.
    npt.assert_array_equal(csgraph.todense(), graph,
        'Original graph was modified.')

    # Now let the algorithm modify the csgraph in place.
    mintree = minimum_spanning_tree(csgraph, overwrite=True)
    npt.assert_array_equal(mintree.todense(), expected,
        'Graph was not properly modified to contain MST.')

    np.random.seed(1234)
    for N in (5, 10, 15, 20):

        # Create a random graph.
        graph = 3 + np.random.random((N, N))
        csgraph = csr_matrix(graph)

        # The spanning tree has at most N - 1 edges.
        mintree = minimum_spanning_tree(csgraph)
        assert_(mintree.nnz < N)

        # Set the sub diagonal to 1 to create a known spanning tree.
        idx = np.arange(N-1)
        graph[idx,idx+1] = 1
        csgraph = csr_matrix(graph)
        mintree = minimum_spanning_tree(csgraph)

        # We expect to see this pattern in the spanning tree and otherwise
        # have this zero.
        expected = np.zeros((N, N))
        expected[idx, idx+1] = 1

        npt.assert_array_equal(mintree.todense(), expected,
            'Incorrect spanning tree found.') 
Example 19
Project: pyrcc   Author: yhenon   File: rcc.py    MIT License 4 votes vote down vote up
def m_knn(X, k, measure='euclidean'):
        """
        This code is taken from:
        https://bitbucket.org/sohilas/robust-continuous-clustering/src/
        The original terms of the license apply.
        Construct mutual_kNN for large scale dataset

        If j is one of i's closest neighbors and i is also one of j's closest members,
        the edge will appear once with (i,j) where i < j.

        Parameters
        ----------
        X (array) 2d array of data of shape (n_samples, n_dim)
        k (int) number of neighbors for each sample in X
        measure (string) distance metric, one of 'cosine' or 'euclidean'
        """

        samples = X.shape[0]
        batch_size = 10000
        b = np.arange(k+1)
        b = tuple(b[1:].ravel())

        z = np.zeros((samples, k))
        weigh = np.zeros_like(z)

        # This loop speeds up the computation by operating in batches
        # This can be parallelized to further utilize CPU/GPU resource

        for x in np.arange(0, samples, batch_size):
            start = x
            end = min(x+batch_size, samples)

            w = distance.cdist(X[start:end], X, measure)

            y = np.argpartition(w, b, axis=1)

            z[start:end, :] = y[:, 1:k + 1]
            weigh[start:end, :] = np.reshape(w[tuple(np.repeat(np.arange(end-start), k)),
                                               tuple(y[:, 1:k+1].ravel())], (end-start, k))
            del w

        ind = np.repeat(np.arange(samples), k)

        P = csr_matrix((np.ones((samples*k)), (ind.ravel(), z.ravel())), shape=(samples, samples))
        Q = csr_matrix((weigh.ravel(), (ind.ravel(), z.ravel())), shape=(samples, samples))

        Tcsr = minimum_spanning_tree(Q)
        P = P.minimum(P.transpose()) + Tcsr.maximum(Tcsr.transpose())
        P = triu(P, k=1)

        V = np.asarray(find(P)).T
        return V[:, :2].astype(np.int32) 
Example 20
Project: Computable   Author: ktraunmueller   File: test_spanning_tree.py    MIT License 4 votes vote down vote up
def test_minimum_spanning_tree():

    # Create a graph with two connected components.
    graph = [[0,1,0,0,0],
             [1,0,0,0,0],
             [0,0,0,8,5],
             [0,0,8,0,1],
             [0,0,5,1,0]]
    graph = np.asarray(graph)

    # Create the expected spanning tree.
    expected = [[0,1,0,0,0],
                [0,0,0,0,0],
                [0,0,0,0,5],
                [0,0,0,0,1],
                [0,0,0,0,0]]
    expected = np.asarray(expected)

    # Ensure minimum spanning tree code gives this expected output.
    csgraph = csr_matrix(graph)
    mintree = minimum_spanning_tree(csgraph)
    npt.assert_array_equal(mintree.todense(), expected,
        'Incorrect spanning tree found.')

    # Ensure that the original graph was not modified.
    npt.assert_array_equal(csgraph.todense(), graph,
        'Original graph was modified.')

    # Now let the algorithm modify the csgraph in place.
    mintree = minimum_spanning_tree(csgraph, overwrite=True)
    npt.assert_array_equal(mintree.todense(), expected,
        'Graph was not properly modified to contain MST.')

    np.random.seed(1234)
    for N in (5, 10, 15, 20):

        # Create a random graph.
        graph = 3 + np.random.random((N, N))
        csgraph = csr_matrix(graph)

        # The spanning tree has at most N - 1 edges.
        mintree = minimum_spanning_tree(csgraph)
        assert_(mintree.nnz < N)

        # Set the sub diagonal to 1 to create a known spanning tree.
        idx = np.arange(N-1)
        graph[idx,idx+1] = 1
        csgraph = csr_matrix(graph)
        mintree = minimum_spanning_tree(csgraph)

        # We expect to see this pattern in the spanning tree and otherwise
        # have this zero.
        expected = np.zeros((N, N))
        expected[idx, idx+1] = 1

        npt.assert_array_equal(mintree.todense(), expected,
            'Incorrect spanning tree found.') 
Example 21
Project: poker   Author: surgebiswas   File: test_spanning_tree.py    MIT License 4 votes vote down vote up
def test_minimum_spanning_tree():

    # Create a graph with two connected components.
    graph = [[0,1,0,0,0],
             [1,0,0,0,0],
             [0,0,0,8,5],
             [0,0,8,0,1],
             [0,0,5,1,0]]
    graph = np.asarray(graph)

    # Create the expected spanning tree.
    expected = [[0,1,0,0,0],
                [0,0,0,0,0],
                [0,0,0,0,5],
                [0,0,0,0,1],
                [0,0,0,0,0]]
    expected = np.asarray(expected)

    # Ensure minimum spanning tree code gives this expected output.
    csgraph = csr_matrix(graph)
    mintree = minimum_spanning_tree(csgraph)
    npt.assert_array_equal(mintree.todense(), expected,
        'Incorrect spanning tree found.')

    # Ensure that the original graph was not modified.
    npt.assert_array_equal(csgraph.todense(), graph,
        'Original graph was modified.')

    # Now let the algorithm modify the csgraph in place.
    mintree = minimum_spanning_tree(csgraph, overwrite=True)
    npt.assert_array_equal(mintree.todense(), expected,
        'Graph was not properly modified to contain MST.')

    np.random.seed(1234)
    for N in (5, 10, 15, 20):

        # Create a random graph.
        graph = 3 + np.random.random((N, N))
        csgraph = csr_matrix(graph)

        # The spanning tree has at most N - 1 edges.
        mintree = minimum_spanning_tree(csgraph)
        assert_(mintree.nnz < N)

        # Set the sub diagonal to 1 to create a known spanning tree.
        idx = np.arange(N-1)
        graph[idx,idx+1] = 1
        csgraph = csr_matrix(graph)
        mintree = minimum_spanning_tree(csgraph)

        # We expect to see this pattern in the spanning tree and otherwise
        # have this zero.
        expected = np.zeros((N, N))
        expected[idx, idx+1] = 1

        npt.assert_array_equal(mintree.todense(), expected,
            'Incorrect spanning tree found.') 
Example 22
Project: P3_image_processing   Author: latedude2   File: test_spanning_tree.py    MIT License 4 votes vote down vote up
def test_minimum_spanning_tree():

    # Create a graph with two connected components.
    graph = [[0,1,0,0,0],
             [1,0,0,0,0],
             [0,0,0,8,5],
             [0,0,8,0,1],
             [0,0,5,1,0]]
    graph = np.asarray(graph)

    # Create the expected spanning tree.
    expected = [[0,1,0,0,0],
                [0,0,0,0,0],
                [0,0,0,0,5],
                [0,0,0,0,1],
                [0,0,0,0,0]]
    expected = np.asarray(expected)

    # Ensure minimum spanning tree code gives this expected output.
    csgraph = csr_matrix(graph)
    mintree = minimum_spanning_tree(csgraph)
    npt.assert_array_equal(mintree.todense(), expected,
        'Incorrect spanning tree found.')

    # Ensure that the original graph was not modified.
    npt.assert_array_equal(csgraph.todense(), graph,
        'Original graph was modified.')

    # Now let the algorithm modify the csgraph in place.
    mintree = minimum_spanning_tree(csgraph, overwrite=True)
    npt.assert_array_equal(mintree.todense(), expected,
        'Graph was not properly modified to contain MST.')

    np.random.seed(1234)
    for N in (5, 10, 15, 20):

        # Create a random graph.
        graph = 3 + np.random.random((N, N))
        csgraph = csr_matrix(graph)

        # The spanning tree has at most N - 1 edges.
        mintree = minimum_spanning_tree(csgraph)
        assert_(mintree.nnz < N)

        # Set the sub diagonal to 1 to create a known spanning tree.
        idx = np.arange(N-1)
        graph[idx,idx+1] = 1
        csgraph = csr_matrix(graph)
        mintree = minimum_spanning_tree(csgraph)

        # We expect to see this pattern in the spanning tree and otherwise
        # have this zero.
        expected = np.zeros((N, N))
        expected[idx, idx+1] = 1

        npt.assert_array_equal(mintree.todense(), expected,
            'Incorrect spanning tree found.') 
Example 23
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_spanning_tree.py    MIT License 4 votes vote down vote up
def test_minimum_spanning_tree():

    # Create a graph with two connected components.
    graph = [[0,1,0,0,0],
             [1,0,0,0,0],
             [0,0,0,8,5],
             [0,0,8,0,1],
             [0,0,5,1,0]]
    graph = np.asarray(graph)

    # Create the expected spanning tree.
    expected = [[0,1,0,0,0],
                [0,0,0,0,0],
                [0,0,0,0,5],
                [0,0,0,0,1],
                [0,0,0,0,0]]
    expected = np.asarray(expected)

    # Ensure minimum spanning tree code gives this expected output.
    csgraph = csr_matrix(graph)
    mintree = minimum_spanning_tree(csgraph)
    npt.assert_array_equal(mintree.todense(), expected,
        'Incorrect spanning tree found.')

    # Ensure that the original graph was not modified.
    npt.assert_array_equal(csgraph.todense(), graph,
        'Original graph was modified.')

    # Now let the algorithm modify the csgraph in place.
    mintree = minimum_spanning_tree(csgraph, overwrite=True)
    npt.assert_array_equal(mintree.todense(), expected,
        'Graph was not properly modified to contain MST.')

    np.random.seed(1234)
    for N in (5, 10, 15, 20):

        # Create a random graph.
        graph = 3 + np.random.random((N, N))
        csgraph = csr_matrix(graph)

        # The spanning tree has at most N - 1 edges.
        mintree = minimum_spanning_tree(csgraph)
        assert_(mintree.nnz < N)

        # Set the sub diagonal to 1 to create a known spanning tree.
        idx = np.arange(N-1)
        graph[idx,idx+1] = 1
        csgraph = csr_matrix(graph)
        mintree = minimum_spanning_tree(csgraph)

        # We expect to see this pattern in the spanning tree and otherwise
        # have this zero.
        expected = np.zeros((N, N))
        expected[idx, idx+1] = 1

        npt.assert_array_equal(mintree.todense(), expected,
            'Incorrect spanning tree found.') 
Example 24
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_spanning_tree.py    MIT License 4 votes vote down vote up
def test_minimum_spanning_tree():

    # Create a graph with two connected components.
    graph = [[0,1,0,0,0],
             [1,0,0,0,0],
             [0,0,0,8,5],
             [0,0,8,0,1],
             [0,0,5,1,0]]
    graph = np.asarray(graph)

    # Create the expected spanning tree.
    expected = [[0,1,0,0,0],
                [0,0,0,0,0],
                [0,0,0,0,5],
                [0,0,0,0,1],
                [0,0,0,0,0]]
    expected = np.asarray(expected)

    # Ensure minimum spanning tree code gives this expected output.
    csgraph = csr_matrix(graph)
    mintree = minimum_spanning_tree(csgraph)
    npt.assert_array_equal(mintree.todense(), expected,
        'Incorrect spanning tree found.')

    # Ensure that the original graph was not modified.
    npt.assert_array_equal(csgraph.todense(), graph,
        'Original graph was modified.')

    # Now let the algorithm modify the csgraph in place.
    mintree = minimum_spanning_tree(csgraph, overwrite=True)
    npt.assert_array_equal(mintree.todense(), expected,
        'Graph was not properly modified to contain MST.')

    np.random.seed(1234)
    for N in (5, 10, 15, 20):

        # Create a random graph.
        graph = 3 + np.random.random((N, N))
        csgraph = csr_matrix(graph)

        # The spanning tree has at most N - 1 edges.
        mintree = minimum_spanning_tree(csgraph)
        assert_(mintree.nnz < N)

        # Set the sub diagonal to 1 to create a known spanning tree.
        idx = np.arange(N-1)
        graph[idx,idx+1] = 1
        csgraph = csr_matrix(graph)
        mintree = minimum_spanning_tree(csgraph)

        # We expect to see this pattern in the spanning tree and otherwise
        # have this zero.
        expected = np.zeros((N, N))
        expected[idx, idx+1] = 1

        npt.assert_array_equal(mintree.todense(), expected,
            'Incorrect spanning tree found.') 
Example 25
Project: 2019-ICML-COMIC   Author: limit-scu   File: edgeConstruction.py    MIT License 4 votes vote down vote up
def mkNN(X, k, measure='euclidean'):
    """
    Construct mutual_kNN for large scale dataset

    If j is one of i's closest neighbors and i is also one of j's closest members,
    the edge will appear once with (i,j) where i < j.

    Parameters
    ----------
    X : [n_samples, n_dim] array
    k : int
      number of neighbors for each sample in X
    """
    from scipy.spatial import distance
    from scipy.sparse import csr_matrix, triu, find
    from scipy.sparse.csgraph import minimum_spanning_tree

    samples = X.shape[0]
    batchsize = 10000
    b = np.arange(k+1)
    b = tuple(b[1:].ravel())

    z=np.zeros((samples,k))
    weigh=np.zeros_like(z)

    # This loop speeds up the computation by operating in batches
    # This can be parallelized to further utilize CPU/GPU resource
    for x in np.arange(0, samples, batchsize):
        start = x
        end = min(x+batchsize,samples)

        w = distance.cdist(X[start:end], X, measure)

        y = np.argpartition(w, b, axis=1)

        z[start:end,:] = y[:, 1:k + 1]
        weigh[start:end,:] = np.reshape(w[tuple(np.repeat(np.arange(end-start), k)), tuple(y[:, 1:k+1].ravel())], (end-start, k))
        del(w)

    ind = np.repeat(np.arange(samples), k)

    P = csr_matrix((np.ones((samples*k)), (ind.ravel(), z.ravel())), shape=(samples,samples))
    Q = csr_matrix((weigh.ravel(), (ind.ravel(), z.ravel())), shape=(samples,samples))

    Tcsr = minimum_spanning_tree(Q)
    P = P.minimum(P.transpose()) + Tcsr.maximum(Tcsr.transpose())
    P = triu(P, k=1)

    return np.asarray(find(P)).T 
Example 26
Project: openelec   Author: carderne   File: network.py    GNU General Public License v3.0 4 votes vote down vote up
def spanning_tree(X, approximate=False):
    """
    Function to calculate the Minimum spanning tree connecting
    the provided points X.
    Modified from astroML code in mst_clustering.py

    Parameters
    ----------
    X: array_like
        2D array of shape (n_sample, 2) containing the x- and y-coordinates
        of the points.

    Returns
    -------
    x_coords, y_coords : ndarrays
        the x and y coordinates for plotting the graph.  They are of size
        [2, n_links], and can be visualized using
        ``plt.plot(x_coords, y_coords, '-k')``
    """

    if approximate:
        n_neighbors = 50

    else:
        n_neighbors = len(X) - 1

    n_neighbors = min(n_neighbors, len(X) - 1)
    if n_neighbors < 2:
        raise ValueError("Need at least three sample points")

    G = kneighbors_graph(X, n_neighbors=n_neighbors, mode="distance")
    full_tree = minimum_spanning_tree(G, overwrite=True)

    X = np.asarray(X)
    if X.ndim != 2 or X.shape[1] != 2:
        raise ValueError("shape of X should be (n_samples, 2)")

    coo = sparse.coo_matrix(full_tree)
    A = X[coo.row].T
    B = X[coo.col].T

    start_points = [(Ax, Ay) for Ax, Ay in zip(A[0], A[1])]
    end_points = [(Bx, By) for Bx, By in zip(B[0], B[1])]
    nodes_connected = [(s, e) for s, e in zip(coo.row, coo.col)]

    return start_points, end_points, nodes_connected 
Example 27
Project: wine-ml-on-aws-lambda   Author: pierreant   File: test_spanning_tree.py    Apache License 2.0 4 votes vote down vote up
def test_minimum_spanning_tree():

    # Create a graph with two connected components.
    graph = [[0,1,0,0,0],
             [1,0,0,0,0],
             [0,0,0,8,5],
             [0,0,8,0,1],
             [0,0,5,1,0]]
    graph = np.asarray(graph)

    # Create the expected spanning tree.
    expected = [[0,1,0,0,0],
                [0,0,0,0,0],
                [0,0,0,0,5],
                [0,0,0,0,1],
                [0,0,0,0,0]]
    expected = np.asarray(expected)

    # Ensure minimum spanning tree code gives this expected output.
    csgraph = csr_matrix(graph)
    mintree = minimum_spanning_tree(csgraph)
    npt.assert_array_equal(mintree.todense(), expected,
        'Incorrect spanning tree found.')

    # Ensure that the original graph was not modified.
    npt.assert_array_equal(csgraph.todense(), graph,
        'Original graph was modified.')

    # Now let the algorithm modify the csgraph in place.
    mintree = minimum_spanning_tree(csgraph, overwrite=True)
    npt.assert_array_equal(mintree.todense(), expected,
        'Graph was not properly modified to contain MST.')

    np.random.seed(1234)
    for N in (5, 10, 15, 20):

        # Create a random graph.
        graph = 3 + np.random.random((N, N))
        csgraph = csr_matrix(graph)

        # The spanning tree has at most N - 1 edges.
        mintree = minimum_spanning_tree(csgraph)
        assert_(mintree.nnz < N)

        # Set the sub diagonal to 1 to create a known spanning tree.
        idx = np.arange(N-1)
        graph[idx,idx+1] = 1
        csgraph = csr_matrix(graph)
        mintree = minimum_spanning_tree(csgraph)

        # We expect to see this pattern in the spanning tree and otherwise
        # have this zero.
        expected = np.zeros((N, N))
        expected[idx, idx+1] = 1

        npt.assert_array_equal(mintree.todense(), expected,
            'Incorrect spanning tree found.') 
Example 28
Project: dynamo-release   Author: aristoteleo   File: time_series.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def directed_pg(adata, basis='umap', maxIter=10, sigma=0.001, Lambda=None, gamma=10, ncenter=None, raw_embedding=True):
    """A function that learns a direct principal graph by integrating the transition matrix between and DDRTree.

    Parameters
    ----------
        adata: :class:`~anndata.AnnData`
            an Annodata object
        maxIter: `int` (default: 10)
            maximum iterations
        sigma: `float` (default: 0.001)
            bandwidth parameter
        Lambda: None or `float` (default: None)
            regularization parameter for inverse graph embedding
        ncenter: None or `int` (default: None)
            number of nodes allowed in the regularization graph
        gamma: `float` (default: 10)
            regularization parameter for k-means.
        raw_embedding: `bool` (default: True)
            Whether to project the nodes on the principal graph into the original embedding.

    Returns
    -------
        An updated AnnData object that is updated with principal_g_transition, X__DDRTree and and X_DDRTree_pg keys.

    """
    X = adata.obsm['X_' + basis].T if basis in adata.obsm.keys() else None
    if X is None:
        raise Exception('{} is not a key of obsm ({} dimension reduction is not performed yet.).'.format(basis, basis))

    transition_matrix = adata.uns['transition_matrix'] if 'transition_matrix' in adata.uns.keys() else None
    if transition_matrix is None:
        raise Exception('transition_matrix is not a key of uns. Please first run cell_velocity.')
    
    Lambda = 5 * X.shape[1] if Lambda is None else Lambda
    ncenter = 250 if cal_ncenter(X.shape[1]) is None else ncenter

    DDRTree_res = DDRTree_py(X, maxIter=maxIter, Lambda=Lambda, sigma=sigma, gamma=gamma, ncenter=ncenter)
    principal_g, cell_membership = DDRTree_res.loc[maxIter - 1, 'stree'], DDRTree_res.loc[maxIter - 1, 'R']

    X = csr_matrix(principal_g)
    Tcsr = minimum_spanning_tree(X)
    principal_g = Tcsr.toarray().astype(int)

    # here we can also identify siginificant links using methods related to PAGA
    principal_g_transition = cell_membership.T.dot(transition_matrix).dot(cell_membership) * principal_g

    adata.uns['principal_g_transition'] = principal_g_transition
    adata.obsm['X_DDRTree'] = X.T if raw_embedding else DDRTree_res.loc[maxIter - 1, 'Z']
    adata.uns['X_DDRTree_pg'] = cell_membership.dot(X.T) if raw_embedding else DDRTree_res.loc[maxIter - 1, 'Y']

    return adata 
Example 29
Project: loons   Author: juliakreutzer   File: visualize.py    Apache License 2.0 4 votes vote down vote up
def getSimMSTs(self, inverse=True, plotGraph=True, root="UNK"):
        rootId1 = self.emb1.d[root]
        rootId2 = self.emb2.d[root]
        if inverse == True:
            d = -1
        else:
            d = 1
        g1 = minimum_spanning_tree(csr_matrix(d*self.s1))
        g2 = minimum_spanning_tree(csr_matrix(d*self.s2))

        a1 = g1.toarray()
        a2 = g2.toarray()

        if plotGraph==True:
            t1 = Graph()
            t2 = Graph()
            t3 = Graph()
            t1.add_vertices(self.emb1.vocab_size)
            t2.add_vertices(self.emb2.vocab_size)
            t3.add_vertices(self.emb1.vocab_size)
            t1.vs["color"] = "white"
            t2.vs["color"] = "white"
            t3.vs["color"] = "white"
            t1.vs["label"] = [w for w,i in sorted(self.emb1.d.items(), key=itemgetter(1))]
            t2.vs["label"] = [w for w,i in sorted(self.emb2.d.items(), key=itemgetter(1))]
            t3.vs["label"] = t1.vs["label"]
            for i in xrange(a1.shape[0]):
                for j in xrange(a1.shape[1]):
                    if a1[i,j] != 0:
                        t1.add_edge(i,j, weight=a1[i,j], color="blue")
                        t3.add_edge(i,j, weight=a1[i,j], color="blue")
            for i in xrange(a2.shape[0]):
                for j in xrange(a2.shape[1]):
                    if a2[i,j] != 0:
                        t2.add_edge(i,j, weight=a2[i,j], color="red")
                        if t3.are_connected(i,j): #edge in both MSTs
                            t3.es[i,j]["color"] = "black"
                        else:
                            t3.add_edge(i,j, weight=a1[i,j], color="red")
            layout1 = t1.layout_reingold_tilford(mode="in", root=rootId1)
            layout2 = t2.layout_reingold_tilford(mode="in", root=rootId2)
            layout3 = t3.layout_reingold_tilford(mode="in", root=rootId1)
            graphs = [Graph.GRG(10, 0.4) for _ in xrange(5)]
            figure = Plot(bbox=(0,0,2000,1000))
            figure.add(t1, layout=layout1, margin=100, bbox=(0,0,1000,1000))
            figure.add(t2, layout=layout2, margin=100, bbox=(1000,0,2000,1000))
            plotname1 = "plots/"+NAME+".mst_trees.png"
            figure.save(plotname1)
            plotname3 = "plots/"+NAME+".merged_mst.png"
            plot(t3, plotname3 , layout=layout3, bbox=(1000,1000), margin=100)
            print("\tSaved MST plots in '%s', '%s'" % (plotname1, plotname3))

        return t1,t2,t3