SquarewaveFourierSeries#

class braintools.surrogate.SquarewaveFourierSeries(n=2, t_period=8.0)#

Judge spiking state with a squarewave Fourier series.

The forward function:

\[\begin{split}g(x) = \begin{cases} 1, & x \geq 0 \\ 0, & x < 0 \\ \end{cases}\end{split}\]

The original function:

\[g(x) = 0.5 + \frac{1}{\pi}*\sum_{i=1}^n {\sin\left({(2i-1)*2\pi}*x/T\right) \over 2i-1 }\]

Backward function:

\[g'(x) = \sum_{i=1}^n\frac{4\cos\left((2 * i - 1.) * 2\pi * x / T\right)}{T}\]
Parameters:
  • n (int, optional) – Number of Fourier terms. Default is 2.

  • t_period (float, optional) – Period of the square wave. Default is 8.0.

See also

squarewave_fourier_series

Function version of this class.

Examples

>>> import brainstate
>>> import jax.numpy as jnp
>>>
>>> # Create a squarewave Fourier series surrogate
>>> sfs_fn = braintools.surrogate.SquarewaveFourierSeries(n=4, t_period=8.0)
>>>
>>> # Apply to input
>>> x = jnp.array([-2.0, -1.0, 0.0, 1.0, 2.0])
>>> spikes = sfs_fn(x)
>>> print(spikes)  # [0., 0., 1., 1., 1.]
>>> import jax
>>> import brainstate as brainstate
>>> import matplotlib.pyplot as plt
>>> xs = jax.numpy.linspace(-3, 3, 1000)
>>> for n in [2, 4, 8]:
>>>   sfs_fn = braintools.surrogate.SquarewaveFourierSeries(n=n)
>>>   grads = brainstate.augment.vector_grad(sfs_fn)(xs)
>>>   plt.plot(xs, grads, label=f'n={n}')
>>> plt.legend()
>>> plt.show()

(Source code)

Notes

This surrogate uses a Fourier series approximation of a square wave, providing a periodic gradient that can be useful for certain types of spiking neural networks.

surrogate_fun(x)[source]#

The surrogate function.

surrogate_grad(x)[source]#

The gradient function of the surrogate function.