diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 4f70c9e..1b13a0a 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -33,6 +33,12 @@ jobs: # source: ["source"] # A trailing "t" means the free-threaded (no-GIL) build of that version. python-version: ["3.11", "3.12", "3.13", "3.14", "3.14t", "3.15", "3.15t"] + include: + # Also build psg without complex types (GraphBLAS always has them) and test that. + # GraphBLAS is from conda-forge; "-no-complex" sets the switch in "Build". + - os: ubuntu-latest + source: conda-forge-no-complex + python-version: "3.15" steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -100,8 +106,13 @@ jobs: # make install # popd - name: Build + env: + SUITESPARSE_GRAPHBLAS_NO_COMPLEX: ${{ contains(matrix.source, 'no-complex') && '1' || '' }} run: | pip install -e . --no-deps + if [[ -n $SUITESPARSE_GRAPHBLAS_NO_COMPLEX ]]; then + python -c 'import suitesparse_graphblas as ssgb; assert not ssgb.supports_complex()' + fi - name: Test env: PYVER: ${{ matrix.python-version }} @@ -134,7 +145,7 @@ jobs: # The "Coverage report" step wrote coverage.xml, so skip the uploader's own search for # gcov, Xcode, Swift and coverage.py data (it only logs a warning for each). plugins: noop - name: ${{ matrix.os }} ${{ matrix.python-version }} + name: ${{ matrix.os }} ${{ matrix.python-version }}${{ contains(matrix.source, 'no-complex') && ' no-complex' || '' }} # PRs from forks upload without a token. Pushes to main need the repository # secret CODECOV_TOKEN. An upload that fails doesn't fail the job. token: ${{ secrets.CODECOV_TOKEN }} diff --git a/build_graphblas_cffi.py b/build_graphblas_cffi.py index 94594e6..8c45d9c 100644 --- a/build_graphblas_cffi.py +++ b/build_graphblas_cffi.py @@ -49,7 +49,12 @@ library_dirs=library_dirs, ) -ffibuilder.cdef((ss_g / "suitesparse_graphblas.h").read_text()) +# SUITESPARSE_GRAPHBLAS_NO_COMPLEX=1 leaves out the complex types and functions, so that CI +# can test the package without them. +header = "suitesparse_graphblas.h" +if os.environ.get("SUITESPARSE_GRAPHBLAS_NO_COMPLEX"): + header = "suitesparse_graphblas_no_complex.h" +ffibuilder.cdef((ss_g / header).read_text()) def get_extension(apply_msvc_patch: bool = None, extra_compile_args=()): diff --git a/suitesparse_graphblas/__init__.py b/suitesparse_graphblas/__init__.py index 48eac6c..58a0ef7 100644 --- a/suitesparse_graphblas/__init__.py +++ b/suitesparse_graphblas/__init__.py @@ -103,7 +103,8 @@ def initialize(*, blocking=False, memory_manager="numpy"): info = lib.GrB_init(blocking) else: raise ValueError(f'memory_manager argument must be "numpy" or "c"; got: {memory_manager!r}') - if info != lib.GrB_SUCCESS: + # Fails only if already initialized (checked above), on bad arguments, or out of memory + if info != lib.GrB_SUCCESS: # pragma: no cover (defensive) raise _error_code_lookup.get(info, RuntimeError)( f"Failed to initialize GraphBLAS (info={info})" ) @@ -187,9 +188,12 @@ def libget(name): lib.GrB_INDEX_OUT_OF_BOUNDS: ex.IndexOutOfBound, lib.GrB_PANIC: ex.Panic, lib.GrB_NOT_IMPLEMENTED: ex.NotImplementedException, + lib.GrB_ALREADY_SET: ex.AlreadySet, # GxB Errors lib.GxB_EXHAUSTED: StopIteration, lib.GxB_JIT_ERROR: ex.JitError, + lib.GxB_GPU_ERROR: ex.GpuError, + lib.GxB_OUTPUT_IS_READONLY: ex.OutputIsReadonly, } GrB_SUCCESS = lib.GrB_SUCCESS GrB_NO_VALUE = lib.GrB_NO_VALUE @@ -238,7 +242,9 @@ def check_status(obj, response_code): string = ffi.new("char**") error_func(string, obj) text = ffi.string(string[0]).decode() - raise _error_code_lookup[response_code](text) + # Codes without a class of their own (GrB_ALREADY_SET, GxB_OUTPUT_IS_READONLY, + # GxB_GPU_ERROR, or any new one) raise the base class + raise _error_code_lookup.get(response_code, ex.GraphBLASException)(text) class burble: @@ -266,8 +272,8 @@ class burble: Example as a context manager: - >>> with burble(): - >>> n = matrix.matrix_nvals(A) + >>> with burble: + ... n = matrix.matrix_nvals(A) [ GrB_Matrix_nvals 1.91e-06 sec ] @@ -282,25 +288,25 @@ def is_enabled(self): val_ptr = ffi.new("int32_t*") info = lib.GxB_Global_Option_get_INT32(lib.GxB_BURBLE, val_ptr) if info != lib.GrB_SUCCESS: - raise _error_code_lookup[info]( - "Failed to get burble status (has GraphBLAS been initialized?" + raise _error_code_lookup.get(info, ex.GraphBLASException)( + "Failed to get burble status (has GraphBLAS been initialized?)" ) - return val_ptr[0] + return bool(val_ptr[0]) def enable(self): """Enable diagnostic output""" info = lib.GxB_Global_Option_set_INT32(lib.GxB_BURBLE, ffi.cast("int32_t", 1)) if info != lib.GrB_SUCCESS: - raise _error_code_lookup[info]( - "Failed to enable burble (has GraphBLAS been initialized?" + raise _error_code_lookup.get(info, ex.GraphBLASException)( + "Failed to enable burble (has GraphBLAS been initialized?)" ) def disable(self): """Disable diagnostic output""" info = lib.GxB_Global_Option_set_INT32(lib.GxB_BURBLE, ffi.cast("int32_t", 0)) if info != lib.GrB_SUCCESS: - raise _error_code_lookup[info]( - "Failed to disable burble (has GraphBLAS been initialized?" + raise _error_code_lookup.get(info, ex.GraphBLASException)( + "Failed to disable burble (has GraphBLAS been initialized?)" ) def __enter__(self): diff --git a/suitesparse_graphblas/api/binaryop.py b/suitesparse_graphblas/api/binaryop.py index cc87358..7faa009 100644 --- a/suitesparse_graphblas/api/binaryop.py +++ b/suitesparse_graphblas/api/binaryop.py @@ -182,7 +182,10 @@ def binaryop_get_string(op, field): True """ - val = ffi.new("char[256]") + # GraphBLAS copies the whole string, so make room for all of it + size = ffi.new("size_t*") + check_status(op, lib.GrB_BinaryOp_get_SIZE(op[0], size, field)) + val = ffi.new("char[]", size[0]) check_status(op, lib.GrB_BinaryOp_get_String(op[0], val, field)) return ffi.string(val).decode() diff --git a/suitesparse_graphblas/api/container.py b/suitesparse_graphblas/api/container.py index 2418f0a..fd323b6 100644 --- a/suitesparse_graphblas/api/container.py +++ b/suitesparse_graphblas/api/container.py @@ -9,7 +9,7 @@ def container_free(c): """ info = lib.GxB_Container_free(c) - if info != lib.GrB_SUCCESS: + if info != lib.GrB_SUCCESS: # pragma: no cover (GxB_Container_free always succeeds) raise _error_code_lookup.get(info, RuntimeError)( f"GxB_Container_free failed with info={info}" ) diff --git a/suitesparse_graphblas/api/descriptor.py b/suitesparse_graphblas/api/descriptor.py index 308a071..9b57de8 100644 --- a/suitesparse_graphblas/api/descriptor.py +++ b/suitesparse_graphblas/api/descriptor.py @@ -111,7 +111,10 @@ def descriptor_get_string(desc, field): True """ - val = ffi.new("char[256]") + # GraphBLAS copies the whole string, so make room for all of it + size = ffi.new("size_t*") + check_status(desc, lib.GrB_Descriptor_get_SIZE(desc, size, field)) + val = ffi.new("char[]", size[0]) check_status(desc, lib.GrB_Descriptor_get_String(desc, val, field)) return ffi.string(val).decode() diff --git a/suitesparse_graphblas/api/global_options.py b/suitesparse_graphblas/api/global_options.py index 85224e4..ab0998b 100644 --- a/suitesparse_graphblas/api/global_options.py +++ b/suitesparse_graphblas/api/global_options.py @@ -129,12 +129,16 @@ def global_get_string(field): True """ - val = ffi.new("char[256]") - info = lib.GrB_Global_get_String(lib.GrB_GLOBAL, val, field) + # GraphBLAS copies the whole string, so make room for all of it + size = ffi.new("size_t*") + call = "GrB_Global_get_SIZE" + info = lib.GrB_Global_get_SIZE(lib.GrB_GLOBAL, size, field) + if info == lib.GrB_SUCCESS: + val = ffi.new("char[]", size[0]) + call = "GrB_Global_get_String" + info = lib.GrB_Global_get_String(lib.GrB_GLOBAL, val, field) if info != lib.GrB_SUCCESS: - raise _error_code_lookup.get(info, RuntimeError)( - f"GrB_Global_get_String failed with info={info}" - ) + raise _error_code_lookup.get(info, RuntimeError)(f"{call} failed with info={info}") return ffi.string(val).decode() diff --git a/suitesparse_graphblas/api/grb_type.py b/suitesparse_graphblas/api/grb_type.py index 1c01fc3..5552de0 100644 --- a/suitesparse_graphblas/api/grb_type.py +++ b/suitesparse_graphblas/api/grb_type.py @@ -155,7 +155,10 @@ def grb_type_get_string(T, field): 'GrB_INT64' """ - val = ffi.new("char[256]") + # GraphBLAS copies the whole string, so make room for all of it + size = ffi.new("size_t*") + check_status(T, lib.GrB_Type_get_SIZE(T[0], size, field)) + val = ffi.new("char[]", size[0]) check_status(T, lib.GrB_Type_get_String(T[0], val, field)) return ffi.string(val).decode() diff --git a/suitesparse_graphblas/api/indexbinaryop.py b/suitesparse_graphblas/api/indexbinaryop.py index 4d513ae..4ababdb 100644 --- a/suitesparse_graphblas/api/indexbinaryop.py +++ b/suitesparse_graphblas/api/indexbinaryop.py @@ -120,7 +120,10 @@ def indexbinaryop_get_size(op, field): def indexbinaryop_get_string(op, field): """Get an operator option as a string.""" - val = ffi.new("char[256]") + # GraphBLAS copies the whole string, so make room for all of it + size = ffi.new("size_t*") + check_status(op, lib.GxB_IndexBinaryOp_get_SIZE(op[0], size, field)) + val = ffi.new("char[]", size[0]) check_status(op, lib.GxB_IndexBinaryOp_get_String(op[0], val, field)) return ffi.string(val).decode() diff --git a/suitesparse_graphblas/api/indexunaryop.py b/suitesparse_graphblas/api/indexunaryop.py index b333fc1..f2414c6 100644 --- a/suitesparse_graphblas/api/indexunaryop.py +++ b/suitesparse_graphblas/api/indexunaryop.py @@ -167,7 +167,10 @@ def indexunaryop_get_string(op, field): True """ - val = ffi.new("char[256]") + # GraphBLAS copies the whole string, so make room for all of it + size = ffi.new("size_t*") + check_status(op, lib.GrB_IndexUnaryOp_get_SIZE(op[0], size, field)) + val = ffi.new("char[]", size[0]) check_status(op, lib.GrB_IndexUnaryOp_get_String(op[0], val, field)) return ffi.string(val).decode() diff --git a/suitesparse_graphblas/api/io/binary.py b/suitesparse_graphblas/api/io/binary.py index 974ecf0..5265d21 100644 --- a/suitesparse_graphblas/api/io/binary.py +++ b/suitesparse_graphblas/api/io/binary.py @@ -3,7 +3,7 @@ import numpy as np -from suitesparse_graphblas import __version__, check_status, ffi, lib +from suitesparse_graphblas import __version__, check_status, ffi, lib, supports_complex from suitesparse_graphblas.api import matrix from suitesparse_graphblas.utils import empty, give_buffer @@ -42,8 +42,6 @@ lib.GrB_UINT64: 8, lib.GrB_FP32: 9, lib.GrB_FP64: 10, - lib.GxB_FC32: 11, - lib.GxB_FC64: 12, } _ss_typenames = { @@ -58,10 +56,14 @@ lib.GrB_UINT64: "GrB_UINT64", lib.GrB_FP32: "GrB_FP32", lib.GrB_FP64: "GrB_FP64", - lib.GxB_FC32: "GxB_FC32", - lib.GxB_FC64: "GxB_FC64", } +if supports_complex(): + _ss_typecodes[lib.GxB_FC32] = 11 + _ss_typecodes[lib.GxB_FC64] = 12 + _ss_typenames[lib.GxB_FC32] = "GxB_FC32" + _ss_typenames[lib.GxB_FC64] = "GxB_FC64" + _ss_codetypes = {v: k for k, v in _ss_typecodes.items()} @@ -71,6 +73,9 @@ def binwrite(A, filename, comments=None, opener=Path.open): ``opener`` opens the file for writing (e.g. ``gzip.open`` to compress it). To avoid a copy, ``A`` is unpacked while it is written and packed again afterwards (even if writing fails), so other threads must not use ``A`` meanwhile. + + ``comments`` must be ASCII, and short enough that the text header fits in + ``GRB_HEADER_LEN`` (512) bytes; otherwise this raises ValueError and writes nothing. """ if isinstance(filename, str): filename = Path(filename) @@ -218,7 +223,7 @@ def binwrite(A, filename, comments=None, opener=Path.open): nvec[0] = nrows[0] fmt_string = "FULLR" - else: # pragma nocover + else: # pragma: no cover (defensive: a materialized matrix is one of the above) raise TypeError(f"Unknown Matrix format {format[0]}") suitesparse_version = ( @@ -227,23 +232,28 @@ def binwrite(A, filename, comments=None, opener=Path.open): f"{lib.GxB_IMPLEMENTATION_SUB}" ) - vars = dict( # noqa: C408 - suitesparse_version=suitesparse_version, - user_agent="pygraphblas-" + __version__, - nrows=nrows[0], - ncols=ncols[0], - nvals=nvals[0], - nvec=nvec[0], - format=fmt_string, - size=typesize[0], - type=_ss_typenames[matrix_type[0]], - iso=int(is_iso[0]), - comments=comments, - ) - header_content = header_template.format(**vars) - header = f"{header_content: <{GRB_HEADER_LEN}}".encode("ascii") - try: + vars = dict( # noqa: C408 + suitesparse_version=suitesparse_version, + user_agent="pygraphblas-" + __version__, + nrows=nrows[0], + ncols=ncols[0], + nvals=nvals[0], + nvec=nvec[0], + format=fmt_string, + size=typesize[0], + type=_ss_typenames[matrix_type[0]], + iso=int(is_iso[0]), + comments=comments, + ) + header_content = header_template.format(**vars) + header = f"{header_content: <{GRB_HEADER_LEN}}".encode("ascii") + if len(header) > GRB_HEADER_LEN: + raise ValueError( + f"comments are too long: the header would be {len(header)} bytes, " + f"and binread reads only the first {GRB_HEADER_LEN}" + ) + with opener(filename, "wb") as f: fwrite = f.write fwrite(header) @@ -377,9 +387,15 @@ def binwrite(A, filename, comments=None, opener=Path.open): elif by_row and is_full: check_status(A, lib.GxB_Matrix_pack_FullR(A[0], Ax, Ax_size[0], is_iso[0], NULL)) - else: + else: # pragma: no cover (unreachable: the unpacking above raised already) raise TypeError("This should never happen") + # Packing resets these to their defaults, so restore them (in the order `binread` sets + # them) + matrix.matrix_set_sparsity_control(A, sparsity_control[0]) + matrix.matrix_set_hyper_switch(A, hyper_switch[0]) + matrix.matrix_set_bitmap_switch(A, bitmap_switch[0]) + def binread(filename, opener=Path.open): """Read a Matrix from ``filename``, written by ``binwrite``. @@ -390,7 +406,13 @@ def binread(filename, opener=Path.open): filename = Path(filename) with opener(filename, "rb") as f: - fread = f.read + + def fread(nbytes): + # A short read would leave `frombuff` pointing past the end of the data + data = f.read(nbytes) + if len(data) != nbytes: + raise EOFError(f"{filename} is truncated") + return data fread(GRB_HEADER_LEN) impl = frombuff("uint64_t*", fread(sizeof("uint64_t"))) diff --git a/suitesparse_graphblas/api/iterator.py b/suitesparse_graphblas/api/iterator.py index bf47f1a..9382707 100644 --- a/suitesparse_graphblas/api/iterator.py +++ b/suitesparse_graphblas/api/iterator.py @@ -40,8 +40,8 @@ def iterator_new(*, free=iterator_free): def matrix_iterator_attach(it, A, desc=None): """Attach an iterator to a matrix for entry-wise iteration. - Returns ``lib.GrB_SUCCESS`` or ``lib.GxB_EXHAUSTED`` (if the matrix - has no entries). Raises on other errors. + Returns ``lib.GrB_SUCCESS``, and raises on errors. The iterator is not at + any entry yet: move it to one with :func:`matrix_iterator_seek`. >>> from suitesparse_graphblas import matrix >>> A = matrix.matrix_new(lib.GrB_INT64, 2, 2) @@ -66,7 +66,9 @@ def matrix_iterator_attach(it, A, desc=None): def row_iterator_attach(it, A, desc=None): """Attach an iterator to a matrix for row-wise iteration. - Returns ``lib.GrB_SUCCESS`` or ``lib.GxB_EXHAUSTED``. + Returns ``lib.GrB_SUCCESS``, and raises on errors: ``NotImplementedException`` + if the matrix is held by column. The iterator is not at any row yet: move it + to one with :func:`row_iterator_seek_row` or :func:`row_iterator_kseek`. >>> from suitesparse_graphblas import matrix >>> A = matrix.matrix_new(lib.GrB_INT64, 2, 2) @@ -91,7 +93,9 @@ def row_iterator_attach(it, A, desc=None): def col_iterator_attach(it, A, desc=None): """Attach an iterator to a matrix for column-wise iteration. - Returns ``lib.GrB_SUCCESS`` or ``lib.GxB_EXHAUSTED``. + Returns ``lib.GrB_SUCCESS``, and raises on errors: ``NotImplementedException`` + if the matrix is held by row. The iterator is not at any column yet: move it + to one with :func:`col_iterator_seek_col` or :func:`col_iterator_kseek`. >>> from suitesparse_graphblas import matrix >>> A = matrix.matrix_new(lib.GrB_INT64, 2, 2) @@ -116,7 +120,8 @@ def col_iterator_attach(it, A, desc=None): def vector_iterator_attach(it, v, desc=None): """Attach an iterator to a vector. - Returns ``lib.GrB_SUCCESS`` or ``lib.GxB_EXHAUSTED``. + Returns ``lib.GrB_SUCCESS``, and raises on errors. The iterator is not at + any entry yet: move it to one with :func:`vector_iterator_seek`. >>> from suitesparse_graphblas import vector >>> v = vector.vector_new(lib.GrB_INT64, 3) @@ -145,7 +150,9 @@ def vector_iterator_attach(it, v, desc=None): def matrix_iterator_seek(it, p): """Seek the matrix entry iterator to position p. - Returns ``lib.GrB_SUCCESS`` or ``lib.GxB_EXHAUSTED``. + Returns ``lib.GrB_SUCCESS``, or ``lib.GxB_EXHAUSTED`` if ``p >= pmax``. For a + bitmap matrix, the iterator moves to the first entry at or after ``p``, and is + exhausted if there is none. >>> from suitesparse_graphblas import matrix >>> A = matrix.matrix_new(lib.GrB_INT64, 2, 2) @@ -219,12 +226,20 @@ def matrix_iterator_get_index(it): def matrix_iterator_getp(it): - """Get the current position of the matrix entry iterator.""" + """Get the current position of the matrix entry iterator. + + See :func:`matrix_iterator_getpmax`. + """ return lib.GxB_Matrix_Iterator_getp(it[0]) def matrix_iterator_getpmax(it): - """Get the maximum position of the matrix entry iterator.""" + """Get the end of the matrix entry iterator's positions. + + Positions run from 0 to ``pmax - 1``. ``pmax`` is the number of entries, + except for a bitmap matrix, where it is ``nrows * ncols`` (or 0 if it has no + entries) and a position may have no entry. + """ return lib.GxB_Matrix_Iterator_getpmax(it[0]) @@ -234,9 +249,12 @@ def matrix_iterator_getpmax(it): def row_iterator_seek_row(it, row): - """Seek the row iterator to a specific row. + """Seek the row iterator to a specific row, or the next row it holds. - Returns ``lib.GrB_SUCCESS`` or ``lib.GxB_EXHAUSTED``. + Returns ``lib.GrB_SUCCESS`` at the row's first entry, ``lib.GrB_NO_VALUE`` + if the row has no entries, or ``lib.GxB_EXHAUSTED`` if ``row >= nrows``. For + a hypersparse matrix, a row it doesn't hold is skipped for the next one it + does (see :func:`row_iterator_get_row_index`). >>> from suitesparse_graphblas import matrix >>> A = matrix.matrix_new(lib.GrB_INT64, 2, 2) @@ -258,9 +276,9 @@ def row_iterator_seek_row(it, row): def row_iterator_next_row(it): - """Advance the row iterator to the next non-empty row. + """Advance the row iterator to the next row (which may skip empty rows). - Returns ``lib.GrB_SUCCESS`` or ``lib.GxB_EXHAUSTED``. + Returns as :func:`row_iterator_seek_row` does. >>> from suitesparse_graphblas import matrix >>> A = matrix.matrix_new(lib.GrB_INT64, 2, 2) @@ -271,12 +289,16 @@ def row_iterator_next_row(it): >>> it = iterator_new() >>> row_iterator_attach(it, A) == lib.GrB_SUCCESS True + >>> row_iterator_seek_row(it, 0) == lib.GrB_SUCCESS + True >>> row_iterator_get_row_index(it) 0 >>> row_iterator_next_row(it) == lib.GrB_SUCCESS True >>> row_iterator_get_row_index(it) 1 + >>> row_iterator_next_row(it) == lib.GxB_EXHAUSTED + True """ info = lib.GxB_rowIterator_nextRow(it[0]) @@ -286,7 +308,8 @@ def row_iterator_next_row(it): def row_iterator_next_col(it): """Advance the row iterator to the next entry in the current row. - Returns ``lib.GrB_SUCCESS`` or ``lib.GxB_EXHAUSTED``. + Returns ``lib.GrB_SUCCESS``, or ``lib.GrB_NO_VALUE`` if the row has no more + entries. >>> from suitesparse_graphblas import matrix >>> A = matrix.matrix_new(lib.GrB_INT64, 2, 2) @@ -297,13 +320,18 @@ def row_iterator_next_col(it): >>> it = iterator_new() >>> row_iterator_attach(it, A) == lib.GrB_SUCCESS True + >>> row_iterator_seek_row(it, 0) == lib.GrB_SUCCESS + True >>> iterator_get_int64(it) 10 - >>> _ = row_iterator_next_col(it) + >>> row_iterator_next_col(it) == lib.GrB_SUCCESS + True >>> iterator_get_int64(it) 20 >>> row_iterator_get_col_index(it) 1 + >>> row_iterator_next_col(it) == lib.GrB_NO_VALUE + True """ info = lib.GxB_rowIterator_nextCol(it[0]) @@ -311,26 +339,31 @@ def row_iterator_next_col(it): def row_iterator_kseek(it, k): - """Seek the row iterator to the k-th entry in the current row. + """Seek the row iterator to the k-th row it holds, for ``0 <= k < kount``. - Returns ``lib.GrB_SUCCESS`` or ``lib.GxB_EXHAUSTED``. + That is row ``k``, unless the matrix is hypersparse (see + :func:`row_iterator_kount`). Returns as :func:`row_iterator_seek_row` does. """ info = lib.GxB_rowIterator_kseek(it[0], k) return _check_info(info) def row_iterator_get_row_index(it): - """Get the current row index of the row iterator.""" + """Get the current row index of the row iterator (``nrows`` once exhausted).""" return lib.GxB_rowIterator_getRowIndex(it[0]) def row_iterator_get_col_index(it): - """Get the current column index of the row iterator.""" + """Get the column index of the row iterator's current entry.""" return lib.GxB_rowIterator_getColIndex(it[0]) def row_iterator_kount(it): - """Get the number of entries in the current row.""" + """Get the number of rows the row iterator holds, for :func:`row_iterator_kseek`. + + This is ``nrows``, unless the matrix is hypersparse; then it is the number of + rows in its hyperlist, which bounds the number of non-empty rows. + """ return lib.GxB_rowIterator_kount(it[0]) @@ -340,9 +373,12 @@ def row_iterator_kount(it): def col_iterator_seek_col(it, col): - """Seek the column iterator to a specific column. + """Seek the column iterator to a specific column, or the next column it holds. - Returns ``lib.GrB_SUCCESS`` or ``lib.GxB_EXHAUSTED``. + Returns ``lib.GrB_SUCCESS`` at the column's first entry, ``lib.GrB_NO_VALUE`` + if the column has no entries, or ``lib.GxB_EXHAUSTED`` if ``col >= ncols``. + For a hypersparse matrix, a column it doesn't hold is skipped for the next + one it does (see :func:`col_iterator_get_col_index`). >>> from suitesparse_graphblas import matrix >>> A = matrix.matrix_new(lib.GrB_INT64, 2, 2) @@ -365,9 +401,9 @@ def col_iterator_seek_col(it, col): def col_iterator_next_col(it): - """Advance the column iterator to the next non-empty column. + """Advance the column iterator to the next column (which may skip empty columns). - Returns ``lib.GrB_SUCCESS`` or ``lib.GxB_EXHAUSTED``. + Returns as :func:`col_iterator_seek_col` does. >>> from suitesparse_graphblas import matrix >>> A = matrix.matrix_new(lib.GrB_INT64, 2, 2) @@ -379,12 +415,16 @@ def col_iterator_next_col(it): >>> it = iterator_new() >>> col_iterator_attach(it, A) == lib.GrB_SUCCESS True + >>> col_iterator_seek_col(it, 0) == lib.GrB_SUCCESS + True >>> col_iterator_get_col_index(it) 0 >>> col_iterator_next_col(it) == lib.GrB_SUCCESS True >>> col_iterator_get_col_index(it) 1 + >>> col_iterator_next_col(it) == lib.GxB_EXHAUSTED + True """ info = lib.GxB_colIterator_nextCol(it[0]) @@ -394,33 +434,39 @@ def col_iterator_next_col(it): def col_iterator_next_row(it): """Advance the column iterator to the next entry in the current column. - Returns ``lib.GrB_SUCCESS`` or ``lib.GxB_EXHAUSTED``. + Returns ``lib.GrB_SUCCESS``, or ``lib.GrB_NO_VALUE`` if the column has no + more entries. """ info = lib.GxB_colIterator_nextRow(it[0]) return _check_info(info) def col_iterator_kseek(it, k): - """Seek the column iterator to the k-th entry in the current column. + """Seek the column iterator to the k-th column it holds, for ``0 <= k < kount``. - Returns ``lib.GrB_SUCCESS`` or ``lib.GxB_EXHAUSTED``. + That is column ``k``, unless the matrix is hypersparse (see + :func:`col_iterator_kount`). Returns as :func:`col_iterator_seek_col` does. """ info = lib.GxB_colIterator_kseek(it[0], k) return _check_info(info) def col_iterator_get_col_index(it): - """Get the current column index of the column iterator.""" + """Get the current column index of the column iterator (``ncols`` once exhausted).""" return lib.GxB_colIterator_getColIndex(it[0]) def col_iterator_get_row_index(it): - """Get the current row index of the column iterator.""" + """Get the row index of the column iterator's current entry.""" return lib.GxB_colIterator_getRowIndex(it[0]) def col_iterator_kount(it): - """Get the number of entries in the current column.""" + """Get the number of columns the column iterator holds, for :func:`col_iterator_kseek`. + + This is ``ncols``, unless the matrix is hypersparse; then it is the number of + columns in its hyperlist, which bounds the number of non-empty columns. + """ return lib.GxB_colIterator_kount(it[0]) @@ -432,7 +478,9 @@ def col_iterator_kount(it): def vector_iterator_seek(it, p): """Seek the vector iterator to position p. - Returns ``lib.GrB_SUCCESS`` or ``lib.GxB_EXHAUSTED``. + Returns ``lib.GrB_SUCCESS``, or ``lib.GxB_EXHAUSTED`` if ``p >= pmax``. For a + bitmap vector, the iterator moves to the first entry at or after ``p``, and is + exhausted if there is none. >>> from suitesparse_graphblas import vector >>> v = vector.vector_new(lib.GrB_INT64, 3) @@ -491,12 +539,20 @@ def vector_iterator_get_index(it): def vector_iterator_getp(it): - """Get the current position of the vector iterator.""" + """Get the current position of the vector iterator. + + See :func:`vector_iterator_getpmax`. + """ return lib.GxB_Vector_Iterator_getp(it[0]) def vector_iterator_getpmax(it): - """Get the maximum position of the vector iterator.""" + """Get the end of the vector iterator's positions. + + Positions run from 0 to ``pmax - 1``. ``pmax`` is the number of entries, + except for a bitmap vector, where it is its size (or 0 if it has no entries) + and a position may have no entry. + """ return lib.GxB_Vector_Iterator_getpmax(it[0]) diff --git a/suitesparse_graphblas/api/monoid.py b/suitesparse_graphblas/api/monoid.py index 4706b05..1f55125 100644 --- a/suitesparse_graphblas/api/monoid.py +++ b/suitesparse_graphblas/api/monoid.py @@ -549,7 +549,10 @@ def monoid_get_string(m, field): True """ - val = ffi.new("char[256]") + # GraphBLAS copies the whole string, so make room for all of it + size = ffi.new("size_t*") + check_status(m, lib.GrB_Monoid_get_SIZE(m[0], size, field)) + val = ffi.new("char[]", size[0]) check_status(m, lib.GrB_Monoid_get_String(m[0], val, field)) return ffi.string(val).decode() @@ -577,6 +580,18 @@ def monoid_operator(m): return op[0] +def _value_buffer(m): + """Return a buffer that holds one value of the monoid's type.""" + op = ffi.new("GrB_BinaryOp*", monoid_operator(m)) + T = ffi.new("GrB_Type*") + check_status(op, lib.GxB_BinaryOp_ztype(T, op[0])) + size = ffi.new("size_t*") + check_status(T, lib.GxB_Type_size(size, T[0])) + # A user-defined type can be of any size; keep at least the 256 bytes these + # functions have always returned + return ffi.new("char[]", max(size[0], 256)) + + def monoid_identity(m): """Return a buffer containing the identity value of a monoid. @@ -584,7 +599,7 @@ def monoid_identity(m): >>> val = monoid_identity(m) """ - val = ffi.new("char[256]") + val = _value_buffer(m) check_status(m, lib.GxB_Monoid_identity(val, m[0])) return val @@ -602,6 +617,6 @@ def monoid_terminal(m): """ has_terminal = ffi.new("bool*") - val = ffi.new("char[256]") + val = _value_buffer(m) check_status(m, lib.GxB_Monoid_terminal(has_terminal, val, m[0])) return has_terminal[0], val diff --git a/suitesparse_graphblas/api/semiring.py b/suitesparse_graphblas/api/semiring.py index e942c3c..328e342 100644 --- a/suitesparse_graphblas/api/semiring.py +++ b/suitesparse_graphblas/api/semiring.py @@ -147,7 +147,10 @@ def semiring_get_string(s, field): True """ - val = ffi.new("char[256]") + # GraphBLAS copies the whole string, so make room for all of it + size = ffi.new("size_t*") + check_status(s, lib.GrB_Semiring_get_SIZE(s[0], size, field)) + val = ffi.new("char[]", size[0]) check_status(s, lib.GrB_Semiring_get_String(s[0], val, field)) return ffi.string(val).decode() diff --git a/suitesparse_graphblas/api/unaryop.py b/suitesparse_graphblas/api/unaryop.py index f5f4fc3..f26b9eb 100644 --- a/suitesparse_graphblas/api/unaryop.py +++ b/suitesparse_graphblas/api/unaryop.py @@ -166,7 +166,10 @@ def unaryop_get_string(op, field): True """ - val = ffi.new("char[256]") + # GraphBLAS copies the whole string, so make room for all of it + size = ffi.new("size_t*") + check_status(op, lib.GrB_UnaryOp_get_SIZE(op[0], size, field)) + val = ffi.new("char[]", size[0]) check_status(op, lib.GrB_UnaryOp_get_String(op[0], val, field)) return ffi.string(val).decode() diff --git a/suitesparse_graphblas/api/utils.py b/suitesparse_graphblas/api/utils.py index df5d3eb..cbcaaeb 100644 --- a/suitesparse_graphblas/api/utils.py +++ b/suitesparse_graphblas/api/utils.py @@ -7,10 +7,19 @@ def _capture_c_output(fn, *args): sys.stdout.flush() r, w = os.pipe() old = os.dup(1) - os.dup2(w, 1) - fn(*args) - os.dup2(old, 1) - os.close(w) - out = os.read(r, 100000).decode() - os.close(r) - return out + try: + try: + os.dup2(w, 1) + try: + fn(*args) + finally: + os.dup2(old, 1) + finally: + os.close(w) + try: + return os.read(r, 100000).decode() + except BlockingIOError: # pragma: no cover (Emscripten: an empty pipe has no EOF) + return "" + finally: + os.close(old) + os.close(r) diff --git a/suitesparse_graphblas/exceptions.py b/suitesparse_graphblas/exceptions.py index 3761228..a4d69cb 100644 --- a/suitesparse_graphblas/exceptions.py +++ b/suitesparse_graphblas/exceptions.py @@ -64,3 +64,15 @@ class NotImplementedException(GraphBLASException): class JitError(GraphBLASException): pass + + +class AlreadySet(GraphBLASException): + pass + + +class GpuError(GraphBLASException): + pass + + +class OutputIsReadonly(GraphBLASException): + pass diff --git a/suitesparse_graphblas/tests/test_api_matrix_vector.py b/suitesparse_graphblas/tests/test_api_matrix_vector.py new file mode 100644 index 0000000..c5ef022 --- /dev/null +++ b/suitesparse_graphblas/tests/test_api_matrix_vector.py @@ -0,0 +1,89 @@ +"""Matrices and vectors of the functional API: building and extracting each type.""" + +import numpy as np +import pytest + +from suitesparse_graphblas import ffi, lib, libget, supports_complex +from suitesparse_graphblas.api import matrix, vector + +needs_complex = pytest.mark.skipif(not supports_complex(), reason="no complex types") + +# suffix, NumPy dtype, three values +TYPES = [ + ("bool", np.bool_, [True, False, True]), + ("int8", np.int8, [-(2**7), 0, 2**7 - 1]), + ("int16", np.int16, [-(2**15), 0, 2**15 - 1]), + ("int32", np.int32, [-(2**31), 0, 2**31 - 1]), + ("int64", np.int64, [-(2**63), 0, 2**63 - 1]), + ("uint8", np.uint8, [0, 1, 2**8 - 1]), + ("uint16", np.uint16, [0, 1, 2**16 - 1]), + ("uint32", np.uint32, [0, 1, 2**32 - 1]), + ("uint64", np.uint64, [0, 1, 2**64 - 1]), + ("fp32", np.float32, [-1.5, 0.0, 2.25]), + ("fp64", np.float64, [-1.5, 0.0, 1e300]), + pytest.param("fc32", np.complex64, [1.5 - 2j, 0j, -3 + 0.5j], marks=needs_complex), + pytest.param("fc64", np.complex128, [1.5 - 2j, 0j, -3 + 1e300j], marks=needs_complex), +] + + +@pytest.mark.parametrize(("suffix", "dtype", "values"), TYPES) +def test_matrix_build_and_extract_tuples(suffix, dtype, values): + extract = getattr(matrix, f"matrix_extract_tuples_{suffix}") + A = matrix.matrix_new(libget(f"GrB_{suffix.upper()}"), 3, 4) + for array, expected in zip(extract(A), [np.uint64, np.uint64, dtype]): + assert array.dtype == expected + assert array.size == 0 + + rows = np.array([2, 0, 1], dtype=np.uint64) + cols = np.array([1, 3, 0], dtype=np.uint64) + build = getattr(matrix, f"matrix_build_{suffix}") + build(A, rows, cols, np.array(values, dtype=dtype), 3, libget(f"GrB_FIRST_{suffix.upper()}")) + assert matrix.matrix_nvals(A) == 3 + rows, cols, vals = extract(A) + assert vals.dtype == dtype + entries = sorted(zip(rows.tolist(), cols.tolist(), vals.tolist())) + assert entries == [(0, 3, values[1]), (1, 0, values[2]), (2, 1, values[0])] + + +@pytest.mark.parametrize(("suffix", "dtype", "values"), TYPES) +def test_vector_build_and_extract_tuples(suffix, dtype, values): + extract = getattr(vector, f"vector_extract_tuples_{suffix}") + v = vector.vector_new(libget(f"GrB_{suffix.upper()}"), 5) + for array, expected in zip(extract(v), [np.uint64, dtype]): + assert array.dtype == expected + assert array.size == 0 + + indices = np.array([4, 0, 2], dtype=np.uint64) + build = getattr(vector, f"vector_build_{suffix}") + build(v, indices, np.array(values, dtype=dtype), 3, libget(f"GrB_FIRST_{suffix.upper()}")) + assert vector.vector_nvals(v) == 3 + indices, vals = extract(v) + assert vals.dtype == dtype + entries = sorted(zip(indices.tolist(), vals.tolist())) + assert entries == [(0, values[1]), (2, values[2]), (4, values[0])] + + +def test_matrix_without_gc(): + A = matrix.matrix_new(lib.GrB_INT64, 2, 3, free=None) + matrix.set_int64(A, 7, 1, 2) + B = matrix.matrix_dup(A, free=None) + matrix.matrix_free(A) + assert A[0] == ffi.NULL + # The copy has its own data + assert matrix.matrix_shape(B) == (2, 3) + assert matrix.get_int64(B, 1, 2) == 7 + matrix.matrix_free(B) + assert B[0] == ffi.NULL + + +def test_vector_without_gc(): + v = vector.vector_new(lib.GrB_INT64, 3, free=None) + vector.set_int64(v, 7, 2) + w = vector.vector_dup(v, free=None) + vector.vector_free(v) + assert v[0] == ffi.NULL + # The copy has its own data + assert vector.vector_size(w) == 3 + assert vector.get_int64(w, 2) == 7 + vector.vector_free(w) + assert w[0] == ffi.NULL diff --git a/suitesparse_graphblas/tests/test_api_monoid.py b/suitesparse_graphblas/tests/test_api_monoid.py new file mode 100644 index 0000000..5171a73 --- /dev/null +++ b/suitesparse_graphblas/tests/test_api_monoid.py @@ -0,0 +1,118 @@ +"""Monoids of the functional API: the typed constructors, and monoids of user-defined types.""" + +import math + +import pytest + +from suitesparse_graphblas import check_status, exceptions, ffi, lib, libget, supports_complex +from suitesparse_graphblas.api import binaryop, grb_type, monoid, vector + +# Whether a constructor hands its monoid to the garbage collector (its default) or leaves +# freeing it to the caller (`free=None`) +GC = [pytest.param(True, id="gc"), pytest.param(False, id="manual")] + +needs_complex = pytest.mark.skipif(not supports_complex(), reason="no complex types") + +# suffix, C type, identity, terminal. GraphBLAS ignores the identity and terminal given with +# the operator of a known monoid, such as MAX, so these monoids use FIRST, which isn't one. +TYPES = [ + ("bool", "bool", True, False), + ("int8", "int8_t", -(2**7), 2**7 - 1), + ("int16", "int16_t", -(2**15), 2**15 - 1), + ("int32", "int32_t", -(2**31), 2**31 - 1), + ("int64", "int64_t", -(2**63), 2**63 - 1), + ("uint8", "uint8_t", 2**8 - 1, 1), + ("uint16", "uint16_t", 2**16 - 1, 1), + ("uint32", "uint32_t", 2**32 - 1, 1), + ("uint64", "uint64_t", 2**64 - 1, 1), + ("fp32", "float", -math.inf, 2.25), + ("fp64", "double", -math.inf, 1e300), + pytest.param("fc32", "GxB_FC32_t", 1.5 - 2j, -3 + 0.5j, marks=needs_complex), + pytest.param("fc64", "GxB_FC64_t", 1.5 - 2j, -3 + 1e300j, marks=needs_complex), +] + +BIG = 64 # int64s in a value of a large user-defined type + + +@ffi.callback("GxB_binary_function") +def _max_big(z, x, y): + # Elementwise max + x = ffi.cast("int64_t*", x) + y = ffi.cast("int64_t*", y) + z = ffi.cast("int64_t*", z) + for k in range(BIG): + z[k] = max(x[k], y[k]) + + +@pytest.mark.parametrize("gc", GC) +@pytest.mark.parametrize("with_terminal", [False, True], ids=["new", "terminal_new"]) +@pytest.mark.parametrize(("suffix", "ctype", "identity", "terminal"), TYPES) +def test_monoid_new(gc, with_terminal, suffix, ctype, identity, terminal): + op = libget(f"GrB_FIRST_{suffix.upper()}") + kwargs = {} if gc else {"free": None} + if with_terminal: + new = getattr(monoid, f"monoid_terminal_new_{suffix}") + m = new(op, identity, terminal, **kwargs) + else: + m = getattr(monoid, f"monoid_new_{suffix}")(op, identity, **kwargs) + assert monoid.monoid_operator(m) == op + code = libget(f"GrB_{suffix.upper()}_CODE") + assert monoid.monoid_get_int32(m, lib.GrB_OUTP_TYPE_CODE) == code + value = monoid.monoid_identity(m) + assert ffi.cast(f"{ctype}*", value)[0] == identity + has_terminal, value = monoid.monoid_terminal(m) + assert has_terminal == with_terminal + if with_terminal: + assert ffi.cast(f"{ctype}*", value)[0] == terminal + + # An empty vector reduces to the identity + u = vector.vector_new(libget(f"GrB_{suffix.upper()}"), 2) + result = ffi.new(f"{ctype}*") + reduce = libget(f"GrB_Vector_reduce_{suffix.upper()}") + check_status(u, reduce(result, ffi.NULL, m[0], u[0], ffi.NULL)) + assert result[0] == identity + if not gc: + monoid.monoid_free(m) + assert m[0] == ffi.NULL + + +@pytest.mark.parametrize("gc", GC) +@pytest.mark.parametrize("with_terminal", [False, True], ids=["new", "terminal_new"]) +def test_monoid_of_large_type(gc, with_terminal): + size = 8 * BIG + T = grb_type.grb_type_new(size) + op = binaryop.binaryop_new(_max_big, T[0], T[0], T[0]) + identity = ffi.new("int64_t[]", [-(2**63)] * BIG) + terminal = ffi.new("int64_t[]", [2**63 - 1] * BIG) + kwargs = {} if gc else {"free": None} + if with_terminal: + m = monoid.monoid_terminal_new_udt(op[0], identity, terminal, **kwargs) + else: + m = monoid.monoid_new_udt(op[0], identity, **kwargs) + # GraphBLAS copies one value of the monoid's type, whatever its size + value = monoid.monoid_identity(m) + assert len(ffi.buffer(value)) >= size + assert ffi.buffer(value)[:size] == ffi.buffer(identity)[:] + has_terminal, value = monoid.monoid_terminal(m) + assert has_terminal == with_terminal + if with_terminal: + assert len(ffi.buffer(value)) >= size + assert ffi.buffer(value)[:size] == ffi.buffer(terminal)[:] + + u = vector.vector_new(T[0], 3) + first = ffi.new("int64_t[]", list(range(BIG))) + last = ffi.new("int64_t[]", list(range(BIG, 0, -1))) + check_status(u, lib.GrB_Vector_setElement_UDT(u[0], first, 0)) + check_status(u, lib.GrB_Vector_setElement_UDT(u[0], last, 2)) + result = ffi.new("int64_t[]", BIG) + check_status(u, lib.GrB_Vector_reduce_UDT(result, ffi.NULL, m[0], u[0], ffi.NULL)) + assert list(result) == [max(k, BIG - k) for k in range(BIG)] + if not gc: + monoid.monoid_free(m) + assert m[0] == ffi.NULL + + +def test_monoid_new_fails(): + # The operator's inputs and output must have the same type + with pytest.raises(exceptions.DomainMismatch): + monoid.monoid_new_int64(lib.GrB_LT_INT64, 0) diff --git a/suitesparse_graphblas/tests/test_api_objects.py b/suitesparse_graphblas/tests/test_api_objects.py new file mode 100644 index 0000000..4316ecc --- /dev/null +++ b/suitesparse_graphblas/tests/test_api_objects.py @@ -0,0 +1,149 @@ +import pytest + +from suitesparse_graphblas import exceptions, ffi, lib +from suitesparse_graphblas.api import container, context, descriptor, grb_type, semiring + + +def test_grb_type_definition_longer_than_256(): + fields = "; ".join(f"double x{i}" for i in range(40)) + defn = f"typedef struct {{ {fields}; }} wide_type ;" + assert len(defn) > 256 + T = grb_type.grb_type_new_named(40 * 8, "wide_type", defn) + assert grb_type.grb_type_get_string(T, lib.GxB_JIT_C_DEFINITION) == defn + assert grb_type.grb_type_get_size(T, lib.GxB_JIT_C_DEFINITION) == len(defn) + 1 + assert grb_type.grb_type_get_string(T, lib.GxB_JIT_C_NAME) == "wide_type" + + +# `free=None` returns a handle that isn't freed when it is garbage collected, so the caller +# frees it. Freeing sets the handle to NULL. + + +def test_context_free_none(): + ctx = context.context_new(free=None) + assert ctx[0] != ffi.NULL + context.context_set_nthreads(ctx, 3) + assert context.context_get_nthreads(ctx) == 3 + context.context_free(ctx) + assert ctx[0] == ffi.NULL + # A freed context is an error to use, not a crash + with pytest.raises(exceptions.NullPointer): + context.context_get_nthreads(ctx) + + +def test_container_free_none(): + c = container.container_new(free=None) + assert c[0] != ffi.NULL + container.container_free(c) + assert c[0] == ffi.NULL + + +def test_grb_type_free_none(): + T = grb_type.grb_type_new(16, free=None) + assert grb_type.grb_type_size(T) == 16 + grb_type.grb_type_free(T) + assert T[0] == ffi.NULL + + defn = "typedef struct { double a ; double b ; } pair_type ;" + T = grb_type.grb_type_new_named(16, "pair_type", defn, free=None) + assert grb_type.grb_type_size(T) == 16 + assert grb_type.grb_type_name(T) == "pair_type" + assert grb_type.grb_type_get_string(T, lib.GxB_JIT_C_DEFINITION) == defn + grb_type.grb_type_free(T) + assert T[0] == ffi.NULL + + +def test_semiring_free_none(): + s = semiring.semiring_new(lib.GrB_MAX_MONOID_FP64, lib.GrB_PLUS_FP64, free=None) + assert semiring.semiring_add(s) == lib.GrB_MAX_MONOID_FP64 + assert semiring.semiring_multiply(s) == lib.GrB_PLUS_FP64 + semiring.semiring_free(s) + assert s[0] == ffi.NULL + + +def test_context_invalid_field(): + ctx = context.context_new() + with pytest.raises(exceptions.InvalidValue): + context.context_set_int32(ctx, 999999, 1) + with pytest.raises(exceptions.InvalidValue): + context.context_get_fp64(ctx, 999999) + + +def test_descriptor_set_get(): + # Not a fixture: pytest-run-parallel would share it between threads + D = ffi.new("GrB_Descriptor*") + assert lib.GrB_Descriptor_new(D) == lib.GrB_SUCCESS + D = ffi.gc(D, lib.GrB_Descriptor_free) + desc = D[0] + assert descriptor.descriptor_get_int32(desc, lib.GrB_OUTP_FIELD) == lib.GrB_DEFAULT + descriptor.descriptor_set_int32(desc, lib.GrB_OUTP_FIELD, lib.GrB_REPLACE) + assert descriptor.descriptor_get_int32(desc, lib.GrB_OUTP_FIELD) == lib.GrB_REPLACE + descriptor.descriptor_set_int32(desc, lib.GrB_MASK_FIELD, lib.GrB_STRUCTURE) + assert descriptor.descriptor_get_int32(desc, lib.GrB_MASK_FIELD) == lib.GrB_STRUCTURE + + descriptor.descriptor_set_string(desc, lib.GrB_NAME, "my_descriptor") + assert descriptor.descriptor_get_string(desc, lib.GrB_NAME) == "my_descriptor" + assert descriptor.descriptor_get_size(desc, lib.GrB_NAME) == len("my_descriptor") + 1 + descriptor.descriptor_wait(desc) + + +def test_builtin_descriptor_is_read_only(): + with pytest.raises(exceptions.InvalidValue): + descriptor.descriptor_set_int32(lib.GrB_DESC_S, lib.GrB_OUTP_FIELD, lib.GrB_REPLACE) + with pytest.raises(exceptions.InvalidValue): + descriptor.descriptor_set_string(lib.GrB_DESC_S, lib.GrB_NAME, "renamed") + assert descriptor.descriptor_get_int32(lib.GrB_DESC_S, lib.GrB_OUTP_FIELD) == lib.GrB_DEFAULT + assert descriptor.descriptor_get_string(lib.GrB_DESC_S, lib.GrB_NAME) == "GrB_DESC_S" + + +def test_grb_type_name(): + T = grb_type.grb_type_new(8) + # A new type has no name until it is given one + assert grb_type.grb_type_get_string(T, lib.GrB_NAME) == "" + grb_type.grb_type_set_string(T, lib.GrB_NAME, "my_type") + assert grb_type.grb_type_get_string(T, lib.GrB_NAME) == "my_type" + assert grb_type.grb_type_get_size(T, lib.GrB_NAME) == len("my_type") + 1 + # GrB_SIZE is a number, not a string + with pytest.raises(exceptions.InvalidValue): + grb_type.grb_type_get_string(T, lib.GrB_SIZE) + + +def test_semiring_set(): + s = semiring.semiring_new(lib.GrB_MAX_MONOID_FP64, lib.GrB_PLUS_FP64) + semiring.semiring_set_string(s, lib.GrB_NAME, "max_plus") + assert semiring.semiring_get_string(s, lib.GrB_NAME) == "max_plus" + # A semiring's integer properties (its types) are read-only + code = semiring.semiring_get_int32(s, lib.GrB_INP0_TYPE_CODE) + assert code == lib.GrB_FP64_CODE + with pytest.raises(exceptions.InvalidValue): + semiring.semiring_set_int32(s, lib.GrB_INP0_TYPE_CODE, lib.GrB_INT64_CODE) + assert semiring.semiring_get_int32(s, lib.GrB_INP0_TYPE_CODE) == code + # Built-in semirings can't be renamed + builtin = ffi.new("GrB_Semiring*", lib.GrB_PLUS_TIMES_SEMIRING_INT64) + with pytest.raises(exceptions.InvalidValue): + semiring.semiring_set_string(builtin, lib.GrB_NAME, "renamed") + + +# GraphBLAS doesn't limit the length of a name set with GrB_NAME + + +def test_descriptor_name_longer_than_256(): + D = ffi.new("GrB_Descriptor*") + assert lib.GrB_Descriptor_new(D) == lib.GrB_SUCCESS + D = ffi.gc(D, lib.GrB_Descriptor_free) + name = "d" * 1000 + descriptor.descriptor_set_string(D[0], lib.GrB_NAME, name) + assert descriptor.descriptor_get_string(D[0], lib.GrB_NAME) == name + assert descriptor.descriptor_get_size(D[0], lib.GrB_NAME) == len(name) + 1 + # GrB_NAME is a descriptor's only string. (GrB_Descriptor_get_String itself ignores the + # field and returns the name, or "" when none is set, but GrB_Descriptor_get_SIZE rejects + # every field but GrB_NAME.) + with pytest.raises(exceptions.InvalidValue): + descriptor.descriptor_get_string(D[0], lib.GrB_OUTP_FIELD) + + +def test_semiring_name_longer_than_256(): + s = semiring.semiring_new(lib.GrB_MAX_MONOID_FP64, lib.GrB_PLUS_FP64) + name = "s" * 1000 + semiring.semiring_set_string(s, lib.GrB_NAME, name) + assert semiring.semiring_get_string(s, lib.GrB_NAME) == name + assert semiring.semiring_get_size(s, lib.GrB_NAME) == len(name) + 1 diff --git a/suitesparse_graphblas/tests/test_api_ops.py b/suitesparse_graphblas/tests/test_api_ops.py new file mode 100644 index 0000000..790b9ff --- /dev/null +++ b/suitesparse_graphblas/tests/test_api_ops.py @@ -0,0 +1,387 @@ +"""User-defined operators of the functional API, made from cffi callbacks.""" + +import pytest + +from suitesparse_graphblas import exceptions, ffi, lib +from suitesparse_graphblas.api import ( + binaryop, + indexbinaryop, + indexunaryop, + matrix, + monoid, + scalar, + selectop, + unaryop, + vector, +) +from suitesparse_graphblas.api.utils import _capture_c_output + +INT64 = lib.GrB_INT64 + +# Whether a constructor hands its object to the garbage collector (its default) or leaves +# freeing it to the caller (`free=None`) +GC = [pytest.param(True, id="gc"), pytest.param(False, id="manual")] + +# GraphBLAS calls these through the function pointers cffi makes for them. They live at +# module level so that they outlive every operator built from them. + + +@ffi.callback("GxB_unary_function") +def _square_plus_half(z, x): + # FP64 <- INT32 + value = ffi.cast("int32_t*", x)[0] + ffi.cast("double*", z)[0] = value * value + 0.5 + + +@ffi.callback("GxB_binary_function") +def _times10_plus(z, x, y): + # INT64 <- INT64, INT64 + ffi.cast("int64_t*", z)[0] = 10 * ffi.cast("int64_t*", x)[0] + ffi.cast("int64_t*", y)[0] + + +@ffi.callback("GxB_index_unary_function") +def _plus_position(z, x, i, j, y): + # INT64 <- INT64 at (i, j), INT64 thunk + x = ffi.cast("int64_t*", x)[0] + y = ffi.cast("int64_t*", y)[0] + ffi.cast("int64_t*", z)[0] = x + 100 * i + 10 * j + y + + +@ffi.callback("GxB_index_binary_function") +def _plus_positions(z, x, ix, jx, y, iy, jy, theta): + # INT64 <- INT64 at (ix, jx), INT64 at (iy, jy), INT64 theta + x = ffi.cast("int64_t*", x)[0] + y = ffi.cast("int64_t*", y)[0] + theta = ffi.cast("int64_t*", theta)[0] + ffi.cast("int64_t*", z)[0] = x + y + theta * (1000 * ix + 100 * jx + 10 * iy + jy) + + +# C definitions of the callbacks, as the JIT would want them +DEFINITIONS = { + "unaryop": ( + "square_plus_half", + "void square_plus_half (double *z, const int32_t *x) " + "{ (*z) = ((double) (*x)) * (*x) + 0.5 ; }", + ), + "binaryop": ( + "times10_plus", + "void times10_plus (int64_t *z, const int64_t *x, const int64_t *y) " + "{ (*z) = 10 * (*x) + (*y) ; }", + ), + "indexunaryop": ( + "plus_position", + "void plus_position (int64_t *z, const int64_t *x, GrB_Index i, GrB_Index j, " + "const int64_t *y) { (*z) = (*x) + 100 * i + 10 * j + (*y) ; }", + ), + "indexbinaryop": ( + "plus_positions", + "void plus_positions (int64_t *z, const int64_t *x, GrB_Index ix, GrB_Index jx, " + "const int64_t *y, GrB_Index iy, GrB_Index jy, const int64_t *theta) " + "{ (*z) = (*x) + (*y) + (*theta) * (1000 * ix + 100 * jx + 10 * iy + jy) ; }", + ), +} + +MODULES = { + "unaryop": unaryop, + "binaryop": binaryop, + "indexunaryop": indexunaryop, + "indexbinaryop": indexbinaryop, + "monoid": monoid, +} + + +def _user_defined(kind, *, gc=True): + """Return a new user-defined object of `kind`, without a name.""" + kwargs = {} if gc else {"free": None} + if kind == "unaryop": + return unaryop.unaryop_new(_square_plus_half, lib.GrB_FP64, lib.GrB_INT32, **kwargs) + if kind == "binaryop": + return binaryop.binaryop_new(_times10_plus, INT64, INT64, INT64, **kwargs) + if kind == "indexunaryop": + return indexunaryop.indexunaryop_new(_plus_position, INT64, INT64, INT64, **kwargs) + if kind == "indexbinaryop": + return indexbinaryop.indexbinaryop_new( + _plus_positions, INT64, INT64, INT64, INT64, ffi.NULL, ffi.NULL, **kwargs + ) + assert kind == "monoid" + return monoid.monoid_new_int64(lib.GrB_PLUS_INT64, 0, **kwargs) + + +def _named(kind, name, defn, *, gc=True): + """Return a new operator of `kind` with a JIT name and definition.""" + kwargs = {} if gc else {"free": None} + if kind == "unaryop": + return unaryop.unaryop_new_named( + _square_plus_half, lib.GrB_FP64, lib.GrB_INT32, name, defn, **kwargs + ) + if kind == "binaryop": + return binaryop.binaryop_new_named(_times10_plus, INT64, INT64, INT64, name, defn, **kwargs) + if kind == "indexunaryop": + return indexunaryop.indexunaryop_new_named( + _plus_position, INT64, INT64, INT64, name, defn, **kwargs + ) + assert kind == "indexbinaryop" + return indexbinaryop.indexbinaryop_new( + _plus_positions, INT64, INT64, INT64, INT64, name, defn, **kwargs + ) + + +def _func(kind, name): + """Return the function `_` of the module for `kind`.""" + return getattr(MODULES[kind], f"{kind}_{name}") + + +def _free(kind, obj, gc): + """Free `obj` if it isn't garbage collected, and check that it's gone.""" + if not gc: + _func(kind, "free")(obj) + assert obj[0] == ffi.NULL + + +def _entries(A): + """Return the entries of an INT64 matrix as sorted (row, col, value) tuples.""" + rows, cols, values = matrix.matrix_extract_tuples_int64(A) + return sorted(zip(rows.tolist(), cols.tolist(), values.tolist())) + + +@pytest.mark.parametrize("kind", list(MODULES)) +def test_get_string_long_name(kind): + # GraphBLAS doesn't limit the length of a name the user sets + obj = _user_defined(kind) + name = "long_name_" + "x" * 500 + _func(kind, "set_string")(obj, lib.GrB_NAME, name) + assert _func(kind, "get_size")(obj, lib.GrB_NAME) == len(name) + 1 + assert _func(kind, "get_string")(obj, lib.GrB_NAME) == name + + +@pytest.mark.parametrize("kind", list(DEFINITIONS)) +def test_get_string_long_definition(kind): + # A definition is as long as its C code + name, defn = DEFINITIONS[kind] + defn = f"/* {'x' * 500} */\n{defn}" + op = _named(kind, name, defn) + assert _func(kind, "get_string")(op, lib.GxB_JIT_C_NAME) == name + assert _func(kind, "get_size")(op, lib.GxB_JIT_C_DEFINITION) == len(defn) + 1 + assert _func(kind, "get_string")(op, lib.GxB_JIT_C_DEFINITION) == defn + + +@pytest.mark.parametrize("gc", GC) +def test_unaryop_new(gc): + op = _user_defined("unaryop", gc=gc) + assert unaryop.unaryop_xtype(op) == lib.GrB_INT32 + assert unaryop.unaryop_ztype(op) == lib.GrB_FP64 + assert unaryop.unaryop_xtype_name(op) == "int32_t" + assert unaryop.unaryop_ztype_name(op) == "double" + assert unaryop.unaryop_get_int32(op, lib.GrB_INP0_TYPE_CODE) == lib.GrB_INT32_CODE + assert unaryop.unaryop_get_int32(op, lib.GrB_OUTP_TYPE_CODE) == lib.GrB_FP64_CODE + assert unaryop.unaryop_get_string(op, lib.GrB_NAME) == "" + unaryop.unaryop_wait(op) + + u = vector.vector_new(lib.GrB_INT32, 4) + vector.set_int32(u, 3, 1) + vector.set_int32(u, -2, 3) + w = vector.vector_new(lib.GrB_FP64, 4) + vector.vector_apply(w, op[0], u) + indices, values = vector.vector_extract_tuples_fp64(w) + assert indices.tolist() == [1, 3] + assert values.tolist() == [9.5, 4.5] + _free("unaryop", op, gc) + + +@pytest.mark.parametrize("gc", GC) +def test_binaryop_new(gc): + op = _user_defined("binaryop", gc=gc) + assert binaryop.binaryop_xtype(op) == INT64 + assert binaryop.binaryop_ytype(op) == INT64 + assert binaryop.binaryop_ztype(op) == INT64 + assert binaryop.binaryop_xtype_name(op) == "int64_t" + assert binaryop.binaryop_ytype_name(op) == "int64_t" + assert binaryop.binaryop_ztype_name(op) == "int64_t" + for field in (lib.GrB_INP0_TYPE_CODE, lib.GrB_INP1_TYPE_CODE, lib.GrB_OUTP_TYPE_CODE): + assert binaryop.binaryop_get_int32(op, field) == lib.GrB_INT64_CODE + binaryop.binaryop_wait(op) + + A = matrix.matrix_new(INT64, 2, 2) + B = matrix.matrix_new(INT64, 2, 2) + matrix.set_int64(A, 3, 0, 0) + matrix.set_int64(B, 4, 0, 0) + matrix.set_int64(B, 7, 0, 1) + matrix.set_int64(A, 5, 1, 1) + C = matrix.matrix_new(INT64, 2, 2) + # The operator applies only where both have an entry + matrix.matrix_ewise_add(C, op[0], A, B) + assert _entries(C) == [(0, 0, 34), (0, 1, 7), (1, 1, 5)] + _free("binaryop", op, gc) + + +@pytest.mark.parametrize("gc", GC) +def test_binaryop_new_indexop(gc): + idxop = _user_defined("indexbinaryop") + theta = scalar.scalar_new(INT64) + scalar.set_int64(theta, 2) + kwargs = {} if gc else {"free": None} + op = binaryop.binaryop_new_indexop(idxop[0], theta[0], **kwargs) + assert binaryop.binaryop_ztype(op) == INT64 + + A = matrix.matrix_new(INT64, 3, 3) + B = matrix.matrix_new(INT64, 3, 3) + matrix.set_int64(A, 1, 1, 2) + matrix.set_int64(B, 2, 1, 2) + matrix.set_int64(A, 3, 2, 0) + matrix.set_int64(B, 4, 2, 0) + matrix.set_int64(A, 5, 0, 0) + C = matrix.matrix_new(INT64, 3, 3) + # x + y + theta * (1000 * ix + 100 * jx + 10 * iy + jy), where both have an entry + matrix.matrix_ewise_mult(C, op[0], A, B) + assert _entries(C) == [(1, 2, 1 + 2 + 2 * 1212), (2, 0, 3 + 4 + 2 * 2020)] + _free("binaryop", op, gc) + + +@pytest.mark.parametrize("gc", GC) +def test_indexunaryop_new(gc): + op = _user_defined("indexunaryop", gc=gc) + assert indexunaryop.indexunaryop_xtype_name(op) == "int64_t" + assert indexunaryop.indexunaryop_ytype_name(op) == "int64_t" + assert indexunaryop.indexunaryop_ztype_name(op) == "int64_t" + for field in (lib.GrB_INP0_TYPE_CODE, lib.GrB_INP1_TYPE_CODE, lib.GrB_OUTP_TYPE_CODE): + assert indexunaryop.indexunaryop_get_int32(op, field) == lib.GrB_INT64_CODE + indexunaryop.indexunaryop_wait(op) + + A = matrix.matrix_new(INT64, 3, 3) + matrix.set_int64(A, 1, 1, 2) + matrix.set_int64(A, 5, 2, 0) + thunk = scalar.scalar_new(INT64) + scalar.set_int64(thunk, 7) + C = matrix.matrix_new(INT64, 3, 3) + # x + 100 * i + 10 * j + thunk + matrix.matrix_apply_indexop(C, op[0], A, thunk) + assert _entries(C) == [(1, 2, 128), (2, 0, 212)] + _free("indexunaryop", op, gc) + + +@pytest.mark.parametrize("gc", GC) +def test_indexbinaryop_new(gc): + name, defn = DEFINITIONS["indexbinaryop"] + op = _named("indexbinaryop", name, defn, gc=gc) + for field in ( + lib.GrB_INP0_TYPE_CODE, + lib.GrB_INP1_TYPE_CODE, + lib.GrB_OUTP_TYPE_CODE, + lib.GxB_THETA_TYPE_CODE, + ): + assert indexbinaryop.indexbinaryop_get_int32(op, field) == lib.GrB_INT64_CODE + for field in ( + lib.GrB_INP0_TYPE_STRING, + lib.GrB_INP1_TYPE_STRING, + lib.GrB_OUTP_TYPE_STRING, + lib.GxB_THETA_TYPE_STRING, + ): + assert indexbinaryop.indexbinaryop_get_string(op, field) == "GrB_INT64" + indexbinaryop.indexbinaryop_wait(op) + _free("indexbinaryop", op, gc) + + +@pytest.mark.parametrize("kind", list(DEFINITIONS)) +@pytest.mark.parametrize("gc", GC) +@pytest.mark.parametrize("encode", [False, True], ids=["str", "bytes"]) +def test_new_named(kind, gc, encode): + # Only the strings: using an operator that has a definition could start the JIT + name, defn = DEFINITIONS[kind] + if encode: + op = _named(kind, name.encode(), defn.encode(), gc=gc) + else: + op = _named(kind, name, defn, gc=gc) + get_string = _func(kind, "get_string") + assert get_string(op, lib.GxB_JIT_C_NAME) == name + assert get_string(op, lib.GxB_JIT_C_DEFINITION) == defn + assert get_string(op, lib.GrB_NAME) == "" + _free(kind, op, gc) + + +@pytest.mark.parametrize("kind", list(MODULES)) +def test_set_int32_not_allowed(kind): + # The types of an operator or a monoid are fixed when it's made + get_int32 = _func(kind, "get_int32") + obj = _user_defined(kind) + code = get_int32(obj, lib.GrB_OUTP_TYPE_CODE) + with pytest.raises(exceptions.InvalidValue): + _func(kind, "set_int32")(obj, lib.GrB_OUTP_TYPE_CODE, lib.GrB_BOOL_CODE) + assert get_int32(obj, lib.GrB_OUTP_TYPE_CODE) == code + + +@pytest.mark.parametrize( + ("kind", "name"), + [ + ("unaryop", "GrB_AINV_INT64"), + ("binaryop", "GrB_PLUS_INT64"), + ("indexunaryop", "GrB_VALUEEQ_INT64"), + ("monoid", "GrB_PLUS_MONOID_INT64"), + ], +) +def test_set_string_of_builtin(kind, name): + # A built-in keeps its name + ctype = { + "unaryop": "GrB_UnaryOp*", + "binaryop": "GrB_BinaryOp*", + "indexunaryop": "GrB_IndexUnaryOp*", + "monoid": "GrB_Monoid*", + }[kind] + obj = ffi.new(ctype, getattr(lib, name)) + with pytest.raises(exceptions.InvalidValue): + _func(kind, "set_string")(obj, lib.GrB_NAME, "renamed") + assert _func(kind, "get_string")(obj, lib.GrB_NAME) == name + + +@pytest.mark.parametrize( + "new", + [ + lambda: unaryop.unaryop_new(_square_plus_half, ffi.NULL, lib.GrB_INT32), + lambda: binaryop.binaryop_new(_times10_plus, ffi.NULL, INT64, INT64), + lambda: indexunaryop.indexunaryop_new(_plus_position, ffi.NULL, INT64, INT64), + lambda: indexbinaryop.indexbinaryop_new( + _plus_positions, ffi.NULL, INT64, INT64, INT64, ffi.NULL, ffi.NULL + ), + lambda: binaryop.binaryop_new_indexop(ffi.NULL, ffi.NULL), + ], + ids=["unaryop", "binaryop", "indexunaryop", "indexbinaryop", "binaryop_indexop"], +) +def test_new_fails(new): + with pytest.raises(exceptions.NullPointer): + new() + + +@pytest.mark.thread_unsafe(reason="redirects the process's stdout file descriptor") +@pytest.mark.parametrize("kind", list(DEFINITIONS)) +def test_print(kind): + name, defn = DEFINITIONS[kind] + op = _named(kind, name, defn) + out = _capture_c_output(_func(kind, "print"), op, "my_op", lib.GxB_COMPLETE) + assert "my_op (user-defined)" in out + assert f"z={name}(" in out + assert defn in out + + def fprint_silent_then_short(): + # A capture that gets no output at all fails on Emscripten, where reading the empty + # pipe raises BlockingIOError + _func(kind, "fprint")(op, ffi.NULL, "silent_op", lib.GxB_SILENT) + _func(kind, "fprint")(op, ffi.NULL, b"short_op", lib.GxB_SHORT) + + out = _capture_c_output(fprint_silent_then_short) + assert "silent_op" not in out + assert "short_op (user-defined)" in out + + +@pytest.mark.parametrize( + "func", + [ + selectop.selectop_xtype, + selectop.selectop_ttype, + selectop.selectop_print, + lambda op: selectop.selectop_fprint(op, ffi.NULL), + ], + ids=["xtype", "ttype", "print", "fprint"], +) +def test_selectop_null(func): + # These check the status themselves, rather than with check_status + with pytest.raises(exceptions.NullPointer, match="GxB_SelectOp_.* failed with info=-2"): + func(ffi.new("GxB_SelectOp*")) diff --git a/suitesparse_graphblas/tests/test_api_utils.py b/suitesparse_graphblas/tests/test_api_utils.py new file mode 100644 index 0000000..81c6d7d --- /dev/null +++ b/suitesparse_graphblas/tests/test_api_utils.py @@ -0,0 +1,67 @@ +import os + +import pytest + +from suitesparse_graphblas import exceptions, ffi, lib +from suitesparse_graphblas.api import context +from suitesparse_graphblas.api.utils import _capture_c_output + + +def _free_fds(): + # New file descriptors take the lowest free numbers, so these change if one leaks + fds = [os.dup(1) for _ in range(8)] + for fd in fds: + os.close(fd) + return fds + + +def _stdout_id(): + st = os.fstat(1) + return st.st_dev, st.st_ino + + +@pytest.mark.thread_unsafe(reason="redirects file descriptor 1") +def test_capture_c_output(): + ctx = context.context_new() + fds = _free_fds() + stdout = _stdout_id() + for _ in range(3): + out = _capture_c_output(context.context_print, ctx, "my_ctx", lib.GxB_SHORT) + assert "my_ctx" in out + assert _stdout_id() == stdout + assert _free_fds() == fds + + +@pytest.mark.thread_unsafe(reason="redirects file descriptor 1") +def test_capture_c_output_restores_stdout_on_error(): + ctx = context.context_new(free=None) + context.context_free(ctx) + fds = _free_fds() + stdout = _stdout_id() + with pytest.raises(exceptions.NullPointer): + _capture_c_output(context.context_print, ctx) + assert ctx[0] == ffi.NULL + assert _stdout_id() == stdout + assert _free_fds() == fds + + +@pytest.mark.thread_unsafe(reason="redirects file descriptor 1") +def test_capture_c_output_of_nothing(): + fds = _free_fds() + assert _capture_c_output(lambda: None) == "" + assert _free_fds() == fds + + +@pytest.mark.thread_unsafe(reason="patches os.dup2") +def test_capture_c_output_closes_fds_when_redirecting_fails(monkeypatch): + def failing_dup2(fd, fd2): + raise OSError("dup2 failed") + + fds = _free_fds() + stdout = _stdout_id() + monkeypatch.setattr(os, "dup2", failing_dup2) + with pytest.raises(OSError, match="dup2 failed"): + _capture_c_output(lambda: None) + monkeypatch.undo() + assert _stdout_id() == stdout + assert _free_fds() == fds diff --git a/suitesparse_graphblas/tests/test_bfs.py b/suitesparse_graphblas/tests/test_bfs.py new file mode 100644 index 0000000..93738aa --- /dev/null +++ b/suitesparse_graphblas/tests/test_bfs.py @@ -0,0 +1,119 @@ +import random +import runpy + +import pytest + +import suitesparse_graphblas +from suitesparse_graphblas import lib, matrix, vector +from suitesparse_graphblas.api.examples import bfs as bfs_module +from suitesparse_graphblas.api.examples.bfs import bfs + + +def _reference_bfs(n, edges, src): + """BFS levels, and parents chosen as bfs() does: the lowest-numbered one.""" + out = [[] for _ in range(n)] + for i, j in edges: + out[i].append(j) + level = {src: 0} + parent = {src: src} + frontier = [src] + while frontier: + reached = {} + for i in frontier: + for j in out[i]: + if j not in level: + reached[j] = min(reached.get(j, i), i) + for j, p in reached.items(): + level[j] = level[p] + 1 + parent[j] = p + frontier = list(reached) + return level, parent + + +def _to_dict(v): + indices, values = vector.vector_extract_tuples_int64(v) + return {int(i): int(x) for i, x in zip(indices, values)} + + +def _random_graph(n, nedges, T=lib.GrB_BOOL): + # Directed, with cycles, self-loops, and nodes that can't be reached from 0 + rng = random.Random(12345) + edges = {(rng.randrange(n), rng.randrange(n)) for _ in range(nedges)} + A = matrix.matrix_new(T, n, n) + for i, j in edges: + if T == lib.GrB_BOOL: + matrix.set_bool(A, True, i, j) + else: + matrix.set_fp64(A, 0.5, i, j) + return A, edges + + +@pytest.mark.parametrize("T", [lib.GrB_BOOL, lib.GrB_FP64]) +@pytest.mark.parametrize("src", [0, 45]) +def test_bfs_matches_reference(T, src): + n = 60 + A, edges = _random_graph(n, 90, T) + expected_level, expected_parent = _reference_bfs(n, edges, src) + assert 1 < len(expected_level) < n # the graph is neither trivial nor all reachable + + level, parent = bfs(A, src) + assert _to_dict(level) == expected_level + assert _to_dict(parent) == expected_parent + + level, parent = bfs(A, src, compute_parent=False) + assert parent is None + assert _to_dict(level) == expected_level + + level, parent = bfs(A, src, compute_level=False) + assert level is None + assert _to_dict(parent) == expected_parent + + +def test_bfs_lowest_parent(): + # 3 can be reached from 1 or 2; MIN_FIRST picks 1 + A = matrix.matrix_new(lib.GrB_BOOL, 4, 4) + for i, j in [(0, 2), (0, 1), (2, 3), (1, 3)]: + matrix.set_bool(A, True, i, j) + level, parent = bfs(A, 0) + assert _to_dict(level) == {0: 0, 1: 1, 2: 1, 3: 2} + assert _to_dict(parent) == {0: 0, 1: 0, 2: 0, 3: 1} + + +def test_bfs_isolated_source(): + A = matrix.matrix_new(lib.GrB_BOOL, 3, 3) + matrix.set_bool(A, True, 1, 2) + level, parent = bfs(A, 0) + assert _to_dict(level) == {0: 0} + assert _to_dict(parent) == {0: 0} + assert vector.vector_size(level) == vector.vector_size(parent) == 3 + + +def test_bfs_needs_an_output(): + A = matrix.matrix_new(lib.GrB_BOOL, 3, 3) + with pytest.raises(ValueError, match="at least one"): + bfs(A, 0, compute_level=False, compute_parent=False) + + +@pytest.mark.thread_unsafe(reason="patches suitesparse_graphblas.initialize and captures stdout") +def test_bfs_script(monkeypatch, capsys): + # The script initializes GraphBLAS, which this session already did + monkeypatch.setattr(suitesparse_graphblas, "initialize", lambda: None) + runpy.run_path(bfs_module.__file__, run_name="__main__") + lines = capsys.readouterr().out.splitlines() + assert lines[0] == "BFS from node 0:" + assert lines[1].split() == ["node", "level", "parent"] + rows = [tuple(int(x) for x in line.split()) for line in lines[2:]] + # 0 --- 1 --- 2 + # | | + # 3 4 --- 5 + # | + # 6 + assert rows == [ + (0, 0, 0), + (1, 1, 0), + (2, 2, 1), + (3, 1, 0), + (4, 2, 1), + (5, 3, 4), + (6, 3, 4), + ] diff --git a/suitesparse_graphblas/tests/test_burble.py b/suitesparse_graphblas/tests/test_burble.py new file mode 100644 index 0000000..d9c6b2b --- /dev/null +++ b/suitesparse_graphblas/tests/test_burble.py @@ -0,0 +1,62 @@ +import pickle + +import pytest + +from suitesparse_graphblas import burble, lib, matrix +from suitesparse_graphblas.api.utils import _capture_c_output + + +@pytest.mark.thread_unsafe(reason="burble is a global option") +def test_is_enabled(): + assert burble.is_enabled is False + burble.enable() + try: + assert burble.is_enabled is True + assert repr(burble) == "" + finally: + burble.disable() + assert burble.is_enabled is False + assert repr(burble) == "" + + +@pytest.mark.thread_unsafe(reason="burble is a global option, and this captures stdout") +def test_context_manager_prints_diagnostics(): + A = matrix.matrix_new(lib.GrB_BOOL, 3, 3) + # A pending tuple, so that matrix_nvals has work to do and report + matrix.set_bool(A, True, 0, 1) + with burble as b: + assert b is burble + assert burble.is_enabled is True + out = _capture_c_output(matrix.matrix_nvals, A) + assert burble.is_enabled is False + assert "GrB_Matrix_nvals" in out + matrix.set_bool(A, True, 1, 2) + assert _capture_c_output(matrix.matrix_nvals, A) == "" + + +@pytest.mark.thread_unsafe(reason="burble is a global option") +def test_context_manager_restores_the_previous_state(): + with burble: + with burble: + assert burble.is_enabled is True + # The inner block found burble enabled, so it leaves it enabled + assert burble.is_enabled is True + assert burble.is_enabled is False + + burble.enable() + try: + with burble: + pass + assert burble.is_enabled is True + finally: + burble.disable() + + with pytest.raises(ZeroDivisionError): + with burble: + 1 / 0 + assert burble.is_enabled is False + + +def test_pickle(): + # burble is a singleton, and unpickles as itself + assert pickle.loads(pickle.dumps(burble)) is burble diff --git a/suitesparse_graphblas/tests/test_completeness.py b/suitesparse_graphblas/tests/test_completeness.py new file mode 100644 index 0000000..477d3d8 --- /dev/null +++ b/suitesparse_graphblas/tests/test_completeness.py @@ -0,0 +1,167 @@ +"""Guards that the package covers everything the GraphBLAS it is built against declares. + +Each expected set is derived from GraphBLAS itself (the cffi `lib` and `ffi`), never from a hand +list, so a GraphBLAS that adds a type, a compression codec or a sparsity format fails a test here +and prompts a decision, instead of the package quietly falling behind. +""" + +import importlib +import re + +import pytest + +import suitesparse_graphblas as sg +from suitesparse_graphblas import ffi, lib +from suitesparse_graphblas.api.io import binary + +_TYPE_NAME = re.compile(r"G[rx]B_(BOOL|U?INT\d+|FP\d+|FC\d+)") + +_GrB_Type = ffi.typeof("GrB_Type") + +# The complex types are present exactly when the GraphBLAS was built with them +_builtin_names = sorted(n for n in dir(lib) if _TYPE_NAME.fullmatch(n)) +_builtin_types = {n: getattr(lib, n) for n in _builtin_names} + + +def _type_code(T): + value = ffi.new("int32_t*") + assert lib.GrB_Type_get_INT32(T, value, lib.GrB_EL_TYPE_CODE) == lib.GrB_SUCCESS + return value[0] + + +def _type_name(T): + size = ffi.new("size_t*") + assert lib.GrB_Type_get_SIZE(T, size, lib.GrB_NAME) == lib.GrB_SUCCESS + buf = ffi.new("char[]", size[0]) + assert lib.GrB_Type_get_String(T, buf, lib.GrB_NAME) == lib.GrB_SUCCESS + return ffi.string(buf).decode() + + +def test_builtin_type_names_are_all_types(): + # The pattern that finds the built-in types must not pick up anything else + for name in _builtin_names: + assert ffi.typeof(getattr(lib, name)) is _GrB_Type, name + assert len(_builtin_names) == (13 if sg.supports_complex() else 11) + # ... and must miss none: every GrB_Type constant is a built-in type + all_types = { + n + for n in dir(lib) + if n.startswith(("GrB_", "GxB_")) + and isinstance(getattr(lib, n), ffi.CData) + and ffi.typeof(getattr(lib, n)) is _GrB_Type + } + assert all_types == set(_builtin_names) + + +def test_grb_types_has_every_builtin_type(): + assert sg.grb_types == frozenset(_builtin_types.values()) + + +def test_type_families_partition_by_type_code(): + codes = ffi.typeof("GrB_Type_Code").relements + families = { + "BOOL": sg.bool_types, + "INT": sg.signed_integer_types, + "UINT": sg.unsigned_integer_types, + "FP": sg.real_types, + "FC": sg.complex_types, + } + expected = {name: set() for name in families} + for name, T in _builtin_types.items(): + code = _type_code(T) + (code_name,) = (n for n, v in codes.items() if v == code) + assert code_name == f"{name}_CODE" + family = re.fullmatch(r"G[rx]B_(BOOL|U?INT|FP|FC)\d*", name).group(1) + expected[family].add(T) + for family, types in families.items(): + assert types == expected[family], family + assert sg.integer_types == sg.signed_integer_types | sg.unsigned_integer_types + # The type codes are the built-in types plus the user-defined one + assert set(codes) == {f"{n}_CODE" for n in _builtin_names} | {"GrB_UDT_CODE"} + + +def test_binary_type_tables_cover_every_type(): + assert set(binary._ss_typecodes) == set(binary._ss_typenames) == set(sg.grb_types) + # The on-disk ordinals are unique, and decode back to the type + assert len(set(binary._ss_typecodes.values())) == len(binary._ss_typecodes) + assert {binary._ss_codetypes[c] for c in binary._ss_typecodes.values()} == set(sg.grb_types) + + +@pytest.mark.parametrize("name", _builtin_names) +def test_binary_type_name_matches_graphblas(name): + T = _builtin_types[name] + assert binary._ss_typenames[T] == _type_name(T) + + +_compression_names = sorted( + n for n in dir(lib) if n.startswith("GxB_COMPRESSION_") and not callable(getattr(lib, n)) +) + + +def test_compression_codecs_are_known(): + # A new codec needs a decision: whether it takes a level, as LZ4HC and ZSTD do (see + # `serialize.get_serialize_desc`), and a case in the `_serialize_options` tests in test_io.py + assert _compression_names == [ + "GxB_COMPRESSION_DEFAULT", + "GxB_COMPRESSION_LZ4", + "GxB_COMPRESSION_LZ4HC", + "GxB_COMPRESSION_NONE", + "GxB_COMPRESSION_ZSTD", + ] + + +@pytest.mark.parametrize("name", _compression_names) +def test_every_compression_codec_is_tested(name): + from suitesparse_graphblas.tests.test_io import _serialize_options + + assert getattr(lib, name) in {compression for compression, _ in _serialize_options.values()} + + +_ALL_TYPES = [n[4:].lower() for n in _builtin_names] + +# (module, family prefix, whether there is also a user-defined-type variant) +_families = [ + ("matrix", "get", False), + ("matrix", "set", False), + ("matrix", "matrix_build", False), + ("matrix", "matrix_extract_tuples", False), + ("vector", "get", False), + ("vector", "set", False), + ("vector", "vector_build", False), + ("vector", "vector_extract_tuples", False), + ("scalar", "get", False), + ("scalar", "set", False), + ("iterator", "iterator_get", False), + ("monoid", "monoid_new", True), + ("monoid", "monoid_terminal_new", True), +] + + +@pytest.mark.parametrize("module, prefix, udt", _families) +def test_wrapper_family_covers_every_type(module, prefix, udt): + mod = importlib.import_module(f"suitesparse_graphblas.api.{module}") + suffixes = _ALL_TYPES + (["udt"] if udt else []) + # Functions named `_` (functions of other families, such as + # `matrix_option_get_int32`, are named differently) + found = { + name[len(prefix) + 1 :] + for name in vars(mod) + if name.startswith(prefix + "_") + and callable(getattr(mod, name)) + and re.fullmatch(r"(bool|u?int\d+|fp\d+|fc\d+|udt)", name[len(prefix) + 1 :]) + } + assert found == set(suffixes) + + +def test_sparsity_formats_are_known(): + from suitesparse_graphblas.tests.test_io import _sparsities + + found = { + getattr(lib, n) + for n in dir(lib) + if re.fullmatch(r"GxB_(HYPERSPARSE|SPARSE|BITMAP|FULL)", n) + } + assert found == set(_sparsities) + from suitesparse_graphblas.tests import test_iterator + + assert set(test_iterator._sparsities) == found diff --git a/suitesparse_graphblas/tests/test_exceptions.py b/suitesparse_graphblas/tests/test_exceptions.py index 26b7861..477ac39 100644 --- a/suitesparse_graphblas/tests/test_exceptions.py +++ b/suitesparse_graphblas/tests/test_exceptions.py @@ -1,6 +1,14 @@ import pytest -from suitesparse_graphblas import check_status, exceptions, ffi, lib +from suitesparse_graphblas import ( + _error_code_lookup, + _error_func_lookup, + check_status, + exceptions, + ffi, + lib, +) +from suitesparse_graphblas.api import grb_type def test_check_status(): @@ -10,3 +18,94 @@ def test_check_status(): check_status(A, lib.GrB_PANIC) with pytest.raises(exceptions.Panic): check_status(A[0], lib.GrB_PANIC) + + +def test_check_status_success_and_no_value(): + A = ffi.new("GrB_Matrix*") + check_status(A, lib.GrB_Matrix_new(A, lib.GrB_BOOL, 2, 2)) + assert check_status(A, lib.GrB_SUCCESS) is None + # GrB_NO_VALUE is not an error: the exception class is returned, not raised + assert check_status(A, lib.GrB_NO_VALUE) is exceptions.NoValue + + +_error_names = sorted( + name + for name, info in ffi.typeof("GrB_Info").relements.items() + if info not in {lib.GrB_SUCCESS, lib.GrB_NO_VALUE} +) + + +@pytest.mark.parametrize("name", _error_names) +def test_check_status_raises_for_every_error_code(name): + # Every GrB_Info that GraphBLAS can return has its own exception class. + # This fails when a new GraphBLAS adds a code, as a reminder to add one. + info = getattr(lib, name) + assert info in _error_code_lookup + expected = _error_code_lookup[info] + assert expected is StopIteration or ( + issubclass(expected, exceptions.GraphBLASException) + and expected is not exceptions.GraphBLASException + ) + A = ffi.new("GrB_Matrix*") + check_status(A, lib.GrB_Matrix_new(A, lib.GrB_BOOL, 2, 2)) + with pytest.raises(expected): + check_status(A, info) + + +def test_check_status_unknown_code(): + # A code that this build doesn't know raises the base class, not KeyError + A = ffi.new("GrB_Matrix*") + check_status(A, lib.GrB_Matrix_new(A, lib.GrB_BOOL, 2, 2)) + unknown = -12345 + assert unknown not in _error_code_lookup + with pytest.raises(exceptions.GraphBLASException) as excinfo: + check_status(A, unknown) + assert type(excinfo.value) is exceptions.GraphBLASException + + +def test_check_status_already_set(): + # GraphBLAS returns GrB_ALREADY_SET when the name of an object is set twice + T = grb_type.grb_type_new(8) + grb_type.grb_type_set_string(T, lib.GrB_NAME, "first_name") + with pytest.raises(exceptions.AlreadySet): + grb_type.grb_type_set_string(T, lib.GrB_NAME, "second_name") + assert grb_type.grb_type_get_string(T, lib.GrB_NAME) == "first_name" + + +def test_check_status_output_is_readonly(): + # A vector loaded with GxB_IS_READONLY borrows the buffer, so GraphBLAS + # refuses to write to it with GxB_OUTPUT_IS_READONLY + v = ffi.new("GrB_Vector*") + check_status(v, lib.GrB_Vector_new(v, lib.GrB_INT64, 0)) + buf = ffi.new("int64_t[4]", [1, 2, 3, 4]) + X = ffi.new("void**", buf) + try: + check_status( + v, + lib.GxB_Vector_load( + v[0], X, lib.GrB_INT64, 4, ffi.sizeof(buf), lib.GxB_IS_READONLY, ffi.NULL + ), + ) + with pytest.raises(exceptions.OutputIsReadonly): + check_status(v, lib.GrB_Vector_setElement_INT64(v[0], 9, 0)) + assert list(buf) == [1, 2, 3, 4] + finally: + check_status(v, lib.GrB_Vector_free(v)) + + +def test_error_func_lookup_has_every_object_type(): + # check_status gets the error string with the object's *_error function. + # Every *_error function's object type must be in the table, or a new + # GraphBLAS object type would raise TypeError instead of its error. + error_funcs = [name for name in dir(lib) if name.endswith("_error")] + assert error_funcs + for name in error_funcs: + cname = ffi.typeof(getattr(lib, name)).args[1].cname + assert cname in _error_func_lookup, name + + +def test_check_status_unknown_object(): + # The error string is looked up by the type of the object, so an object + # that isn't a GraphBLAS handle is a TypeError, not a crash + with pytest.raises(TypeError, match="Unknown cname int \\*"): + check_status(ffi.new("int*"), lib.GrB_INVALID_VALUE) diff --git a/suitesparse_graphblas/tests/test_global_options.py b/suitesparse_graphblas/tests/test_global_options.py new file mode 100644 index 0000000..04b3507 --- /dev/null +++ b/suitesparse_graphblas/tests/test_global_options.py @@ -0,0 +1,102 @@ +import pytest + +from suitesparse_graphblas import exceptions, lib, matrix +from suitesparse_graphblas.api import global_options as go + +INVALID_FIELD = 999999 + + +@pytest.mark.parametrize( + "func, args", + [ + (go.global_option_get_int32, ()), + (go.global_option_set_int32, (1,)), + (go.global_option_get_fp64, ()), + (go.global_option_set_fp64, (1.0,)), + (go.global_option_get_char, ()), + (go.global_get_int32, ()), + (go.global_set_int32, (1,)), + (go.global_get_size, ()), + (go.global_get_string, ()), + (go.global_set_string, ("x",)), + ], +) +def test_invalid_field(func, args): + with pytest.raises(exceptions.InvalidValue, match="failed with info=-3"): + func(INVALID_FIELD, *args) + + +def test_global_get_string_names_the_call_that_failed(): + # The size is asked for first, so an invalid field fails there + with pytest.raises(exceptions.InvalidValue, match="^GrB_Global_get_SIZE failed with"): + go.global_get_string(INVALID_FIELD) + + +@pytest.mark.parametrize("field", ["GxB_API_ABOUT", "GxB_LIBRARY_LICENSE"]) +def test_global_get_string_longer_than_256(field): + # Both are longer than 256 characters in every build + field = getattr(lib, field) + value = go.global_get_string(field) + assert value == go.global_option_get_char(field) + assert len(value) > 256 + assert go.global_get_size(field) == len(value.encode()) + 1 + + +def test_global_get_string_and_size(): + assert go.global_get_string(lib.GrB_NAME) == "SuiteSparse:GraphBLAS" + assert go.global_get_size(lib.GrB_NAME) == len("SuiteSparse:GraphBLAS") + 1 + + +@pytest.mark.thread_unsafe(reason="sets a global option") +def test_global_set_string(): + # The C preface goes at the top of each JIT kernel; setting it compiles nothing + old = go.global_get_string(lib.GxB_JIT_C_PREFACE) + new = "/* " + "x" * 1000 + " */" + go.global_set_string(lib.GxB_JIT_C_PREFACE, new) + try: + assert go.global_get_string(lib.GxB_JIT_C_PREFACE) == new + assert go.global_option_get_char(lib.GxB_JIT_C_PREFACE) == new + assert go.global_get_size(lib.GxB_JIT_C_PREFACE) == len(new) + 1 + finally: + go.global_set_string(lib.GxB_JIT_C_PREFACE, old) + assert go.global_get_string(lib.GxB_JIT_C_PREFACE) == old + + +@pytest.mark.thread_unsafe(reason="sets a global option") +def test_global_option_int32(): + old = go.global_option_get_int32(lib.GxB_PRINT_1BASED) + try: + for value in (1, 0): + go.global_option_set_int32(lib.GxB_PRINT_1BASED, value) + assert go.global_option_get_int32(lib.GxB_PRINT_1BASED) == value + # The GxB_Global_Option and GrB_Global interfaces share the setting + assert go.global_get_int32(lib.GxB_PRINT_1BASED) == value + finally: + go.global_option_set_int32(lib.GxB_PRINT_1BASED, old) + + +@pytest.mark.thread_unsafe(reason="sets a global option") +def test_global_set_int32(): + old = go.global_get_int32(lib.GxB_PRINT_1BASED) + try: + for value in (1, 0): + go.global_set_int32(lib.GxB_PRINT_1BASED, value) + assert go.global_get_int32(lib.GxB_PRINT_1BASED) == value + assert go.global_option_get_int32(lib.GxB_PRINT_1BASED) == value + finally: + go.global_set_int32(lib.GxB_PRINT_1BASED, old) + + +@pytest.mark.thread_unsafe(reason="sets a global option") +def test_global_option_fp64(): + old = go.global_option_get_fp64(lib.GxB_HYPER_SWITCH) + new = 0.25 if old != 0.25 else 0.125 + go.global_option_set_fp64(lib.GxB_HYPER_SWITCH, new) + try: + assert go.global_option_get_fp64(lib.GxB_HYPER_SWITCH) == new + # The global setting is the default for new matrices + A = matrix.matrix_new(lib.GrB_BOOL, 3, 3) + assert matrix.matrix_hyper_switch(A) == new + finally: + go.global_option_set_fp64(lib.GxB_HYPER_SWITCH, old) + assert go.global_option_get_fp64(lib.GxB_HYPER_SWITCH) == old diff --git a/suitesparse_graphblas/tests/test_initialize.py b/suitesparse_graphblas/tests/test_initialize.py index fbd4db7..0c8775c 100644 --- a/suitesparse_graphblas/tests/test_initialize.py +++ b/suitesparse_graphblas/tests/test_initialize.py @@ -1,10 +1,34 @@ if __name__ == "__main__": + import numpy as np import pytest import suitesparse_graphblas as ssgb + from suitesparse_graphblas import burble, exceptions, lib, utils + from suitesparse_graphblas.api import container, global_options assert ssgb.is_initialized() is False - ssgb.initialize() + + # Before initialize, GraphBLAS calls fail with GrB_PANIC + for func in (lambda: burble.is_enabled, burble.enable, burble.disable): + with pytest.raises(exceptions.Panic, match="has GraphBLAS been initialized"): + func() + with pytest.raises(exceptions.Panic, match="info=-101"): + global_options.global_option_get_int32(lib.GxB_BURBLE) + with pytest.raises(exceptions.Panic, match="info=-101"): + container.container_new() + + # An unknown memory manager is an error, and leaves GraphBLAS uninitialized + with pytest.raises(ValueError, match='"numpy" or "c"'): + ssgb.initialize(memory_manager="malloc") + assert ssgb.is_initialized() is False + + # Every pytest session initializes with the default, "numpy" (see conftest.py), so + # use the C library's allocator here, spelled in another case + ssgb.initialize(memory_manager="C") assert ssgb.is_initialized() is True + # NumPy's memory can't be handed to GraphBLAS without a copy, since GraphBLAS frees it + # with libc free + assert utils.can_unclaim_buffer(np.empty(3)) is False with pytest.raises(RuntimeError, match="GraphBLAS is already initialized"): ssgb.initialize() + assert burble.is_enabled is False diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index 1134314..00507ce 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -1,8 +1,10 @@ import bz2 import gzip import platform +import struct from pathlib import Path +import numpy as np import pytest from suitesparse_graphblas import ( @@ -28,7 +30,8 @@ if platform.system() == "Windows": pytest.skip("skipping windows-only tests", allow_module_level=True) -from suitesparse_graphblas.io import binary # isort:skip +from suitesparse_graphblas.exceptions import InvalidObject, InvalidValue # isort:skip +from suitesparse_graphblas.io import binary, serialize # isort:skip NULL = ffi.NULL @@ -149,28 +152,18 @@ def test_matrix_binfile_read_write(tmp_path): for sparsity in (lib.GxB_HYPERSPARSE, lib.GxB_SPARSE, lib.GxB_BITMAP, lib.GxB_FULL): A = matrix.matrix_new(T, 2, 2) - if T is not lib.GxB_FULL: + if sparsity == lib.GxB_FULL: + # A matrix can only be full if it has a value everywhere + values = _test_elements(T)[0] + for k, (i, j) in enumerate([(0, 0), (0, 1), (1, 0), (1, 1)]): + check_status(A, _element_setters[T](A[0], values[k % 2], i, j)) + else: for args in zip(*_test_elements(T)): f = _element_setters[T] check_status(A, f(A[0], *args)) - else: - Tone = _test_elements(T)[0][0] - check_status( - A[0], - lib.GrB_assign( - A, - NULL, - NULL, - Tone, - lib.GrB_ALL, - 0, - lib.GrB_ALL, - 0, - NULL, - ), - ) matrix.matrix_set_sparsity_control(A, sparsity) matrix.matrix_set_format(A, format) + assert matrix.matrix_sparsity_status(A) == sparsity binfilef = tmp_path / "binfilewrite_test.binfile" binary.binwrite(A, binfilef, opener=opener) @@ -181,7 +174,9 @@ def test_matrix_binfile_read_write(tmp_path): assert matrix.matrix_ncols(A) == matrix.matrix_ncols(B) assert matrix.matrix_hyper_switch(A) == matrix.matrix_hyper_switch(B) assert matrix.matrix_bitmap_switch(A) == matrix.matrix_bitmap_switch(B) - # assert matrix.matrix_sparsity_control(A) == matrix.matrix_sparsity_control(B) + assert matrix.matrix_sparsity_control(A) == matrix.matrix_sparsity_control(B) + assert matrix.matrix_sparsity_status(B) == sparsity + assert matrix.matrix_format(B) == format C = matrix.matrix_new(lib.GrB_BOOL, 2, 2) @@ -214,3 +209,396 @@ def test_binwrite_failure_keeps_matrix(tmp_path): with pytest.raises(OSError): binary.binwrite(A, tmp_path / "missing_directory" / "matrix.binfile") assert matrix.matrix_nvals(A) == 1 + + +_extract_tuples = { + lib.GrB_BOOL: matrix.matrix_extract_tuples_bool, + lib.GrB_INT8: matrix.matrix_extract_tuples_int8, + lib.GrB_INT16: matrix.matrix_extract_tuples_int16, + lib.GrB_INT32: matrix.matrix_extract_tuples_int32, + lib.GrB_INT64: matrix.matrix_extract_tuples_int64, + lib.GrB_UINT8: matrix.matrix_extract_tuples_uint8, + lib.GrB_UINT16: matrix.matrix_extract_tuples_uint16, + lib.GrB_UINT32: matrix.matrix_extract_tuples_uint32, + lib.GrB_UINT64: matrix.matrix_extract_tuples_uint64, + lib.GrB_FP32: matrix.matrix_extract_tuples_fp32, + lib.GrB_FP64: matrix.matrix_extract_tuples_fp64, +} + +if supports_complex(): + _extract_tuples.update( + { + lib.GxB_FC32: matrix.matrix_extract_tuples_fc32, + lib.GxB_FC64: matrix.matrix_extract_tuples_fc64, + } + ) + +_sparsities = { + lib.GxB_HYPERSPARSE: "hypersparse", + lib.GxB_SPARSE: "sparse", + lib.GxB_BITMAP: "bitmap", + lib.GxB_FULL: "full", +} + +# 3x4, so a matrix held by row and by column differ; "sparse" leaves row 1 and column 2 empty +_shape = (3, 4) +_sparse_indices = [(0, 1), (2, 3), (2, 0)] +_full_indices = [(i, j) for i in range(_shape[0]) for j in range(_shape[1])] + + +def _values(T): + """Four distinct values (two for BOOL) of type T, for entries to cycle through.""" + if T in bool_types: + return [True, False] + if T in signed_integer_types: + return [1, -42, 7, -100] + if T in unsigned_integer_types: + return [1, 42, 7, 200] + if T in real_types: + return [1.0, -42.5, 0.25, 3.0e5] + return [complex(1.0, 1.0), complex(42.0, -42.0), -0.5j, complex(3.0, 0.0)] + + +def _make_matrix(T, kind): + """A matrix of type T: "empty", "sparse", "full", or iso ("iso_sparse", "iso_full").""" + A = matrix.matrix_new(T, *_shape) + indices = {"empty": [], "sparse": _sparse_indices, "iso_sparse": _sparse_indices}.get( + kind, _full_indices + ) + values = _values(T) + setter = _element_setters[T] + for k, (i, j) in enumerate(indices): + value = values[0] if kind.startswith("iso") else values[k % len(values)] + check_status(A, setter(A[0], value, i, j)) + return A + + +def _is_iso(A): + iso = ffi.new("bool*") + check_status(A, lib.GxB_Matrix_iso(iso, A[0])) + return iso[0] + + +def _settings(A): + return { + "format": matrix.matrix_format(A), + "sparsity_status": matrix.matrix_sparsity_status(A), + "sparsity_control": matrix.matrix_sparsity_control(A), + "hyper_switch": matrix.matrix_hyper_switch(A), + "bitmap_switch": matrix.matrix_bitmap_switch(A), + "iso": _is_iso(A), + } + + +def _assert_matrices_equal(A, B): + T = matrix.matrix_type(A) + assert matrix.matrix_type(B) == T + assert matrix.matrix_shape(B) == matrix.matrix_shape(A) + for x, y in zip(_extract_tuples[T](A), _extract_tuples[T](B), strict=True): + np.testing.assert_array_equal(x, y) + + +@pytest.mark.parametrize("sparsity", _sparsities, ids=_sparsities.get) +@pytest.mark.parametrize( + "T", sorted(grb_types, key=binary._ss_typecodes.get), ids=binary._ss_typenames.get +) +def test_binwrite_binread_round_trip(tmp_path, T, sparsity): + path = tmp_path / "matrix.binfile" + for format in (lib.GxB_BY_ROW, lib.GxB_BY_COL): + for kind in ("empty", "sparse", "iso_sparse", "iso_full"): + A = _make_matrix(T, kind) + matrix.matrix_set_format(A, format) + matrix.matrix_set_sparsity_control(A, sparsity) + matrix.matrix_set_hyper_switch(A, 0.25) + matrix.matrix_set_bitmap_switch(A, 0.75) + matrix.matrix_wait(A, lib.GrB_MATERIALIZE) + expected = _settings(A) + # The cases cover what they say: GraphBLAS makes a matrix iso when its values are, + # and holds a matrix with every entry as asked (bitmap stands in for full otherwise) + assert expected["iso"] == kind.startswith("iso") + if kind.endswith("full"): + assert expected["sparsity_status"] == sparsity + + binary.binwrite(A, path) + B = binary.binread(path) + + _assert_matrices_equal(A, B) + assert _settings(B) == expected, (format, kind) + + +_openers = {"open": Path.open, "gzip": gzip.open, "bz2": bz2.open} +if lzma is not None: + _openers["lzma"] = lzma.open + + +@pytest.mark.parametrize("opener", _openers.values(), ids=_openers) +def test_binwrite_binread_opener(tmp_path, opener): + A = _make_matrix(lib.GrB_FP64, "sparse") + matrix.matrix_set_sparsity_control(A, lib.GxB_HYPERSPARSE) + path = str(tmp_path / "matrix.binfile") # a str works as well as a Path + binary.binwrite(A, path, opener=opener, comments="three entries") + B = binary.binread(path, opener=opener) + _assert_matrices_equal(A, B) + + # The file was written through `opener`, and starts with a readable header + with opener(path, "rb") as f: + header = f.read(binary.GRB_HEADER_LEN) + assert header.startswith(b"SuiteSparse:GraphBLAS matrix\n") + lines = header.decode("ascii").split("\n") + for line in ["nrows: 3", "ncols: 4", "nvals: 3", "format: HCSR", "type: GrB_FP64"]: + assert line in lines + assert "three entries" in lines + with Path(path).open("rb") as f: + assert f.read(len(header)).startswith(header) == (opener is Path.open) + + +@pytest.mark.parametrize("fails", [False, True], ids=["written", "failed"]) +@pytest.mark.parametrize("sparsity", _sparsities, ids=_sparsities.get) +def test_binwrite_keeps_matrix_settings(tmp_path, sparsity, fails): + # Packing the arrays back into the matrix resets its sparsity control and switches to the + # defaults, and `binwrite` must leave the matrix as it was, whether or not writing worked + A = _make_matrix(lib.GrB_INT64, "full") + matrix.matrix_set_sparsity_control(A, sparsity) + matrix.matrix_set_hyper_switch(A, 0.25) + matrix.matrix_set_bitmap_switch(A, 0.75) + matrix.matrix_wait(A, lib.GrB_MATERIALIZE) + expected = _settings(A) + path = tmp_path / ("missing_directory" if fails else "") / "matrix.binfile" + if fails: + with pytest.raises(OSError): + binary.binwrite(A, path) + else: + binary.binwrite(A, path) + assert _settings(A) == expected + _assert_matrices_equal(A, _make_matrix(lib.GrB_INT64, "full")) + + +def test_binwrite_header_error_keeps_matrix(tmp_path): + # The header (which must be ASCII) is made after the matrix is unpacked, so a failure there + # must also put the arrays back + A = _make_matrix(lib.GrB_INT64, "sparse") + path = tmp_path / "matrix.binfile" + with pytest.raises(UnicodeEncodeError): + binary.binwrite(A, path, comments="café") + assert not path.exists() + _assert_matrices_equal(A, _make_matrix(lib.GrB_INT64, "sparse")) + + +@pytest.mark.parametrize("sparsity", _sparsities, ids=_sparsities.get) +def test_binread_truncated(tmp_path, sparsity): + A = _make_matrix(lib.GrB_INT64, "sparse") + matrix.matrix_set_sparsity_control(A, sparsity) + path = tmp_path / "matrix.binfile" + binary.binwrite(A, path) + data = path.read_bytes() + _assert_matrices_equal(A, binary.binread(path)) + for size in range(len(data)): + path.write_bytes(data[:size]) + with pytest.raises(EOFError, match="truncated"): + binary.binread(path) + + +# Where binwrite puts the matrix's format and sparsity status (int32 each), after the text +# header and the GraphBLAS version +_format_offset = binary.GRB_HEADER_LEN + ffi.sizeof("uint64_t") +_sparsity_offset = _format_offset + ffi.sizeof("GxB_Format_Value") + + +@pytest.mark.parametrize( + "offset, value, message", + [ + (_format_offset, 99, "Unknown format 99"), + (_sparsity_offset, 3, "Unknown sparsity status 3"), + ], + ids=["format", "sparsity"], +) +def test_binread_unknown_field(tmp_path, offset, value, message): + path = tmp_path / "matrix.binfile" + binary.binwrite(_make_matrix(lib.GrB_INT64, "sparse"), path) + data = bytearray(path.read_bytes()) + struct.pack_into("=i", data, offset, value) + path.write_bytes(data) + with pytest.raises(TypeError, match=message): + binary.binread(path) + + +def test_binwrite_long_comments(tmp_path): + # binread skips a header of exactly GRB_HEADER_LEN bytes, so binwrite refuses + # comments that would make it longer, before it opens the file + A = _make_matrix(lib.GrB_INT64, "sparse") + path = tmp_path / "matrix.binfile" + binary.binwrite(A, path, comments="") + used = len(path.read_bytes()[: binary.GRB_HEADER_LEN].rstrip(b" ")) + room = binary.GRB_HEADER_LEN - used + # The longest comment that fits round-trips + binary.binwrite(A, path, comments="x" * room) + _assert_matrices_equal(A, binary.binread(path)) + # One more character is refused, and nothing is written + path.unlink() + with pytest.raises(ValueError, match="comments are too long"): + binary.binwrite(A, path, comments="x" * (room + 1)) + assert not path.exists() + with pytest.raises(ValueError, match="comments are too long"): + binary.binwrite(A, path, comments="x" * binary.GRB_HEADER_LEN) + assert not path.exists() + _assert_matrices_equal(A, _make_matrix(lib.GrB_INT64, "sparse")) + + +def _compression(desc): + value = ffi.new("int32_t*") + check_status(desc, lib.GrB_Descriptor_get_INT32(desc, value, lib.GxB_COMPRESSION)) + return value[0] + + +def test_get_serialize_desc(): + # The default needs no descriptor, whatever the level + assert serialize.get_serialize_desc() is None + assert serialize.get_serialize_desc(None) is None + assert serialize.get_serialize_desc(lib.GxB_COMPRESSION_DEFAULT, 5) is None + # A level is added to the methods that have levels, and ignored by the others + get = serialize.get_serialize_desc + ZSTD, LZ4HC = lib.GxB_COMPRESSION_ZSTD, lib.GxB_COMPRESSION_LZ4HC + assert _compression(get(ZSTD)) == ZSTD + assert _compression(get(ZSTD, 19)) == ZSTD + 19 + assert _compression(get(LZ4HC, 9)) == LZ4HC + 9 + assert _compression(get(lib.GxB_COMPRESSION_LZ4, 9)) == lib.GxB_COMPRESSION_LZ4 + assert _compression(get(lib.GxB_COMPRESSION_NONE, 9)) == lib.GxB_COMPRESSION_NONE + + +_serialize_options = { + "none": (lib.GxB_COMPRESSION_NONE, None), + "default": (lib.GxB_COMPRESSION_DEFAULT, None), + "lz4": (lib.GxB_COMPRESSION_LZ4, None), + "lz4hc": (lib.GxB_COMPRESSION_LZ4HC, None), + "lz4hc-9": (lib.GxB_COMPRESSION_LZ4HC, 9), + "zstd": (lib.GxB_COMPRESSION_ZSTD, None), + "zstd-1": (lib.GxB_COMPRESSION_ZSTD, 1), + "zstd-19": (lib.GxB_COMPRESSION_ZSTD, 19), + "unset": (None, None), +} + + +def _numbered_matrix(n): + """An n-by-n INT64 matrix whose entries are 0, 1, ..., n*n - 1, by row.""" + A = matrix.matrix_new(lib.GrB_INT64, n, n) + rows = np.repeat(np.arange(n, dtype=np.uint64), n) + cols = np.tile(np.arange(n, dtype=np.uint64), n) + values = np.arange(n * n, dtype=np.int64) + matrix.matrix_build_int64(A, rows, cols, values, n * n, lib.GrB_PLUS_INT64) + return A + + +@pytest.mark.parametrize("option", _serialize_options) +def test_serialize_matrix_compression(option): + compression, level = _serialize_options[option] + for kind in ("empty", "sparse", "full", "iso_full"): + A = _make_matrix(lib.GrB_FP64, kind) + data = serialize.serialize_matrix(A, compression, level) + assert data.dtype == np.uint8 + _assert_matrices_equal(A, serialize.deserialize_matrix(data)) + # Anything with the buffer protocol will do + _assert_matrices_equal(A, serialize.deserialize_matrix(data.tobytes())) + + +@pytest.mark.parametrize("option", _serialize_options) +def test_serialize_vector_compression(option): + compression, level = _serialize_options[option] + v = vector.vector_new(lib.GrB_FP64, 5) + vector.set_fp64(v, 1.5, 1) + vector.set_fp64(v, -2.5, 4) + w = serialize.deserialize_vector(serialize.serialize_vector(v, compression, level)) + assert vector.vector_type(w) == lib.GrB_FP64 + assert vector.vector_size(w) == 5 + for x, y in zip( + vector.vector_extract_tuples_fp64(v), vector.vector_extract_tuples_fp64(w), strict=True + ): + np.testing.assert_array_equal(x, y) + + +def test_serialize_compression_reaches_graphblas(): + # The compression and level change the result, so they get to GraphBLAS + A = _numbered_matrix(100) + size = { + option: serialize.serialize_matrix(A, compression, level).nbytes + for option, compression, level in [ + ("none", lib.GxB_COMPRESSION_NONE, None), + ("lz4", lib.GxB_COMPRESSION_LZ4, None), + ("lz4hc-1", lib.GxB_COMPRESSION_LZ4HC, 1), + ("lz4hc-9", lib.GxB_COMPRESSION_LZ4HC, 9), + ("zstd-1", lib.GxB_COMPRESSION_ZSTD, 1), + ("zstd-19", lib.GxB_COMPRESSION_ZSTD, 19), + ] + } + assert size["none"] > 100 * 100 * 8 + assert size["none"] > size["lz4"] > size["zstd-1"] > size["zstd-19"] + assert size["lz4hc-1"] > size["lz4hc-9"] + v = vector.vector_new(lib.GrB_INT64, 1000) + for i in range(0, 1000, 3): + vector.set_int64(v, i, i) + none = serialize.serialize_vector(v, lib.GxB_COMPRESSION_NONE).nbytes + assert none > serialize.serialize_vector(v, lib.GxB_COMPRESSION_ZSTD).nbytes + + +@pytest.mark.parametrize("free", [None, False], ids=["None", "False"]) +def test_deserialize_without_free(free): + # The caller frees the result + A = _make_matrix(lib.GrB_INT64, "sparse") + B = serialize.deserialize_matrix(serialize.serialize_matrix(A), free=free) + _assert_matrices_equal(A, B) + matrix.matrix_free(B) + assert B[0] == NULL + v = vector.vector_new(lib.GrB_INT64, 3) + vector.set_int64(v, 7, 2) + w = serialize.deserialize_vector(serialize.serialize_vector(v), free=free) + assert vector.vector_nvals(w) == 1 + vector.vector_free(w) + assert w[0] == NULL + + +def test_deserialize_with_free(): + # `free` is called with the result once it is released + freed = [] + + def free_matrix(A): + freed.append(matrix.matrix_nvals(A)) + matrix.matrix_free(A) + + def free_vector(v): + freed.append(vector.vector_nvals(v)) + vector.vector_free(v) + + A = _make_matrix(lib.GrB_INT64, "sparse") + B = serialize.deserialize_matrix(serialize.serialize_matrix(A), free=free_matrix) + _assert_matrices_equal(A, B) + v = vector.vector_new(lib.GrB_INT64, 3) + vector.set_int64(v, 7, 2) + w = serialize.deserialize_vector(serialize.serialize_vector(v), free=free_vector) + assert freed == [] + ffi.release(B) + ffi.release(w) + assert freed == [3, 1] + + +def test_deserialize_invalid(): + for deserialize in (serialize.deserialize_matrix, serialize.deserialize_vector): + with pytest.raises(InvalidObject): + deserialize(bytes(64)) + + +@pytest.mark.xfail( + strict=True, + raises=InvalidValue, + reason="serialize sets nthreads on a descriptor, which GraphBLAS 10 rejects with " + "GrB_INVALID_VALUE: the number of threads is a GxB_Context setting now", +) +@pytest.mark.parametrize("kind", ["matrix", "vector"]) +def test_serialize_nthreads(kind): + if kind == "matrix": + A = _make_matrix(lib.GrB_INT64, "sparse") + B = serialize.deserialize_matrix(serialize.serialize_matrix(A, nthreads=1), nthreads=1) + _assert_matrices_equal(A, B) + else: + v = vector.vector_new(lib.GrB_INT64, 3) + vector.set_int64(v, 7, 2) + w = serialize.deserialize_vector(serialize.serialize_vector(v, nthreads=1), nthreads=1) + assert vector.vector_nvals(w) == 1 diff --git a/suitesparse_graphblas/tests/test_iterator.py b/suitesparse_graphblas/tests/test_iterator.py new file mode 100644 index 0000000..af2fe4e --- /dev/null +++ b/suitesparse_graphblas/tests/test_iterator.py @@ -0,0 +1,328 @@ +import pytest + +from suitesparse_graphblas import ( + bool_types, + complex_types, + exceptions, + ffi, + grb_types, + lib, + matrix, + real_types, + signed_integer_types, + supports_complex, + vector, +) +from suitesparse_graphblas.api import iterator + +SUCCESS = lib.GrB_SUCCESS +NO_VALUE = lib.GrB_NO_VALUE +EXHAUSTED = lib.GxB_EXHAUSTED + +_sparsities = { + lib.GxB_HYPERSPARSE: "hypersparse", + lib.GxB_SPARSE: "sparse", + lib.GxB_BITMAP: "bitmap", + lib.GxB_FULL: "full", +} + +# 5x4, with rows 1 and 3 and column 1 empty +_shape = (5, 4) +_entries = {(0, 2): 10, (2, 3): 20, (2, 0): 30, (4, 2): 40, (0, 0): 50} + + +def _matrix(format, sparsity): + """An INT64 matrix with `_entries`, or with every entry (i * 10 + j) if `sparsity` is full.""" + A = matrix.matrix_new(lib.GrB_INT64, *_shape) + if sparsity == lib.GxB_FULL: + entries = {(i, j): i * 10 + j for i in range(_shape[0]) for j in range(_shape[1])} + else: + entries = _entries + for (i, j), value in entries.items(): + matrix.set_int64(A, value, i, j) + matrix.matrix_set_format(A, format) + matrix.matrix_set_sparsity_control(A, sparsity) + matrix.matrix_wait(A, lib.GrB_MATERIALIZE) + assert matrix.matrix_sparsity_status(A) == sparsity + return A, sorted((i, j, value) for (i, j), value in entries.items()) + + +def test_check_info(): + for info in [SUCCESS, NO_VALUE, EXHAUSTED]: + assert iterator._check_info(info) == info + with pytest.raises(exceptions.InvalidIndex): + iterator._check_info(lib.GrB_INVALID_INDEX) + with pytest.raises(RuntimeError, match="info=-12345"): + iterator._check_info(-12345) + + +def test_iterator_new_free(): + it = iterator.iterator_new(free=None) + assert it[0] != ffi.NULL + iterator.iterator_free(it) + assert it[0] == ffi.NULL + + freed = [] + + def free(it): + freed.append(it) + iterator.iterator_free(it) + + it = iterator.iterator_new(free=free) + assert freed == [] + ffi.release(it) + assert len(freed) == 1 + assert freed[0][0] == ffi.NULL + + +@pytest.mark.parametrize("sparsity", _sparsities, ids=_sparsities.get) +@pytest.mark.parametrize("format", [lib.GxB_BY_ROW, lib.GxB_BY_COL], ids=["by_row", "by_col"]) +def test_matrix_iterator(format, sparsity): + A, expected = _matrix(format, sparsity) + it = iterator.iterator_new() + assert iterator.matrix_iterator_attach(it, A) == SUCCESS + pmax = iterator.matrix_iterator_getpmax(it) + if sparsity == lib.GxB_BITMAP: + assert pmax == _shape[0] * _shape[1] + else: + assert pmax == len(expected) + entries = [] + info = iterator.matrix_iterator_seek(it, 0) + while info != EXHAUSTED: + assert info == SUCCESS + p = iterator.matrix_iterator_getp(it) + assert 0 <= p < pmax + i, j = iterator.matrix_iterator_get_index(it) + entries.append((i, j, iterator.iterator_get_int64(it))) + info = iterator.matrix_iterator_next(it) + assert sorted(entries) == expected + # Held by row, the entries come by row; held by column, by column + if format == lib.GxB_BY_ROW: + assert entries == expected + else: + assert entries == sorted(expected, key=lambda e: (e[1], e[0])) + + # Seeking a position goes to the entry there, or (for bitmap) the next one + for p in range(pmax): + assert iterator.matrix_iterator_seek(it, p) == SUCCESS or sparsity == lib.GxB_BITMAP + if sparsity != lib.GxB_BITMAP: + assert iterator.matrix_iterator_getp(it) == p + assert iterator.matrix_iterator_seek(it, pmax) == EXHAUSTED + + +def _row_iterate(it, seek, next_vector, next_entry, get_vector_index, get_entry_index): + """Iterate over the entries of A as GraphBLAS's documentation does.""" + entries = [] + info = seek(it, 0) + while info != EXHAUSTED: + k = get_vector_index(it) + while info == SUCCESS: + entries.append((k, get_entry_index(it), iterator.iterator_get_int64(it))) + info = next_entry(it) + assert info == NO_VALUE + info = next_vector(it) + return entries + + +@pytest.mark.parametrize("sparsity", _sparsities, ids=_sparsities.get) +def test_row_iterator(sparsity): + A, expected = _matrix(lib.GxB_BY_ROW, sparsity) + nrows = _shape[0] + it = iterator.iterator_new() + assert iterator.row_iterator_attach(it, A) == SUCCESS + entries = _row_iterate( + it, + iterator.row_iterator_seek_row, + iterator.row_iterator_next_row, + iterator.row_iterator_next_col, + iterator.row_iterator_get_row_index, + iterator.row_iterator_get_col_index, + ) + assert entries == expected + assert iterator.row_iterator_get_row_index(it) == nrows # exhausted + + rows = sorted({i for i, _, _ in expected}) + kount = iterator.row_iterator_kount(it) + if sparsity == lib.GxB_HYPERSPARSE: + assert len(rows) <= kount <= nrows + else: + assert kount == nrows + visited = [] + for k in range(kount): + info = iterator.row_iterator_kseek(it, k) + i = iterator.row_iterator_get_row_index(it) + if sparsity != lib.GxB_HYPERSPARSE: + assert i == k + assert info == (SUCCESS if i in rows else NO_VALUE) + visited.append(i) + assert set(rows) <= set(visited) + assert iterator.row_iterator_kseek(it, kount) == EXHAUSTED + + # Seeking an empty row: it has no entries, or (if hypersparse) the next row is found + info = iterator.row_iterator_seek_row(it, 1) + if sparsity == lib.GxB_HYPERSPARSE: + assert info == SUCCESS + assert iterator.row_iterator_get_row_index(it) == 2 + else: + assert info == (SUCCESS if sparsity == lib.GxB_FULL else NO_VALUE) + assert iterator.row_iterator_get_row_index(it) == 1 + assert iterator.row_iterator_seek_row(it, nrows) == EXHAUSTED + + +@pytest.mark.parametrize("sparsity", _sparsities, ids=_sparsities.get) +def test_col_iterator(sparsity): + A, expected = _matrix(lib.GxB_BY_COL, sparsity) + expected = sorted((j, i, value) for i, j, value in expected) + ncols = _shape[1] + it = iterator.iterator_new() + assert iterator.col_iterator_attach(it, A) == SUCCESS + entries = _row_iterate( + it, + iterator.col_iterator_seek_col, + iterator.col_iterator_next_col, + iterator.col_iterator_next_row, + iterator.col_iterator_get_col_index, + iterator.col_iterator_get_row_index, + ) + assert entries == expected + assert iterator.col_iterator_get_col_index(it) == ncols # exhausted + + cols = sorted({j for j, _, _ in expected}) + kount = iterator.col_iterator_kount(it) + if sparsity == lib.GxB_HYPERSPARSE: + assert len(cols) <= kount <= ncols + else: + assert kount == ncols + visited = [] + for k in range(kount): + info = iterator.col_iterator_kseek(it, k) + j = iterator.col_iterator_get_col_index(it) + if sparsity != lib.GxB_HYPERSPARSE: + assert j == k + assert info == (SUCCESS if j in cols else NO_VALUE) + visited.append(j) + assert set(cols) <= set(visited) + assert iterator.col_iterator_kseek(it, kount) == EXHAUSTED + + # Seeking an empty column: it has no entries, or (if hypersparse) the next column is found + info = iterator.col_iterator_seek_col(it, 1) + if sparsity == lib.GxB_HYPERSPARSE: + assert info == SUCCESS + assert iterator.col_iterator_get_col_index(it) == 2 + else: + assert info == (SUCCESS if sparsity == lib.GxB_FULL else NO_VALUE) + assert iterator.col_iterator_get_col_index(it) == 1 + assert iterator.col_iterator_seek_col(it, ncols) == EXHAUSTED + + +def test_row_and_col_iterators_need_their_format(): + it = iterator.iterator_new() + by_col, _ = _matrix(lib.GxB_BY_COL, lib.GxB_SPARSE) + with pytest.raises(exceptions.NotImplementedException): + iterator.row_iterator_attach(it, by_col) + by_row, _ = _matrix(lib.GxB_BY_ROW, lib.GxB_SPARSE) + with pytest.raises(exceptions.NotImplementedException): + iterator.col_iterator_attach(it, by_row) + # The entry iterator takes either + assert iterator.matrix_iterator_attach(it, by_col) == SUCCESS + assert iterator.matrix_iterator_attach(it, by_row) == SUCCESS + + +@pytest.mark.parametrize("sparsity", _sparsities, ids=_sparsities.get) +def test_vector_iterator(sparsity): + size = 6 + v = vector.vector_new(lib.GrB_FP64, size) + if sparsity == lib.GxB_FULL: + expected = [(i, i + 0.5) for i in range(size)] + else: + expected = [(1, 1.5), (4, -2.5), (5, 0.25)] + for i, value in expected: + vector.set_fp64(v, value, i) + check = lib.GxB_Vector_Option_set_INT32(v[0], lib.GxB_SPARSITY_CONTROL, sparsity) + assert check == SUCCESS + vector.vector_wait(v, lib.GrB_MATERIALIZE) + + it = iterator.iterator_new() + assert iterator.vector_iterator_attach(it, v) == SUCCESS + pmax = iterator.vector_iterator_getpmax(it) + assert pmax == (size if sparsity == lib.GxB_BITMAP else len(expected)) + entries = [] + info = iterator.vector_iterator_seek(it, 0) + while info != EXHAUSTED: + assert info == SUCCESS + assert 0 <= iterator.vector_iterator_getp(it) < pmax + entries.append((iterator.vector_iterator_get_index(it), iterator.iterator_get_fp64(it))) + info = iterator.vector_iterator_next(it) + assert entries == expected + if sparsity == lib.GxB_BITMAP: + # Position 2 has no entry, so seeking it finds the one at 4 + assert iterator.vector_iterator_seek(it, 2) == SUCCESS + assert iterator.vector_iterator_getp(it) == 4 + assert iterator.vector_iterator_get_index(it) == 4 + else: + assert iterator.vector_iterator_seek(it, 1) == SUCCESS + assert iterator.vector_iterator_getp(it) == 1 + assert iterator.vector_iterator_seek(it, pmax) == EXHAUSTED + + +def test_vector_iterator_empty(): + v = vector.vector_new(lib.GrB_INT64, 3) + it = iterator.iterator_new() + assert iterator.vector_iterator_attach(it, v) == SUCCESS + assert iterator.vector_iterator_getpmax(it) == 0 + assert iterator.vector_iterator_seek(it, 0) == EXHAUSTED + + +_type_names = { + lib.GrB_BOOL: "bool", + lib.GrB_INT8: "int8", + lib.GrB_INT16: "int16", + lib.GrB_INT32: "int32", + lib.GrB_INT64: "int64", + lib.GrB_UINT8: "uint8", + lib.GrB_UINT16: "uint16", + lib.GrB_UINT32: "uint32", + lib.GrB_UINT64: "uint64", + lib.GrB_FP32: "fp32", + lib.GrB_FP64: "fp64", +} +if supports_complex(): + _type_names[lib.GxB_FC32] = "fc32" + _type_names[lib.GxB_FC64] = "fc64" + + +def _extreme_values(T): + """Values of type T, including its limits, that its C type holds exactly.""" + name = _type_names[T] + if T in bool_types: + return [True, False] + if T in signed_integer_types: + bits = int(name[3:]) + return [-(2 ** (bits - 1)), -1, 2 ** (bits - 1) - 1] + if T in real_types: + return [-0.5, 2.0**100, 2.0**-20] + if T in complex_types: + return [complex(-0.5, 2.0), complex(2.0**100, -1.0), 2.0j] + bits = int(name[4:]) + return [0, 1, 2**bits - 1] + + +@pytest.mark.parametrize("T", sorted(grb_types, key=_type_names.get), ids=_type_names.get) +def test_iterator_get(T): + name = _type_names[T] + values = _extreme_values(T) + v = vector.vector_new(T, len(values)) + setter = getattr(vector, f"set_{name}") + for i, value in enumerate(values): + setter(v, value, i) + vector.vector_wait(v, lib.GrB_MATERIALIZE) + get = getattr(iterator, f"iterator_get_{name}") + it = iterator.iterator_new() + iterator.vector_iterator_attach(it, v) + got = [] + info = iterator.vector_iterator_seek(it, 0) + while info == SUCCESS: + got.append(get(it)) + info = iterator.vector_iterator_next(it) + assert got == values + assert all(type(x) is type(y) for x, y in zip(got, values, strict=True)) diff --git a/suitesparse_graphblas/tests/test_package.py b/suitesparse_graphblas/tests/test_package.py index 4fe0bb7..8d513aa 100644 --- a/suitesparse_graphblas/tests/test_package.py +++ b/suitesparse_graphblas/tests/test_package.py @@ -1,9 +1,27 @@ +import importlib +import os import sys import pytest import suitesparse_graphblas -from suitesparse_graphblas import ffi, lib +from suitesparse_graphblas import ( + bool_types, + check_status, + complex_types, + ffi, + grb_types, + integer_types, + lib, + libget, + matrix, + real_types, + signed_integer_types, + supports_complex, + unsigned_integer_types, + vararg, +) +from suitesparse_graphblas.api import grb_type def test_matrix_existence(): @@ -71,3 +89,94 @@ def test_version_tracks_libgraphblas(): pytest.skip(f"development build between releases: {version}") parts = tuple(int(x) for x in version.split(".")[:3]) assert parts == suitesparse_graphblas.libgraphblas_version + + +def test_libget(): + assert libget("GrB_INP0") == lib.GrB_INP0 + assert libget("GrB_FP64") == lib.GrB_FP64 + # A GrB_ name that GraphBLAS has only as GxB_ falls back to it + assert not hasattr(lib, "GrB_HYPER_SWITCH") + assert libget("GrB_HYPER_SWITCH") == lib.GxB_HYPER_SWITCH + assert not hasattr(lib, "GrB_FC64") + if supports_complex(): + assert libget("GrB_FC64") == lib.GxB_FC64 + # If neither exists, the error names what was asked for + with pytest.raises(AttributeError, match="GrB_NO_SUCH_NAME"): + libget("GrB_NO_SUCH_NAME") + + +def _type_names(types): + return {grb_type.grb_type_get_string(ffi.new("GrB_Type*", T), lib.GrB_NAME) for T in types} + + +def test_type_sets(): + assert _type_names(bool_types) == {"GrB_BOOL"} + assert _type_names(signed_integer_types) == {"GrB_INT8", "GrB_INT16", "GrB_INT32", "GrB_INT64"} + assert _type_names(unsigned_integer_types) == { + "GrB_UINT8", + "GrB_UINT16", + "GrB_UINT32", + "GrB_UINT64", + } + assert integer_types == signed_integer_types | unsigned_integer_types + assert _type_names(real_types) == {"GrB_FP32", "GrB_FP64"} + expected_complex = {"GxB_FC32", "GxB_FC64"} if supports_complex() else set() + assert _type_names(complex_types) == expected_complex + assert grb_types == bool_types | integer_types | real_types | complex_types + assert len(grb_types) == 11 + len(complex_types) + + +_complex_functions = { + "matrix": ["set", "get", "matrix_build", "matrix_extract_tuples"], + "vector": ["set", "get", "vector_build", "vector_extract_tuples"], + "scalar": ["set", "get"], + "monoid": ["monoid_new", "monoid_terminal_new"], + "iterator": ["iterator_get"], +} + + +@pytest.mark.parametrize("module", _complex_functions) +def test_complex_functions(module): + # The functional API has its fc32 and fc64 functions only when the build has complex types + mod = importlib.import_module(f"suitesparse_graphblas.api.{module}") + names = {name for name in vars(mod) if name.endswith(("_fc32", "_fc64"))} + expected = {f"{prefix}_{t}" for prefix in _complex_functions[module] for t in ["fc32", "fc64"]} + assert names == (expected if supports_complex() else set()) + + +# conda-forge's cffi links conda's libffi, and through it a variadic call on macOS arm64 loses +# its variadic arguments, with or without vararg: a double arrives as 0.0 and an int32 setting +# doesn't change (cffi 2.0.0, libffi 3.5.2). PyPI's cffi links the system libffi and works. +_conda_on_osx_arm64 = ( + sys.platform == "darwin" + and suitesparse_graphblas._is_osx_arm64 + and os.path.isdir(os.path.join(sys.prefix, "conda-meta")) +) + + +@pytest.mark.xfail( + _conda_on_osx_arm64, + reason="variadic calls lose their arguments with conda-forge's cffi on macOS arm64", +) +def test_vararg(): + # vararg makes a value safe to pass to a variadic GraphBLAS function on every + # platform: double, int32, and pointer (for the getters) + A = matrix.matrix_new(lib.GrB_FP64, 3, 3) + check_status( + A, + lib.GxB_Matrix_Option_set(A[0], lib.GxB_HYPER_SWITCH, vararg(ffi.cast("double", 0.375))), + ) + assert matrix.matrix_hyper_switch(A) == 0.375 + check_status( + A, + lib.GxB_Matrix_Option_set( + A[0], lib.GxB_SPARSITY_CONTROL, vararg(ffi.cast("int32_t", lib.GxB_BITMAP)) + ), + ) + assert matrix.matrix_sparsity_control(A) == lib.GxB_BITMAP + hyper_switch = ffi.new("double*") + check_status(A, lib.GxB_Matrix_Option_get(A[0], lib.GxB_HYPER_SWITCH, vararg(hyper_switch))) + assert hyper_switch[0] == 0.375 + sparsity = ffi.new("int32_t*") + check_status(A, lib.GxB_Matrix_Option_get(A[0], lib.GxB_SPARSITY_CONTROL, vararg(sparsity))) + assert sparsity[0] == lib.GxB_BITMAP diff --git a/suitesparse_graphblas/tests/test_scalar.py b/suitesparse_graphblas/tests/test_scalar.py index d413c29..f313dcb 100644 --- a/suitesparse_graphblas/tests/test_scalar.py +++ b/suitesparse_graphblas/tests/test_scalar.py @@ -1,6 +1,6 @@ import pytest -from suitesparse_graphblas import ffi, lib, supports_complex # noqa: F401 +from suitesparse_graphblas import ffi, lib, scalar, supports_complex @pytest.mark.skipif("not supports_complex()") @@ -10,3 +10,96 @@ def test_complex(): assert lib.GrB_Scalar_new(s, lib.GxB_FC64) == success assert lib.GxB_Scalar_setElement_FC64(s[0], 1j) == success assert lib.GrB_Scalar_free(s) == success + + +_type_names = { + lib.GrB_BOOL: "bool", + lib.GrB_INT8: "int8", + lib.GrB_INT16: "int16", + lib.GrB_INT32: "int32", + lib.GrB_INT64: "int64", + lib.GrB_UINT8: "uint8", + lib.GrB_UINT16: "uint16", + lib.GrB_UINT32: "uint32", + lib.GrB_UINT64: "uint64", + lib.GrB_FP32: "fp32", + lib.GrB_FP64: "fp64", +} +if supports_complex(): + _type_names[lib.GxB_FC32] = "fc32" + _type_names[lib.GxB_FC64] = "fc64" + + +def _values(name): + """Values for a scalar of type `name`, including its limits, that it holds exactly.""" + if name == "bool": + return [True, False] + if name.startswith("int"): + bits = int(name[3:]) + return [-(2 ** (bits - 1)), -1, 2 ** (bits - 1) - 1] + if name.startswith("uint"): + bits = int(name[4:]) + return [0, 1, 2**bits - 1] + if name.startswith("fp"): + return [-0.5, 2.0**100, 2.0**-20] + return [complex(-0.5, 2.0), complex(2.0**100, -1.0), 2.0j] + + +@pytest.mark.parametrize("T", sorted(_type_names, key=_type_names.get), ids=_type_names.get) +def test_set_get(T): + name = _type_names[T] + set_value = getattr(scalar, f"set_{name}") + get_value = getattr(scalar, f"get_{name}") + s = scalar.scalar_new(T) + assert scalar.scalar_type(s) == T + assert get_value(s) is None # no value yet + for value in _values(name): + set_value(s, value) + got = get_value(s) + assert got == value + assert type(got) is type(value) + + t = scalar.scalar_dup(s) + assert scalar.scalar_type(t) == T + scalar.scalar_clear(s) + assert get_value(s) is None + assert get_value(t) == value # the duplicate has its own value + + +def test_free(): + # With free=None, the caller frees the scalar + s = scalar.scalar_new(lib.GrB_INT64, free=None) + scalar.set_int64(s, 3) + t = scalar.scalar_dup(s, free=None) + assert scalar.get_int64(t) == 3 + scalar.scalar_free(s) + scalar.scalar_free(t) + assert s[0] == ffi.NULL + assert t[0] == ffi.NULL + + # Otherwise `free` is called with it once it is released + freed = [] + + def free(s): + freed.append(scalar.get_int64(s)) + scalar.scalar_free(s) + + s = scalar.scalar_new(lib.GrB_INT64, free=free) + scalar.set_int64(s, 4) + t = scalar.scalar_dup(s, free=free) + scalar.set_int64(t, 5) + assert freed == [] + ffi.release(s) + ffi.release(t) + assert freed == [4, 5] + + +def test_get_casts(): + # A getter of another type casts the value, as C does + s = scalar.scalar_new(lib.GrB_INT32) + scalar.set_int32(s, -7) + assert scalar.get_fp64(s) == -7.0 + assert scalar.get_int8(s) == -7 + assert scalar.get_bool(s) is True + scalar.set_fp64(s, 2.75) + assert scalar.get_int32(s) == 2