Python scipy.sparse.csgraph.connected_components() Examples

The following are code examples for showing how to use scipy.sparse.csgraph.connected_components(). 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: DCC   Author: shahsohil   File: DCCComputation.py    MIT License 6 votes vote down vote up
def computeObj(U, pairs, _delta, gtlabels, numeval):
    """ This is similar to computeObj function in Matlab """
    numsamples = len(U)
    diff = np.linalg.norm(U[pairs[:, 0].astype(int)] - U[pairs[:, 1].astype(int)], axis=1)**2

    # computing clustering measures
    index1 = np.sqrt(diff) < _delta
    index = np.where(index1)
    adjacency = csr_matrix((np.ones(len(index[0])), (pairs[index[0], 0].astype(int), pairs[index[0], 1].astype(int))),
                           shape=(numsamples, numsamples))
    adjacency = adjacency + adjacency.transpose()
    n_components, labels = connected_components(adjacency, directed=False)

    index2 = labels[pairs[:, 0].astype(int)] == labels[pairs[:, 1].astype(int)]

    ari, ami, nmi, acc = benchmarking(gtlabels[:numeval], labels[:numeval])

    return index2, ari, ami, nmi, acc, n_components, labels 
Example 2
Project: pyrcc   Author: yhenon   File: rcc.py    MIT License 6 votes vote down vote up
def compute_assignment(self, epsilon):
        """
        Assigns points to clusters based on their representative. Two points are part of the same cluster if their
        representative are close enough (their squared euclidean distance is < delta)
        """
        diff = np.sum((self.U[self.i, :] - self.U[self.j, :])**2, axis=1)

        # computing connected components.
        is_conn = np.sqrt(diff) <= self.clustering_threshold*epsilon

        G = scipy.sparse.coo_matrix((np.ones((2*np.sum(is_conn),)),
                                     (np.concatenate([self.i[is_conn], self.j[is_conn]], axis=0),
                                      np.concatenate([self.j[is_conn], self.i[is_conn]], axis=0))),
                                    shape=[self.n_samples, self.n_samples])

        num_components, labels = connected_components(G, directed=False)

        return labels, num_components 
Example 3
Project: 2019-ICML-COMIC   Author: limit-scu   File: comic.py    MIT License 6 votes vote down vote up
def compute_assignment(self, epsilon_list):
        ret = {}
        is_conn_list = []
        for view in range(self.view_size):
            # computing connected components.
            diff = self.EuclideanDistances(self.Z_list[view], self.Z_list[view])
            is_conn = np.sqrt(diff) <= self.clustering_threshold*epsilon_list[view]
            is_conn = is_conn + 0
            is_conn_list.append(is_conn)
        
        conn = 0
        for is_conn in is_conn_list:
            conn = conn + is_conn
        conn = conn > self.view_size/2

        G = scipy.sparse.coo_matrix(conn)
        num_components, labels = connected_components(G, directed=False)
        ret['vote'] = labels

        return ret 
Example 4
Project: wine-ml-on-aws-lambda   Author: pierreant   File: spectral_embedding_.py    Apache License 2.0 6 votes vote down vote up
def _graph_is_connected(graph):
    """ Return whether the graph is connected (True) or Not (False)

    Parameters
    ----------
    graph : array-like or sparse matrix, shape: (n_samples, n_samples)
        adjacency matrix of the graph, non-zero weight means an edge
        between the nodes

    Returns
    -------
    is_connected : bool
        True means the graph is fully connected and False means not
    """
    if sparse.isspmatrix(graph):
        # sparse graph, find all the connected components
        n_connected_components, _ = connected_components(graph)
        return n_connected_components == 1
    else:
        # dense graph, find all connected components start from node 0
        return _graph_connected_component(graph, 0).sum() == graph.shape[0] 
Example 5
Project: design_embeddings_jmd_2016   Author: IDEALLab   File: util.py    MIT License 5 votes vote down vote up
def get_geo_dist(X, K='auto', verbose=0):
    
    m = X.shape[0]
    
    if K == 'auto':
        # Choose the smallest k that gives a fully connected graph
        for k in range(2, m):
            G = create_graph(X, k, verbose=verbose)
            if connected_components(G, directed=False, return_labels=False) == 1:
                break;
        return G, k
        
    else:
        return create_graph(X, K, verbose=verbose) 
Example 6
Project: design_embeddings_jmd_2016   Author: IDEALLab   File: util.py    MIT License 5 votes vote down vote up
def get_k_range(X, verbose=0):
    
    N = X.shape[0]
        
    # Select k_min
    for k in range(1, N):
        G = create_graph(X, k, include_self=False, verbose=verbose)
        if connected_components(G,directed=False,return_labels=False) == 1:
            break;
    k_min = k
    
    # Select k_max
    for k in range(k_min, N):
        kng = kneighbors_graph(X, k, include_self=False).toarray()
        A = np.logical_or(kng, kng.T) # convert to undirrected graph
        P = np.sum(A)/2
        if 2*P/float(N) > k+2:
            break;
    k_max = k-1#min(k_min+10, N)
    
    if verbose == 2:
        print 'k_range: [%d, %d]' % (k_min, k_max)
        
    if k_max < k_min:
        print 'No suitable neighborhood size!'
        
    return k_min, k_max 
Example 7
Project: nettack   Author: danielzuegner   File: utils.py    MIT License 5 votes vote down vote up
def largest_connected_components(adj, n_components=1):
    """Select the largest connected components in the graph.

    Parameters
    ----------
    sparse_graph : gust.SparseGraph
        Input graph.
    n_components : int, default 1
        Number of largest connected components to keep.

    Returns
    -------
    sparse_graph : gust.SparseGraph
        Subgraph of the input graph where only the nodes in largest n_components are kept.

    """
    _, component_indices = connected_components(adj)
    component_sizes = np.bincount(component_indices)
    components_to_keep = np.argsort(component_sizes)[::-1][:n_components]  # reverse order to sort descending
    nodes_to_keep = [
        idx for (idx, component) in enumerate(component_indices) if component in components_to_keep


    ]
    print("Selecting {0} largest connected components".format(n_components))
    return nodes_to_keep 
Example 8
Project: LaserTOF   Author: kyleuckert   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_weak_connections():
    Xde = np.array([[0, 1, 0],
                    [0, 0, 0],
                    [0, 0, 0]])

    Xsp = csgraph.csgraph_from_dense(Xde, null_value=0)

    for X in Xsp, Xde:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='weak')

        assert_equal(n_components, 2)
        assert_array_almost_equal(labels, [0, 0, 1]) 
Example 9
Project: LaserTOF   Author: kyleuckert   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_strong_connections():
    X1de = np.array([[0, 1, 0],
                     [0, 0, 0],
                     [0, 0, 0]])
    X2de = X1de + X1de.T

    X1sp = csgraph.csgraph_from_dense(X1de, null_value=0)
    X2sp = csgraph.csgraph_from_dense(X2de, null_value=0)

    for X in X1sp, X1de:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='strong')

        assert_equal(n_components, 3)
        labels.sort()
        assert_array_almost_equal(labels, [0, 1, 2])

    for X in X2sp, X2de:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='strong')

        assert_equal(n_components, 2)
        labels.sort()
        assert_array_almost_equal(labels, [0, 0, 1]) 
Example 10
Project: LaserTOF   Author: kyleuckert   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_strong_connections2():
    X = np.array([[0, 0, 0, 0, 0, 0],
                  [1, 0, 1, 0, 0, 0],
                  [0, 0, 0, 1, 0, 0],
                  [0, 0, 1, 0, 1, 0],
                  [0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 1, 0]])
    n_components, labels =\
        csgraph.connected_components(X, directed=True,
                                     connection='strong')
    assert_equal(n_components, 5)
    labels.sort()
    assert_array_almost_equal(labels, [0, 1, 2, 2, 3, 4]) 
Example 11
Project: LaserTOF   Author: kyleuckert   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_weak_connections2():
    X = np.array([[0, 0, 0, 0, 0, 0],
                  [1, 0, 0, 0, 0, 0],
                  [0, 0, 0, 1, 0, 0],
                  [0, 0, 1, 0, 1, 0],
                  [0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 1, 0]])
    n_components, labels =\
        csgraph.connected_components(X, directed=True,
                                     connection='weak')
    assert_equal(n_components, 2)
    labels.sort()
    assert_array_almost_equal(labels, [0, 0, 1, 1, 1, 1]) 
Example 12
Project: LaserTOF   Author: kyleuckert   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_ticket1876():
    # Regression test: this failed in the original implementation
    # There should be two strongly-connected components; previously gave one
    g = np.array([[0, 1, 1, 0],
                  [1, 0, 0, 1],
                  [0, 0, 0, 1],
                  [0, 0, 1, 0]])
    n_components, labels = csgraph.connected_components(g, connection='strong')

    assert_equal(n_components, 2)
    assert_equal(labels[0], labels[1])
    assert_equal(labels[2], labels[3]) 
Example 13
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_weak_connections():
    Xde = np.array([[0, 1, 0],
                    [0, 0, 0],
                    [0, 0, 0]])

    Xsp = csgraph.csgraph_from_dense(Xde, null_value=0)

    for X in Xsp, Xde:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='weak')

        assert_equal(n_components, 2)
        assert_array_almost_equal(labels, [0, 0, 1]) 
Example 14
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_strong_connections():
    X1de = np.array([[0, 1, 0],
                     [0, 0, 0],
                     [0, 0, 0]])
    X2de = X1de + X1de.T

    X1sp = csgraph.csgraph_from_dense(X1de, null_value=0)
    X2sp = csgraph.csgraph_from_dense(X2de, null_value=0)

    for X in X1sp, X1de:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='strong')

        assert_equal(n_components, 3)
        labels.sort()
        assert_array_almost_equal(labels, [0, 1, 2])

    for X in X2sp, X2de:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='strong')

        assert_equal(n_components, 2)
        labels.sort()
        assert_array_almost_equal(labels, [0, 0, 1]) 
Example 15
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_strong_connections2():
    X = np.array([[0, 0, 0, 0, 0, 0],
                  [1, 0, 1, 0, 0, 0],
                  [0, 0, 0, 1, 0, 0],
                  [0, 0, 1, 0, 1, 0],
                  [0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 1, 0]])
    n_components, labels =\
        csgraph.connected_components(X, directed=True,
                                     connection='strong')
    assert_equal(n_components, 5)
    labels.sort()
    assert_array_almost_equal(labels, [0, 1, 2, 2, 3, 4]) 
Example 16
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_weak_connections2():
    X = np.array([[0, 0, 0, 0, 0, 0],
                  [1, 0, 0, 0, 0, 0],
                  [0, 0, 0, 1, 0, 0],
                  [0, 0, 1, 0, 1, 0],
                  [0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 1, 0]])
    n_components, labels =\
        csgraph.connected_components(X, directed=True,
                                     connection='weak')
    assert_equal(n_components, 2)
    labels.sort()
    assert_array_almost_equal(labels, [0, 0, 1, 1, 1, 1]) 
Example 17
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_ticket1876():
    # Regression test: this failed in the original implementation
    # There should be two strongly-connected components; previously gave one
    g = np.array([[0, 1, 1, 0],
                  [1, 0, 0, 1],
                  [0, 0, 0, 1],
                  [0, 0, 1, 0]])
    n_components, labels = csgraph.connected_components(g, connection='strong')

    assert_equal(n_components, 2)
    assert_equal(labels[0], labels[1])
    assert_equal(labels[2], labels[3]) 
Example 18
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_connected_components.py    GNU General Public License v3.0 5 votes vote down vote up
def test_weak_connections():
    Xde = np.array([[0, 1, 0],
                    [0, 0, 0],
                    [0, 0, 0]])

    Xsp = csgraph.csgraph_from_dense(Xde, null_value=0)

    for X in Xsp, Xde:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='weak')

        assert_equal(n_components, 2)
        assert_array_almost_equal(labels, [0, 0, 1]) 
Example 19
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_connected_components.py    GNU General Public License v3.0 5 votes vote down vote up
def test_strong_connections():
    X1de = np.array([[0, 1, 0],
                     [0, 0, 0],
                     [0, 0, 0]])
    X2de = X1de + X1de.T

    X1sp = csgraph.csgraph_from_dense(X1de, null_value=0)
    X2sp = csgraph.csgraph_from_dense(X2de, null_value=0)

    for X in X1sp, X1de:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='strong')

        assert_equal(n_components, 3)
        labels.sort()
        assert_array_almost_equal(labels, [0, 1, 2])

    for X in X2sp, X2de:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='strong')

        assert_equal(n_components, 2)
        labels.sort()
        assert_array_almost_equal(labels, [0, 0, 1]) 
Example 20
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_connected_components.py    GNU General Public License v3.0 5 votes vote down vote up
def test_strong_connections2():
    X = np.array([[0, 0, 0, 0, 0, 0],
                  [1, 0, 1, 0, 0, 0],
                  [0, 0, 0, 1, 0, 0],
                  [0, 0, 1, 0, 1, 0],
                  [0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 1, 0]])
    n_components, labels =\
        csgraph.connected_components(X, directed=True,
                                     connection='strong')
    assert_equal(n_components, 5)
    labels.sort()
    assert_array_almost_equal(labels, [0, 1, 2, 2, 3, 4]) 
Example 21
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_connected_components.py    GNU General Public License v3.0 5 votes vote down vote up
def test_weak_connections2():
    X = np.array([[0, 0, 0, 0, 0, 0],
                  [1, 0, 0, 0, 0, 0],
                  [0, 0, 0, 1, 0, 0],
                  [0, 0, 1, 0, 1, 0],
                  [0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 1, 0]])
    n_components, labels =\
        csgraph.connected_components(X, directed=True,
                                     connection='weak')
    assert_equal(n_components, 2)
    labels.sort()
    assert_array_almost_equal(labels, [0, 0, 1, 1, 1, 1]) 
Example 22
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_connected_components.py    GNU General Public License v3.0 5 votes vote down vote up
def test_ticket1876():
    # Regression test: this failed in the original implementation
    # There should be two strongly-connected components; previously gave one
    g = np.array([[0, 1, 1, 0],
                  [1, 0, 0, 1],
                  [0, 0, 0, 1],
                  [0, 0, 1, 0]])
    n_components, labels = csgraph.connected_components(g, connection='strong')

    assert_equal(n_components, 2)
    assert_equal(labels[0], labels[1])
    assert_equal(labels[2], labels[3]) 
Example 23
Project: deepGroupv2   Author: albu5   File: utils.py    MIT License 5 votes vote down vote up
def draw_groups_at_time_t(features, gd, ax):
    n_people = len(features)
    for i in range(n_people):
        ped_i = features[i][0]

        # don't draw invalid ones
        if np.sum(ped_i[4:8]) == 0:
            continue

        (_, gl) = csgraph.connected_components(gd, directed=False)

        # top left are x, y
        x = int(ped_i[4])
        y = int(ped_i[5])
        w = int(ped_i[6])
        h = int(ped_i[7])

        # add rectangles, color coding according to group activity
        color_code = gl[i]
        ax.add_patch(patches.Rectangle((x, y), w, h, fill=False, color=COLORS[color_code]))

        # add velocity arrow
        arrow_len = 50
        ax.arrow(x+w/2,
                 y+h,
                 arrow_len*ped_i[0], arrow_len*ped_i[1],
                 head_width=5.0, head_length=5.0,
                 linewidth=2.0)

        # add pose
        pose_i = np.argmax(ped_i[8:16])
        ax.text(x, y, pose_info[pose_i],
                color=COLORS[color_code], fontsize=8,
                bbox={'facecolor': COLORS[color_code], 'alpha': 0.2, 'pad': 1})

        # add action
        action_i = np.argmax(ped_i[16:19])
        ax.text(x, y + h + 8, action_info[action_i],
                color=COLORS[color_code], fontsize=8,
                bbox={'facecolor': COLORS[color_code], 'alpha': 0.2, 'pad': 1}) 
Example 24
Project: ble5-nrf52-mac   Author: tomasero   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_weak_connections():
    Xde = np.array([[0, 1, 0],
                    [0, 0, 0],
                    [0, 0, 0]])

    Xsp = csgraph.csgraph_from_dense(Xde, null_value=0)

    for X in Xsp, Xde:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='weak')

        assert_equal(n_components, 2)
        assert_array_almost_equal(labels, [0, 0, 1]) 
Example 25
Project: ble5-nrf52-mac   Author: tomasero   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_strong_connections():
    X1de = np.array([[0, 1, 0],
                     [0, 0, 0],
                     [0, 0, 0]])
    X2de = X1de + X1de.T

    X1sp = csgraph.csgraph_from_dense(X1de, null_value=0)
    X2sp = csgraph.csgraph_from_dense(X2de, null_value=0)

    for X in X1sp, X1de:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='strong')

        assert_equal(n_components, 3)
        labels.sort()
        assert_array_almost_equal(labels, [0, 1, 2])

    for X in X2sp, X2de:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='strong')

        assert_equal(n_components, 2)
        labels.sort()
        assert_array_almost_equal(labels, [0, 0, 1]) 
Example 26
Project: ble5-nrf52-mac   Author: tomasero   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_strong_connections2():
    X = np.array([[0, 0, 0, 0, 0, 0],
                  [1, 0, 1, 0, 0, 0],
                  [0, 0, 0, 1, 0, 0],
                  [0, 0, 1, 0, 1, 0],
                  [0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 1, 0]])
    n_components, labels =\
        csgraph.connected_components(X, directed=True,
                                     connection='strong')
    assert_equal(n_components, 5)
    labels.sort()
    assert_array_almost_equal(labels, [0, 1, 2, 2, 3, 4]) 
Example 27
Project: ble5-nrf52-mac   Author: tomasero   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_weak_connections2():
    X = np.array([[0, 0, 0, 0, 0, 0],
                  [1, 0, 0, 0, 0, 0],
                  [0, 0, 0, 1, 0, 0],
                  [0, 0, 1, 0, 1, 0],
                  [0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 1, 0]])
    n_components, labels =\
        csgraph.connected_components(X, directed=True,
                                     connection='weak')
    assert_equal(n_components, 2)
    labels.sort()
    assert_array_almost_equal(labels, [0, 0, 1, 1, 1, 1]) 
Example 28
Project: ble5-nrf52-mac   Author: tomasero   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_ticket1876():
    # Regression test: this failed in the original implementation
    # There should be two strongly-connected components; previously gave one
    g = np.array([[0, 1, 1, 0],
                  [1, 0, 0, 1],
                  [0, 0, 0, 1],
                  [0, 0, 1, 0]])
    n_components, labels = csgraph.connected_components(g, connection='strong')

    assert_equal(n_components, 2)
    assert_equal(labels[0], labels[1])
    assert_equal(labels[2], labels[3]) 
Example 29
Project: kaggle_dsb   Author: syagev   File: candidates.py    Apache License 2.0 5 votes vote down vote up
def merge_candidates_scan(candidates, seriesuid, distance=5.):
    distances = pdist(candidates, metric='euclidean')
    adjacency_matrix = squareform(distances)

    # Determine nodes within distance, replace by 1 (=adjacency matrix)
    adjacency_matrix = np.where(adjacency_matrix<=distance,1,0)

    # Determine all connected components in the graph
    n, labels = connected_components(adjacency_matrix)
    new_candidates = np.zeros((n,3))

    # Take the mean for these connected components
    for cluster_i in range(n):
        points = candidates[np.where(labels==cluster_i)]
        center = np.mean(points,axis=0)
        new_candidates[cluster_i,:] = center

    x = new_candidates[:,0]
    y = new_candidates[:,1]
    z = new_candidates[:,2]
    labels = [seriesuid]*len(x)
    class_name = [0]*len(x)

    data= zip(labels,x,y,z,class_name)

    new_candidates = pd.DataFrame(data,columns=CANDIDATES_COLUMNS)

    return new_candidates 
Example 30
Project: Computable   Author: ktraunmueller   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_weak_connections():
    Xde = np.array([[0, 1, 0],
                    [0, 0, 0],
                    [0, 0, 0]])

    Xsp = csgraph.csgraph_from_dense(Xde, null_value=0)

    for X in Xsp, Xde:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='weak')

        assert_equal(n_components, 2)
        assert_array_almost_equal(labels, [0, 0, 1]) 
Example 31
Project: Computable   Author: ktraunmueller   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_strong_connections():
    X1de = np.array([[0, 1, 0],
                     [0, 0, 0],
                     [0, 0, 0]])
    X2de = X1de + X1de.T

    X1sp = csgraph.csgraph_from_dense(X1de, null_value=0)
    X2sp = csgraph.csgraph_from_dense(X2de, null_value=0)

    for X in X1sp, X1de:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='strong')

        assert_equal(n_components, 3)
        labels.sort()
        assert_array_almost_equal(labels, [0, 1, 2])

    for X in X2sp, X2de:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='strong')

        assert_equal(n_components, 2)
        labels.sort()
        assert_array_almost_equal(labels, [0, 0, 1]) 
Example 32
Project: Computable   Author: ktraunmueller   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_strong_connections2():
    X = np.array([[0, 0, 0, 0, 0, 0],
                  [1, 0, 1, 0, 0, 0],
                  [0, 0, 0, 1, 0, 0],
                  [0, 0, 1, 0, 1, 0],
                  [0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 1, 0]])
    n_components, labels =\
        csgraph.connected_components(X, directed=True,
                                     connection='strong')
    assert_equal(n_components, 5)
    labels.sort()
    assert_array_almost_equal(labels, [0, 1, 2, 2, 3, 4]) 
Example 33
Project: Computable   Author: ktraunmueller   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_weak_connections2():
    X = np.array([[0, 0, 0, 0, 0, 0],
                  [1, 0, 0, 0, 0, 0],
                  [0, 0, 0, 1, 0, 0],
                  [0, 0, 1, 0, 1, 0],
                  [0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 1, 0]])
    n_components, labels =\
        csgraph.connected_components(X, directed=True,
                                     connection='weak')
    assert_equal(n_components, 2)
    labels.sort()
    assert_array_almost_equal(labels, [0, 0, 1, 1, 1, 1]) 
Example 34
Project: Computable   Author: ktraunmueller   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_ticket1876():
    # Regression test: this failed in the original implementation
    # There should be two strongly-connected components; previously gave one
    g = np.array([[0, 1, 1, 0],
                  [1, 0, 0, 1],
                  [0, 0, 0, 1],
                  [0, 0, 1, 0]])
    n_components, labels = csgraph.connected_components(g, connection='strong')

    assert_equal(n_components, 2)
    assert_equal(labels[0], labels[1])
    assert_equal(labels[2], labels[3]) 
Example 35
Project: poker   Author: surgebiswas   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_weak_connections():
    Xde = np.array([[0, 1, 0],
                    [0, 0, 0],
                    [0, 0, 0]])

    Xsp = csgraph.csgraph_from_dense(Xde, null_value=0)

    for X in Xsp, Xde:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='weak')

        assert_equal(n_components, 2)
        assert_array_almost_equal(labels, [0, 0, 1]) 
Example 36
Project: poker   Author: surgebiswas   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_strong_connections():
    X1de = np.array([[0, 1, 0],
                     [0, 0, 0],
                     [0, 0, 0]])
    X2de = X1de + X1de.T

    X1sp = csgraph.csgraph_from_dense(X1de, null_value=0)
    X2sp = csgraph.csgraph_from_dense(X2de, null_value=0)

    for X in X1sp, X1de:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='strong')

        assert_equal(n_components, 3)
        labels.sort()
        assert_array_almost_equal(labels, [0, 1, 2])

    for X in X2sp, X2de:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='strong')

        assert_equal(n_components, 2)
        labels.sort()
        assert_array_almost_equal(labels, [0, 0, 1]) 
Example 37
Project: poker   Author: surgebiswas   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_strong_connections2():
    X = np.array([[0, 0, 0, 0, 0, 0],
                  [1, 0, 1, 0, 0, 0],
                  [0, 0, 0, 1, 0, 0],
                  [0, 0, 1, 0, 1, 0],
                  [0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 1, 0]])
    n_components, labels =\
        csgraph.connected_components(X, directed=True,
                                     connection='strong')
    assert_equal(n_components, 5)
    labels.sort()
    assert_array_almost_equal(labels, [0, 1, 2, 2, 3, 4]) 
Example 38
Project: poker   Author: surgebiswas   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_weak_connections2():
    X = np.array([[0, 0, 0, 0, 0, 0],
                  [1, 0, 0, 0, 0, 0],
                  [0, 0, 0, 1, 0, 0],
                  [0, 0, 1, 0, 1, 0],
                  [0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 1, 0]])
    n_components, labels =\
        csgraph.connected_components(X, directed=True,
                                     connection='weak')
    assert_equal(n_components, 2)
    labels.sort()
    assert_array_almost_equal(labels, [0, 0, 1, 1, 1, 1]) 
Example 39
Project: poker   Author: surgebiswas   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_ticket1876():
    # Regression test: this failed in the original implementation
    # There should be two strongly-connected components; previously gave one
    g = np.array([[0, 1, 1, 0],
                  [1, 0, 0, 1],
                  [0, 0, 0, 1],
                  [0, 0, 1, 0]])
    n_components, labels = csgraph.connected_components(g, connection='strong')

    assert_equal(n_components, 2)
    assert_equal(labels[0], labels[1])
    assert_equal(labels[2], labels[3]) 
Example 40
Project: luna16   Author: gzuidhof   File: candidates.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def merge_candidates_scan(candidates, seriesuid, distance=5.):
    distances = pdist(candidates, metric='euclidean')
    adjacency_matrix = squareform(distances)

    # Determine nodes within distance, replace by 1 (=adjacency matrix)
    adjacency_matrix = np.where(adjacency_matrix<=distance,1,0)

    # Determine all connected components in the graph
    n, labels = connected_components(adjacency_matrix)
    new_candidates = np.zeros((n,3))

    # Take the mean for these connected components
    for cluster_i in range(n):
        points = candidates[np.where(labels==cluster_i)]
        center = np.mean(points,axis=0)
        new_candidates[cluster_i,:] = center

    x = new_candidates[:,0]
    y = new_candidates[:,1]
    z = new_candidates[:,2]
    labels = [seriesuid]*len(x)
    class_name = [0]*len(x)

    data= zip(labels,x,y,z,class_name)

    new_candidates = pd.DataFrame(data,columns=CANDIDATES_COLUMNS)

    return new_candidates 
Example 41
Project: P3_image_processing   Author: latedude2   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_weak_connections():
    Xde = np.array([[0, 1, 0],
                    [0, 0, 0],
                    [0, 0, 0]])

    Xsp = csgraph.csgraph_from_dense(Xde, null_value=0)

    for X in Xsp, Xde:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='weak')

        assert_equal(n_components, 2)
        assert_array_almost_equal(labels, [0, 0, 1]) 
Example 42
Project: P3_image_processing   Author: latedude2   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_strong_connections():
    X1de = np.array([[0, 1, 0],
                     [0, 0, 0],
                     [0, 0, 0]])
    X2de = X1de + X1de.T

    X1sp = csgraph.csgraph_from_dense(X1de, null_value=0)
    X2sp = csgraph.csgraph_from_dense(X2de, null_value=0)

    for X in X1sp, X1de:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='strong')

        assert_equal(n_components, 3)
        labels.sort()
        assert_array_almost_equal(labels, [0, 1, 2])

    for X in X2sp, X2de:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='strong')

        assert_equal(n_components, 2)
        labels.sort()
        assert_array_almost_equal(labels, [0, 0, 1]) 
Example 43
Project: P3_image_processing   Author: latedude2   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_strong_connections2():
    X = np.array([[0, 0, 0, 0, 0, 0],
                  [1, 0, 1, 0, 0, 0],
                  [0, 0, 0, 1, 0, 0],
                  [0, 0, 1, 0, 1, 0],
                  [0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 1, 0]])
    n_components, labels =\
        csgraph.connected_components(X, directed=True,
                                     connection='strong')
    assert_equal(n_components, 5)
    labels.sort()
    assert_array_almost_equal(labels, [0, 1, 2, 2, 3, 4]) 
Example 44
Project: P3_image_processing   Author: latedude2   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_weak_connections2():
    X = np.array([[0, 0, 0, 0, 0, 0],
                  [1, 0, 0, 0, 0, 0],
                  [0, 0, 0, 1, 0, 0],
                  [0, 0, 1, 0, 1, 0],
                  [0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 1, 0]])
    n_components, labels =\
        csgraph.connected_components(X, directed=True,
                                     connection='weak')
    assert_equal(n_components, 2)
    labels.sort()
    assert_array_almost_equal(labels, [0, 0, 1, 1, 1, 1]) 
Example 45
Project: P3_image_processing   Author: latedude2   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_ticket1876():
    # Regression test: this failed in the original implementation
    # There should be two strongly-connected components; previously gave one
    g = np.array([[0, 1, 1, 0],
                  [1, 0, 0, 1],
                  [0, 0, 0, 1],
                  [0, 0, 1, 0]])
    n_components, labels = csgraph.connected_components(g, connection='strong')

    assert_equal(n_components, 2)
    assert_equal(labels[0], labels[1])
    assert_equal(labels[2], labels[3]) 
Example 46
Project: pyMHT   Author: erikliland   File: tracker.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _findClustersFromSets(self):
        self.superSet = set()
        for targetSet in self.__associatedMeasurements__:
            self.superSet |= targetSet
        nTargets = len(self.__associatedMeasurements__)
        nNodes = nTargets + len(self.superSet)
        adjacencyMatrix = np.zeros((nNodes, nNodes), dtype=bool)
        for targetIndex, targetSet in enumerate(self.__associatedMeasurements__):
            for measurementIndex, measurement in enumerate(self.superSet):
                adjacencyMatrix[targetIndex, measurementIndex +
                                nTargets] = (measurement in targetSet)
        (nClusters, labels) = connected_components(adjacencyMatrix)
        return [np.where(labels[:nTargets] == clusterIndex)[0]
                for clusterIndex in range(nClusters)] 
Example 47
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_weak_connections():
    Xde = np.array([[0, 1, 0],
                    [0, 0, 0],
                    [0, 0, 0]])

    Xsp = csgraph.csgraph_from_dense(Xde, null_value=0)

    for X in Xsp, Xde:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='weak')

        assert_equal(n_components, 2)
        assert_array_almost_equal(labels, [0, 0, 1]) 
Example 48
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_strong_connections():
    X1de = np.array([[0, 1, 0],
                     [0, 0, 0],
                     [0, 0, 0]])
    X2de = X1de + X1de.T

    X1sp = csgraph.csgraph_from_dense(X1de, null_value=0)
    X2sp = csgraph.csgraph_from_dense(X2de, null_value=0)

    for X in X1sp, X1de:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='strong')

        assert_equal(n_components, 3)
        labels.sort()
        assert_array_almost_equal(labels, [0, 1, 2])

    for X in X2sp, X2de:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='strong')

        assert_equal(n_components, 2)
        labels.sort()
        assert_array_almost_equal(labels, [0, 0, 1]) 
Example 49
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_strong_connections2():
    X = np.array([[0, 0, 0, 0, 0, 0],
                  [1, 0, 1, 0, 0, 0],
                  [0, 0, 0, 1, 0, 0],
                  [0, 0, 1, 0, 1, 0],
                  [0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 1, 0]])
    n_components, labels =\
        csgraph.connected_components(X, directed=True,
                                     connection='strong')
    assert_equal(n_components, 5)
    labels.sort()
    assert_array_almost_equal(labels, [0, 1, 2, 2, 3, 4]) 
Example 50
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_weak_connections2():
    X = np.array([[0, 0, 0, 0, 0, 0],
                  [1, 0, 0, 0, 0, 0],
                  [0, 0, 0, 1, 0, 0],
                  [0, 0, 1, 0, 1, 0],
                  [0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 1, 0]])
    n_components, labels =\
        csgraph.connected_components(X, directed=True,
                                     connection='weak')
    assert_equal(n_components, 2)
    labels.sort()
    assert_array_almost_equal(labels, [0, 0, 1, 1, 1, 1]) 
Example 51
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_ticket1876():
    # Regression test: this failed in the original implementation
    # There should be two strongly-connected components; previously gave one
    g = np.array([[0, 1, 1, 0],
                  [1, 0, 0, 1],
                  [0, 0, 0, 1],
                  [0, 0, 1, 0]])
    n_components, labels = csgraph.connected_components(g, connection='strong')

    assert_equal(n_components, 2)
    assert_equal(labels[0], labels[1])
    assert_equal(labels[2], labels[3]) 
Example 52
Project: image-stitcher   Author: kupiakos   File: stitcher.py    MIT License 5 votes vote down vote up
def validate(self):
        cc, groups = csgraph.connected_components(self._edge_matrix, directed=False)
        if cc != 1:
            most_common = np.bincount(groups).argmax()
            raise ValueError('Image(s) %s could not be stitched' % ','.join(
                self._images[img].name for img in np.where(groups != most_common)[0]
            )) 
Example 53
Project: VehicleTracking   Author: ChengeLi   File: trjcluster_func_SBS.py    MIT License 5 votes vote down vote up
def visCC(self):
        """fix me.... :/"""

        """to visualize the neighbours"""
        if isVisualize:
            fig888 = plt.figure()
            ax     = plt.subplot(1,1,1)

        """ visualization, see if connected components make sense"""
        s111,c111 = connected_components(sparsemtx) #s is the total CComponent, c is the label
        color     = np.array([np.random.randint(0,255) for _ in range(3*int(s111))]).reshape(s111,3)
        fig888    = plt.figure(888)
        ax        = plt.subplot(1,1,1)
        # im = plt.imshow(np.zeros([528,704,3]))
        for i in range(s111):
            ind = np.where(c111==i)[0]
            print ind
            for jj in range(len(ind)):
                startlimit = np.min(np.where(x[ind[jj],:]!=0))
                endlimit = np.max(np.where(x[ind[jj],:]!=0))
                # lines = ax.plot(x[ind[jj],startlimit:endlimit], y[ind[jj],startlimit:endlimit],color = (0,1,0),linewidth=2)
                lines = ax.plot(x[ind[jj],startlimit:endlimit], y[ind[jj],startlimit:endlimit],color = (color[i-1].T)/255.,linewidth=2)
                fig888.canvas.draw()
            plt.pause(0.0001) 
        plt.show()


# if __name__ == '__main__': 
Example 54
Project: crnpy   Author: etonello   File: crn.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def strong_conn_components(self):
        """Return the number of strongly connected components of the graph of complexes,
        and an array of labels for the strongly connected components."""
        adjacency = csr_matrix(np.array(self.complex_graph_adj().tolist()).astype(np.int))
        return connected_components(adjacency, connection = 'strong') 
Example 55
Project: crnpy   Author: etonello   File: crn.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def weak_conn_components(self):
        """Return the number of weakly connected components of the graph of complexes,
        and an array of labels for the weakly connected components."""
        return connected_components(csr_matrix(np.array(self.complex_graph_adj().tolist()).astype(np.int))) 
Example 56
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_weak_connections():
    Xde = np.array([[0, 1, 0],
                    [0, 0, 0],
                    [0, 0, 0]])

    Xsp = csgraph.csgraph_from_dense(Xde, null_value=0)

    for X in Xsp, Xde:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='weak')

        assert_equal(n_components, 2)
        assert_array_almost_equal(labels, [0, 0, 1]) 
Example 57
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_strong_connections():
    X1de = np.array([[0, 1, 0],
                     [0, 0, 0],
                     [0, 0, 0]])
    X2de = X1de + X1de.T

    X1sp = csgraph.csgraph_from_dense(X1de, null_value=0)
    X2sp = csgraph.csgraph_from_dense(X2de, null_value=0)

    for X in X1sp, X1de:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='strong')

        assert_equal(n_components, 3)
        labels.sort()
        assert_array_almost_equal(labels, [0, 1, 2])

    for X in X2sp, X2de:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='strong')

        assert_equal(n_components, 2)
        labels.sort()
        assert_array_almost_equal(labels, [0, 0, 1]) 
Example 58
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_strong_connections2():
    X = np.array([[0, 0, 0, 0, 0, 0],
                  [1, 0, 1, 0, 0, 0],
                  [0, 0, 0, 1, 0, 0],
                  [0, 0, 1, 0, 1, 0],
                  [0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 1, 0]])
    n_components, labels =\
        csgraph.connected_components(X, directed=True,
                                     connection='strong')
    assert_equal(n_components, 5)
    labels.sort()
    assert_array_almost_equal(labels, [0, 1, 2, 2, 3, 4]) 
Example 59
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_weak_connections2():
    X = np.array([[0, 0, 0, 0, 0, 0],
                  [1, 0, 0, 0, 0, 0],
                  [0, 0, 0, 1, 0, 0],
                  [0, 0, 1, 0, 1, 0],
                  [0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 1, 0]])
    n_components, labels =\
        csgraph.connected_components(X, directed=True,
                                     connection='weak')
    assert_equal(n_components, 2)
    labels.sort()
    assert_array_almost_equal(labels, [0, 0, 1, 1, 1, 1]) 
Example 60
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_connected_components.py    MIT License 5 votes vote down vote up
def test_ticket1876():
    # Regression test: this failed in the original implementation
    # There should be two strongly-connected components; previously gave one
    g = np.array([[0, 1, 1, 0],
                  [1, 0, 0, 1],
                  [0, 0, 0, 1],
                  [0, 0, 1, 0]])
    n_components, labels = csgraph.connected_components(g, connection='strong')

    assert_equal(n_components, 2)
    assert_equal(labels[0], labels[1])
    assert_equal(labels[2], labels[3]) 
Example 61
Project: quiesce   Author: egtaonline   File: trace.py    Apache License 2.0 5 votes vote down vote up
def _merge_traces(game0, game1, traces, thresh, trace_args): # pylint: disable=too-many-locals
    """Merge a list of traces

    Parameters
    ----------
    traces : [(ts, eqa)]
        A list of traces, which are themselves tuples of times and equilibria.
    thresh : float
        How similar traces need to be in order to be merged. This is the
        average norm between the traces.
    interp : str
        The way to interpolate between equilibria. This is passed to interp1d.
    """
    distances = np.zeros([len(traces)] * 2)
    for i, trace1 in enumerate(traces):
        for j, trace2 in enumerate(traces[:i]):
            distances[i, j] = distances[j, i] = _trace_distance(
                game0, game1, trace1, trace2, trace_args)
    num, comps = csgraph.connected_components(distances <= thresh, False)
    new_traces = []
    for i in range(num):
        times = np.concatenate([
            t for (t, _), m in zip(traces, comps == i) if m])
        eqa = np.concatenate([
            eqms for (_, eqms), m in zip(traces, comps == i) if m])
        inds = np.argsort(times)
        new_traces.append((times[inds], eqa[inds]))
    return new_traces 
Example 62
Project: wine-ml-on-aws-lambda   Author: pierreant   File: test_image.py    Apache License 2.0 5 votes vote down vote up
def test_grid_to_graph():
    # Checking that the function works with graphs containing no edges
    size = 2
    roi_size = 1
    # Generating two convex parts with one vertex
    # Thus, edges will be empty in _to_graph
    mask = np.zeros((size, size), dtype=np.bool)
    mask[0:roi_size, 0:roi_size] = True
    mask[-roi_size:, -roi_size:] = True
    mask = mask.reshape(size ** 2)
    A = grid_to_graph(n_x=size, n_y=size, mask=mask, return_as=np.ndarray)
    assert_true(connected_components(A)[0] == 2)

    # Checking that the function works whatever the type of mask is
    mask = np.ones((size, size), dtype=np.int16)
    A = grid_to_graph(n_x=size, n_y=size, n_z=size, mask=mask)
    assert_true(connected_components(A)[0] == 1)

    # Checking dtype of the graph
    mask = np.ones((size, size))
    A = grid_to_graph(n_x=size, n_y=size, n_z=size, mask=mask, dtype=np.bool)
    assert_true(A.dtype == np.bool)
    A = grid_to_graph(n_x=size, n_y=size, n_z=size, mask=mask, dtype=np.int)
    assert_true(A.dtype == np.int)
    A = grid_to_graph(n_x=size, n_y=size, n_z=size, mask=mask,
                      dtype=np.float64)
    assert_true(A.dtype == np.float64) 
Example 63
Project: wine-ml-on-aws-lambda   Author: pierreant   File: test_image.py    Apache License 2.0 5 votes vote down vote up
def test_connect_regions():
    try:
        face = sp.face(gray=True)
    except AttributeError:
        # Newer versions of scipy have face in misc
        from scipy import misc
        face = misc.face(gray=True)
    for thr in (50, 150):
        mask = face > thr
        graph = img_to_graph(face, mask)
        assert_equal(ndimage.label(mask)[1], connected_components(graph)[0]) 
Example 64
Project: wine-ml-on-aws-lambda   Author: pierreant   File: test_image.py    Apache License 2.0 5 votes vote down vote up
def test_connect_regions_with_grid():
    try:
        face = sp.face(gray=True)
    except AttributeError:
        # Newer versions of scipy have face in misc
        from scipy import misc
        face = misc.face(gray=True)
    mask = face > 50
    graph = grid_to_graph(*face.shape, mask=mask)
    assert_equal(ndimage.label(mask)[1], connected_components(graph)[0])

    mask = face > 150
    graph = grid_to_graph(*face.shape, mask=mask, dtype=None)
    assert_equal(ndimage.label(mask)[1], connected_components(graph)[0]) 
Example 65
Project: wine-ml-on-aws-lambda   Author: pierreant   File: test_connected_components.py    Apache License 2.0 5 votes vote down vote up
def test_strong_connections():
    X1de = np.array([[0, 1, 0],
                     [0, 0, 0],
                     [0, 0, 0]])
    X2de = X1de + X1de.T

    X1sp = csgraph.csgraph_from_dense(X1de, null_value=0)
    X2sp = csgraph.csgraph_from_dense(X2de, null_value=0)

    for X in X1sp, X1de:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='strong')

        assert_equal(n_components, 3)
        labels.sort()
        assert_array_almost_equal(labels, [0, 1, 2])

    for X in X2sp, X2de:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='strong')

        assert_equal(n_components, 2)
        labels.sort()
        assert_array_almost_equal(labels, [0, 0, 1]) 
Example 66
Project: wine-ml-on-aws-lambda   Author: pierreant   File: test_connected_components.py    Apache License 2.0 5 votes vote down vote up
def test_strong_connections2():
    X = np.array([[0, 0, 0, 0, 0, 0],
                  [1, 0, 1, 0, 0, 0],
                  [0, 0, 0, 1, 0, 0],
                  [0, 0, 1, 0, 1, 0],
                  [0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 1, 0]])
    n_components, labels =\
        csgraph.connected_components(X, directed=True,
                                     connection='strong')
    assert_equal(n_components, 5)
    labels.sort()
    assert_array_almost_equal(labels, [0, 1, 2, 2, 3, 4]) 
Example 67
Project: wine-ml-on-aws-lambda   Author: pierreant   File: test_connected_components.py    Apache License 2.0 5 votes vote down vote up
def test_weak_connections2():
    X = np.array([[0, 0, 0, 0, 0, 0],
                  [1, 0, 0, 0, 0, 0],
                  [0, 0, 0, 1, 0, 0],
                  [0, 0, 1, 0, 1, 0],
                  [0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 1, 0]])
    n_components, labels =\
        csgraph.connected_components(X, directed=True,
                                     connection='weak')
    assert_equal(n_components, 2)
    labels.sort()
    assert_array_almost_equal(labels, [0, 0, 1, 1, 1, 1]) 
Example 68
Project: wine-ml-on-aws-lambda   Author: pierreant   File: test_connected_components.py    Apache License 2.0 5 votes vote down vote up
def test_ticket1876():
    # Regression test: this failed in the original implementation
    # There should be two strongly-connected components; previously gave one
    g = np.array([[0, 1, 1, 0],
                  [1, 0, 0, 1],
                  [0, 0, 0, 1],
                  [0, 0, 1, 0]])
    n_components, labels = csgraph.connected_components(g, connection='strong')

    assert_equal(n_components, 2)
    assert_equal(labels[0], labels[1])
    assert_equal(labels[2], labels[3]) 
Example 69
Project: wine-ml-on-aws-lambda   Author: pierreant   File: test_connected_components.py    Apache License 2.0 5 votes vote down vote up
def test_fully_connected_graph():
    # Fully connected dense matrices raised an exception.
    # https://github.com/scipy/scipy/issues/3818
    g = np.ones((4, 4))
    n_components, labels = csgraph.connected_components(g)
    assert_equal(n_components, 1) 
Example 70
Project: cgtools   Author: tneumann   File: topology.py    MIT License 5 votes vote down vote up
def largest_connected_component(tris):
    """
    Returns vertex indices of the largest connected component of the mesh
    as well as a reindexed triangle array, e.g. use it like so:

    ix, tris_new = largest_connected_component(tris)
    show_mesh(verts[ix], tris_new)
    """
    _, labels = connected_components(edge_adjacency_matrix(tris), directed=False)
    largest = np.bincount(labels).argmax()
    mask = labels == largest
    vertex_indices = mask.nonzero()[0]
    tris_new = filter_reindex(mask, tris)
    return vertex_indices, tris_new 
Example 71
Project: skan   Author: jni   File: csr.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def summarize(skel: Skeleton):
    """Compute statistics for every skeleton and branch in ``skel``.

    Parameters
    ----------
    skel : skan.csr.Skeleton
        A Skeleton object.

    Returns
    -------
    summary : pandas.DataFrame
        A summary of the branches including branch length, mean branch value,
        branch euclidean distance, etc.
    """
    summary = {}
    ndim = skel.coordinates.shape[1]
    _, skeleton_ids = csgraph.connected_components(skel.graph,
                                                   directed=False)
    endpoints_src = skel.paths.indices[skel.paths.indptr[:-1]]
    endpoints_dst = skel.paths.indices[skel.paths.indptr[1:] - 1]
    summary['skeleton-id'] = skeleton_ids[endpoints_src]
    summary['node-id-src'] = endpoints_src
    summary['node-id-dst'] = endpoints_dst
    summary['branch-distance'] = skel.path_lengths()
    deg_src = skel.degrees[endpoints_src]
    deg_dst = skel.degrees[endpoints_dst]
    kind = np.full(deg_src.shape, 2)  # default: junction-to-junction
    kind[(deg_src == 1) | (deg_dst == 1)] = 1  # tip-junction
    kind[(deg_src == 1) & (deg_dst == 1)] = 0  # tip-tip
    kind[endpoints_src == endpoints_dst] = 3  # cycle
    summary['branch-type'] = kind
    summary['mean-pixel-value'] = skel.path_means()
    summary['stdev-pixel-value'] = skel.path_stdev()
    for i in range(ndim):  # keep loops separate for best insertion order
        summary[f'image-coord-src-{i}'] = skel.coordinates[endpoints_src, i]
    for i in range(ndim):
        summary[f'image-coord-dst-{i}'] = skel.coordinates[endpoints_dst, i]
    coords_real_src = skel.coordinates[endpoints_src] * skel.spacing
    for i in range(ndim):
        summary[f'coord-src-{i}'] = coords_real_src[:, i]
    coords_real_dst = skel.coordinates[endpoints_dst] * skel.spacing
    for i in range(ndim):
        summary[f'coord-dst-{i}'] = coords_real_dst[:, i]
    summary['euclidean-distance'] = (
            np.sqrt((coords_real_dst - coords_real_src)**2 @ np.ones(ndim))
    )
    df = pd.DataFrame(summary)
    return df 
Example 72
Project: scanpy   Author: theislab   File: __init__.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def __init__(self, adata: AnnData, n_dcs: Optional[int] = None):
        self._adata = adata
        self._init_iroot()
        # use the graph in adata
        info_str = ''
        self.knn: Optional[bool] = None
        self._distances: Union[np.ndarray, csr_matrix, None] = None
        self._connectivities: Union[np.ndarray, csr_matrix, None] = None
        self._transitions_sym: Union[np.ndarray, csr_matrix, None] = None
        self._number_connected_components: Optional[int] = None
        self._rp_forest: Optional[RPForestDict] = None
        if 'neighbors' in adata.uns:
            if 'distances' in adata.uns['neighbors']:
                self.knn = issparse(adata.uns['neighbors']['distances'])
                self._distances = adata.uns['neighbors']['distances']
            if 'connectivities' in adata.uns['neighbors']:
                self.knn = issparse(adata.uns['neighbors']['connectivities'])
                self._connectivities = adata.uns['neighbors']['connectivities']
            if 'rp_forest' in adata.uns['neighbors']:
                self._rp_forest = adata.uns['neighbors']['rp_forest']
            if 'params' in adata.uns['neighbors']:
                self.n_neighbors = adata.uns['neighbors']['params']['n_neighbors']
            else:
                def count_nonzero(a: Union[np.ndarray, csr_matrix]) -> int:
                    return a.count_nonzero() if issparse(a) else np.count_nonzero(a)
                # estimating n_neighbors
                if self._connectivities is None:
                    self.n_neighbors = int(count_nonzero(self._distances) / self._distances.shape[0])
                else:
                    self.n_neighbors = int(count_nonzero(self._connectivities) / self._connectivities.shape[0] / 2)
            info_str += '`.distances` `.connectivities` '
            self._number_connected_components = 1
            if issparse(self._connectivities):
                from scipy.sparse.csgraph import connected_components
                self._connected_components = connected_components(self._connectivities)
                self._number_connected_components = self._connected_components[0]
        if 'X_diffmap' in adata.obsm_keys():
            self._eigen_values = _backwards_compat_get_full_eval(adata)
            self._eigen_basis = _backwards_compat_get_full_X_diffmap(adata)
            if n_dcs is not None:
                if n_dcs > len(self._eigen_values):
                    raise ValueError(
                        'Cannot instantiate using `n_dcs`={}. '
                        'Compute diffmap/spectrum with more components first.'
                        .format(n_dcs))
                self._eigen_values = self._eigen_values[:n_dcs]
                self._eigen_basis = self._eigen_basis[:, :n_dcs]
            self.n_dcs = len(self._eigen_values)
            info_str += '`.eigen_values` `.eigen_basis` `.distances_dpt`'
        else:
            self._eigen_values = None
            self._eigen_basis = None
            self.n_dcs = None
        if info_str != '':
            logg.debug(f'    initialized {info_str}') 
Example 73
Project: spectrassembler   Author: antrec   File: spectral.py    MIT License 4 votes vote down vote up
def remove_bridge_reads(a_mat):
    """ Remove some edges from the similarity graph.

    When the set of neighbors N(i) of a node i are not connected if that node i is removed from the graph,
    the edges between i and j are cut for all j that is not in the largest connected group among N(i).

    Parameters
    ----------
    a_mat : scipy.sparse matrix (similarity matrix)

    Returns
    ----------
    a_clr : scipy.sparse matrix (similarity matrix pre-preocessed)

    """
    Ikill = []
    Jkill = []
    if not(isspmatrix_csr(a_mat)):
        a_mat = a_mat.tocsr()
    for i in xrange(a_mat.shape[0]):
        (_, J, _) = find(a_mat[i, :])
        if len(J) == 0:
            continue
        Jl = list(set(J))
        a_r = a_mat[Jl, :].tocsc()
        a_r = a_r[:, Jl]
        Jl = np.array(Jl)
        (n_c, lbl) = connected_components(a_r, directed=False, return_labels=True)
        if n_c > 1:
            sizeccs = np.zeros(n_c)
            for ncc in xrange(n_c):
                sizeccs[ncc] = sum(lbl == ncc)
            ccmax = np.argmax(sizeccs)
            away_idx = np.where(lbl != ccmax)[0]
            away_nbrs = list(Jl[away_idx])
            Ikill.extend([i] * len(away_nbrs))
            Jkill.extend(away_nbrs)

    Ikill = np.array(Ikill)
    Jkill = np.array(Jkill)
    Vkill = np.ones(Ikill.size)
    kill_mat = coo_matrix((Vkill, (Ikill, Jkill)), shape=a_mat.shape, dtype=int).tocsr()
    kill_mat = sym_max(kill_mat)
    kill_mat = kill_mat.multiply(a_mat)
    a_clr = a_mat - kill_mat
    if not(isspmatrix_csr(a_clr)):
        a_clr = a_clr.tocsr()

    return a_clr


###############################################################################
###### Spectral ordering related functions (gets coarse-grained layout) #######
############################################################################### 
Example 74
Project: spectrassembler   Author: antrec   File: spectral.py    MIT License 4 votes vote down vote up
def reorder_mat(A, thr_list, min_cc_len, VERB):

    if not isspmatrix_csr(A):
        A = A.tocsr()
    # Initialization.
    ccs_ord = []
    #Create list of unordered connected components
    todo_ccs = [np.arange(A.shape[0])]
    todo_next = []
    n_loop = 0

    while len(todo_ccs) > 0:
        thr_sub = thr_list[n_loop] # starts at 0.4 for n_loop=0
        # Reorder each of them
        for cc in todo_ccs:
            # if statement
            # in order not to make the preprocessing twice. We could also remove
            # the preprocessing from the pipeline and do it here.
            if n_loop > 0:
                A_sub = A[cc, :][:, cc]
                A_sub = remove_bridge_reads(A_sub.multiply(A_sub > thr_sub))
            else:
                A_sub = A

            # Compute connected components
            (n_cc, labels) = connected_components(A_sub, directed=False, return_labels=True)

            # Reorder each cc with spectral and keep the ordering if it looks OK
            for i_cc in xrange(n_cc):
                cc_sub = np.argwhere(labels == i_cc)[:, 0]
                if len(cc_sub) <= min_cc_len:
                    continue
                msg = " Running spectral algorithm in connected"\
                      "component of size %d..." % (len(cc_sub))
                oprint(msg, cond=(VERB >= 2))
                (_, fidvec) = get_fiedler(A_sub[cc_sub, :][:, cc_sub])
                permu = np.argsort(fidvec)
                (ii, jj, _) = find(A_sub[cc_sub[permu], :][:, cc_sub[permu]])
                bw = max(abs(ii - jj))
                if bw >= 80:
                    oprint("Bandwidth larger than 80 in reordered matrix.",
                           cond=(VERB >= 2))
                    todo_next.append(cc[cc_sub])
                else:
                    ccs_ord.append(cc[cc_sub[permu]])

        todo_ccs = todo_next
        todo_next = []
        n_loop += 1

    return ccs_ord 
Example 75
Project: spectrassembler   Author: antrec   File: spectral.py    MIT License 4 votes vote down vote up
def reord_submat(in_tuple, A, opts):

    (thr_sub, cc) = in_tuple
    min_len = int(opts['MIN_CC_LEN'])
    verb = int(opts['VERB'])
    JULIA_PATH = opts['JULIA_PATH']
    JULIA_SCRIPT = opts['JULIA_SCRIPT']
    # rep_time_fh = open('%s/time_evs.txt' %(opts['ROOT_DIR']), 'a')

    sub_todo_next = []
    sub_ccs_ord = []

    A_sub = A[cc, :][:, cc]
    A_sub = remove_bridge_reads(A_sub.multiply(A_sub > thr_sub))
    # Compute connected components
    (n_cc, labels) = connected_components(A_sub, directed=False, return_labels=True)

    # Reorder each cc with spectral and keep the ordering if it looks OK
    for i_cc in xrange(n_cc):
        cc_sub = np.argwhere(labels == i_cc)[:, 0]
        if len(cc_sub) <= min_len:
            continue
        msg = " Running spectral algorithm in connected "\
              "component of size %d..." % (len(cc_sub))
        oprint(msg, cond=(verb >= 2))
        t1 = time()

        if JULIA_PATH and (len(cc_sub) > 3000):
            permu = get_fiedler_julia(A_sub[cc_sub, :][:, cc_sub], JULIA_PATH, JULIA_SCRIPT)
            # rep_time_fh.write("%d\t%3.6f\t(julia)\n" %(len(cc_sub), time()-t1))
        else:
            (_, fidvec) = get_fiedler(A_sub[cc_sub, :][:, cc_sub])
            permu = np.argsort(fidvec)
            # rep_time_fh.write("%d\t%3.6f\n" %(len(cc_sub), time()-t1))

        oprint("Done in %3.6fs" % (time()-t1), cond=(verb>=2))

        (ii, jj, _) = find(A_sub[cc_sub[permu], :][:, cc_sub[permu]])
        bw = max(abs(ii - jj))
        if bw >= 80:
            oprint("Bandwidth larger than 90 in reordered matrix.",
                   cond=(verb >= 2))
            sub_todo_next.append(cc[cc_sub])
        else:
            sub_ccs_ord.append(cc[cc_sub[permu]])

    # rep_time_fh.close()

    return sub_ccs_ord, sub_todo_next 
Example 76
Project: spectrassembler   Author: antrec   File: spectral.py    MIT License 4 votes vote down vote up
def reorder_mat_par(A, thr_list, opts):

    partial_reorder = partial(reord_submat, A=A, opts=opts)
    N_PROC = int(opts['N_PROC'])//4
    min_cc_len = opts['MIN_CC_LEN']

    if not isspmatrix_csr(A):
        A = A.tocsr()
    # Initialization.
    ccs_ord = []
    #Create list of unordered connected components
    todo_ccs = [np.arange(A.shape[0])]
    todo_next = []
    n_loop = 0

    todo_ccs = []
    (ncs, lbls) = connected_components(A, directed=False, return_labels=True)
    for nc in xrange(ncs):
        cc_sub = np.argwhere(lbls == nc)[:, 0]
        if len(cc_sub) <= min_cc_len:
            continue
        todo_ccs.append(cc_sub)


    while len(todo_ccs) > 0:
        thr_sub = thr_list[n_loop] # starts at 0.4 for n_loop=0
        args_list = zip(repeat(thr_sub), todo_ccs)

        pool = Pool(processes=N_PROC)
        results = pool.map(partial_reorder, args_list)
        pool.close()
        pool.join()

        for tple in results:
            (sub_ccs_ord, sub_todo_next) = tple
            ccs_ord += sub_ccs_ord
            todo_next += sub_todo_next

        todo_ccs = todo_next
        todo_next = []
        n_loop += 1
    return ccs_ord 
Example 77
Project: crnpy   Author: etonello   File: crn.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def split_by_ems(self, same_react = False, warn = False):
        """Split reactions according to the elementary modes they take part in.

        Return a list of reactions grouped by elementary mode, and the list of reactions
        not taking part in any elementary mode.

        :param same_react: if True, do not split reactions with the same reactant.
        :type same_react: boolean
        :param warn: if True, give a warning if not all reactions take part in at least
                     one elementary mode.
        :type warn: boolean

        :rtype: (list of lists reactions, list of reactions).
        """
        subnet = {}
        tinvs = self.t_invariants

        if tinvs.rows == 0:
            return [self.reactions], []

        # case of reactions not taking part in any em
        if warn:
            if any(sum(tinvs[:, c]) == 0 for c in range(tinvs.cols)):
                warnings.warn("Network not covered by elementary modes.")

        a = sp.SparseMatrix(sp.zeros(self.n_reactions))
        for t in range(tinvs.rows):
            inds = [r for r in range(self.n_reactions) if tinvs[t, r] != 0]
            for i in inds:
                for j in inds:
                    a[i, j] = 1
        if same_react:
            for c in self.complexes:
                inds = [r for r in range(self.n_reactions) if self.reactions[r].reactant == c]
                for i in inds:
                    for j in inds:
                        a[i, j] = 1
        ncc, cc = connected_components(csr_matrix(np.array(a.tolist()).astype(np.int)))
        rcc = [[self.reactions[r] for r in range(self.n_reactions) if cc[r] == l] for l in range(ncc)]

        return [rc for rc in rcc if len(rc) > 1], [rc[0] for rc in rcc if len(rc) == 1]


    ### Print ### 
Example 78
Project: antitile   Author: brsr   File: gcopoly.py    MIT License 4 votes vote down vote up
def _find_dupe_verts(base, bf, group, freq, bkdns):
    """
    Find duplicate vertices in a subdivided polyhedron.

    Args:
        base: Base polyhedron
        bf: Corresponding base face of each vertex
        group: Group number of each vertex
        freq: Frequency of subdivision (a 2-tuple)
        bkdns: A map from {3, 4} to the breakdown structures for
            triangle and quadrilaterals, respectively.
    """
    #find redundant vertices
    base_edges = base.edges
    base_edge_corr, base_face_corr = base.faces_by_edge(base_edges)
    l0 = []
    l1 = []
    for i in range(len(base_edges)):
        edge = base_edges[i]
        index = base_edge_corr == i
        facex = base_face_corr[index]
        fn = len(facex)
        if fn > 2:
            warnings.warn("More than 2 faces meet at a single edge. "
                          "Choosing 2 faces arbitrarily...")
            facex = facex[:2]
        elif fn < 2:#external edge, skip it
            continue
        index_0 = bf == facex[0]
        index_1 = bf == facex[1]
        faces = [base.faces[facex[0]], base.faces[facex[1]]]
        match = _stitch(edge, faces, bkdns, freq)
        lx0 = np.argwhere(index_0)[match[..., 0]].flatten()
        lx1 = np.argwhere(index_1)[match[..., 1]].flatten()
        l0.extend(lx0)
        l1.extend(lx1)
    matches = np.stack([l0, l1], axis=-1)
    #TODO replace this with np.unique when 1.13 comes out
    matches = np.array(sorted(list({tuple(sorted(t)) for t in matches})))
    vno = len(group)
    conns = sparse.coo_matrix((np.ones(len(matches)),
                               (matches[:, 0], matches[:, 1])),
                              shape=(vno, vno))
    ncp, cp = csgraph.connected_components(conns)
    verts = np.arange(vno, dtype=int)
    for i in range(ncp):
        component = np.argwhere(cp == i).flatten()
        gp = group[component]
        order = np.argsort(gp)
        component = component[order]
        v = verts[component[0]]
        verts[component] = v
    unique_index = verts == np.arange(len(verts))
    renumbered = xmath.renumber(unique_index)
    return renumbered[verts], unique_index 
Example 79
Project: antitile   Author: brsr   File: tiling.py    MIT License 4 votes vote down vote up
def id_dupe_faces(self, face_group=None, oriented=False):
        """Identify duplicate faces. Should use `normalize_faces` first.

        Args:
            face_group: Optional. Of a collection with duplicate faces,
                the faces with lowest value will be preferred to those
                with higher values. By default, just uses the face that
                is earlier in the face list.
            oriented: If True, consider opposite orientations of
                the same face to be different. Default False.

        Returns:
            An array of face indexes. Non-duplicated faces will have an entry
            equal to its position in the array. If a face is duplicated, its
            antry will equal the preferred face's position
        """
        if face_group is None:
            face_group = np.zeros(len(self.faces))
        fs = self.faces_by_size
        fn = self.face_size
        n = len(fn)
        comp = np.zeros((n, n), dtype=bool)
        for i in fs:
            faces = fs[i]
            index = fn == i
            #TODO replace this with np.unique when 1.13 comes out
            reps = np.all(faces[:, np.newaxis] == faces[np.newaxis], axis=-1)
            if not oriented:
                revfaces = np.roll(faces[..., ::-1], 1, axis=-1)
                revreps = np.all(faces[:, np.newaxis] == revfaces[np.newaxis],
                                 axis=-1)
                reps |= revreps
            reps[np.diag_indices_from(reps)] = False
            comp[np.ix_(index, index)] = reps
        ncp, cp = csgraph.connected_components(comp)
        result = np.ones(n, dtype=bool)
        for i in range(ncp):
            index = cp == i
            fg = face_group[index]
            am = np.argmin(fg)
            result_i = np.zeros(fg.shape, dtype=bool)
            result_i[am] = True
            result[index] = result_i
        return result 
Example 80
Project: wine-ml-on-aws-lambda   Author: pierreant   File: hierarchical.py    Apache License 2.0 4 votes vote down vote up
def _fix_connectivity(X, connectivity, affinity):
    """
    Fixes the connectivity matrix

        - copies it
        - makes it symmetric
        - converts it to LIL if necessary
        - completes it if necessary
    """
    n_samples = X.shape[0]
    if (connectivity.shape[0] != n_samples or
            connectivity.shape[1] != n_samples):
        raise ValueError('Wrong shape for connectivity matrix: %s '
                         'when X is %s' % (connectivity.shape, X.shape))

    # Make the connectivity matrix symmetric:
    connectivity = connectivity + connectivity.T

    # Convert connectivity matrix to LIL
    if not sparse.isspmatrix_lil(connectivity):
        if not sparse.isspmatrix(connectivity):
            connectivity = sparse.lil_matrix(connectivity)
        else:
            connectivity = connectivity.tolil()

    # Compute the number of nodes
    n_components, labels = connected_components(connectivity)

    if n_components > 1:
        warnings.warn("the number of connected components of the "
                      "connectivity matrix is %d > 1. Completing it to avoid "
                      "stopping the tree early." % n_components,
                      stacklevel=2)
        # XXX: Can we do without completing the matrix?
        for i in xrange(n_components):
            idx_i = np.where(labels == i)[0]
            Xi = X[idx_i]
            for j in xrange(i):
                idx_j = np.where(labels == j)[0]
                Xj = X[idx_j]
                D = pairwise_distances(Xi, Xj, metric=affinity)
                ii, jj = np.where(D == np.min(D))
                ii = ii[0]
                jj = jj[0]
                connectivity[idx_i[ii], idx_j[jj]] = True
                connectivity[idx_j[jj], idx_i[ii]] = True

    return connectivity, n_components


###############################################################################
# Hierarchical tree building functions