Anymatrix Module

The anymatrix module provides programmatic generation of test matrices with well-defined mathematical properties.

AnyMatrix

class matrix_toolkit.anymatrix.AnyMatrix[source]

Bases: object

Main interface for anymatrix - generate test matrices by name

Examples

>>> from matrix_toolkit.anymatrix import AnyMatrix
>>> am = AnyMatrix()

# List all available groups >>> groups = am.groups()

# List matrices in a group >>> matrices = am.list(‘core’)

# Generate a matrix >>> A = am.generate(‘core/beta’, 10)

# Get matrix properties >>> props = am.properties(‘core/beta’)

# Search for matrices with specific properties >>> results = am.search([‘symmetric’, ‘positive definite’])

__init__()[source]

Initialize anymatrix registry

__call__(matrix_id: str, *args, **kwargs)[source]

Shorthand for generate()

__init__()[source]

Initialize anymatrix registry

register_matrix(group: str, name: str, generator: Callable, properties: List[str], description: str = '')[source]

Register a matrix generator

Parameters:
  • group – Group name (e.g., ‘core’, ‘gallery’)

  • name – Matrix name within the group

  • generator – Function to generate the matrix

  • properties – List of matrix properties

  • description – Description of the matrix

groups() List[str][source]

List all available groups

list(group: str | None = None) Dict[str, List[str]] | List[str][source]

List matrices in a group or all groups

Parameters:

group – Group name. If None, returns all groups with their matrices

Returns:

List of matrix names or dict of group->matrices

generate(matrix_id: str, *args, **kwargs) Any[source]

Generate a matrix by its ID

Parameters:
  • matrix_id – Matrix identifier in format ‘group/name’

  • *args – Positional arguments for the generator

  • **kwargs – Keyword arguments for the generator

Returns:

Generated matrix

Examples

>>> am = AnyMatrix()
>>> A = am.generate('core/beta', 10)
>>> B = am.generate('core/fourier', 8)
properties(matrix_id: str | None = None) List[str] | Dict[str, List[str]][source]

Get properties of a matrix or all matrices

Parameters:

matrix_id – Matrix identifier. If None, returns all matrices with properties

Returns:

List of properties or dict of matrix_id->properties

search(properties: List[str], match_all: bool = True) List[str][source]

Search for matrices with specific properties

Parameters:
  • properties – List of required properties

  • match_all – If True, matrix must have all properties. If False, matrix must have at least one property.

Returns:

List of matrix IDs matching the criteria

Examples

>>> am = AnyMatrix()
>>> # Find all symmetric matrices
>>> matrices = am.search(['symmetric'])
>>>
>>> # Find matrices that are both symmetric and positive definite
>>> matrices = am.search(['symmetric', 'positive definite'])
help(matrix_id: str) str[source]

Get help information for a matrix

Parameters:

matrix_id – Matrix identifier

Returns:

Help string with description and properties

count() Dict[str, int][source]

Get count of matrices by group

__call__(matrix_id: str, *args, **kwargs)[source]

Shorthand for generate()

Main Methods

AnyMatrix.generate(matrix_id: str, *args, **kwargs) Any[source]

Generate a matrix by its ID

Parameters:
  • matrix_id – Matrix identifier in format ‘group/name’

  • *args – Positional arguments for the generator

  • **kwargs – Keyword arguments for the generator

Returns:

Generated matrix

Examples

>>> am = AnyMatrix()
>>> A = am.generate('core/beta', 10)
>>> B = am.generate('core/fourier', 8)
AnyMatrix.search(properties: List[str], match_all: bool = True) List[str][source]

Search for matrices with specific properties

Parameters:
  • properties – List of required properties

  • match_all – If True, matrix must have all properties. If False, matrix must have at least one property.

Returns:

List of matrix IDs matching the criteria

Examples

>>> am = AnyMatrix()
>>> # Find all symmetric matrices
>>> matrices = am.search(['symmetric'])
>>>
>>> # Find matrices that are both symmetric and positive definite
>>> matrices = am.search(['symmetric', 'positive definite'])
AnyMatrix.properties(matrix_id: str | None = None) List[str] | Dict[str, List[str]][source]

Get properties of a matrix or all matrices

Parameters:

matrix_id – Matrix identifier. If None, returns all matrices with properties

Returns:

List of properties or dict of matrix_id->properties

AnyMatrix.list(group: str | None = None) Dict[str, List[str]] | List[str][source]

List matrices in a group or all groups

Parameters:

group – Group name. If None, returns all groups with their matrices

Returns:

List of matrix names or dict of group->matrices

AnyMatrix.groups() List[str][source]

List all available groups

AnyMatrix.help(matrix_id: str) str[source]

Get help information for a matrix

Parameters:

matrix_id – Matrix identifier

Returns:

Help string with description and properties

AnyMatrix.count() Dict[str, int][source]

Get count of matrices by group

Examples

Basic usage:

from matrix_toolkit.anymatrix import AnyMatrix

am = AnyMatrix()

# List all groups
print(am.groups())

# Generate a matrix
beta = am.generate('core/beta', 10)

# Shorthand syntax
fourier = am('core/fourier', 8)

# Search for matrices
symmetric = am.search(['symmetric', 'positive definite'])

# Get help
print(am.help('core/beta'))

MatrixProperties

class matrix_toolkit.anymatrix.MatrixProperties[source]

Bases: object

Matrix property checking utilities

This class provides methods to verify various mathematical properties of matrices, similar to the MATLAB anymatrix property tests.

DEFAULT_TOL = 1e-10
static is_symmetric(matrix: Any, tol: float = None) bool[source]

Check if matrix is symmetric (A = A^T)

Parameters:
  • matrix – Input matrix

  • tol – Tolerance for floating point comparison

Returns:

True if symmetric, False otherwise

static is_hermitian(matrix: Any, tol: float = None) bool[source]

Check if matrix is Hermitian (A = A^H)

static is_positive_definite(matrix: Any, tol: float = None) bool[source]

Check if matrix is positive definite

A matrix is positive definite if all eigenvalues are positive. For large matrices, uses Cholesky decomposition.

static is_orthogonal(matrix: Any, tol: float = None) bool[source]

Check if matrix is orthogonal (Q^T Q = I)

static is_unitary(matrix: Any, tol: float = None) bool[source]

Check if matrix is unitary (Q^H Q = I)

static is_tridiagonal(matrix: Any, tol: float = None) bool[source]

Check if matrix is tridiagonal

static is_diagonal(matrix: Any, tol: float = None) bool[source]

Check if matrix is diagonal

static is_upper_triangular(matrix: Any, tol: float = None) bool[source]

Check if matrix is upper triangular

static is_lower_triangular(matrix: Any, tol: float = None) bool[source]

Check if matrix is lower triangular

static is_toeplitz(matrix: Any, tol: float = None) bool[source]

Check if matrix is Toeplitz (constant along diagonals)

static is_circulant(matrix: Any, tol: float = None) bool[source]

Check if matrix is circulant

static is_hankel(matrix: Any, tol: float = None) bool[source]

Check if matrix is Hankel (constant along anti-diagonals)

static is_stochastic(matrix: Any, tol: float = None) bool[source]

Check if matrix is row stochastic (rows sum to 1, non-negative)

static is_doubly_stochastic(matrix: Any, tol: float = None) bool[source]

Check if matrix is doubly stochastic

static is_nilpotent(matrix: Any, max_power: int = None, tol: float = None) bool[source]

Check if matrix is nilpotent (A^k = 0 for some k)

static is_involutory(matrix: Any, tol: float = None) bool[source]

Check if matrix is involutory (A^2 = I)

static is_sparse(matrix: Any) bool[source]

Check if matrix is stored in sparse format

static is_binary(matrix: Any, tol: float = None) bool[source]

Check if all matrix elements are 0 or 1

static is_integer(matrix: Any, tol: float = None) bool[source]

Check if all matrix elements are integers

classmethod check_properties(matrix: Any, expected_properties: List[str], tol: float = None) Dict[str, bool][source]

Check multiple properties of a matrix

Parameters:
  • matrix – Matrix to check

  • expected_properties – List of property names to check

  • tol – Tolerance for comparisons

Returns:

Dictionary mapping property names to boolean results

classmethod get_checker(property_name: str) Callable[source]

Get property checker function by name

classmethod list_all_properties() List[str][source]

List all supported property names

Property Checkers

static MatrixProperties.is_symmetric(matrix: Any, tol: float = None) bool[source]

Check if matrix is symmetric (A = A^T)

Parameters:
  • matrix – Input matrix

  • tol – Tolerance for floating point comparison

Returns:

True if symmetric, False otherwise

static MatrixProperties.is_hermitian(matrix: Any, tol: float = None) bool[source]

Check if matrix is Hermitian (A = A^H)

static MatrixProperties.is_positive_definite(matrix: Any, tol: float = None) bool[source]

Check if matrix is positive definite

A matrix is positive definite if all eigenvalues are positive. For large matrices, uses Cholesky decomposition.

static MatrixProperties.is_orthogonal(matrix: Any, tol: float = None) bool[source]

Check if matrix is orthogonal (Q^T Q = I)

static MatrixProperties.is_unitary(matrix: Any, tol: float = None) bool[source]

Check if matrix is unitary (Q^H Q = I)

static MatrixProperties.is_tridiagonal(matrix: Any, tol: float = None) bool[source]

Check if matrix is tridiagonal

static MatrixProperties.is_diagonal(matrix: Any, tol: float = None) bool[source]

Check if matrix is diagonal

static MatrixProperties.is_upper_triangular(matrix: Any, tol: float = None) bool[source]

Check if matrix is upper triangular

static MatrixProperties.is_lower_triangular(matrix: Any, tol: float = None) bool[source]

Check if matrix is lower triangular

static MatrixProperties.is_toeplitz(matrix: Any, tol: float = None) bool[source]

Check if matrix is Toeplitz (constant along diagonals)

static MatrixProperties.is_circulant(matrix: Any, tol: float = None) bool[source]

Check if matrix is circulant

static MatrixProperties.is_hankel(matrix: Any, tol: float = None) bool[source]

Check if matrix is Hankel (constant along anti-diagonals)

static MatrixProperties.is_stochastic(matrix: Any, tol: float = None) bool[source]

Check if matrix is row stochastic (rows sum to 1, non-negative)

static MatrixProperties.is_doubly_stochastic(matrix: Any, tol: float = None) bool[source]

Check if matrix is doubly stochastic

static MatrixProperties.is_nilpotent(matrix: Any, max_power: int = None, tol: float = None) bool[source]

Check if matrix is nilpotent (A^k = 0 for some k)

static MatrixProperties.is_involutory(matrix: Any, tol: float = None) bool[source]

Check if matrix is involutory (A^2 = I)

static MatrixProperties.is_sparse(matrix: Any) bool[source]

Check if matrix is stored in sparse format

static MatrixProperties.is_binary(matrix: Any, tol: float = None) bool[source]

Check if all matrix elements are 0 or 1

static MatrixProperties.is_integer(matrix: Any, tol: float = None) bool[source]

Check if all matrix elements are integers

Utility Methods

classmethod MatrixProperties.check_properties(matrix: Any, expected_properties: List[str], tol: float = None) Dict[str, bool][source]

Check multiple properties of a matrix

Parameters:
  • matrix – Matrix to check

  • expected_properties – List of property names to check

  • tol – Tolerance for comparisons

Returns:

Dictionary mapping property names to boolean results

classmethod MatrixProperties.get_checker(property_name: str) Callable[source]

Get property checker function by name

classmethod MatrixProperties.list_all_properties() List[str][source]

List all supported property names

Examples

Check individual properties:

from matrix_toolkit.anymatrix import MatrixProperties
import numpy as np

A = np.array([[1, 2], [2, 5]])

# Check if symmetric
is_sym = MatrixProperties.is_symmetric(A)

# Check if positive definite
is_pd = MatrixProperties.is_positive_definite(A)

print(f"Symmetric: {is_sym}, PD: {is_pd}")

Check multiple properties:

properties = ['symmetric', 'positive definite', 'tridiagonal']
results = MatrixProperties.check_properties(A, properties)

for prop, passed in results.items():
    print(f"{prop}: {passed}")

List all supported properties:

all_props = MatrixProperties.list_all_properties()
print(f"Supported properties: {all_props}")

Matrix Groups

Core Group

Basic Matrices

matrix_toolkit.anymatrix.groups.core.beta(n: int, beta_val: float = 0.5) ndarray[source]

Beta matrix - symmetric positive definite

Parameters:
  • n – Matrix size

  • beta_val – Beta parameter (default 0.5)

Returns:

n×n beta matrix

matrix_toolkit.anymatrix.groups.core.fourier(n: int) ndarray[source]

Discrete Fourier transform matrix

Parameters:

n – Matrix size

Returns:

n×n Fourier matrix

matrix_toolkit.anymatrix.groups.core.vand(c: ndarray | None = None, n: int | None = None) ndarray[source]

Vandermonde matrix

Parameters:
  • c – Vector of values (default: 0, 1, …, n-1)

  • n – Matrix size (used if c is None)

Returns:

Vandermonde matrix

matrix_toolkit.anymatrix.groups.core.wilson(n: int = 4) ndarray[source]

Wilson matrix - symmetric positive definite

Parameters:

n – Matrix size (default 4)

Returns:

n×n Wilson matrix

Nilpotent Matrices

matrix_toolkit.anymatrix.groups.core.nilpot_triang(n: int) ndarray[source]

Nilpotent upper triangular matrix

Parameters:

n – Matrix size

Returns:

n×n nilpotent upper triangular matrix

matrix_toolkit.anymatrix.groups.core.nilpot_tridiag(n: int) ndarray[source]

Nilpotent tridiagonal matrix

A tridiagonal matrix that is nilpotent. The matrix has the form: [ 0 1 0 0 … 0 ] [-1 0 2 0 … 0 ] [ 0 -2 0 3 … 0 ] [ 0 0 -3 0 … 0 ] … [ 0 0 0 … 0 n-1] [ 0 0 0 … -(n-1) 0 ]

This is NOT nilpotent! Let me check the original implementation…

Actually, looking at the original anymatrix code, this matrix is skew-symmetric tridiagonal, which means A^T = -A, so A^2 is symmetric.

For a truly nilpotent tridiagonal, we need a different construction.

Parameters:

n – Matrix size

Returns:

n×n nilpotent tridiagonal matrix

Stochastic Matrices

matrix_toolkit.anymatrix.groups.core.stoch_cesaro(n: int) ndarray[source]

Stochastic Cesaro matrix (lower triangular, row stochastic)

Parameters:

n – Matrix size

Returns:

n×n stochastic Cesaro matrix

Structured Matrices

matrix_toolkit.anymatrix.groups.core.circul_binom(n: int) ndarray[source]

Circulant matrix with binomial coefficients

Parameters:

n – Matrix size

Returns:

n×n circulant matrix

matrix_toolkit.anymatrix.groups.core.blockcirc(blocks: list, k: int = 1) ndarray[source]

Block circulant matrix

Parameters:
  • blocks – List of square matrices

  • k – Shift parameter

Returns:

Block circulant matrix

matrix_toolkit.anymatrix.groups.core.perfect_shuffle(n: int) spmatrix[source]

Perfect shuffle permutation matrix

The perfect shuffle permutation interleaves the first and second halves of a vector.

Parameters:

n – Matrix size (should be even)

Returns:

n×n sparse permutation matrix

matrix_toolkit.anymatrix.groups.core.augment(A: ndarray, b: ndarray | None = None) ndarray[source]

Augmented system matrix [A b; b’ 0]

Parameters:
  • A – Original matrix

  • b – Right-hand side vector (default: ones)

Returns:

Augmented matrix

Hadamard Group

matrix_toolkit.anymatrix.groups.hadamard.hadamard(n: int) ndarray[source]

Hadamard matrix of order n

A Hadamard matrix is a square matrix whose entries are +1 or -1 and whose rows are mutually orthogonal.

Parameters:

n – Order (must be 1, 2, or a multiple of 4)

Returns:

n×n Hadamard matrix

matrix_toolkit.anymatrix.groups.hadamard.walsh(n: int) ndarray[source]

Walsh-Hadamard matrix (sequency ordered)

Parameters:

n – Order (must be power of 2)

Returns:

n×n Walsh matrix

MATLAB Group

matrix_toolkit.anymatrix.groups.matlab.magic(n: int) ndarray[source]

Magic square matrix

Parameters:

n – Size (n >= 3)

Returns:

n×n magic square

matrix_toolkit.anymatrix.groups.matlab.pascal(n: int, k: int = 0) ndarray[source]

Pascal matrix

Parameters:
  • n – Size

  • k – Type (0=symmetric, 1=lower, 2=upper)

Returns:

n×n Pascal matrix

matrix_toolkit.anymatrix.groups.matlab.rosser() ndarray[source]

Rosser matrix - 8×8 symmetric test matrix

Classic eigenvalue test matrix with close eigenvalues

matrix_toolkit.anymatrix.groups.matlab.wilkinson(n: int, mode: str = 'plus') ndarray[source]

Wilkinson matrix

Parameters:
  • n – Size (must be odd)

  • mode – ‘plus’ for W+ or ‘minus’ for W-

Returns:

n×n symmetric tridiagonal Wilkinson matrix

matrix_toolkit.anymatrix.groups.matlab.hilbert(n: int) ndarray[source]

Hilbert matrix - H(i,j) = 1/(i+j-1)

Notoriously ill-conditioned matrix

Parameters:

n – Size

Returns:

n×n Hilbert matrix

matrix_toolkit.anymatrix.groups.matlab.invhilb(n: int) ndarray[source]

Inverse of Hilbert matrix

Exact integer inverse of Hilbert matrix

Parameters:

n – Size

Returns:

n×n inverse Hilbert matrix

matrix_toolkit.anymatrix.groups.matlab.frank(n: int, k: int = 0) ndarray[source]

Frank matrix - upper Hessenberg with determinant 1

Parameters:
  • n – Size

  • k – Type (0=default, 1=reflected)

Returns:

n×n Frank matrix

matrix_toolkit.anymatrix.groups.matlab.companion(c: ndarray) ndarray[source]

Companion matrix of polynomial

For polynomial p(x) = c[0] + c[1]*x + … + c[n]*x^n, creates companion matrix whose eigenvalues are roots of p

Parameters:

c – Polynomial coefficients [c0, c1, …, cn]

Returns:

n×n companion matrix

Regtools Group

matrix_toolkit.anymatrix.groups.regtools.deriv2(n: int, example: int = 1) spmatrix[source]

Second derivative operator

Discrete approximation to second derivative (1D Laplacian)

Parameters:
  • n – Size

  • example – 1 for standard, 2 for periodic BC

Returns:

n×n sparse matrix

matrix_toolkit.anymatrix.groups.regtools.shaw(n: int) Tuple[ndarray, ndarray, ndarray][source]

Shaw test problem - 1D image restoration

Parameters:

n – Size

Returns:

Tuple of (A, b, x_true) where A@x_true ≈ b

matrix_toolkit.anymatrix.groups.regtools.phillips(n: int) Tuple[ndarray, ndarray, ndarray][source]

Phillips test problem - image deblurring

Parameters:

n – Size

Returns:

Tuple of (A, b, x_true)

matrix_toolkit.anymatrix.groups.regtools.blur(n: int, band: int = 3, sigma: float = 0.7) spmatrix[source]

Blurring matrix for image deconvolution

Creates a sparse matrix representing Gaussian blur

Parameters:
  • n – Image size (total size will be n×n)

  • band – Bandwidth of blur kernel

  • sigma – Standard deviation of Gaussian

Returns:

n²×n² sparse blurring matrix

matrix_toolkit.anymatrix.groups.regtools.gravity(n: int, example: int = 1, a: float = 0, b: float = 1, d: float = 0.25) Tuple[ndarray, ndarray, ndarray][source]

Gravity surveying test problem

Vertical gravity surveying over a 2D domain

Parameters:
  • n – Number of discretization points

  • example – Problem variant (1 or 2)

  • a – Left endpoint

  • b – Right endpoint

  • d – Depth

Returns:

Tuple of (A, b, x_true)

Testing Utilities

matrix_toolkit.anymatrix.testing.check_matrix_properties(matrix: Any, matrix_id: str, expected_properties: List[str], tol: float = 1e-10, verbose: bool = True) Dict[str, bool][source]

Check if a matrix has its expected properties

This is analogous to anymatrix_check_props.m from the MATLAB version.

Parameters:
  • matrix – Matrix to check

  • matrix_id – Matrix identifier (e.g., ‘core/beta’)

  • expected_properties – List of expected property names

  • tol – Tolerance for checks

  • verbose – Whether to print results

Returns:

Dictionary of property_name -> bool (True if property holds)

matrix_toolkit.anymatrix.testing.run_all_tests(groups: List[str] | None = None, verbose: bool = True, generate_report: bool = False, report_file: str | None = None) Dict[source]

Convenience function to run all anymatrix tests

Parameters:
  • groups – Groups to test (all if None)

  • verbose – Print progress

  • generate_report – Generate detailed report

  • report_file – File to save report

Returns:

Test results dictionary

Example: Running Tests

Run tests on all matrices:

from matrix_toolkit.anymatrix.testing import run_all_tests

# Run all tests
results = run_all_tests(verbose=True)

# Run tests on specific groups
results = run_all_tests(
    groups=['core', 'gallery'],
    verbose=True,
    generate_report=True,
    report_file='test_report.txt'
)

Test a specific matrix:

from matrix_toolkit.anymatrix.testing import check_matrix_properties
from matrix_toolkit.anymatrix import AnyMatrix

am = AnyMatrix()
matrix = am.generate('core/beta', 10)

expected_props = am.properties('core/beta')
results = check_matrix_properties(
    matrix,
    'core/beta',
    expected_props,
    verbose=True
)