Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
47 commits
Select commit Hold shift + click to select a range
2cf8a2d
Size string buffers from get_SIZE in the operator and monoid get_string
eriknw Nov 25, 2026
59b98ca
Size monoid identity and terminal buffers from the monoid's type
eriknw Nov 25, 2026
b5b033a
Test user-defined operators and select operator errors
eriknw Nov 25, 2026
eb4cbc9
Test every typed monoid constructor
eriknw Nov 25, 2026
f812c33
Test building and extracting matrices and vectors of each type
eriknw Nov 25, 2026
d8812d2
Mark the complex-type checks in matrix, vector and monoid as no branch
eriknw Nov 25, 2026
60d5370
Test binwrite/binread round trips of empty, sparse and iso matrices
eriknw Nov 25, 2026
6401beb
binwrite: restore the matrix's sparsity control and switches
eriknw Nov 25, 2026
cab3099
binwrite: repack the matrix when making the header fails
eriknw Nov 25, 2026
46c0298
binread: raise EOFError when the header is truncated
eriknw Nov 25, 2026
8004498
Test binread's errors for an unknown format or sparsity
eriknw Nov 25, 2026
8f3028f
Exclude binwrite's unreachable branches from coverage
eriknw Nov 25, 2026
aacf0ee
Test that long binwrite comments leave a readable file (xfail)
eriknw Nov 25, 2026
864d426
Test serialize's compression options, free argument and nthreads
eriknw Nov 25, 2026
eca077f
iterator: describe kount, kseek and the return codes correctly
eriknw Nov 25, 2026
9cb7314
Test the iterator API
eriknw Nov 25, 2026
df5b39a
Test the scalar getters and setters of every type
eriknw Nov 25, 2026
ba87f68
check_status: raise GraphBLASException for codes it has no class for
eriknw Nov 25, 2026
b5f6adb
Size string buffers from get_SIZE in global_get_string, grb_type_get_…
eriknw Nov 25, 2026
99f49b9
burble.is_enabled: return a bool, as documented
eriknw Nov 25, 2026
c8568d8
burble: fix the context-manager example and close the error messages
eriknw Nov 25, 2026
15092a5
Test the global option getters and setters
eriknw Nov 25, 2026
642ddc3
Test libget, vararg, the type sets and the burble context manager
eriknw Nov 25, 2026
a172277
test_initialize: check calls before initialize, and the "c" allocator
eriknw Nov 25, 2026
29bada9
Test contexts, containers, descriptors, types and semirings
eriknw Nov 25, 2026
5bd9a46
Test the BFS example against a reference BFS
eriknw Nov 25, 2026
2b0cf6c
test_io: really write and read full matrices in the binfile test
eriknw Nov 25, 2026
1e130df
_capture_c_output: restore stdout if the call raises, and close fds
eriknw Nov 25, 2026
f334c88
test_io: check the sparsity control again in the binfile round trip
eriknw Nov 25, 2026
a50ada2
Size string buffers from get_SIZE in descriptor and semiring get_string
eriknw Nov 25, 2026
fdacccf
_capture_c_output: return "" for no output on Pyodide
eriknw Nov 25, 2026
317dc02
_capture_c_output: close the pipe if redirecting stdout fails
eriknw Nov 25, 2026
07b8614
global_get_string: name the call that failed
eriknw Nov 25, 2026
b026b0a
burble: raise GraphBLASException for codes it has no class for
eriknw Nov 25, 2026
c4f6151
test_api_objects: say what GrB_Descriptor_get_String returns for othe…
eriknw Nov 25, 2026
28564de
test_vararg: expect failure with conda-forge's cffi on macOS arm64
eriknw Nov 25, 2026
0c560f0
Mark the complex-type checks in scalar and iterator as no branch
eriknw Nov 25, 2026
db43846
Add AlreadySet, GpuError and OutputIsReadonly exceptions
eriknw Nov 26, 2026
a9bec7e
Test that every object type with an error function is in check_status…
eriknw Nov 26, 2026
748fd38
Add SUITESPARSE_GRAPHBLAS_NO_COMPLEX to build without complex types
eriknw Nov 26, 2026
25790e9
binary: import without complex types
eriknw Nov 26, 2026
b47edf3
test_libget: check the GrB_FC64 fallback only with complex types
eriknw Nov 26, 2026
c7f66a6
Test that the complex functions exist only with complex types
eriknw Nov 26, 2026
8c6bcc4
CI: test a build without complex types
eriknw Nov 26, 2026
b9c8d23
Measure both branches of the complex-type checks
eriknw Nov 26, 2026
73575d3
Add completeness guards derived from GraphBLAS's own declarations
eriknw Nov 26, 2026
cc4854c
binwrite: refuse comments that make the header too long
eriknw Nov 26, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 }}
Expand Down Expand Up @@ -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 }}
Expand Down
7 changes: 6 additions & 1 deletion build_graphblas_cffi.py
Original file line number Diff line number Diff line change
Expand Up @@ -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=()):
Expand Down
28 changes: 17 additions & 11 deletions suitesparse_graphblas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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})"
)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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 ]

Expand All @@ -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):
Expand Down
5 changes: 4 additions & 1 deletion suitesparse_graphblas/api/binaryop.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
2 changes: 1 addition & 1 deletion suitesparse_graphblas/api/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
)
Expand Down
5 changes: 4 additions & 1 deletion suitesparse_graphblas/api/descriptor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
14 changes: 9 additions & 5 deletions suitesparse_graphblas/api/global_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()


Expand Down
5 changes: 4 additions & 1 deletion suitesparse_graphblas/api/grb_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
5 changes: 4 additions & 1 deletion suitesparse_graphblas/api/indexbinaryop.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
5 changes: 4 additions & 1 deletion suitesparse_graphblas/api/indexunaryop.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
70 changes: 46 additions & 24 deletions suitesparse_graphblas/api/io/binary.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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 = {
Expand All @@ -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()}


Expand All @@ -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)
Expand Down Expand Up @@ -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 = (
Expand All @@ -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)
Expand Down Expand Up @@ -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``.
Expand All @@ -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")))
Expand Down
Loading
Loading