finesse.cymath.cmatrix module
Sparse matrix objects with factorisation and solving routines performed via KLU.
- class finesse.cymath.cmatrix.CCSMatrix(name)[source]
Bases:
object- clear_rhs(self, unsigned int rhs_index=0)[source]
Zero all elements in the rhs vector corresponding to rhs_index.
Parameters
- rhs_indexunsigned, optional
The rhs vector to clear; defaults to 0
- construct(self, double complex diagonal_fill=complex(1, 0))[source]
Constructing the matrix involves taking the metadata submatrix positions throughout the matrix and allocating the memory and building the various CCS matrix structures. After this the matrix can be populated and solved.
Parameters
- diagonal_fillcomplex_t, optional
Value to fill the diagonal of the matrix with; defaults to 1+0j
- declare_equations(self, SuiteSparse_long Neqs, SuiteSparse_long index, str name, is_diagonal=True, add_view=True)[source]
This defines generally what equations exist in the matrix. It essentially defines the order of the RHS vector for which equations map to what index.
This method decalres a group of Neqs equations at once which form a “block” or submatrix within the matrix itself. This block can be referenced by the unique index provided.
When adding this block of equations a view of the diagonal of the matrix can also be added and returned if required. By default it will.
Parameters
- NeqsPy_ssize_t
Number of equations this submatrix represents
- indexlong
Subcolumn index
- nameunicode
Name used to indentify this coupling in the matrix for debugging
- is_diagonalbool, optional
If true, the view created and returned is a diagonal submatrix. If False, the view will be a dense submatrix.
- add_viewbool, optional
If True, a submatrix view will be added to the matrix so that the diagonal submatrix for these elements is available for altering the values automatically.
Returns
- viewSubCCSMatrixView
If add_view == True, a view of the diagonal submatrix for these elements will be returned.
- declare_subdiagonal_view(self, Py_ssize_t from_node, Py_ssize_t to_node, str name, bool conjugate_fill)[source]
- declare_submatrix_view(self, Py_ssize_t from_node, Py_ssize_t to_node, str name, bool conjugate_fill)[source]
- factor(self)[source]
Factors the matrix.
This method is not yet implemented.
Raises
- NotImplementedError
Always, as this method is not yet implemented.
- get_matrix_elements(self)[source]
Returns the sparse CCS format for the current state of this matrix.
Returns
- datalist[complex]
Value of each non-zero element
- rowslist[complex]
Row index of each non-zero element
- colslist[complex]
Column index of each non-zero element
- get_rhs_view(self, unsigned int index) double complex[::1]
Returns a view of the rhs vector corresponding to index.
Parameters
- indexunsigned
The rhs vector to return a view of
- matrix_to_str(self, bool round_values: bool = False) str[source]
Creates a string representation of the non-zero elements in the matrix
- print_matrix(self, bool round_values: bool = False)[source]
Print a view of the non-zero elements in this matrix.
- print_rhs(self, unsigned int rhs_index=0, bool round_values: bool = False)[source]
Print a view of the rhs vector corresponding to rhs_index.
Parameters
- rhs_indexunsigned, optional
The rhs vector to print; defaults to 0
- refactor(self)[source]
Refactors the matrix.
This method is not yet implemented.
Raises
- NotImplementedError
Always, as this method is not yet implemented.
- rhs_to_string(self, unsigned int rhs_index=0, bool round_values: bool = False) str[source]
Create a string representation of the rhs vector corresponding to rhs_index.
Parameters
- rhs_indexunsigned, optional
The rhs vector to print; defaults to 0
Returns
- str
RHS vector
- rhs_view
- set_rhs(self, SuiteSparse_long index, double complex value, unsigned int rhs_index=0)[source]
Sets the value of the entry at position index of the rhs_index`th right-hand-side vector to `value.
Parameters
- indexlong
The index in the rhs vector to set
- valuecomplex_t
The value to set
- rhs_indexunsigned, optional
Which rhs vector to change; defaults to 0
- solve(self, int transpose=False, bool conjugate=False, unsigned int rhs_index=0) const double complex[::1]
Solves the matrix equation.
This method is not yet implemented.
Parameters
- transposeint, optional
Whether to transpose the matrix before solving, by default False.
- conjugatebint, optional
Whether to conjugate the matrix before solving, by default False.
- rhs_indexunsigned, optional
The index of the right-hand side to solve for, by default 0.
Raises
- NotImplementedError
Always, as this method is not yet implemented.
Returns
- complex_t[::1]
The solution to the matrix equation.
- solve_extra_rhs(self, int transpose=False, bool conjugate=False) void
Solves the matrix equation for extra right-hand sides.
This method is not yet implemented.
Parameters
- transposeint, optional
Whether to transpose the matrix before solving, by default False.
- conjugatebint, optional
Whether to conjugate the matrix before solving, by default False.
Raises
- NotImplementedError
Always, as this method is not yet implemented.
- sub_columns
- to_scipy_coo(self)[source]
Converts the current matrix to a scipy COO (Coordinate) sparse matrix.
This method retrieves the matrix elements using the get_matrix_elements method and then uses these elements to create a scipy COO sparse matrix.
Returns
- coo_matrix
The scipy COO sparse matrix representation of the current matrix.
- to_scipy_csc(self)[source]
Converts the current matrix to a scipy CSC (Compressed Sparse Column) sparse matrix.
This method retrieves the matrix elements using the get_matrix_elements method and then uses these elements to create a scipy CSC sparse matrix.
Returns
- csc_matrix
The scipy CSC sparse matrix representation of the current matrix.
- to_scipy_csr(self)[source]
Converts the current matrix to a scipy CSR (Compressed Sparse Row) sparse matrix.
This method retrieves the matrix elements using the get_matrix_elements method and then uses these elements to create a scipy CSR sparse matrix.
Returns
- csr_matrix
The scipy CSR sparse matrix representation of the current matrix.
- class finesse.cymath.cmatrix.KLUMatrix(name, klu_ordering=0, *, klu_scale=2, klu_btf=1, klu_maxwork=0, double tol=1e-3)[source]
Bases:
CCSMatrixAn object representation of a CCS matrix with methods to factor and solve the matrix via KLU.
Parameters
- nameunicode
The name of the matrix.
- klu_orderingint, optional
The ordering method to use in KLU, by default 0.
- klu_scaleint, optional
The scaling method to use in KLU, by default 2.
- klu_btfint, optional
Whether to use BTF preordering in KLU, by default 1.
- klu_maxworkint, optional
The maximum amount of work to do in KLU, by default 0.
- tolfloat, optional
The tolerance to use in KLU for partial pivotting, by default 1e-3.
- condest(self) double
klu_condest
Computes a reasonably accurate estimate of the 1-norm condition number, using Hager’s method, as modified by Higham and Tisseur (same method as used in MATLAB’s condest)
- factor(self)[source]
Factor the matrix using KLU.
This method first analyzes the matrix structure using klu_l_analyze, then factors the matrix using klu_zl_factor, and finally sorts the factorization using klu_zl_sort.
Raises
- Exception
If an error occurs in KLU during analysis, factoring, or sorting, an exception is raised with a message indicating the status code and its corresponding string.
- rcond(self) double
klu_rcond: compute min(abs(diag(U))) / max(abs(diag(U)))
This function returns the smallest diagonal entry of U divided by the largest, which is a very crude estimate of the reciprocal of the condition number of the matrix A. It is very cheap to compute, however. In MATLAB notation, rcond = min(abs(diag(U))) / max(abs(diag(U))). If the matrix is singular, rcond will be zero.
- refactor(self)[source]
Refactor the matrix using KLU.
This method attempts to refactor the matrix using klu_zl_refactor. If the refactorization is not successful and the matrix appears singular (status code 1), it tries to factor the matrix again using the factor method. If the matrix is still not factorizable, an exception is raised.
Raises
- RuntimeError
If an error occurs in KLU during refactorization and the matrix does not appear singular, a runtime error is raised with a message indicating the status code and its corresponding string.
- rgrowth(self) double
klu_rgrowth : compute the reciprocal pivot growth
Pivot growth is computed after the input matrix is permuted, scaled, and off-diagonal entries pruned. This is because the LU factorization of each block takes as input the scaled diagonal blocks of the BTF form. The reciprocal pivot growth in column j of an LU factorization of a matrix C is the largest entry in C divided by the largest entry in U; then the overall reciprocal pivot growth is the smallest such value for all columns j. Note that the off-diagonal entries are not scaled, since they do not take part in the LU factorization of the diagonal blocks.
- In MATLAB notation:
rgrowth = min (max (abs ((R A(p,q)) - F)) ./ max (abs (U)))
Returns
reciprocal_pivot_growth : double
- solve(self, int transpose=False, bool conjugate=False, unsigned int rhs_index=0) const double complex[::1]
Solve the matrix with options for transposing and conjugating.
If transpose is False, solves the linear system \(Ax = b\) using the
SymbolicandNumericobjects stored by this class.Otherwise, solves the linear system \(A^T x = b\) or \(A^H x = b\). The conjugate option is zero for \(A^T x = b\) or non-zero for \(A^H x = b\).
Parameters
- transposebool
Flag determining whether to solve the transpose of the matrix.
- conjugatebool
Flag determining whether to solve \(A^T x =b\) or \(A^H x = b\) for the transposed linear system.
- rhs_indexunsigned, optional
Which rhs vector to solve for. If unset, the default rhs vector is used.
Returns
- outnp.ndarray
The (negative) solution vector.
- solve_extra_rhs(self, int transpose=False, bool conjugate=False) void
Solve the matrix for all present rhs vectors except the main one, with options for transposing and conjugating.
If transpose is False, solves the linear system \(Ax = b\) using the
SymbolicandNumericobjects stored by this class.Otherwise, solves the linear system \(A^T x = b\) or \(A^H x = b\). The conjugate option is zero for \(A^T x = b\) or non-zero for \(A^H x = b\).
As multiple rhs vectors are solved simultaneously, the result is not returned here, and must be retrieved via
get_rhs_view.Parameters
- transposebool
Flag determining whether to solve the transpose of the matrix.
- conjugatebool
Flag determining whether to solve \(A^T x =b\) or \(A^H x = b\) for the transposed linear system.
- zgemv(self, double complex[: :1] out, unsigned int rhs_index=0) void
Multiply this matrix with the rhs vector corresponding to rhs_index, and store the result in out.
Performs the operation \(y = A x\).
Parameters
- outcomplex_t[::1]
The vector to store the result in.
- rhs_indexunsigned, optional
The rhs vector to multiply this matrix with; defaults to 0.
- class finesse.cymath.cmatrix.SubCCSMatrixView[source]
Bases:
SubCCSViewThis class represents a sub-matrix view of a CCS sparse matrix. This allows code to access and set values without worrying about the underlying sparse compression being used. Although so far this is just for CCS formats.
This object will get a view of a n-by-m sub-matrix starting at index (i,j). The values of his matrix will be set initially to the coordinates.
- class finesse.cymath.cmatrix.SubCCSMatrixViewDiagonal[source]
Bases:
SubCCSViewThis class represents a sub-matrix view of a CCS sparse matrix. This allows code to access and set values without worrying about the underlying sparse compression being used. Although so far this is just for CCS formats.
This object will get a view of a n-by-m sub-matrix starting at index (i,j). The values of his matrix will be set initially to the coordinates.
- class finesse.cymath.cmatrix.SubCCSView(CCSMatrix Matrix, Py_ssize_t _from, Py_ssize_t _to, str name, bool conjugate_fill)[source]
Bases:
objectAn abstract class representing common features between dense and sparse diagonal structured sub-matrices.
This class serves as a base class for other classes that represent specific types of sub-matrices, such as dense or sparse diagonal structured sub-matrices. It provides a unified interface for accessing and manipulating these sub-matrices.
The class holds a weak reference to the original matrix, the starting and ending indices of the submatrix view in the original matrix, and a flag indicating whether to fill the submatrix view with the conjugate of the original matrix values.
It also provides properties to get the starting and ending indices of the submatrix view (from_idx and to_idx), the shape of the submatrix view (shape), and the strides of the submatrix view (strides).
Attributes
- nameunicode
The name of the submatrix view.
- Mweakref
A weak reference to the original matrix.
- ANoneType
Placeholder for the actual submatrix data. This should be implemented in subclasses.
- _fromPy_ssize_t
The starting index of the submatrix view in the original matrix.
- _toPy_ssize_t
The ending index of the submatrix view in the original matrix.
- conjugate_fillbint
Whether to fill the submatrix view with the conjugate of the original matrix values.
- M
- conjugate_fill
- from_idx[source]
Returns the starting index of the submatrix view in the original matrix.
Returns
- Py_ssize_t
The starting index of the submatrix view.
- from_rhs_index
- from_rhs_view
- from_rhs_view_size
- name
- shape[source]
Returns the shape of the submatrix view.
Returns
- tuple
The shape of the submatrix view, as a tuple of two integers.
- size1
- size2
- start_idx
- stride1
- stride2
- strides[source]
Returns the strides of the submatrix view.
Returns
- tuple
The strides of the submatrix view, as a tuple of two integers.
- class finesse.cymath.cmatrix.SubCCSView1DArray[source]
Bases:
objectThis is a class for storing sub-matrix views for coupling directly to another single SubCCSView. It offers a 1D PyObject* array which can be iterated over in C for fast access matrix data without having to do reference inc/dec in fast loops.
It can be accessed from Python for setting views, however it doesn’t support slicing or wraparounds.
Examples
Cython access to views should be cast to a SubCCSView before using it:
>>>> (<SubCCSView>arr.views[i]).fill()
This should result in no python calls when checking the Cython analysis information.
If you store this SubCCSView into a variable then a reference count will happen.
- size
- class finesse.cymath.cmatrix.SubCCSView2DArray[source]
Bases:
objectThis is a class for storing sub-matrix views. It offers a 2D PyObject** array which can be iterated over in C for fast access matrix data without having to do reference inc/dec in fast loops.
It can be accessed from Python for setting views, however it doesn’t support slicing or wraparounds.
Examples
Cython access to views should be cast to a SubCCSView before using it:
>>>> (<SubCCSView>arr.views[i][j]).fill()
This should result in no python calls when checking the Cython analysis information.
If you store this SubCCSView into a variable then a reference count will happen.
- cols
- rows
- shape