Ensures that a given mapping matrix is a dense numpy array. Raises a
    helpful TypeError if otherwise.
336705
def ensure_object_is_ndarray(item, title):
    
    assert isinstance(title, str)

    if not isinstance(item, np.ndarray):
        msg = "{} must be a np.ndarray. {} passed instead."
        raise TypeError(msg.format(title, type(item)))

    return None
349059
def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None):
    """"""
    del weight_collections
    text_batch = tf.reshape(inputs.get(self), shape=[-1])
    m = module.Module(self.module_spec, trainable=self.trainable and trainable)
    return m(text_batch)
1204643
def _prepare_default_dtype(src_array, dtype):
    """"""
    if dtype is None:
        if isinstance(src_array, (NDArray, np.ndarray)):
            dtype = src_array.dtype
        elif spsp and isinstance(src_array, spsp.csr.csr_matrix):
            dtype = src_array.dtype
        else:
            dtype = mx_real_t
    return dtype
390126
def is_unitary(matrix: np.ndarray) -> bool:
    
    rows, cols = matrix.shape
    if rows != cols:
        return False
    return np.allclose(np.eye(rows), matrix.dot(matrix.T.conj()))
416384
public static DenseMatrix matrix(int nrows, int ncols) {
        if (nlmatrixZeros != null) {
            try {
                return (DenseMatrix) nlmatrixZeros.newInstance(nrows, ncols);
            } catch (Exception e) {
                logger.error("Failed to call NLMatrix(int, int): {}", e);
            }
        }

        return new JMatrix(nrows, ncols);
    }
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
610806
def _resize_with_dtype(arr, dtype):
    
    structured_arrays = dtype.names is not None and arr.dtype.names is not None
    old_columns = arr.dtype.names or []
    new_columns = dtype.names or []

    # In numpy 1.9 the ndarray.astype method used to handle changes in number of fields. The code below
    # should replicate the same behaviour the old astype used to have.
    #
    # One may be tempted to use np.lib.recfunctions.stack_arrays to implement both this step and the
    # concatenate that follows but it 2x slower and it requires providing your own default values (instead
    # of np.zeros).
    #
    # Numpy 1.14 supports doing new_arr[old_columns] = arr[old_columns], which is faster than the code below
    # (in benchmarks it seems to be even slightly faster than using the old astype). However, that is not
    # supported by numpy 1.9.2.
    if structured_arrays and (old_columns != new_columns):
        old_columns = set(old_columns)
        new_columns = set(new_columns)

        new_arr = np.zeros(arr.shape, dtype)
        for c in old_columns & new_columns:
            new_arr[c] = arr[c]

        # missing float columns should default to nan rather than zero
        _is_float_type = lambda _dtype: _dtype.type in (np.float32, np.float64)
        _is_void_float_type = lambda _dtype: _dtype.type == np.void and _is_float_type(_dtype.subdtype[0])
        _is_float_or_void_float_type = lambda _dtype: _is_float_type(_dtype) or _is_void_float_type(_dtype)
        _is_float = lambda column: _is_float_or_void_float_type(dtype.fields[column][0])
        for new_column in filter(_is_float, new_columns - old_columns):
            new_arr[new_column] = np.nan

        return new_arr.astype(dtype)
    else:
        return arr.astype(dtype)
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)))
895786
public static DenseMatrix matrix(double[][] A) {
        if (nlmatrixZeros != null) {
            try {
                return (DenseMatrix) nlmatrixArray2D.newInstance((Object) A);
            } catch (Exception e) {
                logger.error("Failed to call NLMatrix(double[][]): {}", e);
            }
        }

        return new JMatrix(A);
    }
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)
679008
def to_dense(self):
        """"""
        if hasattr(self._X_train, 'todense'):
            self._X_train = self._X_train.todense()
            self._X_test = self._X_test.todense()
143056
def bin_sparse(M, subsampling_factor=3):
    

    try:
        from scipy.sparse import coo_matrix
    except ImportError as e:
        print(str(e))
        print("I am peforming dense binning by default.")
        return bin_dense(M.todense())

    N = M.tocoo()
    n, m = N.shape
    row, col, data = N.row, N.col, N.data

    # Divide row and column indices - duplicate coordinates are added in
    # sparse matrix construction

    binned_row = row // subsampling_factor
    binned_col = col // subsampling_factor
    binned_n = n // subsampling_factor
    binned_m = m // subsampling_factor

    # Attach remaining columns and rows to the last one

    binned_row[binned_row >= binned_n] -= n % subsampling_factor
    binned_col[binned_col >= binned_m] -= m % subsampling_factor

    result = coo_matrix((data, (binned_row, binned_col)),
                        shape=(binned_n, binned_m))
    return result
230900
def unbroadcast(a, b):
    '''
    
    '''
    # they could be sparse:
    spa = sps.issparse(a)
    spb = sps.issparse(b)
    if   spa and spb: return (a,b)
    elif spa or  spb:
        def fix(sp,nm):
            nm = np.asarray(nm)
            dnm = len(nm.shape)
            nnm = np.prod(nm.shape)
            # if we have (sparse matrix) * (high-dim array), unbroadcast the dense array
            if   dnm == 0: return (sp, np.reshape(nm, (1,   1)))
            elif dnm == 1: return (sp, np.reshape(nm, (nnm, 1)))
            elif dnm == 2: return (sp, nm)
            else:          return unbroadcast(sp.toarray(), nm)
        return fix(a, b) if spa else tuple(reversed(fix(b, a)))
    # okay, no sparse matrices found:
    a = np.asarray(a)
    b = np.asarray(b)
    da = len(a.shape)
    db = len(b.shape)
    if   da > db: return (a, np.reshape(b, b.shape + tuple(np.ones(da-db, dtype=np.int))))
    elif da < db: return (np.reshape(a, a.shape + tuple(np.ones(db-da, dtype=np.int))), b)
    else:         return (a, b)
705231
def arrays_to_mgr(arrays, arr_names, index, columns, dtype=None):
    
    # figure out the index, if necessary
    if index is None:
        index = extract_index(arrays)
    else:
        index = ensure_index(index)

    # don't force copy because getting jammed in an ndarray anyway
    arrays = _homogenize(arrays, index, dtype)

    # from BlockManager perspective
    axes = [ensure_index(columns), index]

    return create_block_manager_from_arrays(arrays, arr_names, axes)
996296
def ensure_dtraj(dtraj):
    

    """
    if is_int_vector(dtraj):
        return dtraj
    elif is_list_of_int(dtraj):
        return np.array(dtraj, dtype=int)
    else:
        raise TypeError('Argument dtraj is not a discrete trajectory - only list of integers or int-ndarrays are allowed. Check type.')
1249526
def array(shape, dtype=_np.float64, autolock=False):
    """"""
    assert _NP_AVAILABLE, "To use the shared array object, numpy must be available!"
    if not isinstance(dtype, _np.dtype):
        dtype = _np.dtype(dtype)
    # Not bothering to translate the numpy dtypes to ctype types directly,
    # because they're only partially supported. Instead, create a byte ctypes
    # array of the right size and use a view of the appropriate datatype.
    shared_arr = _multiprocessing.Array(
        "b", int(_np.prod(shape) * dtype.alignment), lock=autolock
    )
    with _warnings.catch_warnings():
        # For more information on why this is necessary, see
        # https://www.reddit.com/r/Python/comments/j3qjb/parformatlabpool_replacement
        _warnings.simplefilter("ignore", RuntimeWarning)
        data = _np.ctypeslib.as_array(shared_arr).view(dtype).reshape(shape)
    return data
1276799
def is_undirected(matrix):
    
    if isspmatrix(matrix):
        return sparse_allclose(matrix, matrix.transpose())
    
    return np.allclose(matrix, matrix.T)