Class CsrMatrix

All Implemented Interfaces:
Serializable, TensorOverField<CsrMatrix,CsrMatrix,double[],Double>, MatrixMixin<CsrMatrix,Matrix,CooVector,Double>, TensorOverRing<CsrMatrix,CsrMatrix,double[],Double>, TensorOverSemiring<CsrMatrix,CsrMatrix,double[],Double>

public class CsrMatrix extends AbstractDoubleTensor<CsrMatrix> implements MatrixMixin<CsrMatrix,Matrix,CooVector,Double>

Instances of this class represent a real sparse matrix using the compressed sparse row (CSR) format. 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.data of length nnz. Any element not specified in data is 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, use dropZeros()
  • Row Pointers: A 1D array rowPointers of length numRows + 1 where rowPointers[i] indicates the starting index in the data and colIndices arrays for row i. The last entry of rowPointers equals the length of data. That is, all non-zero values in data which are in row i are between data[rowIndices[i] (inclusive) and data[rowIndices[i + 1] (exclusive).
  • Column Indices: A 1D array colIndices of length nnz storing the column indices corresponding to each non-zero value in data.

The total number of non-zero elements (nnz) and the shape are fixed for a given instance, but the values in AbstractTensor.data and their corresponding rowPointers and 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 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 coalesce() or 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 toDense().

Usage Examples:


 // Define matrix data.
 Shape shape = new Shape(8, 8);
 double[] data = {1.0, 2.0, 3.0, 4.0};
 int[] rowPointers = {0, 1, 1, 1, 1, 3, 3, 3, 4}
 int[] colIndices = {0, 0, 5, 2};

 // Create CSR matrix.
 CsrMatrix matrix = new CsrMatrix(shape, data, rowPointers, colIndices);

 // Add matrices.
 CsrMatrix sum = matrix.add(matrix);

 // Compute matrix-matrix multiplication.
 Matrix prod = matrix.mult(matrix);
 CsrMatrix sparseProd = matrix.mult2Csr(matrix);

 // Compute matrix-vector multiplication.
 Vector denseVector = new Vector(matrix.numCols, 5.0);
 Matrix matrixVectorProd = matrix.mult(denseVector);
 
See Also:
  • Field Details

    • rowPointers

      public final int[] rowPointers

      Pointers indicating starting index of each row within the colIndices and AbstractTensor.data arrays. Has length numRows + 1.

      The range [data[rowPointers[i]], data[rowPointers[i+1]]) contains all non-zero data within row i.

      Similarly, [colData[rowPointers[i]], colData[rowPointers[i+1]]) contains all column indices for the data in row i.

    • colIndices

      public final int[] colIndices
      Column indices for non-zero values of this sparse CSR matrix.
    • nnz

      public final int nnz
      Number of non-zero data in this CSR matrix.
    • numRows

      public final int numRows
      The number of rows in this matrix.
    • numCols

      public final int numCols
      The number of columns in this matrix.
  • Constructor Details

    • CsrMatrix

      public CsrMatrix(Shape shape, double[] entries, int[] rowPointers, int[] colIndices)
      Creates a sparse CSR matrix with the specified shape, non-zero data, row pointers, and non-zero column indices.
      Parameters:
      shape - Shape of this tensor.
      entries - 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 within data and colData of all values in row i.

      colIndices - Column indices for each non-zero value in this sparse CSR matrix. Must satisfy data.length == colData.length.
      Throws:
      TensorShapeException - If shape.getRank() != 2.
    • CsrMatrix

      public CsrMatrix(int numRows, int numCols, double[] entries, int[] rowPointers, int[] colIndices)
      Creates a sparse CSR matrix with the specified shape, non-zero data, row pointers, and non-zero column indices.
      Parameters:
      numRows - The number of rows in this matrix.
      numCols - The number of columns in this matrix.
      entries - 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 within data and colData of all values in row i.

      colIndices - Column indices for each non-zero value in this sparse CSR matrix. Must satisfy data.length == colData.length.
    • CsrMatrix

      public CsrMatrix(int numRows, int numCols)
      Constructs a zero matrix with the specified shape.
      Parameters:
      numRows - Number of rows in the zero matrix to construct.
      numCols - Number of columns in the zero matrix to construct.
    • CsrMatrix

      public CsrMatrix(Shape shape)
      Constructs zero matrix with the specified shape.
      Parameters:
      shape - Shape of the zero matrix to construct. Must be rank 2.
      Throws:
      TensorShapeException - If shape.getRank() != 2.
  • Method Details

    • dataLength

      public int dataLength()
      Gets the length of the data array which backs this matrix.
      Specified by:
      dataLength in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Returns:
      The length of the data array which backs this matrix.
    • tensorDot

      public Matrix tensorDot(CsrMatrix src2, int[] aAxes, int[] bAxes)
      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.
      Specified by:
      tensorDot in interface TensorOverSemiring<CsrMatrix,CsrMatrix,double[],Double>
      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 for src2 tensor.
      Returns:
      The tensor dot product over the specified axes.
      Throws:
      IllegalArgumentException - If the two tensors shapes do not match along the specified axes pairwise in aAxes and bAxes.
      IllegalArgumentException - If aAxes and bAxes do not match in length, or if any of the axes are out of bounds for the corresponding tensor.
    • tensorTr

      public CooTensor tensorTr(int axis1, int axis2)

      Computes the generalized trace of this tensor along the specified axes.

      The generalized tensor trace is the sum along the diagonal values of the 2D sub-arrays of this tensor specified by axis1 and axis2. The shape of the resulting tensor is equal to this tensor with the axis1 and axis2 removed.

      Specified by:
      tensorTr in interface TensorOverSemiring<CsrMatrix,CsrMatrix,double[],Double>
      Parameters:
      axis1 - First axis for 2D sub-array.
      axis2 - Second axis for 2D sub-array.
      Returns:
      The generalized trace of this tensor along axis1 and axis2.
      Throws:
      IndexOutOfBoundsException - If the two axes are not both larger than zero and less than this tensors rank.
      IllegalArgumentException - If axis1 == axis2 or this.shape.get(axis1) != this.shape.get(axis1) (i.e. the axes are equal or the tensor does not have the same length along the two axes.)
    • set

      public CsrMatrix set(Double value, int... indices)
      Sets the element of this tensor at the specified indices.
      Specified by:
      set in class AbstractTensor<CsrMatrix,double[],Double>
      Parameters:
      value - New value to set the specified index of this tensor to.
      indices - Indices of the element to set.
      Returns:
      A copy of this tensor with the updated value is returned.
      Throws:
      IndexOutOfBoundsException - If indices is not within the bounds of this tensor.
    • flatten

      public CsrMatrix flatten()
      Flattens tensor to single dimension while preserving order of data.
      Specified by:
      flatten in class AbstractTensor<CsrMatrix,double[],Double>
      Returns:
      The flattened tensor.
      See Also:
    • flatten

      public CsrMatrix flatten(int axis)
      Flattens a tensor along the specified axis.
      Specified by:
      flatten in class AbstractTensor<CsrMatrix,double[],Double>
      Parameters:
      axis - Axis along which to flatten tensor.
      Throws:
      ArrayIndexOutOfBoundsException - If the axis is not positive or larger than this.{@link #getRank()}-1.
      See Also:
    • reshape

      public CsrMatrix reshape(Shape newShape)
      Copies and reshapes this tensor.
      Specified by:
      reshape in class AbstractTensor<CsrMatrix,double[],Double>
      Parameters:
      newShape - New shape for the tensor.
      Returns:
      A copy of this tensor with the new shape.
      Throws:
      TensorShapeException - If newShape is not broadcastable to this.shape.
    • get

      public Double get(int... indices)
      Gets the element of this tensor at the specified indices.
      Specified by:
      get in class AbstractTensor<CsrMatrix,double[],Double>
      Parameters:
      indices - Indices of the element to get.
      Returns:
      The element of this tensor at the specified indices.
      Throws:
      ArrayIndexOutOfBoundsException - If any indices are not within this matrix.
    • makeLikeTensor

      public CsrMatrix makeLikeTensor(Shape shape, double[] entries)
      Constructs a CSR matrix of the same type as this matrix with the given the shape and data and the same row pointers and column indices as this matrix.
      Specified by:
      makeLikeTensor in interface TensorOverSemiring<CsrMatrix,CsrMatrix,double[],Double>
      Specified by:
      makeLikeTensor in class AbstractTensor<CsrMatrix,double[],Double>
      Parameters:
      shape - Shape of the tensor to construct.
      entries - Entries of the tensor to construct.
      Returns:
      A CSR matrix of the same type as this matrix with the given the shape and data and the same row pointers and column indices as this matrix.
    • T

      public CsrMatrix T(int axis1, int axis2)
      Computes the transpose of a tensor by exchanging axis1 and axis2.
      Specified by:
      T in class AbstractTensor<CsrMatrix,double[],Double>
      Parameters:
      axis1 - First axis to exchange.
      axis2 - Second axis to exchange.
      Returns:
      The transpose of this tensor according to the specified axes.
      Throws:
      IndexOutOfBoundsException - If either axis1 or axis2 are out of bounds for the rank of this tensor.
      See Also:
    • T

      public CsrMatrix T(int... axes)
      Computes the transpose of this tensor. That is, permutes the axes of this tensor so that it matches the permutation specified by axes.
      Specified by:
      T in class AbstractTensor<CsrMatrix,double[],Double>
      Parameters:
      axes - Permutation of tensor axis. If the tensor has rank N, then this must be an array of length N which is a permutation of {0, 1, 2, ..., N-1}.
      Returns:
      The transpose of this tensor with its axes permuted by the axes array.
      Throws:
      IndexOutOfBoundsException - If any element of axes is out of bounds for the rank of this tensor.
      IllegalArgumentException - If axes is not a permutation of {1, 2, 3, ... N-1}.
      See Also:
    • sparsity

      public double sparsity()
      The sparsity of this sparse CSR matrix. That is, the decimal percentage of elements in this matrix which are zero.
      Returns:
      The density of this sparse matrix.
    • toDense

      public Matrix toDense()
      Converts this sparse CSR matrix to an equivalent dense matrix.
      Returns:
      A dense matrix equivalent to this sparse CSR matrix.
    • toCoo

      public CooMatrix toCoo()
      Converts this CSR matrix to an equivalent COO matrix.
      Returns:
      A COO matrix equivalent to this matrix.
    • sortIndices

      public void sortIndices()
      Sorts the indices of this tensor in lexicographical order while maintaining the associated value for each index.
    • numRows

      public int numRows()
      Gets the number of rows in this matrix.
      Specified by:
      numRows in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Returns:
      The number of rows in this matrix.
    • numCols

      public int numCols()
      Gets the number of columns in this matrix.
      Specified by:
      numCols in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Returns:
      The number of columns in this matrix.
    • get

      public Double get(int row, int col)
      Gets the element of this matrix at this specified row and col.
      Specified by:
      get in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Parameters:
      row - Row index of the item to get from this matrix.
      col - Column index of the item to get from this matrix.
      Returns:
      The element of this matrix at the specified index.
    • tr

      public Double tr()

      Computes the trace of this matrix. That is, the sum of elements along the principle diagonal of this matrix.

      Same as MatrixMixin.trace().

      Specified by:
      tr in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Returns:
      The trace of this matrix.
      Throws:
      IllegalArgumentException - If this matrix is not square.
    • isTriU

      public boolean isTriU()
      Checks if this matrix is upper triangular.
      Specified by:
      isTriU in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Returns:
      true is this matrix is upper triangular; false otherwise.
      See Also:
    • isTriL

      public boolean isTriL()
      Checks if this matrix is lower triangular.
      Specified by:
      isTriL in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Returns:
      true is this matrix is lower triangular; false otherwise.
      See Also:
    • isI

      public boolean isI()
      Checks if this matrix is the identity matrix. That is, checks if this matrix is square and contains only ones along the principle diagonal and zeros everywhere else.
      Specified by:
      isI in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Returns:
      true if this matrix is the identity matrix; false otherwise.
      See Also:
    • isCloseToI

      public boolean isCloseToI()
      Checks that this matrix is close to the identity matrix.
      Returns:
      True if this matrix is approximately the identity matrix.
      See Also:
    • det

      public Double det()

      Computes the determinant of a square matrix.

      WARNING: This method will convert the matrix to a dense matrix in order to compute the determinant.

      Returns:
      The determinant of this matrix.
      Throws:
      LinearAlgebraException - If this matrix is not square.
    • mult

      public Matrix mult(CsrMatrix b)
      Computes the matrix multiplication between two matrices.
      Specified by:
      mult in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Parameters:
      b - Second matrix in the matrix multiplication.
      Returns:
      The result of matrix multiplying this matrix with matrix b.
      Throws:
      LinearAlgebraException - If the number of columns in this matrix do not equal the number of rows in matrix b.
    • mult2Csr

      public CsrCMatrix mult2Csr(CsrCMatrix b)

      Computes the matrix multiplication between two sparse CSR matrices and stores the result in a CSR matrix.

      Warning: This method will likely be slower than mult(CsrMatrix) if the result of multiplying this matrix with b is not very sparse. Further, multiplying two sparse matrices may result in a dense matrix so this method should be used with caution.

      Parameters:
      b - Matrix to multiply to this matrix.
      Returns:
      The result of matrix multiplying this matrix with b as a sparse CSR matrix.
    • mult2Csr

      public CsrMatrix mult2Csr(CsrMatrix b)

      Computes the matrix multiplication between two sparse CSR matrices and stores the result in a CSR matrix.

      Warning: This method will likely be slower than mult(CsrMatrix) if the result of multiplying this matrix with b is not very sparse. Further, multiplying two sparse matrices may result in a dense matrix so this method should be used with caution.

      Parameters:
      b - Matrix to multiply to this matrix.
      Returns:
      The result of matrix multiplying this matrix with b as a sparse CSR matrix.
    • mult

      public CMatrix mult(CsrCMatrix b)
      Computes the matrix multiplication between two matrices.
      Parameters:
      b - Second matrix in the matrix multiplication.
      Returns:
      The result of matrix multiplying this matrix with matrix b.
      Throws:
      LinearAlgebraException - If the number of columns in this matrix do not equal the number of rows in matrix b.
    • multTranspose

      public Matrix multTranspose(CsrMatrix b)
      Multiplies this matrix with the transpose of the b tensor as if by this.mult(b.T()). For large matrices, this method may be significantly faster than directly computing the transpose followed by the multiplication as this.mult(b.T()).
      Specified by:
      multTranspose in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Parameters:
      b - The second matrix in the multiplication and the matrix to transpose.
      Returns:
      The result of multiplying this matrix with the transpose of b.
    • fib

      public Double fib(CsrMatrix b)
      Computes the Frobenius inner product of two matrices.
      Specified by:
      fib in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Parameters:
      b - Second matrix in the Frobenius inner product
      Returns:
      The Frobenius inner product of this matrix and matrix b.
      Throws:
      IllegalArgumentException - If this matrix and b have different shapes.
    • stack

      public CsrMatrix stack(CsrMatrix b)
      Stacks matrices along columns.
      Specified by:
      stack in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Parameters:
      b - Matrix to stack to this matrix.
      Returns:
      The result of stacking this matrix on top of the matrix b.
      Throws:
      IllegalArgumentException - If this matrix and matrix b have a different number of columns.
      See Also:
    • augment

      public CsrMatrix augment(CsrMatrix b)
      Stacks matrices along rows.
      Specified by:
      augment in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Parameters:
      b - Matrix to stack to this matrix.
      Returns:
      The result of stacking b to the right of this matrix.
      Throws:
      IllegalArgumentException - If this matrix and matrix b have a different number of rows.
      See Also:
    • augment

      public CsrMatrix augment(CooVector b)
      Augments a vector to this matrix.
      Specified by:
      augment in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Parameters:
      b - The vector to augment to this matrix.
      Returns:
      The result of augmenting b to this matrix.
    • swapRows

      public CsrMatrix swapRows(int rowIndex1, int rowIndex2)
      Swaps specified rows in the matrix. This is done in place.
      Specified by:
      swapRows in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Parameters:
      rowIndex1 - Index of the first row to swap.
      rowIndex2 - Index of the second row to swap.
      Returns:
      A reference to this matrix.
      Throws:
      ArrayIndexOutOfBoundsException - If either index is outside the matrix bounds.
    • swapCols

      public CsrMatrix swapCols(int colIndex1, int colIndex2)
      Swaps specified columns in the matrix. This is done in place.
      Specified by:
      swapCols in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Parameters:
      colIndex1 - Index of the first column to swap.
      colIndex2 - Index of the second column to swap.
      Returns:
      A reference to this matrix.
      Throws:
      ArrayIndexOutOfBoundsException - If either index is outside the matrix bounds.
    • isSymmetric

      public boolean isSymmetric()
      Checks if a matrix is symmetric. That is, if the matrix is square and equal to its transpose.
      Specified by:
      isSymmetric in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Returns:
      true if this matrix is symmetric; false otherwise.
      See Also:
    • isHermitian

      public boolean isHermitian()
      Checks if a matrix is Hermitian. That is, if the matrix is square and equal to its conjugate transpose.
      Specified by:
      isHermitian in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Returns:
      true if this matrix is Hermitian; false otherwise.
    • isAntiSymmetric

      public boolean isAntiSymmetric()
      Checks if a matrix is anti-symmetric. That is, if the matrix is equal to the negative of its transpose.
      Returns:
      true if this matrix is anti-symmetric; false otherwise.
      See Also:
    • isOrthogonal

      public boolean isOrthogonal()
      Checks if this matrix is orthogonal. That is, if the inverse of this matrix is equal to its transpose.
      Specified by:
      isOrthogonal in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Returns:
      true if this matrix it is orthogonal; false otherwise.
    • removeRow

      public CsrMatrix removeRow(int rowIndex)
      Removes a specified row from this matrix.
      Specified by:
      removeRow in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Parameters:
      rowIndex - Index of the row to remove from this matrix.
      Returns:
      A copy of this matrix with the specified row removed.
    • removeRows

      public CsrMatrix removeRows(int... rowIndices)
      Removes a specified set of rows from this matrix.
      Specified by:
      removeRows in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Parameters:
      rowIndices - The indices of the rows to remove from this matrix. Assumed to contain unique values.
      Returns:
      a copy of this matrix with the specified column removed.
    • removeCol

      public CsrMatrix removeCol(int colIndex)
      Removes a specified column from this matrix.
      Specified by:
      removeCol in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Parameters:
      colIndex - Index of the column to remove from this matrix.
      Returns:
      a copy of this matrix with the specified column removed.
    • removeCols

      public CsrMatrix removeCols(int... colIndices)
      Removes a specified set of columns from this matrix.
      Specified by:
      removeCols in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Parameters:
      colIndices - Indices of the columns to remove from this matrix. Assumed to contain unique values.
      Returns:
      a copy of this matrix with the specified column removed.
    • setSliceCopy

      public CsrMatrix setSliceCopy(CsrMatrix values, int rowStart, int colStart)
      Creates a copy of this matrix and sets a slice of the copy to the specified values. The rowStart and colStart parameters specify the upper left index location of the slice to set.
      Specified by:
      setSliceCopy in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Parameters:
      values - New values for the specified slice.
      rowStart - Starting row index for the slice (inclusive).
      colStart - Starting column index for the slice (inclusive).
      Returns:
      A copy of this matrix with the given slice set to the specified values.
      Throws:
      IndexOutOfBoundsException - If rowStart or colStart are not within the matrix.
      IllegalArgumentException - If the values slice, with upper left corner at the specified location, does not fit completely within this matrix.
    • getSlice

      public CsrMatrix getSlice(int rowStart, int rowEnd, int colStart, int colEnd)
      Gets a specified slice of this matrix.
      Specified by:
      getSlice in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Parameters:
      rowStart - Starting row index of slice (inclusive).
      rowEnd - Ending row index of slice (exclusive).
      colStart - Starting column index of slice (inclusive).
      colEnd - Ending row index of slice (exclusive).
      Returns:
      The specified slice of this matrix. This is a completely new matrix and NOT a view into the matrix.
      Throws:
      ArrayIndexOutOfBoundsException - If any of the indices are out of bounds of this matrix.
      IllegalArgumentException - If rowEnd is not greater than rowStart or if colEnd is not greater than colStart.
    • set

      public CsrMatrix set(Double value, int row, int col)
      Sets an index of this matrix to the specified value.
      Specified by:
      set in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Parameters:
      value - Value to set.
      row - Row index to set.
      col - Column index to set.
      Returns:
      A reference to this matrix.
    • getTriU

      public CsrMatrix getTriU(int diagOffset)
      Extracts the upper-triangular portion of this matrix with a specified diagonal offset. All other data of the resulting matrix will be zero.
      Specified by:
      getTriU in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Parameters:
      diagOffset - Diagonal offset for upper-triangular portion to extract:
      • If zero, then all data at and above the principle diagonal of this matrix are extracted.
      • If positive, then all data at and above the equivalent super-diagonal are extracted.
      • If negative, then all data at and above the equivalent sub-diagonal are extracted.
      Returns:
      The upper-triangular portion of this matrix with a specified diagonal offset. All other data of the returned matrix will be zero.
      Throws:
      IllegalArgumentException - If diagOffset is not in the range (-numRows, numCols).
    • getTriL

      public CsrMatrix getTriL(int diagOffset)
      Extracts the lower-triangular portion of this matrix with a specified diagonal offset. All other data of the resulting matrix will be zero.
      Specified by:
      getTriL in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Parameters:
      diagOffset - Diagonal offset for lower-triangular portion to extract:
      • If zero, then all data at and above the principle diagonal of this matrix are extracted.
      • If positive, then all data at and above the equivalent super-diagonal are extracted.
      • If negative, then all data at and above the equivalent sub-diagonal are extracted.
      Returns:
      The lower-triangular portion of this matrix with a specified diagonal offset. All other data of the returned matrix will be zero.
      Throws:
      IllegalArgumentException - If diagOffset is not in the range (-numRows, numCols).
    • mult

      public Vector mult(CooVector b)
      Computes matrix-vector multiplication.
      Specified by:
      mult in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Parameters:
      b - Vector in the matrix-vector multiplication.
      Returns:
      The result of matrix multiplying this matrix with vector b.
      Throws:
      IllegalArgumentException - If the number of columns in this matrix do not equal the number of data in the vector b.
    • toVector

      public CooVector 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:
      toVector in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Returns:
      A vector equivalent to this matrix.
    • toTensor

      public CooTensor toTensor()
      Converts this sparse CSR matrix to an equivalent sparse COO tensor.
      Returns:
    • getRow

      public CooVector getRow(int rowIdx)
      Get the row of this matrix at the specified index.
      Specified by:
      getRow in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Parameters:
      rowIdx - Index of row to get.
      Returns:
      The specified row of this matrix.
      Throws:
      ArrayIndexOutOfBoundsException - If rowIdx is less than zero or greater than/equal to the number of rows in this matrix.
    • getRow

      public CooVector getRow(int rowIdx, int colStart, int colEnd)
      Gets a specified row of this matrix between colStart (inclusive) and colEnd (exclusive).
      Specified by:
      getRow in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      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 rowIdx of this matrix between the colStart and colEnd indices.
      Throws:
      IndexOutOfBoundsException - If either colEnd are colStart out of bounds for the shape of this matrix.
      IllegalArgumentException - If colEnd is less than colStart.
    • getCol

      public CooVector getCol(int colIdx)
      Get the column of this matrix at the specified index.
      Specified by:
      getCol in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Parameters:
      colIdx - Index of column to get.
      Returns:
      The specified column of this matrix.
      Throws:
      ArrayIndexOutOfBoundsException - If colIdx is less than zero or greater than/equal to the number of columns in this matrix.
    • getCol

      public CooVector getCol(int colIdx, int rowStart, int rowEnd)
      Gets a specified column of this matrix between rowStart (inclusive) and rowEnd (exclusive).
      Specified by:
      getCol in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      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 colIdx of this matrix between the rowStart and rowEnd indices.
      Throws:
      IllegalArgumentException - If rowEnd is less than rowStart.
    • getDiag

      public CooVector getDiag()
      Extracts the diagonal elements of this matrix and returns them as a vector.
      Specified by:
      getDiag in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Returns:
      A vector containing the diagonal data of this matrix.
    • getDiag

      public CooVector getDiag(int diagOffset)
      Gets the elements of this matrix along the specified diagonal.
      Specified by:
      getDiag in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      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-diagonal diagOffset below the principle diagonal are collected.
      • If diagOffset > 0: Then the elements of the super-diagonal diagOffset above the principle diagonal are collected.
      Returns:
      The elements of the specified diagonal as a vector.
    • setCol

      public CsrMatrix setCol(CooVector values, int colIndex)
      Sets a column of this matrix at the given index to the specified values.
      Specified by:
      setCol in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Parameters:
      values - New values for the column.
      colIndex - The index of the column which is to be set.
      Returns:
      A reference to this matrix.
      Throws:
      IndexOutOfBoundsException - If the values vector has a different length than the number of rows of this matrix.
    • setRow

      public CsrMatrix setRow(CooVector values, int rowIndex)
      Sets a row of this matrix at the given index to the specified values.
      Specified by:
      setRow in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Parameters:
      values - New values for the row.
      rowIndex - The index of the row which is to be set.
      Returns:
      A reference to this matrix.
      Throws:
      IndexOutOfBoundsException - If the values vector has a different length than the number of rows of this matrix.
    • T

      public CsrMatrix T()
      Computes the transpose of a tensor by exchanging the first and last axes of this tensor.
      Specified by:
      T in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Overrides:
      T in class AbstractTensor<CsrMatrix,double[],Double>
      Returns:
      The transpose of this tensor.
      See Also:
    • accept

      public <R> R accept(MatrixVisitor<R> visitor)
      Accepts a visitor that implements the MatrixVisitor interface. This method is part of the "Visitor Pattern" and allows operations to be performed on the matrix without modifying the matrix's class directly.
      Specified by:
      accept in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      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 is null.
    • equals

      public boolean equals(Object object)
      Checks if an object is equal to this matrix object.
      Overrides:
      equals in class Object
      Parameters:
      object - Object to check equality with this matrix.
      Returns:
      True if the two matrices have the same shape, are numerically equivalent, and are of type CooMatrix. False otherwise.
    • hashCode

      public int hashCode()
      Overrides:
      hashCode in class Object
    • mult

      public Matrix mult(Matrix b)
      Multiplies this sparse CSR matrix with a real dense matrix.
      Parameters:
      b - The real dense matrix in the matrix-matrix product.
      Returns:
      Computes the matrix product of this matrix and b.
      Throws:
      IllegalArgumentException - If this.numCols != b.numRows.
    • mult

      public CMatrix mult(CMatrix B)
      Computes the matrix multiplication between two matrices.
      Parameters:
      B - Second matrix in the matrix multiplication.
      Returns:
      The result of matrix multiplying this matrix with matrix B.
      Throws:
      IllegalArgumentException - If the number of columns in this matrix do not equal the number of rows in matrix B.
    • add

      public CsrMatrix add(CsrMatrix b)
      Computes the element-wise sum between two tensors of the same shape.
      Specified by:
      add in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Specified by:
      add in interface TensorOverSemiring<CsrMatrix,CsrMatrix,double[],Double>
      Parameters:
      b - Second tensor in the element-wise sum.
      Returns:
      The sum of this tensor with b.
      Throws:
      IllegalArgumentException - If this tensor and b do not have the same shape.
    • elemMult

      public CsrMatrix elemMult(CsrMatrix b)
      Computes the element-wise multiplication of two tensors of the same shape.
      Specified by:
      elemMult in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Specified by:
      elemMult in interface TensorOverSemiring<CsrMatrix,CsrMatrix,double[],Double>
      Parameters:
      b - Second tensor in the element-wise product.
      Returns:
      The element-wise product between this tensor and b.
      Throws:
      IllegalArgumentException - If this tensor and b do not have the same shape.
    • sub

      public CsrMatrix sub(CsrMatrix b)
      Computes the element-wise difference between two tensors of the same shape.
      Specified by:
      sub in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Specified by:
      sub in interface TensorOverRing<CsrMatrix,CsrMatrix,double[],Double>
      Parameters:
      b - Second tensor in the element-wise difference.
      Returns:
      The difference of this tensor with b.
      Throws:
      IllegalArgumentException - If this tensor and b do not have the same shape.
    • H

      public CsrMatrix H()
      Computes the conjugate transpose of a tensor by exchanging the first and last axes of this tensor and conjugating the exchanged values.
      Specified by:
      H in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Specified by:
      H in interface TensorOverRing<CsrMatrix,CsrMatrix,double[],Double>
      Returns:
      The conjugate transpose of this tensor.
      See Also:
    • argmin

      public int[] argmin()
      Finds the indices of the minimum value in this tensor.
      Specified by:
      argmin in interface TensorOverRing<CsrMatrix,CsrMatrix,double[],Double>
      Returns:
      The indices of the minimum value in this tensor. If this value occurs multiple times, the indices of the first entry (in row-major ordering) are returned.
    • argmax

      public int[] argmax()
      Finds the indices of the maximum value in this tensor.
      Specified by:
      argmax in interface TensorOverRing<CsrMatrix,CsrMatrix,double[],Double>
      Returns:
      The indices of the maximum value in this tensor. If this value occurs multiple times, the indices of the first entry (in row-major ordering) are returned.
    • argminAbs

      public int[] argminAbs()
      Finds the indices of the minimum absolute value in this tensor.
      Specified by:
      argminAbs in interface TensorOverRing<CsrMatrix,CsrMatrix,double[],Double>
      Returns:
      The indices of the minimum absolute value in this tensor. If this value occurs multiple times, the indices of the first entry (in row-major ordering) are returned.
    • argmaxAbs

      public int[] argmaxAbs()
      Finds the indices of the maximum absolute value in this tensor.
      Specified by:
      argmaxAbs in interface TensorOverRing<CsrMatrix,CsrMatrix,double[],Double>
      Returns:
      The indices of the maximum absolute value in this tensor. If this value occurs multiple times, the indices of the first entry (in row-major ordering) are returned.
    • add

      public CsrCMatrix add(Complex128 b)
      Adds a complex-valued scalar to all non-zero data of this sparse matrix.
      Parameters:
      b - scalar to add.
      Returns:
      The result of adding this matrix to b.
    • sub

      public CsrCMatrix sub(Complex128 b)
      Subtracts a complex-valued scalar from all non-zero data of this sparse matrix.
      Parameters:
      b - scalar to subtract.
      Returns:
      The result of subtracting b from this matrix's non-zero data.
    • div

      public CsrMatrix div(CsrMatrix b)

      Computes the element-wise quotient between two tensors.

      Warning: This method is not supported for sparse matrices. If called on a sparse matrix, an UnsupportedOperationException will be thrown as the operation would almost certainly result in a division by zero.

      Specified by:
      div in interface MatrixMixin<CsrMatrix,Matrix,CooVector,Double>
      Specified by:
      div in interface TensorOverField<CsrMatrix,CsrMatrix,double[],Double>
      Parameters:
      b - Second tensor in the element-wise quotient.
      Returns:
      The element-wise quotient of this tensor with b.
    • dropZeros

      public CsrMatrix dropZeros()
      Drops any explicit zeros in this sparse COO matrix.
      Returns:
      A copy of this Csr matrix with any explicitly stored zeros removed.
    • coalesce

      public CsrMatrix coalesce()
      Coalesces this sparse CSR matrix. An uncoalesced matrix is a sparse matrix with multiple data for a single index. This method will ensure that each index only has one non-zero value by summing duplicated data. If another form of aggregation other than summing is desired, use coalesce(BinaryOperator).
      Returns:
      A new coalesced sparse CSR matrix which is equivalent to this CSR matrix.
      See Also:
    • coalesce

      public CsrMatrix coalesce(BinaryOperator<Double> aggregator)
      Coalesces this sparse COO matrix. An uncoalesced matrix is a sparse matrix with multiple data for a single index. This method will ensure that each index only has one non-zero value by aggregating duplicated data using aggregator.
      Parameters:
      aggregator - Custom aggregation function to combine multiple.
      Returns:
      A new coalesced sparse COO matrix which is equivalent to this COO matrix.
      See Also:
    • toString

      public String toString()
      Formats this sparse matrix as a human-readable string.
      Overrides:
      toString in class Object
      Returns:
      A human-readable string representing this sparse matrix.