Linear filtering of bivariate signals: tutorial#
This tutorial demonstrates the tools available within the filters module of BiSPy. The examples provided here come along with the paper
Julien Flamant, Pierre Chainais, Nicolas Le Bihan: “A complete framework for linear filtering of bivariate signals”, IEEE Transactions on Signal Processing, 2018; arXiv:1802.02469, doi:10.1109/TSP.2018.2855659
The paper contains theoretical results and several applications that can be reproduced with the following tutorial. Parts of it are adapted from the EUSIPCO 2024 tutorial An introduction to bivariate signal processing: polarization, quaternions and geometric representations, by Nicolas Le Bihan and Julien Flamant, whose notebooks and slides are on GitHub.
This page is a Jupyter notebook, run every time the documentation is built, so its outputs come from the current version of BiSPy. Download the notebook to run it yourself.
Load bispy and necessary modules#
import numpy as np
import matplotlib.pyplot as plt
import quaternion # load the quaternion module
import bispy as bsp
Two kinds of filters#
A second-order stationary bivariate signal \(x\) is described by its quaternion power spectral density (PSD), estimated in the spectral analysis tutorial:
where \(S_0\) is the power spectrum, \(\Phi_x \in [0, 1]\) the degree of polarization and \(\mu_x\) the polarization axis. The axis is a unit pure quaternion, that is a point of the Poincaré sphere. For a polarization ellipse of orientation \(\theta\) and ellipticity \(\chi\), it reads (function utils.polarizationAxis)
BiSPy implements the two elementary kinds of linear time-invariant (LTI) filters of the QFT framework. Both are defined frequency by frequency in the QFT domain, and each matches a physical effect on polarization.
Unitary filters model birefringence. With axis \(\mu(\nu)\) (a unit pure quaternion), angle \(\alpha(\nu)\) and phase \(\varphi(\nu)\),
They keep the power spectrum and the degree of polarization, and rotate the polarization axis on the Poincaré sphere, around \(\mu\) by the angle \(\alpha\):
Hermitian filters model diattenuation, that is partial polarizers. With gain \(K(\nu) \geq 0\), polarizing power \(\eta(\nu) \in [0, 1]\) and axis \(\mu(\nu)\),
A signal polarized along \(\mu\) is multiplied by \(K(1 + \eta)\), one polarized along \(-\mu\) (the orthogonal polarization state) by \(K(1 - \eta)\). With \(\eta = 1\), the filter is a perfect polarizer. The output PSD is
where \(\langle\cdot, \cdot\rangle\) is the scalar product of pure quaternions seen as 3D vectors.
In BiSPy, filter parameters are scalars (constant over frequency) or arrays of size N, one value per frequency of np.fft.fftfreq(N). Only positive frequencies matter: the filters set the negative ones by symmetry, so that the output stays a bivariate signal.
1. Hermitian filters: simulating a signal with a prescribed spectrum#
We want to simulate a signal with a given quaternion PSD. Here, a narrow-band signal around the normalized frequency \(\nu_0 = 0.1\), partially polarized (\(\Phi_x = 0.8\)), with the same polarization ellipse at all frequencies (\(\theta = \pi/6\), \(\chi = \pi/12\)).
N = 1024 # length of the signal
t = np.arange(N) # time vector: unit sampling step, so frequencies are normalized
f = np.fft.fftfreq(N) # frequencies of the QFT
# power spectrum S0: raised cosine of half-width B around nu0
nu0, B = 0.1, 0.04
S0 = np.zeros(N)
band = np.abs(np.abs(f) - nu0) <= B
S0[band] = np.cos(np.pi * (np.abs(f[band]) - nu0) / (2 * B))**2
# polarization: degree, orientation and ellipticity
Phi_x = 0.8
theta_x = np.pi / 6
chi_x = np.pi / 12
# polarization axis: the point (2 theta, 2 chi) of the Poincaré sphere
mu_x = bsp.utils.polarizationAxis(theta_x, chi_x)
target = bsp.spectral.quaternionPSD(N, S0, Phi_x, mu_x)
Feed unpolarized white noise \(w\), with \(\Gamma_{ww}(\nu) = 1\), to a Hermitian filter of axis \(\mu_x\). With \(\Phi_w = 0\), the formulas above give
The output has the target PSD for
eta = (1 - np.sqrt(1 - Phi_x**2)) / Phi_x # 0.5 for Phi_x = 0.8
K = np.sqrt(S0 / (1 + eta**2))
h = bsp.filters.HermitianFilter(N, K, eta, mu_x)
w = bsp.signals.bivariatewhiteNoise(N, 1, rng=2024) # unpolarized: P=0 by default
x = h.output(w)
fig, ax = bsp.utils.visual.plot2D(t, x)
The class signals.stationaryBivariate does exactly this: it builds the Hermitian filter from a quaternionPSD object, and its method simulate(M) filters M independent white noises. With the same seed, its first realization is the signal above.
sim = bsp.signals.stationaryBivariate(target)
print('same gain:', np.allclose(sim.K, h.K), '| same polarizing power:', np.allclose(sim.eta, h.eta))
M = 50 # number of independent realizations
sim.simulate(M, rng=2024)
X = sim.simulation # array of shape (M, N)
print('largest difference between the first realization and x:', np.max(np.abs(X[0] - x)))
same gain: True | same polarizing power: True
largest difference between the first realization and x: 0.0
Checking the result#
Estimating a degree of polarization requires averaging, here of multitaper estimates over the M realizations. The two helper functions below are used in the rest of the tutorial. The second one displays the polarization parameters only where there is power: without power, polarization is undefined.
def average_multitaper(realizations, bw=2.5):
'''Multitaper estimate of the quaternion PSD, averaged over realizations.'''
estimate = bsp.spectral.Multitaper(t, realizations[0], bw=bw)
for x in realizations[1:]:
estimate = estimate + bsp.spectral.Multitaper(t, x, bw=bw)
return 1 / len(realizations) * estimate
def plot_spectra(densities, labels, styles=None, fmax=0.2):
'''Power spectrum, degree of polarization, orientation and ellipticity of
quaternion PSDs (estimates or quaternionPSD objects), at positive frequencies.
Polarization parameters are shown where S0 exceeds 5% of its maximum.'''
styles = styles or [{}] * len(densities)
fig, ax = plt.subplots(ncols=4, figsize=(14, 3), layout='constrained')
for density, label, style in zip(densities, labels, styles, strict=True):
keep = density.S0 > 0.05 * density.S0.max()
Phi, theta, chi = np.full((3, density.S0.size), np.nan)
_, theta[keep], chi[keep], Phi[keep] = bsp.utils.Stokes2geo(
density.S0[keep], density.S1[keep], density.S2[keep], density.S3[keep])
pos = density.f >= 0
for axis, y in zip(ax, [density.S0, Phi, theta, chi], strict=True):
axis.plot(density.f[pos], y[pos], label=label, **style)
titles = [r'$S_0(\nu)$', r'$\Phi(\nu)$', r'$\theta(\nu)$', r'$\chi(\nu)$']
limits = [None, (-0.05, 1.05), (-np.pi / 2, np.pi / 2), (-np.pi / 4, np.pi / 4)]
for axis, title, ylim in zip(ax, titles, limits, strict=True):
axis.set_title(title)
axis.set_xlim(0, fmax)
axis.set_ylim(ylim)
axis.set_xlabel('normalized frequency')
ax[0].legend()
return fig, ax
estimate = average_multitaper(X)
fig, ax = plot_spectra([estimate, target], ['estimate', 'target'], [{}, {'ls': '--', 'color': 'k'}])
The estimated power spectrum, degree of polarization, orientation and ellipticity match the target.
2. Unitary filters: rotating polarization states#
A unitary filter of axis \(\mu = \boldsymbol{i}\) rotates the polarization axis around the \(\boldsymbol{i}\) axis of the Poincaré sphere, the axis of circular polarizations. The ellipticity is kept and the orientation turns by \(\alpha/2\), as light does in optically active media. Here the angle \(\alpha(\nu)\) grows linearly across the band, from \(-\pi/2\) to \(\pi/2\), so that each frequency is rotated differently.
alpha = np.pi / 2 * (np.abs(f) - nu0) / B # birefringence angle: -pi/2 to pi/2 across the band
u = bsp.filters.UnitaryFilter(N, quaternion.x, alpha, 0) # axis i, no phase delay
Y = np.array([u.output(x) for x in X])
# expected output PSD: same S0 and Phi, rotated polarization axis
mu_y = np.exp(quaternion.x * alpha / 2) * mu_x * np.exp(-quaternion.x * alpha / 2)
expected = bsp.spectral.quaternionPSD(N, S0, Phi_x, mu_y)
fig, ax = plot_spectra([estimate, average_multitaper(Y), expected], ['input', 'output', 'expected'],
[{}, {}, {'ls': '--', 'color': 'k'}])
The power spectrum, the degree of polarization and the ellipticity go through unchanged, while the orientation now depends on frequency. Other axes give other effects: with \(\mu = \boldsymbol{j}\), the axis of horizontal and vertical linear polarizations, and \(\alpha = \pi/2\), the filter is a quarter-wave plate, which turns linear polarization at 45° into circular polarization.
3. Decompositions with a Hermitian filter#
The quaternion PSD splits into a polarized and an unpolarized part:
Can linear filtering split the signal the same way, as \(x = x_a + x_b\)? Take for \(x_a\) the output of a Hermitian filter of axis \(\mu_x\) and \(\eta = 1\): a perfect polarizer, so \(x_a\) is fully polarized along \(\mu_x\) whatever the gain \(K\). Then \(x_b = x - x_a\). We would like:
the PSD of \(x_a\) to be the polarized part,
the PSD of \(x_b\) to be the unpolarized part,
\(x_a\) and \(x_b\) to be uncorrelated.
The three cannot hold together, and the gain \(K\) decides which ones do.
def decompose(K):
'''Split each realization into x_a, the output of a Hermitian filter
(gain K, axis mu_x, eta = 1), and x_b = x - x_a.'''
polarizer = bsp.filters.HermitianFilter(N, K, 1, mu_x)
Xa = np.array([polarizer.output(x) for x in X])
return Xa, X - Xa
def print_powers(estimate_a, estimate_b):
'''Powers of x_a, x_b and their sum, relative to the power of x.'''
power = np.sum(estimate.S0)
pa, pb = np.sum(estimate_a.S0) / power, np.sum(estimate_b.S0) / power
print(f'power of x_a / power of x: {pa:.3f}')
print(f'power of x_b / power of x: {pb:.3f}')
print(f'sum of both: {pa + pb:.3f}')
Unpolarized remainder#
\(x_b\) is itself the output of a Hermitian filter,
of axis \(-\mu_x\) and polarizing power \(K/(1 - K)\). From the output PSD formula, it is unpolarized when this polarizing power solves \(\Phi_x = 2\eta/(1 + \eta^2)\), the equation of section 1. So \(K/(1 - K) = \eta\), that is \(K = \eta/(1 + \eta)\) (here \(1/3\)).
Xa, Xb = decompose(eta / (1 + eta))
estimate_a, estimate_b = average_multitaper(Xa), average_multitaper(Xb)
fig, ax = plot_spectra([estimate, estimate_a, estimate_b], ['$x$', '$x_a$', '$x_b$'])
print_powers(estimate_a, estimate_b)
power of x_a / power of x: 0.401
power of x_b / power of x: 0.198
sum of both: 0.599
\(x_b\) is the unpolarized part (property 2): its power is \(1 - \Phi_x = 0.2\) times that of \(x\) and its degree of polarization is close to 0, up to the estimation bias. Its orientation and ellipticity are noise, since an unpolarized signal has no preferred ellipse.
\(x_a\) is fully polarized along \(\mu_x\), but its power is \(2K^2(1 + \Phi_x) = 0.4\) times that of \(x\), not \(\Phi_x = 0.8\) (property 1 fails). The powers of \(x_a\) and \(x_b\) do not add up to that of \(x\): the difference is a cross term, so \(x_a\) and \(x_b\) are correlated (property 3 fails).
On one realization, \(x_a\) draws ellipses of fixed shape and orientation, while \(x_b\) has no preferred direction:
fig, ax = bsp.utils.visual.plot2D(t, Xa[0])
ax[2].set_title('$x_a$: fully polarized')
fig, ax = bsp.utils.visual.plot2D(t, Xb[0])
ax[2].set_title('$x_b$: unpolarized');