numerical methods: fft in astrophysicsusers-phys.au.dk › f041080 › numeric › project.pdf ·...

17
Numerical Methods: FFT in astrophysics Rasmus Handberg 1 Introduction The Fast Fourier Transform has many applications in physics from calculations in quan- tum mechanics to analysis of images and all kinds of oscillating data. The applications I will present here, are most useful in the areas of astronomy and astrophysics. None least in the area of asteroseismology where information about the structure of stars are extracted by analyzing the oscillations of the stellar surfaces. But the applications of the algorithms developed in this project are far more general, and could in fact be used in all areas where two-dimensional data in present. 2 The algorithm For a set of complex (or real) numbers x n , n =0, 1,...,N - 1, the discrete Fourier transform (DFT) is defined as a set of complex numbers c k : c k = N -1 n=0 x n e -2πink/N ,k =0, 1,...,N - 1 (1) And the inverse DFT is defined as x k = 1 N N -1 n=0 c n e 2πink/N (2) Calculating the DFT directly via these definitions is an O(N 2 ) operation and can thus be quite time consuming if the sets of numbers are of an reasonable size. The basic idea behind the Fast Fourier Transform is to provide a remarkable faster way of calculating the DFT. The idea behind the the Cooley-Tukey algorithm, which is the version we will use here, is to split the calculation of the DFT of size N up into two DFT’s of size M = N/2: c k = N -1 n=0 x n e -2πink/N (3) = M-1 m=0 x 2m e -2πi(2m)k/N + M-1 m=0 x 2m e -2πi(2m+1)k/N (4) = M-1 m=0 x 2m e -2πimk/M + e -2πik/N M-1 m=0 x 2m+1 e -2πimk/M (5) = c (even) k + c (odd) k e -2πik/N for k<M c (even) k-M - c (odd) k-M e -2πi(k-M)/N for k M (6) The exponential functions in the above expression is sometime referred to as “twittle factors”: w N e -2πi/N (7) 1

Upload: others

Post on 09-Jun-2020

14 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Numerical Methods: FFT in astrophysicsusers-phys.au.dk › f041080 › numeric › Project.pdf · Numerical Methods: FFT in astrophysics RasmusHandberg 1 Introduction TheFastFourierTransformhasmanyapplicationsinphysicsfromcalculationsinquan-tum

Numerical Methods: FFT in astrophysicsRasmus Handberg

1 Introduction

The Fast Fourier Transform has many applications in physics from calculations in quan-tum mechanics to analysis of images and all kinds of oscillating data. The applicationsI will present here, are most useful in the areas of astronomy and astrophysics. Noneleast in the area of asteroseismology where information about the structure of stars areextracted by analyzing the oscillations of the stellar surfaces. But the applications of thealgorithms developed in this project are far more general, and could in fact be used in allareas where two-dimensional data in present.

2 The algorithm

For a set of complex (or real) numbers xn, n = 0, 1, . . . , N − 1, the discrete Fouriertransform (DFT) is defined as a set of complex numbers ck:

ck =N−1∑n=0

xne−2πink/N , k = 0, 1, . . . , N − 1 (1)

And the inverse DFT is defined as

xk = 1N

N−1∑n=0

cne2πink/N (2)

Calculating the DFT directly via these definitions is an O(N2) operation and can thus bequite time consuming if the sets of numbers are of an reasonable size.The basic idea behind the Fast Fourier Transform is to provide a remarkable faster wayof calculating the DFT. The idea behind the the Cooley-Tukey algorithm, which is theversion we will use here, is to split the calculation of the DFT of size N up into two DFT’sof size M = N/2:

ck =N−1∑n=0

xne−2πink/N (3)

=M−1∑m=0

x2me−2πi(2m)k/N +

M−1∑m=0

x2me−2πi(2m+1)k/N (4)

=M−1∑m=0

x2me−2πimk/M + e−2πik/N

M−1∑m=0

x2m+1e−2πimk/M (5)

=

c(even)k + c

(odd)k e−2πik/N for k < M

c(even)k−M − c

(odd)k−Me

−2πi(k−M)/N for k ≥M(6)

The exponential functions in the above expression is sometime referred to as “twittlefactors”:

wN ≡ e−2πi/N (7)

1

Page 2: Numerical Methods: FFT in astrophysicsusers-phys.au.dk › f041080 › numeric › Project.pdf · Numerical Methods: FFT in astrophysics RasmusHandberg 1 Introduction TheFastFourierTransformhasmanyapplicationsinphysicsfromcalculationsinquan-tum

Numerical Methods: FFT in astrophysics Rasmus Handberg

By some simple mathematics it can be seen that the following relationship holds betweenthe twittle factors in the above expression:

wk−MN = e−2πi(k−M)/N (8)= e−2πik/N · e−2πiM/N (9)= e−2πik/N · e−πi (10)= −wkN (11)

And we can thus rewrite the expression to:

ck =

c(even)k + c

(odd)k wkN for k < M

c(even)k−M + c

(odd)k−Mw

kN for k ≥M

(12)

As it can be seen from the above expression, we have now split the calculation of the DTFof sizeM into two new DFT’s of sizeM . This process can then be continued recursively aslong as N is an even number. Therefore it would be favorable if the number of elements inthe set xn can be written as a power of two, as this would imply that this process can becontinues all the way to N = 1 in which case the DFT of equation (1) is easily calculated.This will change the calculation from being O(N2) to instead being O(N log2(N)) whichis remarkably faster.The program speedtest calculates a number of FFT’s and measures the computation timeas a function of N . The results are shown in figure 1 where the dashed line correspondsto a fit of a function of the form

t = a ·N · log2(N) , (13)

and as it can be seen this corresponds nicely with the measurements.

0

1000

2000

3000

4000

5000

6000

7000

8000

9000

0 50000 100000 150000 200000 250000 300000

Tim

e (m

sec)

N

SpeedFit

Figur 1: Computation time as a function of number of elements N on genryc. Theconstant of the fit is determined to be a = 1.732× 10−3.

The same algorithm can be used to perform the inverse transformation, with the exceptionof a change of sign in the exponent in the definition of wN and the normalization constant.

2

Page 3: Numerical Methods: FFT in astrophysicsusers-phys.au.dk › f041080 › numeric › Project.pdf · Numerical Methods: FFT in astrophysics RasmusHandberg 1 Introduction TheFastFourierTransformhasmanyapplicationsinphysicsfromcalculationsinquan-tum

Numerical Methods: FFT in astrophysics Rasmus Handberg

2.1 Two-dimensional FFT

In the case of a two-dimensional set of numbers xn1n2 where n1 = 0, 1, . . . , N1 − 1 andn2 = 0, 1, . . . , N2 − 1 the discrete Fourier transform instead takes the form:

ck1k2 =N1−1∑n1=0

N2−1∑n2=0

xn1n2e−2πin1k1/N1e−2πin2k2/N2 (14)

=N1−1∑n1=0

e−2πin1k1/N1

N2−1∑n2=0

xn1n2e−2πin2k2/N2

(15)

= FFT1(FFT2(xn1n2)) (16)

where the meaning of the last line is to first perform a FFT along dimension 2 andthereafter doing a FFT along dimension 1. In practice this means that the two dimensionalFFT of a matrix x is calculated by first doing one-dimensional FFT’s on the rows of xand then doing FFT’s on the columns of the resulting matrix.In order for the algorithm to be efficient the image must have dimensions that are powersof two, e.g. 1024×2048.

3 Comparison with the Least Square Spectrum

A very common use of the FFT is in the calculation of power- or amplitude-spectra toanalyze timeseries-data and extract frequency-information from these. By calculating the|FFT|2 of the data the result will be a spectrum of the strength of harmonic oscillationsin the data, evaluated at the fundamental frequencies:

νn = n/T , n = 0, 1, . . . , N − 1 (17)

where T corresponds to the total time over which the timeseries spans.The algorithm that is used in the astronomy-group at Aarhus University for analyzingtimeseries data is completely equivalent to calculating the Fourier transform, but insteadbuilds on a Least Squares fit to sine and cosine:

R(ν) =N−1∑n=0{xn − [α · cos(2πνtn) + β · sin(2πνtn)]}2 (18)

The Least Squares fit is then optained by minimizing this with respect to α and β:

∂R

∂α= ∂R

∂β= 0 (19)

By solving these equations the value of α and β can be calculated as:

α(ν) = s · cc− c · scss · cc− sc2 , β(ν) = c · ss− s · sc

ss · cc− sc2 (20)

3

Page 4: Numerical Methods: FFT in astrophysicsusers-phys.au.dk › f041080 › numeric › Project.pdf · Numerical Methods: FFT in astrophysics RasmusHandberg 1 Introduction TheFastFourierTransformhasmanyapplicationsinphysicsfromcalculationsinquan-tum

Numerical Methods: FFT in astrophysics Rasmus Handberg

where

s =∑

iwi · xi · sin(2πνti) (21)

c =∑

iwi · xi · cos(2πνti) (22)

ss =∑

iwi · sin2(2πνti) (23)

cc =∑

iwi · cos2(2πνti) (24)

sc =∑

iwi · sin(2πνti) · cos(2πνti) (25)

and the Least Square Amplitude-spectrum is given by:

A(ν) =√α(ν)2 + β(ν)2 (26)

This way of calculating the spectrum has a number of advantages over using the FFT ine.g. asteroseismic data.1 First of all, the algorithm is not restricted to timeseries that areequidistant in time, but is capable of handling data with gaps and second it is posibleto “over-sample” the spectrum to get the maximum frequency resolution, as it can beseen in figure 2. While this can somewhat be compensated by padding zeros on the data

0

2

4

6

8

10

1180 1185 1190 1195 1200 1205 1210 1215 1220

Am

plitu

de (

m/s

)

Frequency (microHz)

FFTLeast Squares

Figur 2: Comparison of the FFT and Least Square Spectrum.

before doing the FFT, the Least Squares Spectrum has an extra advantage which it isnot possible with the FFT. The ability to use statistical weights in the calculation of thespectrum. This has shown to have an enormous effect when analyzing asteroseismic data,to be able to down-weight bad datapoints and give larger value to good datapoints.But in cases where where the analysis is of timeseries with measurements equidistant intime and no statistical weights is used, the FFT is still an extremely used tool for doing

1The program that calculates the Least Squares spectrum was made for the course “Timeseriesanalysis in astrophysics” and is available at http://www.phys.au.dk/~f041080/tidsserie/

4

Page 5: Numerical Methods: FFT in astrophysicsusers-phys.au.dk › f041080 › numeric › Project.pdf · Numerical Methods: FFT in astrophysics RasmusHandberg 1 Introduction TheFastFourierTransformhasmanyapplicationsinphysicsfromcalculationsinquan-tum

Numerical Methods: FFT in astrophysics Rasmus Handberg

astero- and in particular helio-seismic analysis. Of cause because it is way superior in caseof computational speed.

4 Image Processing

Where the one-dimensional FFT, in the case of asteroseismology at least, has some disad-vantages, the two-dimensional FFT is an extremely powerful tool as it is very useful inthe field of imageprocessing. It’s large usefulness comes form the fact that it’s extremelyrare that there are gaps in image-data and from the so-called Convolution Theorem:

f(x, y) ∗ h(x, y)⇔ H(u, v)F (u, v) (27)f(x, y)h(x, y)⇔ H(u, v) ∗G(u, v) (28)

Where capital letters denotes Fourier transformed and “∗” denotes convolution.An example of this is that the real image is folded with a noise. By first performing aFFT of the image, the two components can be “deconvoluted” by simple division andmultiplication-operations. This can also be used to low- or highpass-filter an image whicheither means smoothing the image or enhancing sharp features in the image.In the following example I have taken an image of the Crab Nebula2 and tried to removethe noise in the Fourier-domain. In figure 3 the original image and the Fourier transformis shown.

200 400 600 800 1000 1200 1400 1600 1800 2000

200

400

600

800

1000

1200

1400

1600

1800

2000

(a) Original image200 400 600 800 1000 1200 1400 1600 1800 2000

200

400

600

800

1000

1200

1400

1600

1800

2000

(b) Fourier transform

Figur 3: The Crab Nebula.

By then multiplying the Fourier transform with the filter shown in figure 4a and doing theinverse Fourier transform, we end up with the image shown in figure 4b. As it hopefullycan be seen the structures of the nebula are now much more distingusable from the noise.

2Image is taken by the author and collaborators with the IAC80-telescope on Tenerife.

5

Page 6: Numerical Methods: FFT in astrophysicsusers-phys.au.dk › f041080 › numeric › Project.pdf · Numerical Methods: FFT in astrophysics RasmusHandberg 1 Introduction TheFastFourierTransformhasmanyapplicationsinphysicsfromcalculationsinquan-tum

Numerical Methods: FFT in astrophysics Rasmus Handberg

200 400 600 800 1000 1200 1400 1600 1800 2000

200

400

600

800

1000

1200

1400

1600

1800

2000

(a) Filter200 400 600 800 1000 1200 1400 1600 1800 2000

200

400

600

800

1000

1200

1400

1600

1800

2000

(b) Filtered image

Figur 4: The filter used and resulting image after filtering. In (a) black denotesone and white denotes zero.

4.1 Correcting for the Point Spread Function

In all images point-sources have in some way been smeared out by the optics. This isdescribed by the Point Spread Function (PSF) wich describes how a point-source willlook in the resulting image. This means that the image g will actually consist of the real(true) image, f , folded with the PSF, h:

g = h ∗ f (29)

By performing the Fourier-transform (29) becomes G = HF and thus

F = G

H(30)

The restored image f can then be extracted by performing the inverse Fourier transform.This operation is called inverse filtering and is very useful if we know how the image isdistorted, that is, if we know h or H.Generally it can be difficult to obtain information about the PSF, but as astronomers weare really privileged, as there in all our images always will be several point-sources present,namely single stars. In the following example I have used an image form the Sloan DigitalSky Survey3 of the Globular Cluster M92. And I will try to correct the effects from thePSF to better be able to separate the single stars in the cluster. The original image ofthe cluster and its Fourier transform is shown in figure 5.The following algorithm is implemented in the program m92 and the routine dftfilt.The first thing the program does is to select a small region of the image around a singlestar to be used for the PSF. This is shown in figure 6. The routine then pads the twoimages with zeros to make them of equal size. Moreover it makes sure that the images

3http://seds.org/messier/m/m092.html

6

Page 7: Numerical Methods: FFT in astrophysicsusers-phys.au.dk › f041080 › numeric › Project.pdf · Numerical Methods: FFT in astrophysics RasmusHandberg 1 Introduction TheFastFourierTransformhasmanyapplicationsinphysicsfromcalculationsinquan-tum

Numerical Methods: FFT in astrophysics Rasmus Handberg

100 200 300 400 500 600 700 800

100

200

300

400

500

600

700

800

(a) Image of M92 from SDSS.500 1000 1500 2000

200

400

600

800

1000

1200

1400

1600

1800

2000

(b) Fourier transform of the original image.

Figur 5: The Globluar Cluster M92.

has a dimensions that are powers of two to speed up the calculation. Then the routinecomputes the Fourier transforms of the two images and divides the two.It is now necessary to put this result through a filter of the same kind as shown infigure 4a. The reason for this is that the PSF will have a large number of small valuesand i noise is present in the image, dividing this with the vanishing components of thePSF will completely dominate the resulting image. This can however be compensated forby applying the filter, as zeros in the PSF are less likely to be found in the corners.

(a)500 1000 1500 2000

200

400

600

800

1000

1200

1400

1600

1800

2000

(b)

Figur 6: The Point Spread Function.

The result is then put through an inverse Fourier-transform and the resulting image is

7

Page 8: Numerical Methods: FFT in astrophysicsusers-phys.au.dk › f041080 › numeric › Project.pdf · Numerical Methods: FFT in astrophysics RasmusHandberg 1 Introduction TheFastFourierTransformhasmanyapplicationsinphysicsfromcalculationsinquan-tum

Numerical Methods: FFT in astrophysics Rasmus Handberg

cropped to match the dimensions of the original image.

100 200 300 400 500 600 700 800

100

200

300

400

500

600

700

800

(a) Before100 200 300 400 500 600 700 800

100

200

300

400

500

600

700

800

(b) After

Figur 7: Comparison of M92 before and after the filtering.

As it is seen, it is now possible to detect individual stars much closer to the center of thecluster.

Referencer

Gonzales, R. C., R. E. Woods, and S. L. Eddins (2004). Digital Image Processing UsingMatlab. Pearson Prentice Hall.

Press, W. H., S. A. Teukolsky, W. T. Vetterling, and B. P. Flannery (1992). NumericalRecipies (2 ed.). Cambridge University Press.

Teuber, J. (1989). Digital Billedebehandling. Teknisk Forlag A/S.

8

Page 9: Numerical Methods: FFT in astrophysicsusers-phys.au.dk › f041080 › numeric › Project.pdf · Numerical Methods: FFT in astrophysics RasmusHandberg 1 Introduction TheFastFourierTransformhasmanyapplicationsinphysicsfromcalculationsinquan-tum

Numerical Methods: FFT in astrophysics Rasmus Handberg

5 Source Code

5.1 kind_defs.f95

1 module kind_defs2 implicit none3 integer, parameter :: &4 short = SELECTED_INT_KIND(5), &5 long = SELECTED_INT_KIND(10), &6 sgl = SELECTED_REAL_KIND(6), &7 dbl = SELECTED_REAL_KIND(14),&8 quad = SELECTED_REAL_KIND(30)9

10 real(dbl), parameter :: pi = 3.14159265358979323846_dbl11 complex(dbl), parameter :: complexi = (0.0_dbl,1.0_dbl)12 end module

5.2 fft.f95

1 module FourierTransform2 implicit none3 !private calcfft4 private calcfft25

6 interface7 recursive function calcfft(x, sgn) result (c)8 use kind_defs9 implicit none

10 complex(dbl), intent(in) :: x(:)11 integer, intent(in) :: sgn12 complex(dbl) :: c(size(x))13 end function14

15 function calcfft2(x, sgn) result (c)16 use kind_defs17 implicit none18 complex(dbl), intent(in) :: x(:,:)19 integer, intent(in) :: sgn20 complex(dbl) :: c(size(x,1),size(x,2))21 end function22

23 logical function ispower2(N)24 integer, intent(in) :: N25 end function26

27 integer function nextpow2(m)28 integer, intent(in) :: m29 end function30 end interface31

32 interface fft33 module procedure fftc34 module procedure fftd35 end interface36 interface ifft37 module procedure ifftc38 module procedure ifftd39 end interface40 interface fft241 module procedure fft2c42 module procedure fft2d43 end interface

9

Page 10: Numerical Methods: FFT in astrophysicsusers-phys.au.dk › f041080 › numeric › Project.pdf · Numerical Methods: FFT in astrophysics RasmusHandberg 1 Introduction TheFastFourierTransformhasmanyapplicationsinphysicsfromcalculationsinquan-tum

Numerical Methods: FFT in astrophysics Rasmus Handberg

44 interface ifft245 module procedure ifft2c46 module procedure ifft2d47 end interface48 contains49 ! Fast Fourier Transform:50 function fftc(x)51 use kind_defs52 implicit none53 complex(dbl), intent(in) :: x(:)54 complex(dbl) :: fftc(size(x))55

56 fftc = calcfft(x, -1)57 end function58 function fftd(x)59 use kind_defs60 implicit none61 real(dbl), intent(in) :: x(:)62 complex(dbl) :: fftd(size(x))63

64 fftd = calcfft(cmplx(x,kind=dbl), -1)65 end function66

67 ! Inverse FFT:68 function ifftc(x)69 use kind_defs70 implicit none71 complex(dbl), intent(in) :: x(:)72 complex(dbl) :: ifftc(size(x))73

74 ifftc = calcfft(x, 1)75 end function76 function ifftd(x)77 use kind_defs78 implicit none79 real(dbl), intent(in) :: x(:)80 complex(dbl) :: ifftd(size(x))81

82 ifftd = calcfft(cmplx(x,kind=dbl), 1)83 end function84

85 ! 2D-FFT:86 function fft2c(x)87 use kind_defs88 implicit none89 complex(dbl), intent(in) :: x(:,:)90 complex(dbl) :: fft2c(size(x,1),size(x,2))91

92 fft2c = calcfft2(x, -1)93 end function94 function fft2d(x)95 use kind_defs96 implicit none97 real(dbl), intent(in) :: x(:,:)98 complex(dbl) :: fft2d(size(x,1),size(x,2))99

100 fft2d = calcfft2(cmplx(x,kind=dbl), -1)101 end function102

103 ! Inverse 2D-FFT:104 function ifft2c(x)105 use kind_defs106 implicit none107 complex(dbl), intent(in) :: x(:,:)108 complex(dbl) :: ifft2c(size(x,1),size(x,2))109

110 ifft2c = calcfft2(x, 1)

10

Page 11: Numerical Methods: FFT in astrophysicsusers-phys.au.dk › f041080 › numeric › Project.pdf · Numerical Methods: FFT in astrophysics RasmusHandberg 1 Introduction TheFastFourierTransformhasmanyapplicationsinphysicsfromcalculationsinquan-tum

Numerical Methods: FFT in astrophysics Rasmus Handberg

111 end function112 function ifft2d(x)113 use kind_defs114 implicit none115 real(dbl), intent(in) :: x(:,:)116 complex(dbl) :: ifft2d(size(x,1),size(x,2))117

118 ifft2d = calcfft2(cmplx(x,kind=dbl), 1)119 end function120 end module121

122 logical function ispower2(N)123 implicit none124 integer, intent(in) :: N125

126 ispower2 = (IAND(N, N-1) == 0)127 end function128

129 integer function nextpow2(m)130 implicit none131 integer, intent(in) :: m132

133 nextpow2 = nint( log10(real(m))/log10(2.0) )134 end function135

136 recursive function calcfft(x, sgn) result (c)137 use kind_defs138 implicit none139 complex(dbl), intent(in) :: x(:)140 integer, intent(in) :: sgn141 complex(dbl) :: c(size(x))142 integer :: M, N, k, j143 complex(dbl), dimension(size(x)/2) :: odd, even, co, ce144 complex(dbl) :: w145

146 N = size(x)147 w = exp(sgn*2.0_dbl*pi*complexi/real(N))148

149 if (mod(N,2) == 0) then150 ! Fast Fourier Transformation:151 ! Split the data in to odd and even:152 M = N/2153 do k = 1,M154 odd(k) = x(2*k)155 even(k) = x(2*k-1)156 enddo157

158 ! Calculate the FFT of the even and odd part:159 co = calcfft(odd, sgn)160 ce = calcfft(even, sgn)161

162 ! Calculate the coefficients:163 do k = 1,M164 c(k) = ce(k) + co(k) * w**(k-1)165 enddo166 do k = M+1,N167 c(k) = ce(k-M) + co(k-M) * w**(k-1)168 enddo169 c = c/sqrt(2.0_dbl)170 else171 ! Slow Fourier Transformation:172 do k = 1,N173 c(k) = (0.0_dbl,0.0_dbl)174 do j = 1,N175 c(k) = c(k) + x(j) * w**((j-1)*(k-1))176 enddo177 enddo

11

Page 12: Numerical Methods: FFT in astrophysicsusers-phys.au.dk › f041080 › numeric › Project.pdf · Numerical Methods: FFT in astrophysics RasmusHandberg 1 Introduction TheFastFourierTransformhasmanyapplicationsinphysicsfromcalculationsinquan-tum

Numerical Methods: FFT in astrophysics Rasmus Handberg

178 if (sgn == 1) c = c/(real(N))179 endif180 end function181

182 function calcfft2(x, sgn) result (c)183 use kind_defs184 use FourierTransform, only : calcfft185 implicit none186 complex(dbl), intent(in) :: x(:,:)187 integer, intent(in) :: sgn188 complex(dbl) :: c(size(x,1),size(x,2))189 integer :: N1, N2, i190

191 ! Get matrix dimensions:192 N1 = size(x,1)193 N2 = size(x,2)194

195 ! Transform by rows:196 do i = 1,N1197 c(i,:) = calcfft(x(i,:), sgn)198 enddo199

200 ! Transform by cols:201 do i = 1,N2202 c(:,i) = calcfft(c(:,i), sgn)203 enddo204 end function

5.3 image.f95

1 module ImageProc2 interface3 subroutine importimage(filename, img)4 use kind_defs5 implicit none6 character(*), intent(in) :: filename7 real(dbl), intent(out) :: img(:,:)8 end subroutine9

10 subroutine saveimage(filename, img)11 use kind_defs12 implicit none13 character(*), intent(in) :: filename14 real(dbl), intent(in) :: img(:,:)15 end subroutine16

17 function fftshift(x)18 use kind_defs19 implicit none20 real(dbl), intent(in) :: x(:,:)21 real(dbl) :: fftshift(size(x,1),size(x,2))22 end function23

24 function roundfilter(N1, N2, filt)25 implicit none26 integer, intent(in) :: N1, N2, filt27 integer :: roundfilter(N1, N2)28 end function29

30 subroutine dftfilt(img, psf, filt)31 use kind_defs32 implicit none33 real(dbl), intent(inout) :: img(:,:)34 real(dbl), intent(in) :: psf(:,:)

12

Page 13: Numerical Methods: FFT in astrophysicsusers-phys.au.dk › f041080 › numeric › Project.pdf · Numerical Methods: FFT in astrophysics RasmusHandberg 1 Introduction TheFastFourierTransformhasmanyapplicationsinphysicsfromcalculationsinquan-tum

Numerical Methods: FFT in astrophysics Rasmus Handberg

35 integer, intent(in) :: filt36 end subroutine37 end interface38 end module39

40 subroutine importimage(filename, img)41 use kind_defs42 implicit none43 character(*), intent(in) :: filename44 real(dbl), intent(out) :: img(:,:)45

46 open(50, file=trim(filename), status=’old’, action=’read’)47 read(50, *) img48 close(50)49 end subroutine50

51 subroutine saveimage(filename, img)52 use kind_defs53 implicit none54 character(*), intent(in) :: filename55 real(dbl), intent(in) :: img(:,:)56 integer :: i, N1, N257

58 N1 = size(img,1)59 N2 = size(img,2)60 open(51, file=trim(filename), status=’replace’, action=’write’)61 do i = 1,N162 write(51, *) img(i,1:N2)63 enddo64 close(51)65 end subroutine66

67 function fftshift(x)68 use kind_defs69 implicit none70 real(dbl), intent(in) :: x(:,:)71 real(dbl) :: fftshift(size(x,1),size(x,2))72 integer :: N1, N273

74 ! Get the dimensions of the image:75 N1 = size(x,1)76 N2 = size(x,2)77

78 ! Shift the quadrants of the image:79 fftshift(1:N1/2, 1:N2/2) = x(N1/2+1:N1, N2/2+1:N2)80 fftshift(1:N1/2, N2/2+1:N2) = x(N1/2+1:N1, 1:N2/2)81 fftshift(N1/2+1:N1, 1:N2/2) = x(1:N1/2, N2/2+1:N2)82 fftshift(N1/2+1:N1, N2/2+1:N2) = x(1:N1/2, 1:N2/2)83 end function84

85 ! Returns a filter to be used to multiply with the fourier transform86 ! before doing the inverse filtering.87 ! Input: N1 -- Integer -- Size of first dimension of Image88 ! N2 -- Integer -- Size of second dimension of Image89 ! filt -- Integer -- Size of the filter.90 function roundfilter(N1, N2, filt)91 implicit none92 integer, intent(in) :: N1, N2, filt93 integer :: roundfilter(N1, N2)94 integer :: i, j95

96 roundfilter = 097 do i = 1,N198 do j = 1,N299 if (sqrt(real(i**2+j**2)) <= filt .or. sqrt(real((i-N1)**2 + j**2)) <= filt &

100 & .or. sqrt(real(i**2 + (j-N2)**2)) <= filt .or. sqrt(real((i-N1)**2 + (j-N2)**2))<= filt) then

13

Page 14: Numerical Methods: FFT in astrophysicsusers-phys.au.dk › f041080 › numeric › Project.pdf · Numerical Methods: FFT in astrophysics RasmusHandberg 1 Introduction TheFastFourierTransformhasmanyapplicationsinphysicsfromcalculationsinquan-tum

Numerical Methods: FFT in astrophysics Rasmus Handberg

101 roundfilter(i,j) = 1102 endif103 enddo104 enddo105 end function106

107

108 ! Perform filtering for the Point Spread Function.109 ! Input: img -- inout -- The image to be filtered.110 ! psf -- in -- The image of the PSF.111 ! filt -- in -- Integer-value of the size of the pseudoinverse-filter.112 subroutine dftfilt(img, psf, filt)113 use kind_defs114 use FourierTransform115 use ImageProc, only : roundfilter !, saveimage116 implicit none117 real(dbl), intent(inout) :: img(:,:)118 real(dbl), intent(in) :: psf(:,:)119 integer, intent(in) :: filt120 real(dbl), allocatable :: f_img(:,:), f_psf(:,:)121 integer, allocatable :: filter(:,:)122 complex(dbl), allocatable :: c_img(:,:), c_psf(:,:)123 integer :: m, P, N1, N2, M1, M2124

125 ! Get size of the image:126 N1 = size(img,1)127 N2 = size(img,2)128 M1 = size(psf,1)129 M2 = size(psf,2)130

131 ! Make them the same size:132 m = maxval([N1, N2, M1, M2])133 P = 2**nextpow2(2*m)134

135 ! Allocate the images:136 allocate(f_img(P,P), f_psf(P,P), c_img(P,P), c_psf(P,P), filter(P,P))137

138 ! Pad with zeros:139 f_img = 0140 f_img(1:N1, 1:N2) = img141 f_psf = 0142 f_psf(1:M1, 1:M2) = psf143

144 ! Calculate the FFT of the two images:145 print *, ’Calculation Fourier-transforms...’146 c_img = fft2(f_img)147 c_psf = fft2(f_psf)148

149 !print *, ’Saving images...’150 !call saveimage(’c_img.img’, abs(c_img))151 !call saveimage(’c_psf.img’, abs(c_psf))152

153 ! Correct for the PSF:154 print *, ’Correcting for the PSF...’155 c_img = c_img / c_psf156

157 ! To avoid large errors do to zeros in c_psf:158 ! This is called pseudoinverse filtering.159 filter = roundfilter(P, P, filt)160 c_img = c_img*filter161

162 ! Do the inverse transformation:163 f_img = real(ifft2(c_img))164

165 ! Crop to the final image:166 img = f_img(1:N1, 1:N2)167

14

Page 15: Numerical Methods: FFT in astrophysicsusers-phys.au.dk › f041080 › numeric › Project.pdf · Numerical Methods: FFT in astrophysics RasmusHandberg 1 Introduction TheFastFourierTransformhasmanyapplicationsinphysicsfromcalculationsinquan-tum

Numerical Methods: FFT in astrophysics Rasmus Handberg

168 ! Final adjustments to image:169 img = transpose(img)170 img = img - minval(img) ! Make the image positive171

172 ! Clean up the memory:173 deallocate(f_img, f_psf, c_img, c_psf, filter)174 end subroutine

5.4 spectra.f95

1 program spectra2 use kind_defs3 use FourierTransform4 implicit none5 integer, parameter :: N = 327686 real(dbl) :: t(1:N), x(1:N), P(1:N), f, Ttot7 complex(dbl) :: c(1:N)8 integer :: i9

10 ! Import data:11 print *, ’ Importing data from "Data/simpel_short.dat".’12 open(50, file=’Data/simpel_short.dat’, status=’old’, action=’read’)13 do i = 1,N14 read(50, *) t(i), x(i)15 enddo16 close(50)17

18 print *, ’ Making spectrum of data using the FFT for comparison’19 print *, ’ with the Least Square-method.’20

21 ! Make spectrum for comparison of FFT and Least Square:22 c = fft(x)23 P = abs(c)*2.0/sqrt(real(N))24 Ttot = maxval(t)-minval(t)25 open(51, file=’Spectra.dat’, status=’replace’, action=’write’)26 do i = 1,N/227 f = (i-1)*(1e6/Ttot) ! The frequency in microHz28 write(51, *) f, P(i)29 enddo30 close(51)31

32 print *, ’ Done. Spectrum saved in Spectra.dat.’33 end program

5.5 speedtest.f95

1 program speedtest2 use kind_defs3 use FourierTransform4 implicit none5 integer, parameter :: Nmax = 186 integer :: N, i7 real(dbl) :: t1, t2, x(2**Nmax)8 complex(dbl) :: c(2**Nmax)9

10 ! Read data:11 call random_number(x)12

13 do i = 4,Nmax14 N = 2**i

15

Page 16: Numerical Methods: FFT in astrophysicsusers-phys.au.dk › f041080 › numeric › Project.pdf · Numerical Methods: FFT in astrophysics RasmusHandberg 1 Introduction TheFastFourierTransformhasmanyapplicationsinphysicsfromcalculationsinquan-tum

Numerical Methods: FFT in astrophysics Rasmus Handberg

15

16 call cpu_time(t1)17 c(1:N) = fft(x(1:N))18 call cpu_time(t2)19

20 print *, N, (t2-t1)*100021 enddo22

23 end program

5.6 m92.f95

1 program M922 use kind_defs3 use FourierTransform4 use ImageProc5 implicit none6 real(dbl), dimension(891,893) :: img7 real(dbl), dimension(32,32) :: psf8 real(dbl) :: maxv, minv9

10 ! Import the image:11 call importimage(’Data/M92_full.dat’, img)12 maxv = maxval(img)13 minv = minval(img)14 !img = img - minv15 !img = img / maxv16 !call saveimage(’M92.img’, img)17

18 ! Find the PSF:19 psf = img(858:889, 827:858)20 psf = psf - minval(psf)21 psf = psf / maxval(psf)22

23 psf = psf - sum(psf(1:3,:))/real(3*32)24 where(psf<0) psf = 025

26 ! Save the PSF-image:27 call saveimage(’psf.img’, psf)28

29 ! Do the filtering:30 call dftfilt(img, psf, 250)31

32 ! Make the image on the same scale as the original:33 img = (img - minval(img)) + minv34 img = maxv * img / maxval(img)35

36 ! Save the image:37 print *, ’Saving final image...’38 call saveimage(’PSFCorrected.img’, img)39 end program

5.7 crabnebula.f95

1 program crabnebula2 use kind_defs3 use FourierTransform4 use ImageProc5 implicit none6 integer, parameter :: N = 2048

16

Page 17: Numerical Methods: FFT in astrophysicsusers-phys.au.dk › f041080 › numeric › Project.pdf · Numerical Methods: FFT in astrophysics RasmusHandberg 1 Introduction TheFastFourierTransformhasmanyapplicationsinphysicsfromcalculationsinquan-tum

Numerical Methods: FFT in astrophysics Rasmus Handberg

7 real(dbl) :: img(N,N)8 complex(dbl) :: c2(N,N)9 integer :: i, filter(N,N)10

11 print *, ’***************************************************’12 print *, ’ Doing image-filtering on the Crab Nebula.’13

14 ! Loading image of Crab Nebula:15 print *, ’Loading image...’16 call importimage(’Data/Crab.dat’, img)17

18 print *, ’Doing 2D-FFT...’19 c2 = fft2(img)20

21 print *, ’Saving Fourier-Image...’22 call saveimage(’CrabFFT.dat’, abs(c2))23

24 ! Design filter:25 filter = roundfilter(N, N, 300)26 call saveimage(’CrabFilter.img’, real(filter,kind=dbl))27

28 ! Do the filtering:29 print *, ’Filtering...’30 c2 = filter * c231 img = real(ifft2(c2))32

33 ! Save the filtered image:34 print *, ’Saving image...’35 call saveimage(’Filtered.dat’, img)36

37 end program crabnebula

17