def _ensure_sparse_format(spmatrix, accept_sparse, dtype, copy,<EOL>force_all_finite):
if accept_sparse in [None, False]:<EOL><INDENT>raise TypeError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>if dtype is None:<EOL><INDENT>dtype = spmatrix.dtype<EOL><DEDENT>changed_format = False<EOL>if (isinstance(accept_sparse, (list, tuple))<EOL>and spmatrix.format not in accept_sparse):<EOL><INDENT>spmatrix = spmatrix.asformat(accept_sparse[<NUM_LIT:0>])<EOL>changed_format = True<EOL><DEDENT>if dtype != spmatrix.dtype:<EOL><INDENT>spmatrix = spmatrix.astype(dtype)<EOL><DEDENT>elif copy and not changed_format:<EOL><INDENT>spmatrix = spmatrix.copy()<EOL><DEDENT>if force_all_finite:<EOL><INDENT>if not hasattr(spmatrix, "<STR_LIT:data>"):<EOL><INDENT>warnings.warn("<STR_LIT>"<EOL>% spmatrix.format)<EOL><DEDENT>else:<EOL><INDENT>_assert_all_finite(spmatrix.data)<EOL><DEDENT><DEDENT>return spmatrix<EOL>
Convert a sparse matrix to a given format.
    Checks the sparse format of spmatrix and converts if necessary.
    Parameters
    ----------
    spmatrix : scipy sparse matrix
        Input to validate and convert.
    accept_sparse : string, list of string or None (default=None)
        String[s] representing allowed sparse matrix formats ('csc',
        'csr', 'coo', 'dok', 'bsr', 'lil', 'dia'). None means that sparse
        matrix input will raise an error.  If the input is sparse but not in
        the allowed format, it will be converted to the first listed format.
    dtype : string, type or None (default=none)
        Data type of result. If None, the dtype of the input is preserved.
    copy : boolean (default=False)
        Whether a forced copy will be triggered. If copy=False, a copy might
        be triggered by a conversion.
    force_all_finite : boolean (default=True)
        Whether to raise an error on np.inf and np.nan in X.
    Returns
    -------
    spmatrix_converted : scipy sparse matrix.
        Matrix that is ensured to have an allowed type.