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, **opts)#
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, **opts)#
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 caseright
andleft
may not be defined.A
BinaryOp
can also be used, in which case a scalar must be passed asleft
orright
.An
IndexUnaryOp
can also be used with the thunk passed in asright
.- Parameters
- opUnaryOp or BinaryOp or IndexUnaryOp
Operator to apply
- right
Scalar used with BinaryOp or IndexUnaryOp
- left
Scalar used with BinaryOp
- Returns
- MatrixExpression
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 forclear
, 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. Theshape
will not change.
- diag(k=0, dtype=None, *, name=None, **opts)#
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
- dup(dtype=None, *, clear=False, mask=None, name=None, **opts)#
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)#
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
- Returns
- MatrixExpression 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
- MatrixExpression 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
- MatrixExpression 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=1.0, 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, default 1.0
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 inrows
.- ncolsint, optional
Number of columns in the Matrix. If not provided,
ncols
is computed from the maximum column index found incolumns
.- dup_op
BinaryOp
, 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
See also
- classmethod from_csc(indptr, row_indices, values=1.0, 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 invalues[indptr[i]:indptr[i+1]]
. The number of columns is inferred asncols = 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, default 1.0
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 inrow_indices
.- ncolsint, optional
Number of columns in the Matrix. ncols is computed as
len(indptr) - 1
. If provided, it must equallen(indptr) - 1
.- namestr, optional
Name to give the Matrix.
- Returns
- Matrix
See also
from_coo
from_csr
from_dcsc
to_csc
Matrix.ss.import_csc
io.from_scipy_sparse
- classmethod from_csr(indptr, col_indices, values=1.0, 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 invalues[indptr[i]:indptr[i+1]]
. The number of rows is inferred asnrows = 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, default 1.0
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 equallen(indptr) - 1
.- ncolsint, optional
Number of columns in the Matrix. If not provided,
ncols
is computed from the maximum column index found incol_indices
.- namestr, optional
Name to give the Matrix.
- Returns
- Matrix
See also
from_coo
from_csc
from_dcsr
to_csr
Matrix.ss.import_csr
io.from_scipy_sparse
- classmethod from_dcsc(compressed_cols, indptr, row_indices, values=1.0, 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 columncompressed_cols[i]
are stored incol_indices[indptr[compressed_cols[i]]:indptr[compressed_cols[i]+1]]
and the values are stored invalues[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, default 1.0
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 inrow_indices
.- ncolsint, optional
Number of columns in the Matrix. If not provided,
ncols
is computed from the maximum column index found incompressed_cols
.- namestr, optional
Name to give the Matrix.
- Returns
- Matrix
See also
from_coo
from_csc
from_dcsr
to_dcsc
Matrix.ss.import_hypercsc
io.from_scipy_sparse
- classmethod from_dcsr(compressed_rows, indptr, col_indices, values=1.0, 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 rowcompressed_rows[i]
are stored incol_indices[indptr[compressed_row[i]]:indptr[compressed_row[i]+1]]
and the values are stored invalues[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, default 1.0
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 incompressed_rows
.- ncolsint, optional
Number of columns in the Matrix. If not provided,
ncols
is computed from the maximum column index found incol_indices
.- namestr, optional
Name to give the Matrix.
- Returns
- Matrix
See also
from_coo
from_csr
from_dcsc
to_dcsr
Matrix.ss.import_hypercsr
io.from_scipy_sparse
- classmethod from_dense(values, missing_value=None, *, dtype=None, name=None, **opts)#
Create a Matrix from a NumPy array or list of lists.
- Parameters
- valueslist or np.ndarray
List of values.
- missing_valuescalar, optional
A scalar value to consider “missing”; elements of this value will be dropped. If None, then the resulting Matrix will be dense.
- dtypeDataType, optional
Data type of the Matrix. If not provided, the values will be inspected to choose an appropriate dtype.
- namestr, optional
Name to give the Matrix.
- Returns
- Matrix
See also
- 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
See also
- classmethod from_edgelist(edgelist, values=None, dtype=None, *, nrows=None, ncols=None, dup_op=None, name=None)#
Create a new Matrix from edgelist of (row, col) pairs or (row, col, value) triples.
This transforms the data and calls
Matrix.from_coo
.- Parameters
- edgelistlist or np.ndarray or iterable
A sequence of
(row, column)
pairs or(row, column, value)
triples. NumPy edgelist only supports(row, column)
; values must be passed separately.- valueslist or np.ndarray or scalar, optional
List of values. If a scalar is provided, all values will be set to this single value. The default is 1.0 if
edgelist
is a sequence of(row, column)
pairs.- 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 the edgelist.- ncolsint, optional
Number of columns in the Matrix. If not provided,
ncols
is computed from the maximum column index found in the edgelist.- dup_op
BinaryOp
, 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
See also
- classmethod from_scalar(value, nrows, ncols, dtype=None, *, name=None, **opts)#
Create a fully dense Matrix filled with a scalar value.
For SuiteSparse:GraphBLAS backend, this creates an iso-valued full Matrix that stores a single value regardless of the shape of the Matrix, so large matrices created by
Matrix.from_scalar
will use very low memory.If instead you want to create a new iso-valued Matrix with the same structure as an existing Matrix, you may do:
C = binary.second(A, value).new()
.- Parameters
- valuescalar
Scalar value used to fill the Matrix.
- nrowsint
Number of rows.
- ncolsint
Number of columns.
- dtypeDataType, optional
Data type of the Matrix. If not provided, the scalar value will be inspected to choose an appropriate dtype.
- namestr, optional
Name to give the Matrix.
- Returns
- Matrix
See also
- 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, **opts)#
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, **opts)#
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
- op
BinaryOp
Operator used on the combination of elements
- Returns
- MatrixExpression
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
- op
Semiring
Semiring used in the computation
- Returns
- MatrixExpression
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
- op
Semiring
Semiring used in the computation
- Returns
- VectorExpression
Examples
# Method syntax C << A.mxv(v, op=semiring.min_plus) # Functional syntax C << semiring.min_plus(A @ v)
- power(n, op=semiring.plus_times)#
Raise a square Matrix to the (positive integer) power
n
.Matrix power is computed by repeated matrix squaring and matrix multiplication. For a graph as an adjacency matrix, matrix power with default
plus_times
semiring computes the number of walks connecting each pair of nodes. The result can grow very quickly for large matrices and with largern
.- Parameters
- nint
The exponent must be a nonnegative integer. If n=0, the result will be a diagonal matrix with values equal to the identity of the semiring’s binary operator. For example,
plus_times
will have diagonal values of 1, which is the identity oftimes
. The binary operator must be associated with a monoid when n=0 so the identity can be determined; otherwise, ValueError is raised.- op
Semiring
Semiring used in the computation
- Returns
- MatrixExpression
Examples
C << A.power(4, op=semiring.plus_times) # Is equivalent to: tmp = (A @ A).new() tmp << tmp @ tmp C << tmp @ tmp # And is more efficient than the naive implementation: C = A.dup() for i in range(1, 4): C << A @ C
- 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
- op
Monoid
Reduction operator
- op
- Returns
- VectorExpression
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
- op
Monoid
Reduction operator
- op
- Returns
- VectorExpression
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
- op
Monoid
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
- op
- Returns
- ScalarExpression
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
- MatrixExpression
Examples
C = A.reposition(1, 2).new()
- select(op, thunk=None)#
Create a new Matrix by applying
op
to each element of the Matrix and keeping those elements whereop
returns True.See the Select section in the User Guide for more details.
- Parameters
- op
SelectOp
Operator to apply
- thunk
Scalar passed to operator
- op
- Returns
- MatrixExpression
Examples
# Method syntax C << A.select(">=", 1) # Functional syntax C << select.value(A >= 1)
- setdiag(values, k=0, *, mask=None, accum=None, **opts)#
Set k’th diagonal with a Scalar, Vector, or array.
This is not a built-in GraphBLAS operation. It is implemented as a recipe.
- Parameters
- valuesVector or list or np.ndarray or scalar
New values to assign to the diagonal. The length of Vector and array values must match the size of the diagonal being assigned to.
- kint, default=0
Which diagonal or off-diagonal to set. For example, set the elements
A[i, i+k] = values[i]
. The default, k=0, is the main diagonal.- maskMask, optional
Vector or Matrix Mask to control which diagonal elements to set. If it is Matrix Mask, then only the diagonal is used as the mask.
- accumMonoid or BinaryOp, optional
Operator to use to combine existing diagonal values and new values.
- 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 ifFalse
- columns :bool, default=True
Whether to return columns; will return
None
for columns ifFalse
- valuesbool, default=True
Whether to return values; will return
None
for values ifFalse
- 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
See also
- to_csc(dtype=None, *, sort=True)#
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 invalues[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
from_csc
Matrix.ss.export
io.to_scipy_sparse
- to_csr(dtype=None, *, sort=True)#
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 invalues[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
from_csr
Matrix.ss.export
io.to_scipy_sparse
- to_dcsc(dtype=None, *, sort=True)#
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 columncompressed_cols[i]
are stored incol_indices[indptr[compressed_cols[i]]:indptr[compressed_cols[i]+1]]
and the values are stored invalues[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
from_dcsc
Matrix.ss.export
io.to_scipy_sparse
- to_dcsr(dtype=None, *, sort=True)#
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 rowcompressed_rows[i]
are stored incol_indices[indptr[compressed_row[i]]:indptr[compressed_row[i]+1]]
and the values are stored invalues[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
from_dcsc
Matrix.ss.export
io.to_scipy_sparse
- to_dense(fill_value=None, dtype=None, **opts)#
Convert Matrix to NumPy array of the same shape with missing values filled.
Warning
This can create very large arrays that require a lot of memory; please use caution.
- Parameters
- fill_valuescalar, optional
Value used to fill missing values. This is required if there are missing values.
- dtypeDataType, optional
Requested dtype for the output values array.
- Returns
- np.ndarray
See also
- 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
See also
- to_edgelist(dtype=None, *, values=True, sort=True)#
Extract the indices and values as a 2-tuple of numpy arrays.
This calls
to_coo
then transforms the data into an edgelist.- Parameters
- dtype
Requested dtype for the output values array.
- valuesbool, default=True
Whether to return values; will return
None
for values ifFalse
- 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]Edgelist
- np.ndarrayValues
See also
- 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, **opts)#
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, **opts)#
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 caseright
andleft
may not be defined.A
BinaryOp
can also be used, in which case a scalar must be passed asleft
orright
.An
IndexUnaryOp
can also be used with the thunk passed in asright
.- Parameters
- opUnaryOp or BinaryOp or IndexUnaryOp
Operator to apply
- right
Scalar used with BinaryOp or IndexUnaryOp
- left
Scalar used with BinaryOp
- Returns
- VectorExpression
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 forclear
, 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. Thesize
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
- dup(dtype=None, *, clear=False, mask=None, name=None, **opts)#
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)#
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
- Returns
- VectorExpression 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
- Returns
- VectorExpression 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 vectors.
See the Element-wise Union section in the User Guide for more details, especially about the difference between ewise_union and
ewise_add()
.- Parameters
- Returns
- VectorExpression 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=1.0, 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, default 1.0
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 inindices
.- 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
See also
- classmethod from_dense(values, missing_value=None, *, dtype=None, name=None, **opts)#
Create a Vector from a NumPy array or list.
- Parameters
- valueslist or np.ndarray
List of values.
- missing_valuescalar, optional
A scalar value to consider “missing”; elements of this value will be dropped. If None, then the resulting Vector will be dense.
- dtypeDataType, optional
Data type of the Vector. If not provided, the values will be inspected to choose an appropriate dtype.
- namestr, optional
Name to give the Vector.
- Returns
- Vector
See also
- 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 inindices
.- namestr, optional
Name to give the Vector.
- Returns
- Vector
See also
- classmethod from_pairs(pairs, dtype=None, *, size=None, dup_op=None, name=None)#
Create a new Vector from indices and values.
This transforms the data and calls
Vector.from_coo
.- Parameters
- pairslist or iterable
A sequence of
(index, value)
pairs.- 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 inpairs
.- 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
See also
- classmethod from_scalar(value, size, dtype=None, *, name=None, **opts)#
Create a fully dense Vector filled with a scalar value.
For SuiteSparse:GraphBLAS backend, this creates an iso-valued full Vector that stores a single value regardless of the size of the Vector, so large vectors created by
Vector.from_scalar
will use very low memory.If instead you want to create a new iso-valued Vector with the same structure as an existing Vector, you may do:
w = binary.second(v, value).new()
.- Parameters
- valuescalar
Scalar value used to fill the Vector.
- nrowsint
Number of rows.
- ncolsint
Number of columns.
- dtypeDataType, optional
Data type of the Vector. If not provided, the scalar value will be inspected to choose an appropriate dtype.
- namestr, optional
Name to give the Vector.
- Returns
- Vector
See also
- 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
- op
Semiring
Semiring used in the computation
- Returns
- ScalarExpression
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, **opts)#
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, **opts)#
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
- op
BinaryOp
Operator used in the computation
- Returns
- MatrixExpression
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
- op
Monoid
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
- op
- Returns
- ScalarExpression
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
- VectorExpression
Examples
w = v.reposition(20).new()
- select(op, thunk=None)#
Create a new Vector by applying
op
to each element of the Vector and keeping those elements whereop
returns True.See the Select section in the User Guide for more details.
- Parameters
- op
SelectOp
Operator to apply
- thunk
Scalar passed to operator
- op
- Returns
- VectorExpression
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 ifFalse
- valuesbool, default=True
Whether to return values; will return
None
for values ifFalse
- sortbool, default=True
Whether to require sorted indices.
- Returns
- np.ndarray[dtype=uint64]Indices
- np.ndarrayValues
- to_dense(fill_value=None, dtype=None, **opts)#
Convert Vector to NumPy array of the same shape with missing values filled.
Warning
This can create very large arrays that require a lot of memory; please use caution.
- Parameters
- fill_valuescalar, optional
Value used to fill missing values. This is required if there are missing values.
- dtypeDataType, optional
Requested dtype for the output values array.
- Returns
- np.ndarray
See also
- to_dict()#
Return Vector as a dict in the form
{index: val}
.- Returns
- dict
- 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
- op
Semiring
Semiring used in the computation
- Returns
- VectorExpression
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.
- apply(op, right=None, *, left=None)#
Create a new Scalar by applying
op
.See the Apply section in the User Guide for more details.
Common usage is to pass a
UnaryOp
, in which caseright
andleft
may not be defined.A
BinaryOp
can also be used, in which case a scalar must be passed asleft
orright
.An
IndexUnaryOp
can also be used with the thunk passed in asright
.- Parameters
- opUnaryOp or BinaryOp or IndexUnaryOp
Operator to apply
- right
Scalar used with BinaryOp or IndexUnaryOp
- left
Scalar used with BinaryOp
- Returns
- ScalarExpression
Examples
# Method syntax b << a.apply(op.abs) # Functional syntax b << op.abs(a)
- 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
- ewise_add(other, op=monoid.plus)#
Perform element-wise computation on the union of sparse values, similar to how one expects addition to work for sparse data.
See the Element-wise Union section in the User Guide for more details, especially about the difference between ewise_add and
ewise_union()
.- Parameters
- Returns
- ScalarExpression that will be non-empty if any of the inputs is non-empty
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 data.
See the Element-wise Intersection section in the User Guide for more details.
- Parameters
- Returns
- ScalarExpression that will be empty if any of the inputs is empty
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 data.
See the Element-wise Union section in the User Guide for more details, especially about the difference between ewise_union and
ewise_add()
.- Parameters
- Returns
- ScalarExpression 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_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
- 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