Source code for matrix_toolkit.anymatrix.groups.hadamard

"""
Hadamard matrix group - Various constructions of Hadamard matrices
"""

import numpy as np
from scipy.linalg import hadamard as scipy_hadamard


def register_hadamard_matrices(registry):
    """Register Hadamard matrix generators"""
    
    registry.register_matrix(
        group='hadamard',
        name='hadamard',
        generator=hadamard,
        properties=['orthogonal', 'binary'],
        description='Hadamard matrix of order n (n must be power of 2)'
    )
    
    registry.register_matrix(
        group='hadamard',
        name='walsh',
        generator=walsh,
        properties=['orthogonal', 'binary'],
        description='Walsh-Hadamard matrix (sequency ordered)'
    )


[docs] def hadamard(n: int) -> np.ndarray: """ Hadamard matrix of order n A Hadamard matrix is a square matrix whose entries are +1 or -1 and whose rows are mutually orthogonal. Args: n: Order (must be 1, 2, or a multiple of 4) Returns: n×n Hadamard matrix """ if n == 1: return np.array([[1]]) # Use scipy's implementation (Sylvester construction) H = scipy_hadamard(n) return H
[docs] def walsh(n: int) -> np.ndarray: """ Walsh-Hadamard matrix (sequency ordered) Args: n: Order (must be power of 2) Returns: n×n Walsh matrix """ # Start with standard Hadamard H = hadamard(n) # Reorder to sequency order (by number of sign changes) def sequency(row): """Count number of sign changes""" return np.sum(row[:-1] != row[1:]) indices = sorted(range(n), key=lambda i: sequency(H[i])) W = H[indices, :] return W