API Reference#

Collections#

Matrix#

class graphblas.Matrix(dtype=FP64, nrows=0, ncols=0, *, name=None)#

Create a new GraphBLAS Sparse Matrix.

Parameters
dtype

Data type for elements in the Matrix.

nrowsint

Number of rows.

ncolsint

Number of columns.

namestr, optional

Name to give the Matrix. This will be displayed in the __repr__.

__contains__(index)#

Indicates whether the (row, col) index has a value present.

Examples

(10, 15) in M
__delitem__(keys)#

Delete a single element, row/column, or submatrix.

Examples

>>> del M[1, 5]
__getitem__(keys)#

Extract a single element, row/column, or submatrix.

See the Extract section in the User Guide for more details.

Examples

subM = M[[1, 3, 5], :].new()
__iter__()#

Iterate over (row, col) indices which are present in the matrix.

__setitem__(keys, expr)#

Assign values to a single element, row/column, or submatrix.

See the Assign section in the User Guide for more details.

Examples

M[0, 0:3] = 17
apply(op, right=None, *, left=None)#

Create a new Matrix by applying op to each element of the Matrix.

See the Apply section in the User Guide for more details.

Common usage is to pass a UnaryOp, in which case right and left may not be defined.

A BinaryOp can also be used, in which case a scalar must be passed as left or right.

An IndexUnaryOp can also be used with the thunk passed in as right.

Parameters
opUnaryOp or BinaryOp or IndexUnaryOp

Operator to apply

right

Scalar used with BinaryOp or IndexUnaryOp

left

Scalar used with BinaryOp

Returns
Matrix

Examples

# Method syntax
C << A.apply(op.abs)

# Functional syntax
C << op.abs(A)
build(rows, columns, values, *, dup_op=None, clear=False, nrows=None, ncols=None)#

Rarely used method to insert values into an existing Matrix.

The typical use case is to create a new Matrix and insert values at the same time using from_coo().

All the arguments are used identically in from_coo(), except for clear, which indicates whether to clear the Matrix prior to adding the new values.

clear()#

In-place operation which clears all values in the Matrix.

After the call, nvals will return 0. The shape will not change.

diag(k=0, dtype=None, *, name=None)#

Return a Vector built from the diagonal values of the Matrix.

Parameters
kint

Off-diagonal offset.

dtype

Data type of the new Vector. Normal typecasting rules apply.

namestr, optional

Name to give the new Vector.

Returns
Vector
dup(dtype=None, *, clear=False, mask=None, name=None)#

Create a duplicate of the Matrix.

This is a full copy, not a view on the original.

Parameters
dtype

Data type of the new Matrix. Normal typecasting rules apply.

clearbool, default=False

If True, the returned Matrix will be empty.

maskMask, optional

Mask controlling which elements of the original to include in the copy.

namestr, optional

Name to give the Matrix.

Returns
Matrix
ewise_add(other, op=monoid.plus, *, require_monoid=None)#

Perform element-wise computation on the union of sparse values, similar to how one expects addition to work for sparse matrices.

See the Element-wise Union section in the User Guide for more details, especially about the difference between ewise_add and ewise_union().

Parameters
otherMatrix

The other matrix in the computation

opMonoid or BinaryOp

Operator to use on intersecting values

require_monoiddeprecated
Returns
Matrix with a structure formed as the union of the input structures

Examples

# Method syntax
C << A.ewise_add(B, op=monoid.max)

# Functional syntax
C << monoid.max(A | B)
ewise_mult(other, op=binary.times)#

Perform element-wise computation on the intersection of sparse values, similar to how one expects multiplication to work for sparse matrices.

See the Element-wise Intersection section in the User Guide for more details.

Parameters
otherMatrix

The other matrix in the computation

opMonoid or BinaryOp

Operator to use on intersecting values

Returns
Matrix with a structure formed as the intersection of the input structures

Examples

# Method syntax
C << A.ewise_mult(B, op=binary.gt)

# Functional syntax
C << binary.gt(A & B)
ewise_union(other, op, left_default, right_default)#

Perform element-wise computation on the union of sparse values, similar to how one expects subtraction to work for sparse matrices.

See the Element-wise Union section in the User Guide for more details, especially about the difference between ewise_union and ewise_add().

Parameters
otherMatrix

The other matrix in the computation

opMonoid or BinaryOp

Operator to use

left_default

Scalar value to use when the index on the left is missing

right_default

Scalar value to use when the index on the right is missing

Returns
Matrix with a structure formed as the union of the input structures

Examples

# Method syntax
C << A.ewise_union(B, op=binary.div, left_default=1, right_default=1)

# Functional syntax
C << binary.div(A | B, left_default=1, right_default=1)
classmethod from_coo(rows, columns, values, dtype=None, *, nrows=None, ncols=None, dup_op=None, name=None)#

Create a new Matrix from row and column indices and values.

Parameters
rowslist or np.ndarray

Row indices.

columnslist or np.ndarray

Column indices.

valueslist or np.ndarray or scalar

List of values. If a scalar is provided, all values will be set to this single value.

dtype

Data type of the Matrix. If not provided, the values will be inspected to choose an appropriate dtype.

nrowsint, optional

Number of rows in the Matrix. If not provided, nrows is computed from the maximum row index found in rows.

ncolsint, optional

Number of columns in the Matrix. If not provided, ncols is computed from the maximum column index found in columns.

dup_opBinaryOp, optional

Function used to combine values if duplicate indices are found. Leaving dup_op=None will raise an error if duplicates are found.

namestr, optional

Name to give the Matrix.

Returns
Matrix
classmethod from_csc(indptr, row_indices, values, dtype=None, *, nrows=None, ncols=None, name=None)#

Create a new Matrix from standard CSC representation of data.

In CSC, the row indices for column i are stored in row_indices[indptr[i]:indptr[i+1]] and the values are stored in values[indptr[i]:indptr[i+1]]. The number of columns is inferred as ncols = len(indptr) - 1.

This always copies data. For zero-copy import with move semantics, see Matrix.ss.import_csc

Parameters
indptrlist or np.ndarray

Pointers for each column into row_indices and values; indptr.size == ncols + 1.

col_indiceslist or np.ndarray

Column indices.

valueslist or np.ndarray or scalar

List of values. If a scalar is provided, all values will be set to this single value.

dtype

Data type of the Matrix. If not provided, the values will be inspected to choose an appropriate dtype.

nrowsint, optional

Number of rows in the Matrix. If not provided, ncols is computed from the maximum row index found in row_indices.

ncolsint, optional

Number of columns in the Matrix. ncols is computed as len(indptr) - 1. If provided, it must equal len(indptr) - 1.

namestr, optional

Name to give the Matrix.

Returns
Matrix

See also

from_coo
from_csr
from_dcsc
Matrix.ss.import_csc
io.from_scipy_sparse
classmethod from_csr(indptr, col_indices, values, dtype=None, *, nrows=None, ncols=None, name=None)#

Create a new Matrix from standard CSR representation of data.

In CSR, the column indices for row i are stored in col_indices[indptr[i]:indptr[i+1]] and the values are stored in values[indptr[i]:indptr[i+1]]. The number of rows is inferred as nrows = len(indptr) - 1.

This always copies data. For zero-copy import with move semantics, see Matrix.ss.import_csr

Parameters
indptrlist or np.ndarray

Pointers for each row into col_indices and values; indptr.size == nrows + 1.

col_indiceslist or np.ndarray

Column indices.

valueslist or np.ndarray or scalar

List of values. If a scalar is provided, all values will be set to this single value.

dtype

Data type of the Matrix. If not provided, the values will be inspected to choose an appropriate dtype.

nrowsint, optional

Number of rows in the Matrix. nrows is computed as len(indptr) - 1. If provided, it must equal len(indptr) - 1.

ncolsint, optional

Number of columns in the Matrix. If not provided, ncols is computed from the maximum column index found in col_indices.

namestr, optional

Name to give the Matrix.

Returns
Matrix

See also

from_coo
from_csc
from_dcsr
Matrix.ss.import_csr
io.from_scipy_sparse
classmethod from_dcsc(compressed_cols, indptr, row_indices, values, dtype=None, *, nrows=None, ncols=None, name=None)#

Create a new Matrix from DCSC (a.k.a. HyperCSC) representation of data.

In DCSC, we store the index of each non-empty column in compressed_cols. The row indices for column compressed_cols[i] are stored in col_indices[indptr[compressed_cols[i]]:indptr[compressed_cols[i]+1]] and the values are stored in values[indptr[compressed_cols[i]]:indptr[compressed_cols[i]+1]].

This always copies data. For zero-copy import with move semantics, see Matrix.ss.import_hypercsc.

Parameters
compressed_colslist or np.ndarray

Indices of non-empty columns; unique and sorted.

indptrlist or np.ndarray

Pointers for each non-empty columns into row_indices and values.

row_indiceslist or np.ndarray

Row indices.

valueslist or np.ndarray or scalar

List of values. If a scalar is provided, all values will be set to this single value.

dtype

Data type of the Matrix. If not provided, the values will be inspected to choose an appropriate dtype.

nrowsint, optional

Number of rows in the Matrix. If not provided, nrows is computed from the maximum row index found in row_indices.

ncolsint, optional

Number of columns in the Matrix. If not provided, ncols is computed from the maximum column index found in compressed_cols.

namestr, optional

Name to give the Matrix.

Returns
Matrix

See also

from_coo
from_csc
from_dcsr
Matrix.ss.import_hypercsc
io.from_scipy_sparse
classmethod from_dcsr(compressed_rows, indptr, col_indices, values, dtype=None, *, nrows=None, ncols=None, name=None)#

Create a new Matrix from DCSR (a.k.a. HyperCSR) representation of data.

In DCSR, we store the index of each non-empty row in compressed_rows. The column indices for row compressed_rows[i] are stored in col_indices[indptr[compressed_row[i]]:indptr[compressed_row[i]+1]] and the values are stored in values[indptr[compressed_row[i]]:indptr[compressed_row[i]+1]].

This always copies data. For zero-copy import with move semantics, see Matrix.ss.import_hypercsr.

Parameters
compressed_rowslist or np.ndarray

Indices of non-empty rows; unique and sorted.

indptrlist or np.ndarray

Pointers for each non-empty row into col_indices and values.

col_indiceslist or np.ndarray

Column indices.

valueslist or np.ndarray or scalar

List of values. If a scalar is provided, all values will be set to this single value.

dtype

Data type of the Matrix. If not provided, the values will be inspected to choose an appropriate dtype.

nrowsint, optional

Number of rows in the Matrix. If not provided, nrows is computed from the maximum row index found in compressed_rows.

ncolsint, optional

Number of columns in the Matrix. If not provided, ncols is computed from the maximum column index found in col_indices.

namestr, optional

Name to give the Matrix.

Returns
Matrix

See also

from_coo
from_csr
from_dcsc
Matrix.ss.import_hypercsr
io.from_scipy_sparse
classmethod from_dicts(nested_dicts, dtype=None, *, order='rowwise', nrows=None, ncols=None, name=None)#

Create a new Matrix from a dict of dicts or list of dicts

A dict of dicts is of the form {row: {col: val}} if order is “rowwise” and of the form {col: {row: val}} if order is “columnwise”.

A list of dicts is of the form [{col: val}, {col: val}, ...] for “rowwise” order where the i’th element of the list is a dict of column and values for row i.

Parameters
dMapping or Sequence

The dict-like object to convert. The keys will be cast to uint64 for the indices.

dtype

Data type of the Matrix. If not provided, the values will be inspected to choose an appropriate dtype.

order{“rowwise”, “columnwise”}, optional

“rowwise” interprets the input dict of dicts as {row: {col: val}} and input list of dicts as [{col: val}, {col: val}]. “columnwise” interprets the input dict of dicts as {col: {row: val}} and input list of dicts as [{row: val}, {row: val}]. The default is “rowwise”.

nrowsint, optional

Number of rows in the Matrix. If not provided, nrows is computed for dict of dicts from the maximum row index found in the dicts, and for list of dicts as the length of the list.

ncolsint, optional

Number of columns in the Matrix. If not provided, ncols is computed from the maximum column index found in the dicts.

namestr, optional

Name to give the Matrix.

Returns
Matrix
classmethod from_pygraphblas(matrix)#

Convert a pygraphblas.Matrix to a new Matrix without copying data.

This gives control of the underlying GraphBLAS memory to python-graphblas, meaning further operations on the original pygraphblas matrix object will fail!

This method requires the pygraphblas library to be installed.

classmethod from_values(rows, columns, values, dtype=None, *, nrows=None, ncols=None, dup_op=None, name=None)#

Create a new Matrix from row and column indices and values.

Deprecated since version 2022.11.0: Matrix.from_values will be removed in a future release. Use Matrix.from_coo instead. Will be removed in version 2023.9.0 or later

Parameters
rowslist or np.ndarray

Row indices.

columnslist or np.ndarray

Column indices.

valueslist or np.ndarray or scalar

List of values. If a scalar is provided, all values will be set to this single value.

dtype

Data type of the Matrix. If not provided, the values will be inspected to choose an appropriate dtype.

nrowsint, optional

Number of rows in the Matrix. If not provided, nrows is computed from the maximum row index found in rows.

ncolsint, optional

Number of columns in the Matrix. If not provided, ncols is computed from the maximum column index found in columns.

dup_opBinaryOp, optional

Function used to combine values if duplicate indices are found. Leaving dup_op=None will raise an error if duplicates are found.

namestr, optional

Name to give the Matrix.

Returns
Matrix
get(row, col, default=None)#

Get an element at (row, col) indices as a Python scalar.

Parameters
rowint

Row index

colint

Column index

default

Value returned if no element exists at (row, col)

Returns
Python scalar
isclose(other, *, rel_tol=1e-07, abs_tol=0.0, check_dtype=False)#

Check for approximate equality (including same size and same structure).

Equivalent to: abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol).

Parameters
otherMatrix

The matrix to compare against.

rel_tolfloat

Relative tolerance.

abs_tolfloat

Absolute tolerance.

check_dtypebool

If True, also checks that dtypes match

Returns
bool

Whether all values of the Matrix are close to the values in other.

isequal(other, *, check_dtype=False)#

Check for exact equality (same size, same structure).

Parameters
otherMatrix

The matrix to compare against

check_dtypesbool

If True, also checks that dtypes match

Returns
bool

See also

isclose()

For equality check of floating point dtypes

kronecker(other, op=binary.times)#

Compute the kronecker product or sum (depending on the op).

See the Kronecker section in the User Guide for more details.

Parameters
otherMatrix

The matrix on the right side in the computation

opBinaryOp

Operator used on the combination of elements

Returns
Matrix

Examples

C << A.kronecker(B, op=binary.times)
mxm(other, op=semiring.plus_times)#

Perform matrix-matrix multiplication.

See the Matrix Multiply section in the User Guide for more details.

Parameters
otherMatrix

The matrix on the right side in the computation

opSemiring

Semiring used in the computation

Returns
Matrix

Examples

# Method syntax
C << A.mxm(B, op=semiring.min_plus)

# Functional syntax
C << semiring.min_plus(A @ B)
mxv(other, op=semiring.plus_times)#

Perform matrix-vector multiplication.

See the Matrix Multiply section in the User Guide for more details.

Parameters
otherVector

The vector, treated as an (nx1) column matrix

opSemiring

Semiring used in the computation

Returns
Vector

Examples

# Method syntax
C << A.mxv(v, op=semiring.min_plus)

# Functional syntax
C << semiring.min_plus(A @ v)
reduce_columnwise(op=monoid.plus)#

Create a new Vector by reducing values per-column in the Matrix using op.

See the Reduce section in the User Guide for more details.

Parameters
opMonoid

Reduction operator

Returns
Vector

Examples

w << A.reduce_columnwise(monoid.plus)
reduce_rowwise(op=monoid.plus)#

Create a new Vector by reducing values per-row in the Matrix using op.

See the Reduce section in the User Guide for more details.

Parameters
opMonoid

Reduction operator

Returns
Vector

Examples

w << A.reduce_rowwise(monoid.plus)
reduce_scalar(op=monoid.plus, *, allow_empty=True)#

Reduce all values in the Matrix into a single value using op.

See the Reduce section in the User Guide for more details.

Parameters
opMonoid

Reduction operator

allow_emptybool, default=True

If False and the Matrix is empty, the Scalar result will hold the monoid identity rather than a missing value

Returns
Scalar

Examples

total << A.reduce_scalar(monoid.plus)
reposition(row_offset, column_offset, *, nrows=None, ncols=None)#

Create a new Matrix with values identical to the original Matrix, but repositioned within the (nrows x ncols) space by adding offsets to the indices.

Positive offset moves values to the right (or down), negative to the left (or up). Values repositioned outside of the new Matrix are dropped (i.e. they don’t wrap around).

Note: This is not a standard GraphBLAS method. It is implemented using extract and assign.

Parameters
row_offsetint

Offset for the row indices.

column_offsetint

Offset for the column indices.

nrowsint, optional

If specified, the new Matrix will be sized with nrows. Default is the same number of rows as the original Matrix.

ncolsint, optional

If specified, the new Matrix will be sized with ncols. Default is the same number of columns as the original Matrix.

Returns
Matrix

Examples

C = A.reposition(1, 2).new()
resize(nrows, ncols)#

In-place operation which changes the shape.

Increasing nrows or ncols will expand with empty values.
Decreasing nrows or ncols will drop existing values above the new indices.
select(op, thunk=None)#

Create a new Matrix by applying op to each element of the Matrix and keeping those elements where op returns True.

See the Select section in the User Guide for more details.

Parameters
op:class:`~graphblas.core.operator.SelectOp`or

IndexUnaryOp

Operator to apply

thunk

Scalar passed to operator

Returns
Matrix

Examples

# Method syntax
C << A.select(">=", 1)

# Functional syntax
C << select.value(A >= 1)
to_coo(dtype=None, *, rows=True, columns=True, values=True, sort=True)#

Extract the indices and values as a 3-tuple of numpy arrays corresponding to the COO format of the Matrix.

Parameters
dtype

Requested dtype for the output values array.

rowsbool, default=True

Whether to return rows; will return None for rows if False

columns :bool, default=True

Whether to return columns; will return None for columns if False

valuesbool, default=True

Whether to return values; will return None for values if False

sortbool, default=True

Whether to require sorted indices. If internally stored rowwise, the sorting will be first by rows, then by column. If internally stored columnwise, the sorting will be first by column, then by row.

Returns
np.ndarray[dtype=uint64]Rows
np.ndarray[dtype=uint64]Columns
np.ndarrayValues
to_csc(dtype=None)#

Returns three arrays of the standard CSC representation: indptr, row_indices, values

In CSC, the row indices for column i are stored in row_indices[indptr[i]:indptr[i+1]] and the values are stored in values[indptr[i]:indptr[i+1]].

This copies data and leaves the Matrix unmodified. For zero-copy move semantics, see Matrix.ss.export.

Returns
np.ndarray[dtype=uint64]indptr
np.ndarray[dtype=uint64]row_indices
np.ndarrayvalues

See also

to_coo
to_csr
to_dcsc
Matrix.ss.export
io.to_scipy_sparse
to_csr(dtype=None)#

Returns three arrays of the standard CSR representation: indptr, col_indices, values

In CSR, the column indices for row i are stored in col_indices[indptr[i]:indptr[i+1]] and the values are stored in values[indptr[i]:indptr[i+1]].

This copies data and leaves the Matrix unmodified. For zero-copy move semantics, see Matrix.ss.export.

Returns
np.ndarray[dtype=uint64]indptr
np.ndarray[dtype=uint64]col_indices
np.ndarrayvalues

See also

to_coo
to_csc
to_dcsr
Matrix.ss.export
io.to_scipy_sparse
to_dcsc(dtype=None)#

Returns four arrays of DCSC representation: compressed_cols, indptr, row_indices, values

In DCSC, we store the index of each non-empty column in compressed_cols. The row indices for column compressed_cols[i] are stored in col_indices[indptr[compressed_cols[i]]:indptr[compressed_cols[i]+1]] and the values are stored in values[indptr[compressed_cols[i]]:indptr[compressed_cols[i]+1]].

This copies data and leaves the Matrix unmodified. For zero-copy move semantics, see Matrix.ss.export.

Returns
np.ndarray[dtype=uint64]compressed_cols
np.ndarray[dtype=uint64]indptr
np.ndarray[dtype=uint64]row_indices
np.ndarrayvalues

See also

to_coo
to_csc
to_dcsr
Matrix.ss.export
io.to_scipy_sparse
to_dcsr(dtype=None)#

Returns four arrays of DCSR representation: compressed_rows, indptr, col_indices, values

In DCSR, we store the index of each non-empty row in compressed_rows. The column indices for row compressed_rows[i] are stored in col_indices[indptr[compressed_row[i]]:indptr[compressed_row[i]+1]] and the values are stored in values[indptr[compressed_row[i]]:indptr[compressed_row[i]+1]].

This copies data and leaves the Matrix unmodified. For zero-copy move semantics, see Matrix.ss.export.

Returns
np.ndarray[dtype=uint64]compressed_rows
np.ndarray[dtype=uint64]indptr
np.ndarray[dtype=uint64]col_indices
np.ndarrayvalues

See also

to_coo
to_csr
to_dcsc
Matrix.ss.export
io.to_scipy_sparse
to_dicts(order='rowwise')#

Return Matrix as a dict of dicts in the form {row: {col: val}}

Parameters
order{“rowwise”, “columnwise”}, optional

“rowwise” returns dict of dicts as {row: {col: val}}. “columnwise” returns dict of dicts as {col: {row: val}}. The default is “rowwise”.

Returns
dict
to_pygraphblas()#

Convert to a pygraphblas.Matrix without copying data.

This gives control of the underlying GraphBLAS memory to pygraphblas, meaning further operations on the current Matrix object will fail!

This method requires the pygraphblas library to be installed.

to_values(dtype=None, *, rows=True, columns=True, values=True, sort=True)#

Extract the indices and values as a 3-tuple of numpy arrays corresponding to the COO format of the Matrix.

Deprecated since version 2022.11.0: Matrix.to_values will be removed in a future release. Use Matrix.to_coo instead. Will be removed in version 2023.9.0 or later

Parameters
dtype

Requested dtype for the output values array.

rowsbool, default=True

Whether to return rows; will return None for rows if False

columns :bool, default=True

Whether to return columns; will return None for columns if False

valuesbool, default=True

Whether to return values; will return None for values if False

sortbool, default=True

Whether to require sorted indices. If internally stored rowwise, the sorting will be first by rows, then by column. If internally stored columnwise, the sorting will be first by column, then by row.

Returns
np.ndarray[dtype=uint64]Rows
np.ndarray[dtype=uint64]Columns
np.ndarrayValues
wait(how='materialize')#

Wait for a computation to complete or establish a “happens-before” relation

Parameters
how{“materialize”, “complete”}

“materialize” fully computes an object. “complete” establishes a “happens-before” relation useful with multi-threading. See GraphBLAS documentation for more details.

In `non-blocking mode <../user_guide/init.html#graphblas-modes>`__,
the computations may be delayed and not yet safe to use by multiple threads.
Use wait to force completion of the Matrix.
Has no effect in `blocking mode <../user_guide/init.html#graphblas-modes>`__.
property S#

Create a Mask based on the structure of the Matrix.

property T#

Indicates the transpose of the Matrix.

Can be used in the arguments of most operations. It also can be used standalone as the Transpose operation.

property V#

Create a Mask based on the values in the Matrix (treating each value as truthy).

property ncols#

Number of columns in the Matrix.

property nrows#

Number of rows in the Matrix.

property nvals#

Number of non-empty values in the Matrix.

property shape#

A tuple of (nrows, ncols).

Vector#

class graphblas.Vector(dtype=FP64, size=0, *, name=None)#

Create a new GraphBLAS Sparse Vector.

Parameters
dtype

Data type for elements in the Vector.

sizeint

Size of the Vector.

namestr, optional

Name to give the Vector. This will be displayed in the __repr__.

__contains__(index)#

Indicates whether a value is present at the index.

Examples

# Check if v[15] is non-empty
15 in v
__delitem__(keys)#

Delete a single element or subvector.

Examples

>>> del v[1:-1]
__getitem__(keys)#

Extract a single element or subvector.

See the Extract section in the User Guide for more details.

Examples

sub_v = v[[1, 3, 5]].new()
__iter__()#

Iterate over indices which are present in the vector.

__setitem__(keys, expr)#

Assign values to a single element or subvector.

See the Assign section in the User Guide for more details.

Examples

# This makes a dense iso-value vector
v[:] = 1
apply(op, right=None, *, left=None)#

Create a new Vector by applying op to each element of the Vector.

See the Apply section in the User Guide for more details.

Common usage is to pass a UnaryOp, in which case right and left may not be defined.

A BinaryOp can also be used, in which case a scalar must be passed as left or right.

An IndexUnaryOp can also be used with the thunk passed in as right.

Parameters
opUnaryOp or BinaryOp or IndexUnaryOp

Operator to apply

right

Scalar used with BinaryOp or IndexUnaryOp

left

Scalar used with BinaryOp

Returns
Vector

Examples

# Method syntax
w << v.apply(op.abs)

# Functional syntax
w << op.abs(v)
build(indices, values, *, dup_op=None, clear=False, size=None)#

Rarely used method to insert values into an existing Vector. The typical use case is to create a new Vector and insert values at the same time using from_coo().

All the arguments are used identically in from_coo(), except for clear, which indicates whether to clear the Vector prior to adding the new values.

clear()#

In-place operation which clears all values in the Vector.

After the call, nvals will return 0. The size will not change.

diag(k=0, *, name=None)#

Return a Matrix with values on the diagonal built from the Vector.

Parameters
kint

Off-diagonal offset in the Matrix.

dtype

Data type of the new Matrix. Normal typecasting rules apply.

namestr, optional

Name to give the new Matrix.

Returns
Matrix
dup(dtype=None, *, clear=False, mask=None, name=None)#

Create a duplicate of the Vector.

This is a full copy, not a view on the original.

Parameters
dtype

Data type of the new Vector. Normal typecasting rules apply.

clearbool, default=False

If True, the returned Vector will be empty.

maskMask, optional

Mask controlling which elements of the original to include in the copy.

namestr, optional

Name to give the Vector.

Returns
Vector
ewise_add(other, op=monoid.plus, *, require_monoid=None)#

Perform element-wise computation on the union of sparse values, similar to how one expects addition to work for sparse vectors.

See the Element-wise Union section in the User Guide for more details, especially about the difference between ewise_add and ewise_union().

Parameters
otherVector

The other vector in the computation

opMonoid or BinaryOp

Operator to use on intersecting values

require_monoiddeprecated
Returns
Vector with a structure formed as the union of the input structures

Examples

# Method syntax
w << u.ewise_add(v, op=monoid.max)

# Functional syntax
w << monoid.max(u | v)
ewise_mult(other, op=binary.times)#

Perform element-wise computation on the intersection of sparse values, similar to how one expects multiplication to work for sparse vectors.

See the Element-wise Intersection section in the User Guide for more details.

Parameters
otherVector

The other vector in the computation

opMonoid or BinaryOp

Operator to use on intersecting values

Returns
Vector with a structure formed as the intersection of the input structures

Examples

# Method syntax
w << u.ewise_mult(v, op=binary.gt)

# Functional syntax
w << binary.gt(u & v)
ewise_union(other, op, left_default, right_default)#

Perform element-wise computation on the union of sparse values, similar to how one expects subtraction to work for sparse matrices.

See the Element-wise Union section in the User Guide for more details, especially about the difference between ewise_union and ewise_add().

Parameters
otherVector

The other vector in the computation

opMonoid or BinaryOp

Operator to use

left_default

Scalar value to use when the index on the left is missing

right_default

Scalar value to use when the index on the right is missing

Returns
Vector with a structure formed as the union of the input structures

Examples

# Method syntax
w << u.ewise_union(v, op=binary.div, left_default=1, right_default=1)

# Functional syntax
w << binary.div(u | v, left_default=1, right_default=1)
classmethod from_coo(indices, values, dtype=None, *, size=None, dup_op=None, name=None)#

Create a new Vector from indices and values.

Parameters
indiceslist or np.ndarray

Vector indices.

valueslist or np.ndarray or scalar

List of values. If a scalar is provided, all values will be set to this single value.

dtype

Data type of the Vector. If not provided, the values will be inspected to choose an appropriate dtype.

sizeint, optional

Size of the Vector. If not provided, size is computed from the maximum index found in indices.

dup_opBinaryOp, optional

Function used to combine values if duplicate indices are found. Leaving dup_op=None will raise an error if duplicates are found.

namestr, optional

Name to give the Vector.

Returns
Vector
classmethod from_dict(d, dtype=None, *, size=None, name=None)#

Create a new Vector from a dict with keys as indices and values as values.

Parameters
dMapping

The dict-like object to convert. The keys will be cast to uint64 for the indices.

dtype

Data type of the Vector. If not provided, the values will be inspected to choose an appropriate dtype.

sizeint, optional

Size of the Vector. If not provided, size is computed from the maximum index found in indices.

namestr, optional

Name to give the Vector.

Returns
Vector
classmethod from_pygraphblas(vector)#

Convert a pygraphblas.Vector to a new Vector without copying data.

This gives control of the underlying GraphBLAS memory to python-graphblas, meaning further operations on the original pygraphblas vector object will fail!

This method requires the pygraphblas library to be installed.

classmethod from_values(indices, values, dtype=None, *, size=None, dup_op=None, name=None)#

Create a new Vector from indices and values.

Deprecated since version 2022.11.0: Vector.from_values will be removed in a future release. Use Vector.from_coo instead. Will be removed in version 2023.9.0 or later

Parameters
indiceslist or np.ndarray

Vector indices.

valueslist or np.ndarray or scalar

List of values. If a scalar is provided, all values will be set to this single value.

dtype

Data type of the Vector. If not provided, the values will be inspected to choose an appropriate dtype.

sizeint, optional

Size of the Vector. If not provided, size is computed from the maximum index found in indices.

dup_opBinaryOp, optional

Function used to combine values if duplicate indices are found. Leaving dup_op=None will raise an error if duplicates are found.

namestr, optional

Name to give the Vector.

Returns
Vector
get(index, default=None)#

Get an element at index as a Python scalar.

Parameters
indexint

Vector index

default

Value returned if no element exists at index

Returns
Python scalar
inner(other, op=semiring.plus_times)#

Perform vector-vector inner (or dot) product.

Parameters
otherVector

The vector on the right side in the computation

opSemiring

Semiring used in the computation

Returns
Scalar

Examples

# Method syntax
s << v.inner(w, op=semiring.min_plus)

# Functional syntax
s << semiring.min_plus(v @ w)

Note: This is not a standard GraphBLAS function, but fits with other functions in the Matrix Multiplication family of functions.

isclose(other, *, rel_tol=1e-07, abs_tol=0.0, check_dtype=False)#

Check for approximate equality (including same size and same structure).

Equivalent to: abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol).

Parameters
otherVector

Vector to compare against

rel_tolfloat

Relative tolerance

abs_tolfloat

Absolute tolerance

check_dtypebool

If True, also checks that dtypes match

Returns
bool
isequal(other, *, check_dtype=False)#

Check for exact equality (same size, same structure)

Parameters
otherVector

The vector to compare against

check_dtypesbool, default=False

If True, also checks that dtypes match

Returns
bool

See also

isclose()

For equality check of floating point dtypes

outer(other, op=binary.times)#

Perform vector-vector outer (or cross) product.

Parameters
otherVector

The vector on the right side in the computation

opBinaryOp

Operator used in the computation

Returns
Matrix

Examples

C << v.outer(w, op=binary.times)

Note: This is not a standard GraphBLAS function.

reduce(op=monoid.plus, *, allow_empty=True)#

Reduce all values in the Vector into a single value using op.

See the Reduce section in the User Guide for more details.

Parameters
opMonoid

Reduction operator

allow_emptybool, default=True

If False and the Vector is empty, the Scalar result will hold the monoid identity rather than a missing value

Returns
Scalar

Examples

total << v.reduce(monoid.plus)
reposition(offset, *, size=None)#

Create a new Vector with values identical to the original Vector, but repositioned within the total size by adding offset to the indices.

Positive offset moves values to the right, negative to the left. Values repositioned outside of the new Vector are dropped (i.e. they don’t wrap around).

Note: This is not a standard GraphBLAS method. It is implemented using extract and assign.

Parameters
offsetint

Offset for the indices.

sizeint, optional

If specified, the new Vector will be resized. Default is the same size as the original Vector.

Returns
Vector

Examples

w = v.reposition(20).new()
resize(size)#

In-place operation which changes the size.

Increasing size will expand with empty values.
Decreasing size will drop existing values above the new maximum index.
select(op, thunk=None)#

Create a new Vector by applying op to each element of the Vector and keeping those elements where op returns True.

See the Select section in the User Guide for more details.

Parameters
opSelectOp or

IndexUnaryOp

Operator to apply

thunk

Scalar passed to operator

Returns
Vector

Examples

# Method syntax
w << v.select(">=", 1)

# Functional syntax
w << select.value(v >= 1)
to_coo(dtype=None, *, indices=True, values=True, sort=True)#

Extract the indices and values as a 2-tuple of numpy arrays.

Parameters
dtype

Requested dtype for the output values array.

indices :bool, default=True

Whether to return indices; will return None for indices if False

valuesbool, default=True

Whether to return values; will return None for values if False

sortbool, default=True

Whether to require sorted indices.

Returns
np.ndarray[dtype=uint64]Indices
np.ndarrayValues
to_dict()#

Return Vector as a dict in the form {index: val}

Returns
dict
to_pygraphblas()#

Convert to a pygraphblas.Vector without copying data.

This gives control of the underlying GraphBLAS memory to pygraphblas, meaning further operations on the current Vector object will fail!

This method requires the pygraphblas library to be installed.

to_values(dtype=None, *, indices=True, values=True, sort=True)#

Extract the indices and values as a 2-tuple of numpy arrays.

Deprecated since version 2022.11.0: Vector.to_values will be removed in a future release. Use Vector.to_coo instead. Will be removed in version 2023.9.0 or later

Parameters
dtype

Requested dtype for the output values array.

indices :bool, default=True

Whether to return indices; will return None for indices if False

valuesbool, default=True

Whether to return values; will return None for values if False

sortbool, default=True

Whether to require sorted indices.

Returns
np.ndarray[dtype=uint64]Indices
np.ndarrayValues
vxm(other, op=semiring.plus_times)#

Perform vector-matrix multiplication with the Vector being treated as a (1xn) row vector on the left side of the computation.

See the Matrix Multiply section in the User Guide for more details.

Parameters
other: Matrix

The matrix on the right side in the computation

opSemiring

Semiring used in the computation

Returns
Vector

Examples

# Method syntax
C << v.vxm(A, op=semiring.min_plus)

# Functional syntax
C << semiring.min_plus(v @ A)
wait(how='materialize')#

Wait for a computation to complete or establish a “happens-before” relation

Parameters
how{“materialize”, “complete”}

“materialize” fully computes an object. “complete” establishes a “happens-before” relation useful with multi-threading. See GraphBLAS documentation for more details.

In `non-blocking mode <../user_guide/init.html#graphblas-modes>`__,
the computations may be delayed and not yet safe to use by multiple threads.
Use wait to force completion of the Vector.
Has no effect in `blocking mode <../user_guide/init.html#graphblas-modes>`__.
property S#

Create a Mask based on the structure of the Vector.

property V#

Create a Mask based on the values in the Vector (treating each value as truthy).

property nvals#

Number of non-empty values in the Vector.

property shape#

A tuple of (size,).

property size#

Size of the Vector.

Scalar#

class graphblas.Scalar(dtype=FP64, *, is_cscalar=False, name=None)#

Create a new GraphBLAS Sparse Scalar.

Parameters
dtype

Data type of the Scalar.

is_cscalarbool, default=False

If True, the empty state is managed on the Python side rather than with a proper GrB_Scalar object.

namestr, optional

Name to give the Scalar. This will be displayed in the __repr__.

__bool__()#

Truthiness check.

The scalar is considered truthy if it is non-empty and the value inside is truthy.

To only check if a value is present, use is_empty.

__eq__(other)#

Check equality.

Equality comparison uses isequal(). Use that directly for finer control of what is considered equal.

clear()#

In-place operation which clears the value in the Scalar.

After the call, nvals will return 0.

dup(dtype=None, *, clear=False, is_cscalar=None, name=None)#

Create a duplicate of the Scalar.

This is a full copy, not a view on the original.

Parameters
dtype

Data type of the new Scalar. Normal typecasting rules apply.

clearbool, default=False

If True, the returned Scalar will be empty.

is_cscalarbool

If True, the empty state is managed on the Python side rather than with a proper GrB_Scalar object.

namestr, optional

Name to give the Scalar.

Returns
Scalar
classmethod from_pygraphblas(scalar)#

Convert a pygraphblas.Scalar to a new Scalar by making a copy of the internal value.

This method requires the pygraphblas library to be installed.

classmethod from_value(value, dtype=None, *, is_cscalar=False, name=None)#

Create a new Scalar from a value.

Parameters
valuePython scalar

Internal value of the Scalar.

dtype

Data type of the Scalar. If not provided, the value will be inspected to choose an appropriate dtype.

is_cscalarbool, default=False

If True, the empty state is managed on the Python side rather than with a proper GrB_Scalar object.

namestr, optional

Name to give the Scalar.

Returns
Scalar
get(default=None)#

Get the internal value of the Scalar as a Python scalar.

Parameters
default

Value returned if internal value is missing.

Returns
Python scalar
isclose(other, *, rel_tol=1e-07, abs_tol=0.0, check_dtype=False)#

Check for approximate equality (including whether the value is missing).

Equivalent to: abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol).

Parameters
otherScalar

Scalar to compare against

rel_tolfloat

Relative tolerance

abs_tolfloat

Absolute tolerance

check_dtypebool

If True, also checks that dtypes match

Returns
bool
isequal(other, *, check_dtype=False)#

Check for exact equality (including whether the value is missing).

Parameters
otherScalar

Scalar to compare against

check_dtypesbool, default=False

If True, also checks that dtypes match

Returns
Bool

See also

isclose()

For equality check of floating point dtypes

to_pygraphblas()#

Convert to a pygraphblas.Scalar by making a copy of the internal value.

This method requires the pygraphblas library to be installed.

wait(how='materialize')#

Wait for a computation to complete or establish a “happens-before” relation

Parameters
how{“materialize”, “complete”}

“materialize” fully computes an object. “complete” establishes a “happens-before” relation useful with multi-threading. See GraphBLAS documentation for more details.

In `non-blocking mode <../user_guide/init.html#graphblas-modes>`__,
the computations may be delayed and not yet safe to use by multiple threads.
Use wait to force completion of the Scalar.
Has no effect in `blocking mode <../user_guide/init.html#graphblas-modes>`__.
property is_cscalar#

Returns True if the empty state is managed on the Python side.

property is_empty#

Indicates whether the Scalar is empty or not.

property is_grbscalar#

Returns True if the empty state is managed by the GraphBLAS backend.

property nvals#

Number of non-empty values.

Can only be 0 or 1.

property value#

Returns the value held by the Scalar as a Python object, or None if the Scalar is empty.

Assigning to value will update the Scalar.

Example Usage:

>>> s.value
15
>>> s.value = 16
>>> s.value
16

Operators#

UnaryOp#

BinaryOp#

Monoid#

Semiring#

IndexUnaryOp#

SelectOp#

Input/Output#

NetworkX#

These methods require networkx to be installed.

graphblas.io.from_networkx(G, nodelist=None, dtype=None, weight='weight', name=None)#

Create a square adjacency Matrix from a networkx Graph.

Parameters
Gnx.Graph

Graph to convert

nodelistlist, optional

List of nodes in the nx.Graph. If not provided, all nodes will be used.

dtype

Data type

weightstr, default=”weight”

Weight attribute

namestr, optional

Name of resulting Matrix

Returns
Matrix
graphblas.io.to_networkx(m, edge_attribute='weight')#

Create a networkx DiGraph from a square adjacency Matrix

Parameters
mMatrix

Square adjacency Matrix

edge_attributestr, optional

Name of edge attribute from values of Matrix. If None, values will be skipped. Default is “weight”.

Returns
nx.DiGraph

Numpy#

These methods require scipy to be installed, as some of the scipy.sparse machinery is used during the conversion process.

graphblas.io.from_numpy(m)#

Create a sparse Vector or Matrix from a dense numpy array.

A value of 0 is considered as “missing”.

  • m.ndim == 1 returns a Vector

  • m.ndim == 2 returns a Matrix

  • m.ndim > 2 raises an error

dtype is inferred from m.dtype

Parameters
mnp.ndarray

Input array

Returns
Vector or Matrix
graphblas.io.to_numpy(m)#

Create a dense numpy array from a sparse Vector or Matrix.

Missing values will become 0 in the output.

numpy dtype will match the GraphBLAS dtype

Parameters
mVector or Matrix

GraphBLAS Vector or Matrix

Returns
np.ndarray

Scipy Sparse#

These methods require scipy to be installed.

graphblas.io.from_scipy_sparse(A, *, dup_op=None, name=None)#

Create a Matrix from a scipy.sparse array or matrix.

Input data in “csr” or “csc” format will be efficient when importing with SuiteSparse:GraphBLAS.

Parameters
Ascipy.sparse

Scipy sparse array or matrix

dup_opBinaryOp, optional

Aggregation function for formats that allow duplicate entries (e.g. coo)

namestr, optional

Name of resulting Matrix

Returns
Matrix
graphblas.io.to_scipy_sparse(A, format='csr')#

Create a scipy.sparse array from a GraphBLAS Matrix or Vector

Parameters
AMatrix or Vector

GraphBLAS object to be converted

formatstr

{‘bsr’, ‘csr’, ‘csc’, ‘coo’, ‘lil’, ‘dia’, ‘dok’}

Returns
scipy.sparse array

Matrix Market#

Matrix Market is a plain-text format for storing graphs.

These methods require scipy to be installed.

graphblas.io.mmread(source, *, dup_op=None, name=None)#

Create a GraphBLAS Matrix from the contents of a Matrix Market file.

This uses scipy.io.mmread.

Parameters
filenamestr or file

Filename (.mtx or .mtz.gz) or file-like object

dup_opBinaryOp, optional

Aggregation function for duplicate coordinates (if found)

namestr, optional

Name of resulting Matrix

Returns
Matrix
graphblas.io.mmwrite(target, matrix, *, comment='', field=None, precision=None, symmetry=None)#

Write a Matrix Market file from the contents of a GraphBLAS Matrix.

This uses scipy.io.mmwrite.

Parameters
filenamestr or file target

Filename (.mtx) or file-like object opened for writing

matrixMatrix

Matrix to be written

commentstr, optional

Comments to be prepended to the Matrix Market file

fieldstr

{“real”, “complex”, “pattern”, “integer”}

precisionint, optional

Number of digits to write for real or complex values

symmetrystr, optional

{“general”, “symmetric”, “skew-symmetric”, “hermetian”}

Visualization#

graphblas.io.draw(m)#

Draw a square adjacency Matrix as a graph.

Requires networkx and matplotlib to be installed.

Example output:

../_images/draw-example.png

Exceptions#

exception graphblas.exceptions.DimensionMismatch#

The input or output dimensions (i.e. shape) are not compatible.

exception graphblas.exceptions.DomainMismatch#

The domains (i.e. data types) of the inputs or outputs are incompatible for the operation.

exception graphblas.exceptions.EmptyObject#

A provided Scalar object is empty, but requires a value.

This could happen, for example, if an empty Scalar is provided as the right argument to apply().

exception graphblas.exceptions.IndexOutOfBound#

A provided index falls outside the dimensions.

In non-blocking mode, this error can be deferred.

exception graphblas.exceptions.InvalidIndex#

Provided index specifies a location outside the dimensions.

This error is always raised immediately, even in non-blocking mode.

exception graphblas.exceptions.InvalidObject#

One of the collection objects (input or output) is in an invalid state due to a previous error.

exception graphblas.exceptions.NotImplementedException#

The backend GraphBLAS implementation does not support the operation for the provided inputs.

exception graphblas.exceptions.OutOfMemory#

GraphBLAS ran out of memory when allocating space for the operation.

exception graphblas.exceptions.OutputNotEmpty#

Attempt to call build() on a non-empty object.

exception graphblas.exceptions.Panic#

Unknown internal GraphBLAS error.

exception graphblas.exceptions.UdfParseError#

Unable to parse the user-defined function.