Construct a sparse adj matrix from a matrix of points (one per row).
  Non-zeros are unweighted/binary distance values, depending on the binary arg.
  Doesn't include self-edges.
12424
def _sparse_neighbor_graph(X, k, binary=False, metric='l2'):
  ''''''
  knn = NearestNeighbors(n_neighbors=k, metric=metric).fit(X)
  mode = 'connectivity' if binary else 'distance'
  try:
    adj = knn.kneighbors_graph(None, mode=mode)
  except IndexError:
    # XXX: we must be running an old (<0.16) version of sklearn
    #  We have to hack around an old bug:
    if binary:
      adj = knn.kneighbors_graph(X, k+1, mode=mode)
      adj.setdiag(0)
    else:
      adj = knn.kneighbors_graph(X, k, mode=mode)
  return Graph.from_adj_matrix(adj)
1154267
protected static void constructM(List<Point2D_F64> obsPts,
									 DMatrixRMaj alphas, DMatrixRMaj M)
	{
		int N = obsPts.size();
		M.reshape(3*alphas.numCols,2*N,false);

		for( int i = 0; i < N; i++ ) {
			Point2D_F64 p2 = obsPts.get(i);

			int row = i*2;

			for( int j = 0; j < alphas.numCols; j++ ) {
				int col = j*3;

				double alpha = alphas.unsafe_get(i, j);
				M.unsafe_set(col, row, alpha);
				M.unsafe_set(col + 1, row, 0);
				M.unsafe_set(col + 2, row, -alpha * p2.x);
				M.unsafe_set(col    , row + 1, 0);
				M.unsafe_set(col + 1, row + 1, alpha);
				M.unsafe_set(col + 2, row + 1, -alpha * p2.y);
			}
		}
	}
1150301
void constructMatrix(DMatrixRMaj L) {
		L.reshape(cameras.size*eqs,10);

		// Known aspect ratio constraint makes more sense as a square
		double RR = this.aspectRatio *this.aspectRatio;

		// F = P*Q*P'
		// F is an arbitrary variable name and not fundamental matrix
		int index = 0;
		for (int i = 0; i < cameras.size; i++) {
			Projective P = cameras.get(i);
			DMatrix3x3 A = P.A;
			DMatrix3 B = P.a;

			// hard to tell if this helped or hurt. Keeping commented out for future investigation on proper scaling
//			double scale = NormOps_DDF3.normF(P.A);
//			CommonOps_DDF3.divide(P.A,scale);
//			CommonOps_DDF3.divide(P.a,scale);

			// constraint for a zero principle point

			// row for F[0,2] == 0
			L.data[index++] = A.a11*A.a31;
			L.data[index++] = (A.a12*A.a31 + A.a11*A.a32);
			L.data[index++] = (A.a13*A.a31 + A.a11*A.a33);
			L.data[index++] = (B.a1*A.a31 + A.a11*B.a3);
			L.data[index++] = A.a12*A.a32;
			L.data[index++] = (A.a13*A.a32 + A.a12*A.a33);
			L.data[index++] = (B.a1*A.a32 + A.a12*B.a3);
			L.data[index++] = A.a13*A.a33;
			L.data[index++] = (B.a1*A.a33 + A.a13*B.a3);
			L.data[index++] = B.a1*B.a3;

			// row for F[1,2] == 0
			L.data[index++] = A.a21*A.a31;
			L.data[index++] = (A.a22*A.a31 + A.a21*A.a32);
			L.data[index++] = (A.a23*A.a31 + A.a21*A.a33);
			L.data[index++] = (B.a2*A.a31 + A.a21*B.a3);
			L.data[index++] = A.a22*A.a32;
			L.data[index++] = (A.a23*A.a32 + A.a22*A.a33);
			L.data[index++] = (B.a2*A.a32 + A.a22*B.a3);
			L.data[index++] = A.a23*A.a33;
			L.data[index++] = (B.a2*A.a33 + A.a23*B.a3);
			L.data[index++] = B.a2*B.a3;

			if( zeroSkew ) {
				// row for F[0,1] == 0
				L.data[index++] = A.a11*A.a21;
				L.data[index++] = (A.a12*A.a21 + A.a11*A.a22);
				L.data[index++] = (A.a13*A.a21 + A.a11*A.a23);
				L.data[index++] = (B.a1*A.a21 + A.a11*B.a2);
				L.data[index++] = A.a12*A.a22;
				L.data[index++] = (A.a13*A.a22 + A.a12*A.a23);
				L.data[index++] = (B.a1*A.a22 + A.a12*B.a2);
				L.data[index++] = A.a13*A.a23;
				L.data[index++] = (B.a1*A.a23 + A.a13*B.a2);
				L.data[index++] = B.a1*B.a2;
			}

			if( knownAspect ) {
				// aspect^2*F[0,0]-F[1,1]
				L.data[index++] = A.a11*A.a11*RR - A.a21*A.a21;
				L.data[index++] = 2*(A.a11*A.a12*RR - A.a21*A.a22);
				L.data[index++] = 2*(A.a11*A.a13*RR - A.a21*A.a23);
				L.data[index++] = 2*(A.a11*B.a1*RR - A.a21*B.a2);
				L.data[index++] = A.a12*A.a12*RR - A.a22*A.a22;
				L.data[index++] = 2*(A.a12*A.a13*RR - A.a22*A.a23);
				L.data[index++] = 2*(A.a12*B.a1*RR - A.a22*B.a2);
				L.data[index++] = A.a13*A.a13*RR - A.a23*A.a23;
				L.data[index++] = 2*(A.a13*B.a1*RR - A.a23*B.a2);
				L.data[index++] = B.a1*B.a1*RR - B.a2*B.a2;
			}
		}
	}
198079
public static SparseTensor diagonal(int[] dimensionNumbers, int[] dimensionSizes, double value) {
    int minDimensionSize = Ints.min(dimensionSizes);
    double[] values = new double[minDimensionSize];
    Arrays.fill(values, value);

    return diagonal(dimensionNumbers, dimensionSizes, values);
  }
1143022
def _init_matrix(self, data, index, columns, dtype=None):
        
        data = prep_ndarray(data, copy=False)
        index, columns = self._prep_index(data, index, columns)
        data = {idx: data[:, i] for i, idx in enumerate(columns)}
        return self._init_dict(data, index, columns, dtype)
457736
def one_hot(cls, ij, sz):
        
        if isinstance(sz, int):
            sz = (sz, sz)
        if isinstance(ij, int):
            ij = (ij, ij)
        m = np.zeros(sz)
        m[ij[0], ij[1]] = 1.0
        return Matrix(m)
363072
def transition_matrix_sparse(self):
        
        P = diags([self.q[1:], self.r, self.p[0:-1]], [-1, 0, 1])
        return P
671325
def perm(A, p):
    
    assert isinstance(A,spmatrix), "argument must be a sparse matrix"
    assert A.size[0] == A.size[1], "A must be a square matrix"
    assert A.size[0] == len(p), "length of p must be equal to the order of A"
    return A[p,p]
91599
public static SparseMatrix from1DArray(int rows, int columns, double[] array) {
        return CRSMatrix.from1DArray(rows, columns, array);
    }
625827
def numpy_array_from_list_or_numpy_array(vectors):
    
    # If vectors is not a numpy matrix, create one
    if not isinstance(vectors, numpy.ndarray):
        V = numpy.zeros((vectors[0].shape[0], len(vectors)))
        for index in range(len(vectors)):
            vector = vectors[index]
            V[:, index] = vector
        return V

    return vectors
1347343
def _M2_sparse(Xvar, mask_X, Yvar, mask_Y, weights=None):
    
    C = np.zeros((len(mask_X), len(mask_Y)))
    C[np.ix_(mask_X, mask_Y)] = _M2_dense(Xvar, Yvar, weights=weights)
    return C
100370
def from_array(cls, arr, index=None, name=None, dtype=None, copy=False,
                   fastpath=False):
        
        warnings.warn("'from_array' is deprecated and will be removed in a "
                      "future version. Please use the pd.Series(..) "
                      "constructor instead.", FutureWarning, stacklevel=2)
        if isinstance(arr, ABCSparseArray):
            from pandas.core.sparse.series import SparseSeries
            cls = SparseSeries
        return cls(arr, index=index, name=name, dtype=dtype,
                   copy=copy, fastpath=fastpath)
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))
1186064
def as_ord_matrix(matrix, alphabet):
    ''''''
    ords = [ord(c) for c in alphabet]
    ord_matrix = np.zeros((max(ords) + 1, max(ords) + 1), dtype=np.integer)
    for i, row_ord in enumerate(ords):
        for j, col_ord in enumerate(ords):
            ord_matrix[row_ord, col_ord] = matrix[i, j]

    return ord_matrix
1283007
def as_sparse_array(self, kind=None, fill_value=None, copy=False):
        

        if fill_value is None:
            fill_value = self.fill_value
        if kind is None:
            kind = self.kind
        return SparseArray(self.values, sparse_index=self.sp_index,
                           fill_value=fill_value, kind=kind, copy=copy)
906416
def get_sparse_matrix(session, key_table, cand_lists, key=None):
    """"""
    result = []
    cand_lists = cand_lists if isinstance(cand_lists, (list, tuple)) else [cand_lists]

    for cand_list in cand_lists:
        if len(cand_list) == 0:
            raise ValueError("cand_lists contain empty cand_list.")
        candidate_class = cand_list[0].__tablename__

        # Keys are used as a global index
        if key:
            keys_map = {key: 0}
            key_size = len(keys_map)
        else:
            all_keys = get_sparse_matrix_keys(session, key_table)
            key_size = len(all_keys)
            keys_map = {}
            for (i, k) in enumerate(all_keys):
                if candidate_class in k.candidate_classes:
                    keys_map[k.name] = i

        indptr = [0]
        indices = []
        data = []
        for cand in cand_list:
            values = _get_cand_values(cand, key_table)
            if values:
                for cand_key, cand_value in zip(values[0].keys, values[0].values):
                    if cand_key in keys_map:
                        indices.append(keys_map[cand_key])
                        data.append(cand_value)

            indptr.append(len(indices))

        result.append(
            csr_matrix((data, indices, indptr), shape=(len(cand_list), key_size))
        )

    return result
1309522
def _init_spmatrix(self, data, index, columns, dtype=None,
                       fill_value=None):
        
        index, columns = self._prep_index(data, index, columns)
        data = data.tocoo()
        N = len(index)

        # Construct a dict of SparseSeries
        sdict = {}
        values = Series(data.data, index=data.row, copy=False)
        for col, rowvals in values.groupby(data.col):
            # get_blocks expects int32 row indices in sorted order
            rowvals = rowvals.sort_index()
            rows = rowvals.index.values.astype(np.int32)
            blocs, blens = get_blocks(rows)

            sdict[columns[col]] = SparseSeries(
                rowvals.values, index=index,
                fill_value=fill_value,
                sparse_index=BlockIndex(N, blocs, blens))

        # Add any columns that were empty and thus not grouped on above
        sdict.update({column: SparseSeries(index=index,
                                           fill_value=fill_value,
                                           sparse_index=BlockIndex(N, [], []))
                      for column in columns
                      if column not in sdict})

        return self._init_dict(sdict, index, columns, dtype)