Skip to content

load_npz

Load a sparse matrix in numpy's .npz format from disk. Note: This is not binary compatible with scipy's save_npz() output. This binary format is not currently stable. Will only load files saved by this package.

Parameters:

Name Type Description Default
filename file-like object, string, or pathlib.Path

The file to read. File-like objects must support the seek() and read() methods.

required

Returns:

Type Description
SparseArray

The sparse matrix at path filename.

Examples:

See sparse.save_npz for usage examples.

See Also
Source code in sparse/numba_backend/_io.py
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
def load_npz(filename):
    """Load a sparse matrix in numpy's `.npz` format from disk.
    Note: This is not binary compatible with scipy's `save_npz()`
    output. This binary format is not currently stable.
    Will only load files saved by this package.

    Parameters
    ----------
    filename : file-like object, string, or pathlib.Path
        The file to read. File-like objects must support the
        `seek()` and `read()` methods.

    Returns
    -------
    SparseArray
        The sparse matrix at path `filename`.

    Examples
    --------
    See [`sparse.save_npz`][] for usage examples.

    See Also
    --------
    - [`sparse.save_npz`][]
    - [`scipy.sparse.save_npz`][]
    - [`scipy.sparse.load_npz`][]
    - [`numpy.savez`][]
    - [`numpy.load`][]

    """

    with np.load(filename) as fp:
        try:
            coords = fp["coords"]
            data = fp["data"]
            shape = tuple(fp["shape"])
            fill_value = fp["fill_value"][()]
            return COO(
                coords=coords,
                data=data,
                shape=shape,
                sorted=True,
                has_duplicates=False,
                fill_value=fill_value,
            )
        except KeyError:
            pass
        try:
            data = fp["data"]
            indices = fp["indices"]
            indptr = fp["indptr"]
            comp_axes = fp["compressed_axes"]
            shape = tuple(fp["shape"])
            fill_value = fp["fill_value"][()]
            return GCXS(
                (data, indices, indptr),
                shape=shape,
                fill_value=fill_value,
                compressed_axes=comp_axes,
            )
        except KeyError as e:
            raise RuntimeError(f"The file {filename!s} does not contain a valid sparse matrix") from e