Apply the trimming procedure to a sparse matrix.

def trim_sparse(M, n_std=3, s_min=None, s_max=None):
    """Apply the trimming procedure to a sparse matrix.
    """

    try:
        from scipy.sparse import coo_matrix
    except ImportError as e:
        print(str(e))
        print("I am peforming dense normalization by default.")
        return trim_dense(M.todense())
    r = M.tocoo()
    sparsity = np.array(r.sum(axis=1)).flatten()
    mean = np.mean(sparsity)
    std = np.std(sparsity)
    if s_min is None:
        s_min = mean - n_std * std
    if s_max is None:
        s_max = mean + n_std * std
    f = (sparsity > s_min) * (sparsity < s_max)
    indices = [u for u in range(len(r.data)) if f[r.row[u]] and f[r.col[u]]]
    rows = np.array([r.row[i] for i in indices])
    cols = np.array([r.col[j] for j in indices])
    data = np.array([r.data[k] for k in indices])

    N = coo_matrix((data, (rows, cols)))
    return N