Sunday, March 10, 2013

Interfacing Armadillo and FFTW

   FFTW, or the Fastest Fourier Transform in the West, is an awesome C library used to, well, perform FFTs. Armadillo, on the other hand, is an awesome C++ library that implements linear algebra operations. Both are renowned for their amazing speed and, especially the latter, ease of use.
   Now suppose you want to use Armadillo in concert with FFTW. By default, FFTW assumes that you are using fftw_complex* arrays which memory are allocated using fftw_malloc. Now, assuming that you want to transform elements of an Armadillo vector or matrix, copying the data from the matrix to a newly allocated array may not be desirable (or it might be, depending on the performance hit incurred by not using fftw_malloc). Then, your C++ code should be something like
   I'm by no means an expert, but this snippet works beautifully in my own code.
   Please feel free to point out any factual errors.
Update: Note that the operations in the Gist do not commute, i.e. the order in which they are done is important. If you put data in the samples matrix before creating the plan, your columns will be overwritten. Pay attention!

2 comments:

  1. Thank you for the nice post. But what if I want to make a 2d or 3d fft over a 2d (or 3d) Armadillo matrix? Any suggestion?

    ReplyDelete
    Replies
    1. Both the Mat and Cube classes in Armadillo provide a memptr() member function. From what I gather from the documentation of both packages (I haven't verified, so it needs testing), Mat, Cube and fftw_complex arrays use row-major ordering, so what is said in the article above should be directly applicable to the 2D and 3D cases, with the appropriate modification for the fftw call. Section 3.2 of the FFTW docs should help.

      And thanks for your comment!

      Delete

I'm very sorry to put you through the CAPTCHA. I tried to remove it, but the spam comments were unbelieveable. Here's a funny website to compensate: http://craptchas.com/