Skip to content

Instantly share code, notes, and snippets.

@zsusswein
Last active October 2, 2023 08:41
Show Gist options
  • Save zsusswein/22dfa202577ddf2a8576472bbc778b97 to your computer and use it in GitHub Desktop.
Save zsusswein/22dfa202577ddf2a8576472bbc778b97 to your computer and use it in GitHub Desktop.
Convolve two sequences in Stan with the FFT. Matches `convolve(x, rev(y), type = "open")` in R.
functions {
vector convolve(vector a, vector b) {
int na = num_elements(a); // Vector lengths
int nb = num_elements(b);
int n_zero_a = nb - 1; // Zero padding lengths
int n_zero_b = na - 1;
vector[nb] b_rev = reverse(b); // The reversed b vector
vector[na + n_zero_a] a_pad; // Instantiate zero padded vectors
vector[nb + n_zero_b] b_rev_pad;
// Perform zero padding
a_pad[1 : n_zero_a] = rep_vector(0, n_zero_a);
b_rev_pad[(nb + 1) : (nb + n_zero_b)] = rep_vector(0, n_zero_b);
// Fill in padded vector
a_pad[(n_zero_a + 1) : (na + n_zero_a)] = a;
b_rev_pad[1 : nb] = b_rev;
// Stan automatically scales the inverse FFT, so no rescaling needed
return get_real(inv_fft(fft(a_pad) .* conj(fft(b_rev_pad))));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment