Getting started: quaternions and polarization#
This tutorial introduces the basic objects of BiSPy: bivariate signals stored as quaternion arrays, the polarization ellipse, Stokes parameters and the quaternion Fourier transform (QFT). The other tutorials build on it. The framework is presented in detail in
Julien Flamant: “A general approach for the analysis and filtering of bivariate signals”, PhD thesis, Université de Lille, 2018; tel-01926941
and in the papers listed on the home page. This tutorial is adapted from the first notebook of 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
1. Bivariate signals are quaternion arrays#
A bivariate signal is a pair of real signals \(u(t)\) and \(v(t)\), such as the two horizontal components of a current velocity or of an electric field. BiSPy writes it as
a complex signal whose imaginary unit is the quaternion \(\boldsymbol{i}\). Quaternions have three imaginary units \(\boldsymbol{i}\), \(\boldsymbol{j}\) and \(\boldsymbol{k}\), with \(\boldsymbol{i}^2 = \boldsymbol{j}^2 = \boldsymbol{k}^2 = \boldsymbol{ijk} = -1\), and their product does not commute: \(\boldsymbol{ij} = \boldsymbol{k} = -\boldsymbol{ji}\).
BiSPy relies on the numpy-quaternion package, which adds a quaternion dtype to numpy and names the three units quaternion.x, quaternion.y and quaternion.z.
i, j, k = quaternion.x, quaternion.y, quaternion.z
print('ij =', i * j, '| ji =', j * i, '| ijk =', i * j * k)
q = np.quaternion(1, 2, 3, 4) # 1 + 2i + 3j + 4k
print('modulus:', np.abs(q), '| conjugate:', np.conj(q), '| q / q =', q / q)
ij = quaternion(0, 0, 0, 1) | ji = quaternion(0, 0, 0, -1) | ijk = quaternion(-1, 0, 0, 0)
modulus: 5.477225575051661 | conjugate: quaternion(1, -2, -3, -4) | q / q = quaternion(1, 0, 0, 0)
The function utils.sympSynth(q1, q2) builds the quaternion \(q_1 + \boldsymbol{i}\,q_2\), and utils.sympSplit returns \(q_1\) and \(q_2\). With two real arrays \(u\) and \(v\), sympSynth(u, v) is the bivariate signal \(u + \boldsymbol{i}\,v\), which utils.visual.plot2D displays: its trajectory in the plane on the left, its components on the right.
fs = 1000 # sampling frequency [Hz]
N = 1000 # number of samples: one second
t = np.arange(N) / fs # time vector
u = np.cos(2 * np.pi * 3 * t)
v = np.sin(2 * np.pi * 2 * t)
x = bsp.utils.sympSynth(u, v) # quaternion array u + i v
print(x[:3])
fig, ax = bsp.utils.visual.plot2D(t, x)
[quaternion(1, 0, 0, 0)
quaternion(0.999822352380809, 0.0125660398833526, 0, 0)
quaternion(0.999289472640589, 0.0251300954433375, 0, 0)]
Note. Complex arrays given to
sympSynth, or returned bysympSplit, are read with numpy’s1jstanding for the quaternion \(\boldsymbol{j}\): \(q_1\) and \(q_2\) belong to \(\mathbb{C}_{\boldsymbol{j}} = \mathrm{span}\{1, \boldsymbol{j}\}\). So bivariate data stored the usual way, as a complex arrayz = u + 1j * v, are converted withsympSynth(z.real, z.imag), not withsympSynth(z, 0). The plotting functions ofutils.visualaccept both quaternion arrays and complex arraysu + 1j * v.
print(bsp.utils.sympSynth(np.array([1 + 2j]), np.array([3 + 4j]))) # 1 + 3i + 2j + 4k
[quaternion(1, 3, 2, 4)]
2. The polarization ellipse#
The simplest bivariate signal oscillates at a single frequency \(f_0\). Its components \(u(t) = A_u\cos(2\pi f_0 t + \varphi_u)\) and \(v(t) = A_v\cos(2\pi f_0 t + \varphi_v)\) draw an ellipse, the polarization ellipse, described by four parameters:
the amplitude \(a \geq 0\), which sets the size of the ellipse,
the orientation \(\theta \in [-\pi/2, \pi/2]\), the angle of its major axis,
the ellipticity \(\chi \in [-\pi/4, \pi/4]\), which sets its shape and direction: \(\chi = 0\) gives a line segment and \(|\chi| = \pi/4\) a circle; the ellipse is run counterclockwise if \(\chi > 0\), clockwise if \(\chi < 0\),
the initial phase \(\varphi\), the position on the ellipse at \(t = 0\).
Quaternions give these parameters directly, through a polar form:
where \(\mathrm{Proj}_{\mathbb{C}_{\boldsymbol{i}}}\) keeps the components along \(1\) and \(\boldsymbol{i}\). Every quaternion has such a polar form \(a\,e^{\boldsymbol{i}\theta}e^{-\boldsymbol{k}\chi}e^{\boldsymbol{j}\varphi}\): utils.euler2quat builds the quaternion from the parameters, and utils.quat2euler returns them.
q = bsp.utils.euler2quat(1.5, np.pi / 5, -np.pi / 8, 0.7) # a, theta, chi, phi
print('q =', q)
a, theta, chi, phi = bsp.utils.quat2euler(q)
print(f'a = {a:.3f}, theta = {theta:.3f}, chi = {chi:.3f}, phi = {phi:.3f}')
print(f'(pi/5 = {np.pi / 5:.3f}, -pi/8 = {-np.pi / 8:.3f})')
q = quaternion(1.07486517462654, 0.323840841485714, 0.46420509489612, 0.87994635952049)
a = 1.500, theta = 0.628, chi = -0.393, phi = 0.700
(pi/5 = 0.628, -pi/8 = -0.393)
The function signals.bivariateAMFM(a, theta, chi, phi) evaluates the polar form on an array of phases. With Hembedding=False it returns the bivariate signal \(x(t)\); add complexOutput=True to get it as a complex array u + 1j * v. By default, it returns the full quaternion \(a\,e^{\boldsymbol{i}\theta}e^{-\boldsymbol{k}\chi}e^{\boldsymbol{j}(2\pi f_0 t + \varphi)}\), the quaternion embedding of \(x(t)\), used in the time-frequency tutorial.
Here are one period of three monochromatic signals, with linear, circular and elliptical polarization. The dot marks \(t = 0\) and the arrow the direction of rotation.
f0 = 10 # frequency [Hz]
period = fs // f0 # number of samples in one period
examples = { # name: (orientation theta, ellipticity chi)
'linear': (np.pi / 4, 0),
'circular': (0, np.pi / 4),
'elliptical': (-np.pi / 4, -np.pi / 6),
}
fig, ax = plt.subplots(ncols=3, figsize=(12, 4), layout='constrained')
for axis, (name, (theta, chi)) in zip(ax, examples.items(), strict=True):
z = bsp.signals.bivariateAMFM(1, theta, chi, 2 * np.pi * f0 * t[:period + 1],
Hembedding=False, complexOutput=True)
axis.plot(z.real, z.imag)
axis.plot(z.real[0], z.imag[0], 'o', color='C1')
axis.annotate('', xy=(z.real[period // 8], z.imag[period // 8]), xytext=(z.real[0], z.imag[0]),
arrowprops={'arrowstyle': '->', 'color': 'C1', 'lw': 2})
axis.set(title=name, xlabel='u(t)', ylabel='v(t)', aspect='equal', xlim=(-1, 1), ylim=(-1, 1))
Over time, the signal runs around its ellipse again and again. utils.visual.plot2D and utils.visual.plot3D show it for a longer signal:
a0, theta0, chi0, phi0 = 1.5, np.pi / 3, -np.pi / 8, 0.7
x = bsp.signals.bivariateAMFM(a0, theta0, chi0, 2 * np.pi * f0 * t + phi0, Hembedding=False)
fig, ax = bsp.utils.visual.plot2D(t, x)
fig, ax = bsp.utils.visual.plot3D(t[:300], x[:300]) # first 0.3 second
3. Stokes parameters and the Poincaré sphere#
Stokes parameters describe polarization with second-order, measurable quantities, as in optics:
\(S_0\) is the power. The normalized parameters \((S_1, S_2, S_3)/S_0\) are a point of the unit sphere, the Poincaré sphere, at longitude \(2\theta\) and latitude \(2\chi\). Linear polarizations lie on the equator, circular ones at the poles. utils.geo2Stokes computes the Stokes parameters, and utils.Stokes2geo goes back.
for name, (theta, chi) in examples.items():
S0, S1, S2, S3 = bsp.utils.geo2Stokes(1, theta, chi)
print(f'{name:>10}: S0 = {S0:.2f}, S1 = {S1:+.2f}, S2 = {S2:+.2f}, S3 = {S3:+.2f}')
linear: S0 = 1.00, S1 = +0.00, S2 = +1.00, S3 = +0.00
circular: S0 = 1.00, S1 = +0.00, S2 = +0.00, S3 = +1.00
elliptical: S0 = 1.00, S1 = +0.00, S2 = -0.50, S3 = -0.87
fig = plt.figure(figsize=(5, 5), layout='constrained')
ax = fig.add_subplot(projection='3d')
# unit sphere and axes
lon, lat = np.meshgrid(np.linspace(0, 2 * np.pi, 25), np.linspace(-np.pi / 2, np.pi / 2, 13))
ax.plot_wireframe(np.cos(lat) * np.cos(lon), np.cos(lat) * np.sin(lon), np.sin(lat), color='0.8', lw=0.5)
ax.plot([-1.3, 1.3], [0, 0], [0, 0], color='k', lw=0.8)
ax.plot([0, 0], [-1.3, 1.3], [0, 0], color='k', lw=0.8)
ax.plot([0, 0], [0, 0], [-1.3, 1.3], color='k', lw=0.8)
ax.text(1.4, 0, 0, '$S_1/S_0$')
ax.text(0, 1.4, 0, '$S_2/S_0$')
ax.text(0, 0, 1.4, '$S_3/S_0$')
# polarization states of the three examples
for name, (theta, chi) in examples.items():
S0, S1, S2, S3 = bsp.utils.geo2Stokes(1, theta, chi)
ax.scatter(S1, S2, S3, s=60, label=name)
ax.legend(loc='upper left')
ax.set_box_aspect((1, 1, 1), zoom=1.4)
ax.set_axis_off()
4. The quaternion Fourier transform#
The QFT of a bivariate signal \(x(t)\) is
The exponential uses \(\boldsymbol{j}\), while the signal uses \(\boldsymbol{i}\). qfft.Qfft computes the QFT with two FFTs, and qfft.Qfftfreq gives the frequencies. For a bivariate signal, \(X(-f) = -\boldsymbol{i}X(f)\boldsymbol{i}\): as for the Fourier transform of a real signal, positive frequencies carry all the information.
X = bsp.qfft.Qfft(x)
f = bsp.qfft.Qfftfreq(N, dt=1 / fs)
# QFT of the quaternion embedding of x, for comparison
X_emb = bsp.qfft.Qfft(bsp.signals.bivariateAMFM(a0, theta0, chi0, 2 * np.pi * f0 * t + phi0))
fig, ax = plt.subplots(figsize=(8, 3), layout='constrained')
ax.plot(bsp.qfft.Qfftshift(f), np.abs(bsp.qfft.Qfftshift(X)), label='bivariate signal')
ax.plot(bsp.qfft.Qfftshift(f), np.abs(bsp.qfft.Qfftshift(X_emb)), '--', label='quaternion embedding')
ax.set(xlim=(-50, 50), xlabel='frequency [Hz]', ylabel='QFT modulus')
ax.legend();
The QFT of the signal has two symmetric peaks, at \(\pm f_0\). The QFT of its quaternion embedding has a single peak at \(f_0\), twice as high, like the analytic signal of a real signal.
The QFT coefficient at \(f_0\) has the polar form of the signal, \(a\,e^{\boldsymbol{i}\theta}e^{-\boldsymbol{k}\chi}e^{\boldsymbol{j}\varphi}\), up to a factor \(N/2\) for the discrete QFT of \(N\) samples: the polarization ellipse can be read on the spectrum.
n0 = np.argmin(np.abs(f - f0)) # index of the frequency f0
X0 = 2 * X[n0] / N
a, theta, chi, phi = bsp.utils.quat2euler(X0)
print(f'from the QFT: a = {a:.3f}, theta = {theta:.3f}, chi = {chi:.3f}, phi = {phi:.3f}')
print(f'true values: a = {a0:.3f}, theta = {theta0:.3f}, chi = {chi0:.3f}, phi = {phi0:.3f}')
from the QFT: a = 1.500, theta = 1.047, chi = -0.393, phi = 0.700
true values: a = 1.500, theta = 1.047, chi = -0.393, phi = 0.700
The Stokes parameters come out of the QFT too:
The second quantity is computed by utils.StokesNorm. Both are invariants of the QFT Parseval theorem, one for energy and one for geometry, and they define the quaternion power spectral density of the spectral analysis tutorial.
g = bsp.utils.StokesNorm(X0) # i S3 + j S1 + k S2
S0, S1, S2, S3 = bsp.utils.geo2Stokes(a0, theta0, chi0)
print(f'from the QFT: S0 = {np.abs(X0)**2:.3f}, S1 = {g.y:.3f}, S2 = {g.z:.3f}, S3 = {g.x:.3f}')
print(f'true values: S0 = {S0:.3f}, S1 = {S1:.3f}, S2 = {S2:.3f}, S3 = {S3:.3f}')
from the QFT: S0 = 2.250, S1 = -0.795, S2 = 1.378, S3 = -1.591
true values: S0 = 2.250, S1 = -0.795, S2 = 1.378, S3 = -1.591
Going further#
The time-frequency tutorial lets the parameters \(a\), \(\theta\), \(\chi\) and \(\varphi\) vary with time, and analyzes non-stationary signals with the quaternion short-time Fourier transform and the quaternion wavelet transform.
The spectral analysis tutorial turns to random signals, whose polarization is described frequency by frequency by the quaternion power spectral density and the degree of polarization.
The filtering tutorial acts on polarization with linear filters.