Make a sparse matrix from an encoded array.

    >>> construct(np.array([0, 1, 0]), np.array([0, 1])).toarray()
    array([[1., 0.],
           [0., 1.],
           [1., 0.]])
552026
def _construct(x, categories):
    
    # type: (np.ndarray, np.ndarray) -> scipy.sparse.csr_matrix
    data = np.ones(len(x))
    rows = np.arange(len(x))
    columns = x.ravel()
    return scipy.sparse.csr_matrix(
        (data, (rows, columns)), shape=(len(x), len(categories))
    )
896113
def convert_sparse_to_dataframe(spark, context, sparse_matrix):
    
    m = sparse_matrix.tocoo()
    data = context.parallelize(numpy.array([m.row, m.col, m.data]).T,
                               numSlices=len(m.row)/1024)
    return spark.createDataFrame(data.map(lambda p: Row(row=int(p[0]),
                                                        col=int(p[1]),
                                                        data=float(p[2]))))
629637
def from_array(arr, name=None):  # type: (np.ndarray[Any], Optional[Text]) -> TensorProto
    
    tensor = TensorProto()
    tensor.dims.extend(arr.shape)
    if name:
        tensor.name = name

    if arr.dtype == np.object:
        # Special care for strings.
        tensor.data_type = mapping.NP_TYPE_TO_TENSOR_TYPE[arr.dtype]
        # TODO: Introduce full string support.
        # We flatten the array in case there are 2-D arrays are specified
        # We throw the error below if we have a 3-D array or some kind of other
        # object. If you want more complex shapes then follow the below instructions.
        # Unlike other types where the shape is automatically inferred from
        # nested arrays of values, the only reliable way now to feed strings
        # is to put them into a flat array then specify type astype(np.object)
        # (otherwise all strings may have different types depending on their length)
        # and then specify shape .reshape([x, y, z])
        flat_array = arr.flatten()
        for e in flat_array:
            if isinstance(e, text_type):
                tensor.string_data.append(e.encode('utf-8'))
            elif isinstance(e, np.ndarray):
                for s in e:
                    if isinstance(s, text_type):
                        tensor.string_data.append(s.encode('utf-8'))
            else:
                raise NotImplementedError(
                    "Unrecognized object in the object array, expect a string, or array of bytes: ", str(type(e)))
        return tensor

    # For numerical types, directly use numpy raw bytes.
    try:
        dtype = mapping.NP_TYPE_TO_TENSOR_TYPE[arr.dtype]
    except KeyError:
        raise RuntimeError(
            "Numpy data type not understood yet: {}".format(str(arr.dtype)))
    tensor.data_type = dtype
    tensor.raw_data = arr.tobytes()  # note: tobytes() is only after 1.9.

    return tensor
895740
public static Basic1DMatrix from2DArray(double[][] array) {
        int rows = array.length;
        int columns = array[0].length;
        double[] array1D = new double[rows * columns];

        int offset = 0;
        for (int i = 0; i < rows; i++) {
            System.arraycopy(array[i], 0, array1D, offset, columns);
            offset += columns;
        }

        return new Basic1DMatrix(rows, columns, array1D);
    }
1265398
def make_2d(array, verbose=True):
    
    array = np.asarray(array)
    if array.ndim < 2:
        msg = 'Expected 2D input data array, but found {}D. '\
              'Expanding to 2D.'.format(array.ndim)
        if verbose:
            warnings.warn(msg)
        array = np.atleast_1d(array)[:,None]
    return array
347553
function makeMatrix(columns, rows) {
  let matrix = [];
  for (let i = 0; i < columns; i++) {
    let column = [];
    for (let j = 0; j < rows; j++) {
      column.push(0);
    }
    matrix.push(column);
  }
  return matrix;
}
616238
private static void enlargeTables(float[][] data, int[][] rowIndex, int cols, int currentRow, int currentCol) {
        while (data[currentRow].length < currentCol + cols) {
            if(data[currentRow].length == SPARSE_MATRIX_DIM) {
                currentCol = 0;
                cols -= (data[currentRow].length - currentCol);
                currentRow++;
                data[currentRow] = malloc4f(ALLOCATED_ARRAY_LEN);
                rowIndex[currentRow] = malloc4(ALLOCATED_ARRAY_LEN);
            } else {
                int newLen = (int) Math.min((long) data[currentRow].length << 1L, (long) SPARSE_MATRIX_DIM);
                data[currentRow] = Arrays.copyOf(data[currentRow], newLen);
                rowIndex[currentRow] = Arrays.copyOf(rowIndex[currentRow], newLen);
            }
        }
    }
480378
def convert_inputs_to_sparse_if_necessary(lhs, rhs):
    '''
    
    '''
    if not sp.issparse(lhs) or not sp.issparse(rhs):
        if sparse_is_desireable(lhs, rhs):
            if not sp.issparse(lhs):
                lhs = sp.csc_matrix(lhs)
                #print "converting lhs into sparse matrix"
            if not sp.issparse(rhs):
                rhs = sp.csc_matrix(rhs)
                #print "converting rhs into sparse matrix"
    return lhs, rhs
475694
def scipy_sparse_to_csv(filepath, matrix, separator=",", directed=False, numbering="matlab"):
    
    matrix = spsp.coo_matrix(matrix)

    shape = matrix.shape
    nnz = matrix.getnnz()

    if numbering == "matlab":
        row = matrix.row + 1
        col = matrix.col + 1
        data = matrix.data
    elif numbering == "c":
        row = matrix.row
        col = matrix.col
        data = matrix.data
    else:
        print("Invalid numbering style.")
        raise RuntimeError

    with open(filepath, "w") as f:
        # Write metadata.
        file_row = "n_rows:" + separator + str(shape[0]) + separator +\
                   "n_cols:" + separator + str(shape[1]) + separator +\
                   "nnz:" + separator + str(nnz) + separator +\
                   "directed:" + separator + str(directed) +\
                   "\n"
        f.write(file_row)

        for edge in range(row.size):
            if directed is False:
                if col[edge] < row[edge]:
                    continue
            file_row = str(row[edge]) + separator + str(col[edge]) + separator + str(data[edge]) + "\n"
            f.write(file_row)
881830
def fast_inverse(M):
    
    diags = M.diagonal()
    new_diag = []
    for value in diags:
        new_diag.append(1.0/value)

    return sparse.diags([new_diag], [0])
508441
public void convertToDense() {
        switch ( mat.getType() ) {
            case DSCC: {
                DMatrix m = new DMatrixRMaj(mat.getNumRows(), mat.getNumCols());
                ConvertDMatrixStruct.convert((DMatrix) mat, m);
                setMatrix(m);
            } break;
            case FSCC: {
                FMatrix m = new FMatrixRMaj(mat.getNumRows(), mat.getNumCols());
                ConvertFMatrixStruct.convert((FMatrix) mat, m);
                setMatrix(m);
            } break;
            case DDRM:
            case FDRM:
            case ZDRM:
            case CDRM:
                break;
            default:
                throw new RuntimeException("Not a sparse matrix!");
        }
    }
798227
def _to_array(self, alpha, normalization='4pi', csphase=1):
        
        coeffs = _shtools.SHVectorToCilm(self.tapers[:, alpha])

        if normalization == 'schmidt':
            for l in range(self.lmax + 1):
                coeffs[:, l, :l+1] *= _np.sqrt(2.0 * l + 1.0)
        elif normalization == 'ortho':
            coeffs *= _np.sqrt(4.0 * _np.pi)

        if csphase == -1:
            for m in range(self.lmax + 1):
                if m % 2 == 1:
                    coeffs[:, :, m] = - coeffs[:, :, m]

        return coeffs
1288581
private SparseMatrix retainColumns(Set<Integer> indicesToKeep) {
        int words = termToIndex.numDimensions();
        int cols = indicesToKeep.size();

        // Create a mapping from old indices to their new index value.
        Map<Integer, Integer> indexMap = new HashMap<Integer, Integer>();
        int newIndex = 0;
        for (Integer index : indicesToKeep)
            indexMap.put(index, newIndex++);

        // Create a reduced matrix that will have only the selected columns in
        // the final space.
        SparseMatrix reduced = new YaleSparseMatrix(
                words, indicesToKeep.size());

        // Iterate over the sparse values in the matrix for added efficiency.
        for (int row = 0; row < words; ++ row) {
            SparseDoubleVector sv = cooccurrenceMatrix.getRowVector(row);
            for (int col : sv.getNonZeroIndices()) {
                double v = cooccurrenceMatrix.get(row, col);

                // If the original column was retained, get it's new index
                // value and add it to the reduced matrix.
                Integer newColIndex = indexMap.get(col);
                if (newColIndex != null)
                    reduced.set(row, newColIndex, v);

                // If the transposed row column was retained, get it's new index
                // value and add it to the reduced matrix.  This turns the col
                // value into the row and the new index as the column.
                newColIndex = indexMap.get(row + words);
                if (newColIndex != null)
                    reduced.set(col, newColIndex, v);
            }
        }

        return reduced;
    }
173161
public static Matrix from1DArray(int rows, int columns, double[] array) {
        return Basic1DMatrix.from1DArray(rows, columns, array);
    }
799277
def _parse_array(self, tensor_proto):
        """"""
        try:
            from onnx.numpy_helper import to_array
        except ImportError as e:
            raise ImportError("Unable to import onnx which is required {}".format(e))
        np_array = to_array(tensor_proto).reshape(tuple(tensor_proto.dims))
        return mx.nd.array(np_array)
735538
def to_vector(np_array):
    
    if len(np_array.shape) == 1:
        return Vectors.dense(np_array)
    else:
        raise Exception("An MLLib Vector can only be created from a one-dimensional " +
                        "numpy array, got {}".format(len(np_array.shape)))
562595
def asML(self):
        
        return newlinalg.SparseMatrix(self.numRows, self.numCols, self.colPtrs, self.rowIndices,
                                      self.values, self.isTransposed)