Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
72f0fb2
modified oaconvolve
NimaSarajpoor Jan 8, 2026
be0035e
update code logic
NimaSarajpoor Jan 8, 2026
907e2e2
minor clean ups
NimaSarajpoor Jan 8, 2026
969f187
major changes to imporve readability
NimaSarajpoor Jan 9, 2026
b366e35
Add param blocksize
NimaSarajpoor Jan 9, 2026
a3d2e44
add temp test for challenger
NimaSarajpoor Jan 9, 2026
22d233b
add func for computing block size
NimaSarajpoor Jan 10, 2026
d6eedfa
remove redundant code
NimaSarajpoor Jan 10, 2026
4e23694
added clearer functions
NimaSarajpoor Jan 11, 2026
01a0e7a
minor change
NimaSarajpoor Jan 11, 2026
dddb708
minor change to help with future refactoring
NimaSarajpoor Jan 11, 2026
41db845
minor change
NimaSarajpoor Jan 11, 2026
99e450b
Added reference for finding optimal block size
NimaSarajpoor Jan 11, 2026
e8fa331
fixed test
NimaSarajpoor Jan 11, 2026
f45f541
revise comment
NimaSarajpoor Jan 12, 2026
39e936c
removed overlap-add explanation. Created PR#36 instead
NimaSarajpoor Jan 13, 2026
f6fed15
renaming private functions to reflect valid convolution
NimaSarajpoor Jan 14, 2026
ccbb651
Merge branch 'main' into oaconvolve
NimaSarajpoor May 17, 2026
1033584
address comments
NimaSarajpoor May 19, 2026
d548d0d
add docstrings and comments
NimaSarajpoor May 19, 2026
c78d67b
improved docstrings and comments
NimaSarajpoor May 20, 2026
fd98840
update comments and docstrings
NimaSarajpoor Aug 1, 2026
0205e15
update comments and docstrings
NimaSarajpoor Aug 1, 2026
bdf8b89
fixed format
NimaSarajpoor Aug 2, 2026
d254ef0
updated imports
NimaSarajpoor Aug 2, 2026
298c5f9
resolved import error and enhanced comment
NimaSarajpoor Aug 10, 2026
3bb3b37
removed redudant code
NimaSarajpoor Aug 10, 2026
d18d010
added a comment
NimaSarajpoor Aug 10, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
205 changes: 198 additions & 7 deletions sdp/challenger_sdp.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,205 @@
import math

import numpy as np
from scipy.fft import next_fast_len
from scipy.special import lambertw


def setup(Q, T):
return
from sdp import pocketfft_r2c_c2r_sdp

# _duccfft replaced _pocketfft in scipy 1.18
try:
from scipy.fft._duccfft.basic import c2r, r2c
except ModuleNotFoundError: # pragma: no cover
from scipy.fft._pocketfft.basic import c2r, r2c


def _compute_block_size(m, n, conv_block_size=None):
Comment thread
NimaSarajpoor marked this conversation as resolved.
"""
Return a block size for the overlap-add method.

Parameters
----------
m : int
Length of the query array Q.

n : int
Length of the time series T.

conv_block_size : int, default None
Block size for the convolution. When `conv_block_size` is None,
it will be automatically set to an optimal value, internally
computed based on the lengths of Q and T.

Returns
-------
conv_block_size : int
Block size for the convolution. Will be at least `m` and at most `n`.
"""
if conv_block_size is None:
if m >= n / 2:

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As I mentioned before, this is purely based on scipy's logic:

https://github.com/scipy/scipy/blob/8c75ae75176236f233824e9a0483c26a69e6dfec/scipy/signal/_signaltools.py#L748-L750

However, the reason is not clear to me.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The overlap-add method adds the last m-1 elements of a block to the first m-1 elements of the next block. Therefore, if conv_block_size is at least 2 * (m-1), then the head and tail of each block will not have common elements and the current implementation works. If conv_block_size is less than 2 * (m-1), the current implementation fails. So: conv_block_size >= 2(m-1)

Also, note that conv_block_size should be <n. Otherwise, there is no point in splitting T into blocks.

Therefore: 2(m-1) <= conv_block_size < n , which gives: m < n/2 + 1


Note:
The current implementation shows conv_block_size = max(conv_block_size, m). However, as mentioned above, the sdp function fails if conv_block_size is < 2 * (m-1). So, we need to:

(1) use conv_block_size = max(conv_block_size, 2 * (m-1)) instead of conv_block_size = max(conv_block_size, m)

(2) Or, we need to revise the implementation so that it can handle cases where conv_block_size is < 2(m-1).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also: I submitted a question in stack overflow regarding the condition if m >= n / 2:

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The overlap-add method adds the last m-1 elements of a block to the first m-1 elements of the next block. Therefore, if conv_block_size is at least 2 * (m-1), then the head and tail of each block will not have common elements and the current implementation works.

If the condition conv_block_size < 2 * (m-1) is not met, the overlap-add approach should still work. See example below.

Example:
Let's compute the sliding dot product between T=[1, 2, 3, 4] and Q=[10, 20, 30]. The sliding dot product is: [140, 200].

The sliding dot product between T and Q is equivalent to the valid convolution between T and Qr, which is the reverse of Q. Let's use overlap-add method and set conv_block_size to m=len(Qr) == 3.

# Each block has zero-padding of length `m-1`

block1: 1, 0, 0 
block2: 2, 0, 0
block3: 3, 0, 0
block4: 4, 0, 0

# reverse of Q
Qr = [30, 20, 10]

In overlap-add method, we compute the circular convolution between each block and Qr. We can use the flip-and-slide method. This gives:

out_block1: 30, 20, 10
out_block2: 60, 40, 20
out_block3: 90, 60, 30
out_block4: 120, 80, 40

We now add m-1 == 2 elements of each block to the first m-1 == 2 elements of next block.

out: out_block1 & out_blokc2 --> 30, 80, 50, 20
out: out & out_block3 --> 30, 80, 140, 80, 30
out: out & out_block4 --> 30, 80, 140, 200, 110, 40

Get the slice (m-1, n), which is (2, 4):
[140, 200]

So, the overlap-add method works if conv_block_size is set to m. The current implementation uses vectorized operation to perform the overlap-add between blocks. However, currently, the vectorized operation used in our implementation fails when conv_block_size is set to a value that is less than 2 * (m - 1).

conv_block_size = n
else:
# To minimize Eq. 3 in
# https://en.wikipedia.org/wiki/Overlap–add_method
# ToDo: Revise `opt_size` by considering RFFT/IRFFT
# instead of FFT/IFFT in the computational cost
overlap = m - 1
Comment thread
NimaSarajpoor marked this conversation as resolved.
opt_size = -overlap * lambertw(-1 / (2 * math.e * overlap), k=-1).real
conv_block_size = next_fast_len(math.ceil(opt_size), real=True)
Comment thread
NimaSarajpoor marked this conversation as resolved.

# Each chunk of `T` is padded with `m - 1` zeros to form a convolution block.
# Since a chunk (from `T`) must contain at least one element,
# the minimum block size is `m`. However, to take advantage of vectorized
# operation at a later step, the minimum block size is set to `2 * (m-1)`
conv_block_size = max(conv_block_size, 2 * (m - 1))

return min(conv_block_size, n)


def _pocketfft_circular_convolve_block(Q, T, conv_block_size):
m = Q.shape[0]
n = T.shape[0]

# Each block in overlap-add method needs to be padded
# with `m-1` zeros. Therefore, the effective block size
# for T is `conv_block_size - (m-1)`.
T_block_size = conv_block_size - (m - 1)
n_blocks = math.ceil(n / T_block_size)
last_block_start = (n_blocks - 1) * T_block_size

# To compute the circular convolution between the zero-padded Q
# and each zero-padded block of T, the data can be loaded into
# a 2D array with `n_blocks + 1` rows, where the first `n_blocks`
# rows correspond to the blocks of T, and the last row is the
# zero-padded Q.
tmp = np.empty((n_blocks + 1, conv_block_size), dtype=np.float64)
tmp[: n_blocks - 1, :T_block_size] = T[:last_block_start].reshape(
n_blocks - 1, T_block_size
)
tmp[: n_blocks - 1, T_block_size:] = 0.0
tmp[n_blocks - 1, : n - last_block_start] = T[last_block_start:]
tmp[n_blocks - 1, n - last_block_start :] = 0.0

tmp[n_blocks, :m] = Q
tmp[n_blocks, m:] = 0.0

fft_2d = r2c(True, tmp, axis=-1)

return c2r(False, np.multiply(fft_2d[:-1], fft_2d[[-1]]), n=conv_block_size)


def _pocketfft_valid_oaconvolve(Q, T, conv_block_size):
"""
Compute the valid convolution between Q and T using the overlap-add method.
This method performs several circular convolutions between Q and blocks of T,
and then combines the results to obtain the valid convolution between Q and T

Parameters
----------
Q : numpy.ndarray
Query array or subsequence.

T : numpy.ndarray
Time series or sequence.

def sliding_dot_product(Q, T):
conv_block_size : int
Block size for the overlap-add method.
The value cannot be less than len(Q).

Returns
-------
out : numpy.ndarray
The valid convolution between Q and T.

Notes
-----
Each block of the convolution contains part of `T`, padded with `len(Q)-1`
zeros. Therefore, `conv_block_size` must be at least `len(Q)` so that it
can cover at least one element of `T` in each block.
"""
# performs several circular convolutions between
# zero-padded Q and zero-padded blocks of T
# and returns a 2D array of the results,
# where each row is associated with a block of T
QT_conv_blocks = _pocketfft_circular_convolve_block(Q, T, conv_block_size)

# The subsequences at the boundaries of the blocks
# are shared between adjacent blocks.
# The following logic is needed to reconstruct
# the valid convolution between Q and T
overlap = len(Q) - 1
out = QT_conv_blocks[:, :-overlap]
out[1:, :overlap] += QT_conv_blocks[:-1, -overlap:]

return np.reshape(out, (-1,))[len(Q) - 1 : len(T)]


def _valid_convolve(Q, T, conv_block_size=None):
"""
Compute the valid convolution between Q and T

Parameters
----------
Q : numpy.ndarray
Query array or subsequence.

T : numpy.ndarray
Time series or sequence.

conv_block_size : int, default None
Block size for the overlap-add method. When `conv_block_size`
is None, it will automatically be set to an optimal value,
internally computed based on the lengths of Q and T.

Returns
-------
out : numpy.ndarray
The valid convolution between Q and T.

Notes
-----
The valid convolution between ``Q`` and ``T`` is equivalent to
the sliding dot product between Q[::-1] and T.
"""
m = len(Q)
l = T.shape[0] - m + 1
out = np.empty(l)
for i in range(l):
out[i] = np.dot(Q, T[i : i + m])
n = len(T)
conv_block_size = _compute_block_size(m, n, conv_block_size=conv_block_size)
if conv_block_size >= n:
out = pocketfft_r2c_c2r_sdp._pocketfft_valid_convolve(Q, T)
else:
out = _pocketfft_valid_oaconvolve(Q, T, conv_block_size)

return out


def setup(Q, T):
return


def sliding_dot_product(Q, T, conv_block_size=None):
Comment thread
NimaSarajpoor marked this conversation as resolved.
"""
Compute the sliding dot product between Q and T

Parameters
----------
Q : numpy.ndarray
Query array or subsequence.

T : numpy.ndarray
Time series or sequence.

conv_block_size : int, default None
Block size for the overlap-add method. When `conv_block_size`
is None, it will automatically be set to an optimal value,
internally computed based on the lengths of Q and T.

Returns
-------
out : numpy.ndarray
The sliding dot product between Q and T.
"""
if len(Q) == len(T):
return np.dot(Q, T)
Comment thread
NimaSarajpoor marked this conversation as resolved.
else:
return _valid_convolve(Q[::-1], T, conv_block_size=conv_block_size)
29 changes: 22 additions & 7 deletions sdp/pocketfft_r2c_c2r_sdp.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,37 @@
import numpy as np
from scipy.fft import next_fast_len
from scipy.fft._pocketfft.basic import r2c, c2r


def setup(Q, T):
return
# _duccfft replaced _pocketfft in scipy 1.18
try:
from scipy.fft._duccfft.basic import c2r, r2c
except ModuleNotFoundError: # pragma: no cover
from scipy.fft._pocketfft.basic import c2r, r2c


def sliding_dot_product(Q, T):
def _pocketfft_valid_convolve(Q, T):
Comment thread
NimaSarajpoor marked this conversation as resolved.
"""
Compute the valid convolution between ``Q`` and ``T``
using circular convolution in the frequency domain
"""
n = len(T)
m = len(Q)
next_fast_n = next_fast_len(n, real=True)

tmp = np.empty((2, next_fast_n))
tmp[0, :m] = Q[::-1]
tmp[0, :m] = Q
tmp[0, m:] = 0.0
tmp[1, :n] = T
tmp[1, n:] = 0.0
fft_2d = r2c(True, tmp, axis=-1)

return c2r(False, np.multiply(fft_2d[0], fft_2d[1]), n=next_fast_n)[m - 1 : n]
return c2r(False, np.multiply(fft_2d[0], fft_2d[1]), n=next_fast_n)[
len(Q) - 1 : len(T)
]


def setup(Q, T):
return


def sliding_dot_product(Q, T):
return _pocketfft_valid_convolve(Q[::-1], T)
15 changes: 15 additions & 0 deletions test.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,3 +210,18 @@ def test_pyfftw_sdp_max_n():
np.testing.assert_allclose(comp, ref)

return


def test_oaconvolve_sdp_blocksize():
from sdp.challenger_sdp import sliding_dot_product

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line needs to be modified if, at a later time, we decide to move the proposal to a new file (module).


T = np.random.rand(2**10)
Q = np.random.rand(2**8)
conv_block_size = 2**9

comp = sliding_dot_product(Q, T, conv_block_size=conv_block_size)
ref = naive_sliding_dot_product(Q, T)

np.testing.assert_allclose(comp, ref)

return
Loading