/* FakePhysicist.com admin@fakephysicist.com 28 May 2017 compile with: g++ fft.cc -o fft `root-config --cflags --libs` */ #include #include #include #include #include #include "TPad.h" #include "TAxis.h" #include "TCanvas.h" #include "TGraph.h" #include "TMath.h" using namespace std; using namespace TMath; typedef std::complex Complex; typedef std::vector CNArray; /********** Cooley–Tukey FFT **********/ void fft(CNArray &x) { const Long64_t N = x.size(); if (N <= 1) return; // divide CNArray even, odd; even.clear(); odd.clear(); for (Long64_t k = 0; k < N; k += 2) { if(k+1 == N) {break;} even.push_back(x[k]); odd.push_back(x[k+1]); } // compute fft(even); fft(odd); // combine for (Long64_t k = 0; k < N/2; k++) { Complex t = std::polar(1.0, - 2. * Pi() * k / N) * odd[k]; x[k ] = even[k] + t; x[k+N/2] = even[k] - t; } }; /********* inverse fft *********/ void ifft(CNArray& x) { const Long64_t N = x.size(); // conjugate the complex numbers for (Long64_t k=0;k pos0,amp0; // Input Data Vector before Padding pos0.clear(); amp0.clear(); /****** Generating Data Points ********/ for(int ij=0;ij=1.) { pFactor++; } else {break;} } const Long64_t nn = pow(2,pFactor); // Number for Padding cout << " Size of FFT Input " << nn << endl; vector outPos,outAmp; // Vector for Padded Data outPos.clear();outAmp.clear(); /******* Padding the Data *********/ double startPos,endPos, startAmp,endAmp; int ampCnt = 0; double interVal = (pos0.back()-pos0.front())/(nn-1); for(Long64_t ij=0;ij endPos) { ampCnt++; } else { outPos.push_back(newPos); outAmp.push_back(startAmp + (newPos - startPos)*(endAmp - startAmp)/(endPos - startPos)); ij++; } } CNArray data_C; // vector for Complex number data_C.clear(); for(Long64_t ij=0;ij cBin,cAmp; cBin.clear();cAmp.clear(); for(Long64_t ij=0;ij iBin,iAmp; iBin.clear();iAmp.clear(); for(Long64_t ij=0;ijDivide(1,4); TGraph* h3 = new TGraph(inputDataPt,&pos0[0],&0[0]); // Gen TGraph* h0 = new TGraph(nn,&outPos[0],&outAmp[0]); // Pad TGraph* h1 = new TGraph(int(nn/2),&cBin[0],&cAmp[0]); // d-FFT TGraph* h2 = new TGraph(nn,&iBin[0],&iAmp[0]); // id-FFT c1->cd(1); h3->Draw("AL*"); c1->cd(2); h0->Draw("AL"); c1->cd(3); h1->Draw("AL*"); gPad->SetLogy(1); h1->GetXaxis()->SetRangeUser(500., 5000.); // h1->GetXaxis()->SetRangeUser(1995., 2005.); c1->cd(4); h2->Draw("AL"); c1->SaveAs("fft.jpg"); return 0; }