Fast Walsh-Hadamard transform through the lens of butterfly operations
An Hadamard matrix for can be created from using Kronecker product:
This matrix has some nice properties:
- is orthonormal
- is symmetric. Since it is also orthonormal, it is its own inverse.
There are also Hadamard matrices where is not a power of but they are not covered here.
The matrix vector product is
At the heart of this product lies the butterfly transform . The matrix vector product is essentially number of butterfly transforms:
def fwht(x):
x = list(x)
N = len(x)
h = 1
while h < N:
for i in range(0, N, 2 * h):
for j in range(i, i + h):
a, b = x[j], x[j + h]
x[j], x[j + h] = a + b, a - b
h *= 2
return x
print(fwht([1, 2, 3, 4])) # [10, -2, -4, 0]
Vectorized version using numpy
import numpy as np
def fwht_np(x):
x = np.array(x)
N = len(x)
h = 1
while h < N:
x = x.reshape(-1, 2, h) # blocks of size 2h, split into two halves
a, b = x[:, 0], x[:, 1]
x = np.stack([a + b, a - b], axis=1).reshape(N)
h *= 2
return x
print(fwht_np([1, 2, 3, 4])) # [10 -2 -4 0]
Rotation matrices with the same structure
One can take a repeated Kronecker product of a rotation matrix to create an orthonormal matrix, , with parameters:
The matrix-vector product retains the efficient requirement. The only change is that the butterfly transform at each level now looks like:
from math import cos, sin, pi
def rotate(x, thetas):
x = list(x)
N = len(x)
h = 1
# R(theta_k) mixes entries 1 apart, ..., R(theta_1) mixes entries N/2 apart
for theta in reversed(thetas):
c, s = cos(theta), sin(theta)
for i in range(0, N, 2 * h):
for j in range(i, i + h):
a, b = x[j], x[j + h]
x[j], x[j + h] = c * a - s * b, s * a + c * b
h *= 2
return x
y = rotate([1, 2, 3, 4], [pi / 2, 0])
print([round(v, 4) for v in y]) # [-3.0, -4.0, 1.0, 2.0]
Rotation matrices with one parameter per block
To create a wider range of rotation matrices with the same structure, one can add a parameter for each block of a matrix. This can be viewed by looking at what the "atomic" butterfly transform now looks like.
At level , the butterfly operation on entries and depends on and both:
The total number of parameters in this case is . Eg for there are levels of butterflies, so angles.
The implementation now looks like:
from math import cos, sin, pi
def rotate_per_block(x, thetas):
x = list(x)
N = len(x)
k = N.bit_length() - 1 # N = 2^k
for i in range(k, 0, -1): # level k first, as in rotate
h = N // 2**i
for start in range(0, N, 2 * h):
for a in range(start, start + h):
b = a + h
c, s = cos(thetas[i, a]), sin(thetas[i, a])
x[a], x[b] = c * x[a] - s * x[b], s * x[a] + c * x[b]
return x
# theta_{i,a} for N = 4; one angle per level gives the same result as rotate above
thetas = {(1, 0): pi / 2, (1, 1): pi / 2, (2, 0): 0, (2, 2): 0}
y = rotate_per_block([1, 2, 3, 4], thetas)
print([round(v, 4) for v in y]) # [-3.0, -4.0, 1.0, 2.0]