Class CsrFieldMatrix<T extends Field<T>>
- Type Parameters:
T- The type of elements stored in this matrix, constrained by theFieldinterface.
- All Implemented Interfaces:
Serializable,FieldTensorMixin<CsrFieldMatrix<T>,,FieldMatrix<T>, T> TensorOverField<CsrFieldMatrix<T>,,FieldMatrix<T>, T[], T> MatrixMixin<CsrFieldMatrix<T>,,FieldMatrix<T>, CooFieldVector<T>, T> RingTensorMixin<CsrFieldMatrix<T>,,FieldMatrix<T>, T> TensorOverRing<CsrFieldMatrix<T>,,FieldMatrix<T>, T[], T> SemiringTensorMixin<CsrFieldMatrix<T>,,FieldMatrix<T>, T> TensorOverSemiring<CsrFieldMatrix<T>,FieldMatrix<T>, T[], T>
Instances of this class represent a sparse matrix using the compressed sparse row (CSR) format where
all data elements belonging to a specified Field type.
This class is optimized for efficient storage and operations on matrices with a high proportion of zero elements.
The non-zero values of the matrix are stored in a compact form, reducing memory usage and improving performance for many matrix
operations.
CSR Representation:
A CSR matrix is represented internally using three main arrays:- Data: Non-zero values are stored in a one-dimensional array
AbstractTensor.dataof lengthAbstractCsrSemiringMatrix.nnz. Any element not specified indatais implicitly zero. It is also possible to explicitly store zero values in this array, although this is generally not desirable. To remove explicitly defined zeros, usedropZeros() - Row Pointers: A 1D array
AbstractCsrSemiringMatrix.rowPointersof lengthnumRows + 1whererowPointers[i]indicates the starting index in thedataandcolIndicesarrays for rowi. The last entry ofrowPointersequals the length ofdata. That is, all non-zero values indatawhich are in rowiare betweendata[rowIndices[i](inclusive) anddata[rowIndices[i + 1](exclusive). - Column Indices: A 1D array
AbstractCsrSemiringMatrix.colIndicesof lengthAbstractCsrSemiringMatrix.nnzstoring the column indices corresponding to each non-zero value indata.
The total number of non-zero elements (AbstractCsrSemiringMatrix.nnz) and the shape are fixed for a given instance, but the values
in AbstractTensor.data and their corresponding AbstractCsrSemiringMatrix.rowPointers and AbstractCsrSemiringMatrix.colIndices may be updated. Many operations
assume that the indices are sorted lexicographically by row, and then by column, but this is not strictly enforced.
All provided operations preserve the lexicographical row-major sorting of data and indices. If there is any doubt about the
ordering of indices, use AbstractCsrSemiringMatrix.sortIndices() to ensure they are explicitly sorted. CSR tensors may also store multiple entries
for the same index (referred to as an uncoalesced tensor). To combine all duplicated entries use AbstractCsrSemiringMatrix.coalesce() or
AbstractCsrSemiringMatrix.coalesce(BinaryOperator).
CSR matrices are optimized for efficient storage and operations on matrices with a high proportion of zero elements.
CSR matrices are ideal for row-wise operations and matrix-vector multiplications. In general, CSR matrices are not efficient at
handling many incremental updates. In this case COO matrices are usually preferred.
Conversion to other formats, such as COO or dense matrices, can be performed using toCoo() or AbstractCsrSemiringMatrix.toDense().
Usage Examples:
// Define matrix data.
Shape shape = new Shape(8, 8);
Complex128[] data = {
new Complex128(1, 2), new Complex128(3, 4),
new Complex128(5, 6), new Complex128(7, 8)
};
int[] rowPointers = {0, 1, 1, 1, 1, 3, 3, 3, 4}
int[] colIndices = {0, 0, 5, 2};
// Create CSR matrix.
CsrFieldMatrix<Complex128> matrix = new CsrFieldMatrix<>(shape, data, rowPointers, colIndices);
// Add matrices.
CsrFieldMatrix<Complex128> sum = matrix.add(matrix);
// Compute matrix-matrix multiplication.
Matrix prod = matrix.mult(matrix);
CsrFieldMatrix<Complex128> sparseProd = matrix.mult2Csr(matrix);
// Compute matrix-vector multiplication.
FieldVector<Complex128> denseVector = new FieldVector(matrix.numCols, new Complex128(5, 6));
FieldMatrix<Complex128> matrixVectorProd = matrix.mult(denseVector);
- See Also:
-
Field Summary
Fields inherited from class org.flag4j.arrays.backend.semiring_arrays.AbstractCsrSemiringMatrix
colIndices, nnz, numCols, numRows, rowPointers, sparsity, zeroElementFields inherited from class org.flag4j.arrays.backend.AbstractTensor
data, rank, shape -
Constructor Summary
ConstructorsConstructorDescriptionCreates a sparse CSR matrix with the specifiedshape, non-zero data, row pointers, and non-zero column indices.CsrFieldMatrix(Shape shape, T fieldElement) Constructs a sparse CSR matrix representing the zero matrix for the field whichfieldElementbelongs to.CsrFieldMatrix(Shape shape, T[] data, int[] rowPointers, int[] colIndices) Creates a sparse CSR matrix with the specifiedshape, non-zero data, row pointers, and non-zero column indices. -
Method Summary
Modifier and TypeMethodDescription<R> Raccept(MatrixVisitor<R> visitor) Accepts a visitor that implements theMatrixVisitorinterface.Drops any explicit zeros in this sparse COO matrix.booleanChecks if an object is equal to this matrix object.getCol(int colIdx) Get the column of this matrix at the specified index.getCol(int colIdx, int rowStart, int rowEnd) Gets a specified column of this matrix betweenrowStart(inclusive) androwEnd(exclusive).getDiag()Extracts the diagonal elements of this matrix and returns them as a vector.getDiag(int diagOffset) Gets the elements of this matrix along the specified diagonal.getRow(int rowIdx) Get the row of this matrix at the specified index.getRow(int rowIdx, int colStart, int colEnd) Gets a specified row of this matrix betweencolStart(inclusive) andcolEnd(exclusive).inthashCode()makeLikeCooMatrix(Shape shape, T[] data, int[] rowIndices, int[] colIndices) Constructs a sparse COO matrix of a similar type to this sparse CSR matrix.makeLikeDenseTensor(Shape shape, T[] data) Constructs a dense matrix which is of a similar type to this sparse CSR matrix.Constructs a CSR matrix with the specified shape, non-zero data, and non-zero indices.makeLikeTensor(Shape shape, T[] data) Constructs a tensor of the same type as this tensor with the given theshapeanddata.makeLikeTensor(Shape shape, T[] data, int[] rowPointers, int[] colIndices) Constructs a sparse CSR tensor of the same type as this tensor with the specified non-zero data and indices.mult(CooFieldVector<T> b) Computes the matrix-vector multiplication of a vector with this matrix.AbstractTensor<?, T[], T> tensorDot(CsrFieldMatrix<T> src2, int[] aAxes, int[] bAxes) Computes the tensor contraction of this tensor with a specified tensor over the specified set of axes.toCoo()Converts this sparse CSR matrix to an equivalent sparse COO matrix.toString()Formats this sparse matrix as a human-readable string.toTensor()Converts this CSR matrix to an equivalent sparse COO tensor.Converts this CSR matrix to an equivalent COO tensor with the specified shape.toVector()Converts this matrix to an equivalent vector.static <T extends Field<T>>
CsrFieldMatrix<T> unsafeMake(Shape shape, Complex128[] data, int[] rowPointers, int[] colIndices) Factory to construct a CSR matrix which bypasses any validation checks on the data and indices.Methods inherited from class org.flag4j.arrays.backend.field_arrays.AbstractCsrFieldMatrix
abs, div, H, H, H, isFinite, isHermitian, isInfinite, isNaN, isUnitary, mult2Csr, sqrtMethods inherited from class org.flag4j.arrays.backend.ring_arrays.AbstractCsrRingMatrix
allClose, allClose, subMethods inherited from class org.flag4j.arrays.backend.semiring_arrays.AbstractCsrSemiringMatrix
add, augment, augment, coalesce, coalesce, copy, dataLength, density, elemMult, flatten, flatten, get, get, getSlice, getTriL, getTriU, getZeroElement, isI, isOrthogonal, isSymmetric, isTriL, isTriU, mult, multToSparse, multTranspose, numCols, numRows, removeCol, removeCols, removeRow, removeRows, reshape, set, set, setCol, setRow, setSliceCopy, setZeroElement, sortIndices, sparsity, stack, swapCols, swapRows, T, T, T, tensorTr, toDense, trMethods inherited from class org.flag4j.arrays.backend.AbstractTensor
getData, getRank, getShape, reshape, sameShape, totalEntriesMethods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, waitMethods inherited from interface org.flag4j.arrays.backend.field_arrays.FieldTensorMixin
add, add, addEq, addEq, argmax, argmaxAbs, argmin, argminAbs, conj, div, div, divEq, divEq, isOnes, isZeros, makeEmptyDataArray, max, maxAbs, min, minAbs, mult, mult, multEq, multEq, norm, norm, prod, recip, sub, sub, subEq, subEq, sumMethods inherited from interface org.flag4j.arrays.backend.MatrixMixin
add, augment, augment, copy, dataLength, elemMult, fib, get, getShape, getSlice, getTriL, getTriL, getTriU, getTriU, isDiag, isI, isOrthogonal, isSquare, isSymmetric, isTri, isTriL, isTriU, isVector, mult, multTranspose, numCols, numRows, removeCol, removeCols, removeRow, removeRows, set, setCol, setRow, setSliceCopy, stack, stack, sub, swapCols, swapRows, T, tr, trace, vectorTypeMethods inherited from interface org.flag4j.arrays.backend.semiring_arrays.SemiringTensorMixin
argmax, argmin, max, minMethods inherited from interface org.flag4j.arrays.backend.ring_arrays.TensorOverRing
sub
-
Constructor Details
-
CsrFieldMatrix
Creates a sparse CSR matrix with the specifiedshape, non-zero data, row pointers, and non-zero column indices.- Parameters:
shape- Shape of this tensor.data- The non-zero data of this CSR matrix.rowPointers- The row pointers for the non-zero values in the sparse CSR matrix.rowPointers[i]indicates the starting index withindataandcolDataof all values in rowi.colIndices- Column indices for each non-zero value in this sparse CSR matrix. Must satisfydata.length == colData.length.
-
CsrFieldMatrix
public CsrFieldMatrix(Shape shape, List<T> data, List<Integer> rowPointers, List<Integer> colIndices) Creates a sparse CSR matrix with the specifiedshape, non-zero data, row pointers, and non-zero column indices.- Parameters:
shape- Shape of this tensor.data- The non-zero data of this CSR matrix.rowPointers- The row pointers for the non-zero values in the sparse CSR matrix.rowPointers[i]indicates the starting index withindataandcolDataof all values in rowi.colIndices- Column indices for each non-zero value in this sparse CSR matrix. Must satisfydata.length == colData.length.
-
CsrFieldMatrix
-
-
Method Details
-
unsafeMake
public static <T extends Field<T>> CsrFieldMatrix<T> unsafeMake(Shape shape, Complex128[] data, int[] rowPointers, int[] colIndices) Factory to construct a CSR matrix which bypasses any validation checks on the data and indices.
Warning: This method should be used with extreme caution. It primarily exists for internal use. Only use this factory if you are 100% certain the parameters are valid as some methods may throw exceptions or exhibit undefined behavior.
- Parameters:
shape- The full size of the COO matrix.data- The non-zero data of the COO matrix.rowPointers- The non-zero row pointers of the COO matrix.colIndices- The non-zero column indices of the COO matrix.- Returns:
- A COO matrix constructed from the provided parameters.
-
makeLikeTensor
Constructs a sparse CSR tensor of the same type as this tensor with the specified non-zero data and indices.- Specified by:
makeLikeTensorin classAbstractCsrSemiringMatrix<CsrFieldMatrix<T extends Field<T>>,FieldMatrix<T extends Field<T>>, CooFieldVector<T extends Field<T>>, T extends Field<T>> - Parameters:
shape- Shape of the matrix.data- Non-zero data of the CSR matrix.rowPointers- Row pointers for the non-zero values in the CSR matrix.colIndices- Non-zero column indices of the CSR matrix.- Returns:
- A sparse CSR tensor of the same type as this tensor with the specified non-zero data and indices.
-
makeLikeTensor
public CsrFieldMatrix<T> makeLikeTensor(Shape shape, List<T> data, List<Integer> rowPointers, List<Integer> colIndices) Constructs a CSR matrix with the specified shape, non-zero data, and non-zero indices.- Specified by:
makeLikeTensorin classAbstractCsrSemiringMatrix<CsrFieldMatrix<T extends Field<T>>,FieldMatrix<T extends Field<T>>, CooFieldVector<T extends Field<T>>, T extends Field<T>> - Parameters:
shape- Shape of the matrix.data- Non-zero values of the CSR matrix.rowPointers- Row pointers for the non-zero values in the CSR matrix.colIndices- Non-zero column indices of the CSR matrix.- Returns:
- A CSR matrix with the specified shape, non-zero data, and non-zero indices.
-
makeLikeDenseTensor
Constructs a dense matrix which is of a similar type to this sparse CSR matrix.- Specified by:
makeLikeDenseTensorin classAbstractCsrSemiringMatrix<CsrFieldMatrix<T extends Field<T>>,FieldMatrix<T extends Field<T>>, CooFieldVector<T extends Field<T>>, T extends Field<T>> - Parameters:
shape- Shape of the dense matrix.data- Entries of the dense matrix.- Returns:
- A dense matrix which is of a similar type to this sparse CSR matrix with the specified
shapeanddata.
-
makeLikeCooMatrix
public CooFieldMatrix<T> makeLikeCooMatrix(Shape shape, T[] data, int[] rowIndices, int[] colIndices) Constructs a sparse COO matrix of a similar type to this sparse CSR matrix.
Note: this method constructs a new COO matrix with the specified data and indices. It does not convert this matrix to a CSR matrix. To convert this matrix to a sparse COO matrix use
toCoo().- Specified by:
makeLikeCooMatrixin classAbstractCsrSemiringMatrix<CsrFieldMatrix<T extends Field<T>>,FieldMatrix<T extends Field<T>>, CooFieldVector<T extends Field<T>>, T extends Field<T>> - Parameters:
shape- Shape of the COO matrix.data- Non-zero data of the COO matrix.rowIndices- Non-zero row indices of the sparse COO matrix.colIndices- Non-zero column indices of the Sparse COO matrix.- Returns:
- A sparse COO matrix of a similar type to this sparse CSR matrix.
-
makeLikeTensor
Constructs a tensor of the same type as this tensor with the given theshapeanddata. The resulting tensor will also have the same non-zero indices as this tensor.- Specified by:
makeLikeTensorin interfaceTensorOverSemiring<CsrFieldMatrix<T extends Field<T>>,FieldMatrix<T extends Field<T>>, T extends Field<T>[], T extends Field<T>> - Specified by:
makeLikeTensorin classAbstractTensor<CsrFieldMatrix<T extends Field<T>>,T extends Field<T>[], T extends Field<T>> - Parameters:
shape- Shape of the tensor to construct.data- Entries of the tensor to construct.- Returns:
- A tensor of the same type and with the same non-zero indices as this tensor with the given the
shapeanddata.
-
toCoo
Converts this sparse CSR matrix to an equivalent sparse COO matrix.- Specified by:
toCooin classAbstractCsrSemiringMatrix<CsrFieldMatrix<T extends Field<T>>,FieldMatrix<T extends Field<T>>, CooFieldVector<T extends Field<T>>, T extends Field<T>> - Returns:
- A sparse COO matrix equivalent to this sparse CSR matrix.
-
toTensor
Converts this CSR matrix to an equivalent sparse COO tensor.- Specified by:
toTensorin classAbstractCsrSemiringMatrix<CsrFieldMatrix<T extends Field<T>>,FieldMatrix<T extends Field<T>>, CooFieldVector<T extends Field<T>>, T extends Field<T>> - Returns:
- An sparse COO tensor equivalent to this CSR matrix.
-
toTensor
Converts this CSR matrix to an equivalent COO tensor with the specified shape.- Overrides:
toTensorin classAbstractCsrSemiringMatrix<CsrFieldMatrix<T extends Field<T>>,FieldMatrix<T extends Field<T>>, CooFieldVector<T extends Field<T>>, T extends Field<T>> - Parameters:
shape- @return A COO tensor equivalent to this CSR matrix which has been reshaped tonewShape- Returns:
- A COO tensor equivalent to this CSR matrix which has been reshaped to
newShape
-
equals
Checks if an object is equal to this matrix object. -
hashCode
-
mult
Computes the matrix-vector multiplication of a vector with this matrix.- Parameters:
b- Vector in the matrix-vector multiplication.- Returns:
- The result of multiplying this matrix with
b. - Throws:
LinearAlgebraException- If the number of columns in this matrix do not equal the size ofb.
-
toVector
Converts this matrix to an equivalent vector. If this matrix is not shaped as a row/column vector, it will first be flattened then converted to a vector.- Specified by:
toVectorin interfaceMatrixMixin<CsrFieldMatrix<T extends Field<T>>,FieldMatrix<T extends Field<T>>, CooFieldVector<T extends Field<T>>, T extends Field<T>> - Overrides:
toVectorin classAbstractCsrSemiringMatrix<CsrFieldMatrix<T extends Field<T>>,FieldMatrix<T extends Field<T>>, CooFieldVector<T extends Field<T>>, T extends Field<T>> - Returns:
- A vector equivalent to this matrix.
-
getRow
Get the row of this matrix at the specified index.- Parameters:
rowIdx- Index of row to get.- Returns:
- The specified row of this matrix.
- Throws:
ArrayIndexOutOfBoundsException- IfrowIdxis less than zero or greater than/equal to the number of rows in this matrix.
-
getRow
Gets a specified row of this matrix betweencolStart(inclusive) andcolEnd(exclusive).- Parameters:
rowIdx- Index of the row of this matrix to get.colStart- Starting column of the row (inclusive).colEnd- Ending column of the row (exclusive).- Returns:
- The row at index
rowIdxof this matrix between thecolStartandcolEndindices. - Throws:
IndexOutOfBoundsException- If eithercolEndarecolStartout of bounds for the shape of this matrix.IllegalArgumentException- IfcolEndis less thancolStart.
-
getCol
Get the column of this matrix at the specified index.- Parameters:
colIdx- Index of column to get.- Returns:
- The specified column of this matrix.
- Throws:
ArrayIndexOutOfBoundsException- IfcolIdxis less than zero or greater than/equal to the number of columns in this matrix.
-
getCol
Gets a specified column of this matrix betweenrowStart(inclusive) androwEnd(exclusive).- Parameters:
colIdx- Index of the column of this matrix to get.rowStart- Starting row of the column (inclusive).rowEnd- Ending row of the column (exclusive).- Returns:
- The column at index
colIdxof this matrix between therowStartandrowEndindices. - Throws:
IllegalArgumentException- IfrowEndis less thanrowStart.
-
getDiag
Extracts the diagonal elements of this matrix and returns them as a vector.- Returns:
- A vector containing the diagonal data of this matrix.
-
getDiag
Gets the elements of this matrix along the specified diagonal.- Parameters:
diagOffset- The diagonal to get within this matrix.- If
diagOffset == 0: Then the elements of the principle diagonal are collected. - If
diagOffset < 0: Then the elements of the sub-diagonaldiagOffsetbelow the principle diagonal are collected. - If
diagOffset > 0: Then the elements of the super-diagonaldiagOffsetabove the principle diagonal are collected.
- If
- Returns:
- The elements of the specified diagonal as a vector.
-
tensorDot
Computes the tensor contraction of this tensor with a specified tensor over the specified set of axes. That is, computes the sum of products between the two tensors along the specified set of axes.- Parameters:
src2- Tensor to contract with this tensor.aAxes- Axes along which to compute products for this tensor.bAxes- Axes along which to compute products forsrc2tensor.- Returns:
- The tensor dot product over the specified axes.
- Throws:
IllegalArgumentException- If the two tensors shapes do not match along the specified axes pairwise inaAxesandbAxes.IllegalArgumentException- IfaAxesandbAxesdo not match in length, or if any of the axes are out of bounds for the corresponding tensor.
-
accept
Accepts a visitor that implements theMatrixVisitorinterface. This method is part of the "Visitor Pattern" and allows operations to be performed on the matrix without modifying the matrix's class directly.- Type Parameters:
R- The return type of the visitor's operation.- Parameters:
visitor- The visitor implementing the operation to be performed.- Returns:
- The result of the visitor's operation, typically another matrix or a scalar value.
- Throws:
NullPointerException- if the visitor isnull.
-
dropZeros
Drops any explicit zeros in this sparse COO matrix.- Returns:
- A copy of this Csr matrix with any explicitly stored zeros removed.
-
toString
-