Parameters
        ----------
        adjacency_mat : sparse matrix (N_obs, N_obs)
            The adjacency matrix to input.
492771
def set_adjacency_matrix(self, adjacency_mat):
        
        adjacency_mat = check_array(adjacency_mat, accept_sparse=sparse_formats)
        if adjacency_mat.shape[0] != adjacency_mat.shape[1]:
            raise ValueError("adjacency matrix is not square")
        self.adjacency_matrix = adjacency_mat
688269
def sparse(self, rows: np.ndarray, cols: np.ndarray) -> scipy.sparse.coo_matrix:
		
		return scipy.sparse.coo_matrix(self.values[rows, :][:, cols])
1318117
def etree(A):
    
    assert isinstance(A,spmatrix), "A must be a sparse matrix"
    assert A.size[0] == A.size[1], "A must be a square matrix"

    n = A.size[0]
    cp,ri,_ = A.CCS
    parent = matrix(0,(n,1))
    w = matrix(0,(n,1))

    for k in range(n):
        parent[k] = k
        w[k] = -1
        for p in range(cp[k],cp[k+1]):
            i = ri[p]
            while ((not i == -1) and (i < k)):
                inext = w[i]
                w[i] = k
                if inext == -1: parent[i] = k
                i = inext;

    return parent
1343145
def _row_sparse_ndarray_from_definition(data, indices, shape=None, ctx=None,
                                        dtype=None, indices_type=None):
    """"""
    storage_type = 'row_sparse'
    # context
    ctx = current_context() if ctx is None else ctx
    # types
    dtype = _prepare_default_dtype(data, dtype)
    indices_type = _STORAGE_AUX_TYPES[storage_type][0] if indices_type is None else indices_type
    # prepare src array and types
    data = _prepare_src_array(data, dtype)
    indices = _prepare_src_array(indices, indices_type)

    # TODO(junwu): Convert data, indptr, and indices to mxnet NDArrays
    # if they are not for now. In the future, we should provide a c-api
    # to accept np.ndarray types to copy from to result.data and aux_data
    if not isinstance(data, NDArray):
        data = _array(data, ctx, dtype)
    if not isinstance(indices, NDArray):
        indices = _array(indices, ctx, indices_type)
    if shape is None:
        num_indices = indices.shape[0]
        if num_indices == 0:
            raise ValueError('invalid shape')
        dim0 = indices[num_indices - 1].asscalar() + 1
        shape = (dim0, ) + data.shape[1:]
    # verify shapes
    if data.ndim != len(shape) or indices.ndim != 1 or np.prod(shape[1:]) == 0:
        raise ValueError("invalid shape")
    result = RowSparseNDArray(_new_alloc_handle(storage_type, shape, ctx, False, dtype,
                                                [indices_type], [indices.shape]))
    check_call(_LIB.MXNDArraySyncCopyFromNDArray(result.handle, data.handle, ctypes.c_int(-1)))
    check_call(_LIB.MXNDArraySyncCopyFromNDArray(result.handle, indices.handle, ctypes.c_int(0)))
    return result
368827
private Matrix loadSparseBinary(InputStream fileStream) throws IOException {
        DataInputStream dis = new DataInputStream(fileStream);
        int rows = dis.readInt();
        int cols = dis.readInt();
        // Create the sparse matrix as individual rows since we can fully
        // allocate the indices values at once, rather than pay the log(n)
        // overhead of sorting them
        CompactSparseVector[] rowVectors = new CompactSparseVector[rows];

        for (int row = 0; row < rows; ++row) {
            String word = dis.readUTF();
            termToIndex.put(word, row);
            
            int nonZero = dis.readInt();
            int[] indices = new int[nonZero];
            double[] values = new double[nonZero];
            for (int i = 0; i < nonZero; ++i) {
                int nz = dis.readInt();
                double val = dis.readDouble();
                indices[i] = nz;
                values[i] = val;
            }
            rowVectors[row] = new CompactSparseVector(indices, values, cols);
        }
        return Matrices.asSparseMatrix(Arrays.asList(rowVectors));
    }
883931
def get_matrix(self):
        
        # Init matrix (remember, a matrix, not an array)
        a = np.zeros((4, 4), dtype=np.float32)
        w, x, y, z = self.w, self.x, self.y, self.z
        # First row
        a[0, 0] = - 2.0 * (y * y + z * z) + 1.0
        a[1, 0] = + 2.0 * (x * y + z * w)
        a[2, 0] = + 2.0 * (x * z - y * w)
        a[3, 0] = 0.0
        # Second row
        a[0, 1] = + 2.0 * (x * y - z * w)
        a[1, 1] = - 2.0 * (x * x + z * z) + 1.0
        a[2, 1] = + 2.0 * (z * y + x * w)
        a[3, 1] = 0.0
        # Third row
        a[0, 2] = + 2.0 * (x * z + y * w)
        a[1, 2] = + 2.0 * (y * z - x * w)
        a[2, 2] = - 2.0 * (x * x + y * y) + 1.0
        a[3, 2] = 0.0
        # Fourth row
        a[0, 3] = 0.0
        a[1, 3] = 0.0
        a[2, 3] = 0.0
        a[3, 3] = 1.0
        return a
781942
def set_laplacian_matrix(self, laplacian_mat):
        
        laplacian_mat = check_array(laplacian_mat, accept_sparse = sparse_formats)
        if laplacian_mat.shape[0] != laplacian_mat.shape[1]:
            raise ValueError("Laplacian matrix is not square")
        self.laplacian_matrix = laplacian_mat
562076
private static int getDataRows(Chunk[] chunks, Frame f, int[] chunksIds, int cols) {
        double totalRows = 0;
        if(null != chunks) {
            for (Chunk ch : chunks) {
                totalRows += ch.len();
            }
        } else {
            for(int chunkId : chunksIds) {
                totalRows += f.anyVec().chunkLen(chunkId);
            }
        }
        return (int) Math.ceil(totalRows * cols / SPARSE_MATRIX_DIM);
    }
351599
def draw_sparse_matrix(
    array_filename,
    output_image,
    vmax=DEFAULT_SATURATION_THRESHOLD,
    max_size_matrix=DEFAULT_MAX_SIZE_MATRIX,
):
    

    matrix = np.loadtxt(array_filename, dtype=np.int32, skiprows=1)
    try:
        row, col, data = matrix.T
    except ValueError:
        row, col, data = matrix
    size = max(np.amax(row), np.amax(col)) + 1
    S = sparse.coo_matrix((data, (row, col)), shape=(size, size))
    if max_size_matrix <= 0:
        binning = 1
    else:
        binning = (size // max_size_matrix) + 1
    binned_S = hcs.bin_sparse(S, subsampling_factor=binning)
    dense_S = binned_S.todense()
    dense_S = dense_S + dense_S.T - np.diag(np.diag(dense_S))
    normed_S = hcs.normalize_dense(dense_S)
    spaceless_pdf_plot_maker(normed_S, output_image, vmax=vmax)
1061856
def sparse(csv, sparse):
    ''' 
    '''
    import pandas as pd
    df = pd.read_csv(csv, index_col=0, header=0)
    pd.Series(df.index).to_csv(sparse + ".rownames", index=False)
    pd.Series(df.columns.values).to_csv(sparse + ".colnames", index=False)
    with open(sparse, "w+b") as out_handle:
        scipy.io.mmwrite(out_handle, scipy.sparse.csr_matrix(df))
655298
def matrix(self) -> np.ndarray:
        
        num_qubits = self.num_qubits()
        if num_qubits is None:
            raise ValueError('Unknown number of qubits')
        num_dim = 2 ** num_qubits
        result = np.zeros((num_dim, num_dim), dtype=np.complex128)
        for gate, coefficient in self.items():
            result += protocols.unitary(gate) * coefficient
        return result
400752
def spectral_embedding(self, n):
        
        coords = spectral_embedding(self._affinity, n)
        return CoordinateMatrix(normalise_rows(coords))
621500
def compute_adjacency_matrix(X, method='auto', **kwargs):
    """"""
    if method == 'auto':
        if X.shape[0] > 10000:
            method = 'cyflann'
        else:
            method = 'kd_tree'
    return Adjacency.init(method, **kwargs).adjacency_graph(X.astype('float'))
1183482
def set_edges(self, name: str, a: np.ndarray, b: np.ndarray, w: np.ndarray, *, axis: int) -> None:
		
		deprecated("'set_edges' is deprecated. Use 'ds.row_graphs[name] = g' or 'ds.col_graphs[name] = g' instead")
		try:
			g = scipy.sparse.coo_matrix((w, (a, b)), (self.shape[axis], self.shape[axis]))
		except Exception:
			raise ValueError("Input arrays could not be converted to a sparse matrix")
		if axis == 0:
			self.row_graphs[name] = g
		elif axis == 1:
			self.col_graphs[name] = g
		else:
			raise ValueError("axis must be 0 (rows) or 1 (columns)")
1238289
def array2d(X, dtype=None, order=None, copy=False):
    """"""
    if sp.issparse(X):
        raise TypeError('A sparse matrix was passed, but dense data '
                        'is required. Use X.toarray() to convert to dense.')
    X_2d = np.asarray(np.atleast_2d(X), dtype=dtype, order=order)
    _assert_all_finite(X_2d)
    if X is X_2d and copy:
        X_2d = safe_copy(X_2d)
    return X_2d
363072
def transition_matrix_sparse(self):
        
        P = diags([self.q[1:], self.r, self.p[0:-1]], [-1, 0, 1])
        return P
1352783
def _zero_many(self, i, j):
    
    i, j, M, N = self._prepare_indices(i, j)

    n_samples = len(i)
    offsets = np.empty(n_samples, dtype=self.indices.dtype)
    ret = _sparsetools.csr_sample_offsets(M, N, self.indptr, self.indices,
                                          n_samples, i, j, offsets)
    if ret == 1:
        # rinse and repeat
        self.sum_duplicates()
        _sparsetools.csr_sample_offsets(M, N, self.indptr,
                                        self.indices, n_samples, i, j,
                                        offsets)

    # only assign zeros to the existing sparsity structure
    self.data[list(offsets[offsets > -1])] = 0