コード例 #1
0
ファイル: mfcc.cpp プロジェクト: RADIO-PROJECT-EU/AUROS
MFCC::MFCC(settings_t & settings)
    : num_coefs(settings.get<unsigned>("mfcc.num_coefs"))
    , fftw_in_(settings.get<unsigned>("mfcc.mel_filters"))
    , fftw_out_(settings.get<unsigned>("mfcc.mel_filters"))
    , dct_(fftw_plan_r2r_1d(fftw_in_.size(), &fftw_in_[0], &fftw_out_[0], FFTW_REDFT10, FFTW_ESTIMATE ))
{
    output = Eigen::VectorXd::Zero(num_coefs);
}
コード例 #2
0
ファイル: TimeSeriesMotion.cpp プロジェクト: jingxu002/strata
void TimeSeriesMotion::fft( const QVector<double>& in, QVector<std::complex<double> >& out ) const
{
/*
    // The number of elements in the double array is 2 * n, but only the first
    // n are filled with data.  For the complex array, n/2 + 1 elements are
    // required.

    // Copy the input QVector into a double array
    double* inArray = (double*) fftw_malloc( sizeof(double) * 2 * in.size() );

    for (int i = 0; i < in.size(); i++) {
        inArray[i] = in.at(i);
    }

    // Allocate the space for the output
    int n = in.size() / 2 + 1;
    fftw_complex* outArray = (fftw_complex*)fftw_malloc( sizeof(fftw_complex) * n);

    // Create the plan and execute the FFT
    fftw_plan p = fftw_plan_dft_r2c_1d( in.size(), inArray, outArray, FFTW_ESTIMATE);
    fftw_execute(p);

    // Copy the data to the output QVector
    out.resize(n);
    for (int i = 0; i < n; i++) {
        out[i] = std::complex<double>(outArray[i][0], outArray[i][1]);
    }

    // Free the memory
    fftw_destroy_plan(p);
    fftw_free(inArray);
    fftw_free(outArray);
*/
    // Load the buffer with the initial values
    const int n = in.size();
    double *d = new double[n];
    // Load the data
    memcpy(d, in.data(), n * sizeof(double));

#ifdef USE_FFTW
    fftw_plan p = fftw_plan_r2r_1d(n, d, d, FFTW_R2HC, FFTW_ESTIMATE);
    fftw_execute(p);
#else
    // Execute FFT
    gsl_fft_real_radix2_transform(d, 1, n);
#endif

    // Load the data into out
    out.resize(1 + n / 2);
    out[0] = std::complex<double>(d[0], 0);
    for (int i = 1; i < (out.size() - 1); ++i) {
        out[i] = std::complex<double>(d[i], d[n - i]);
    }
    out[out.size() - 1] = std::complex<double>(d[n - 1], 0);

    // Delete the buffer
    delete [] d;
}
コード例 #3
0
ファイル: fft.c プロジェクト: apanly/hackprinceton13
aubio_fft_t * new_aubio_fft (uint_t winsize) {
  aubio_fft_t * s = AUBIO_NEW(aubio_fft_t);
#ifdef HAVE_FFTW3
  uint_t i;
  s->winsize  = winsize;
  /* allocate memory */
  s->in       = AUBIO_ARRAY(real_t,winsize);
  s->out      = AUBIO_ARRAY(real_t,winsize);
  s->compspec = new_fvec(winsize);
  /* create plans */
  pthread_mutex_lock(&aubio_fftw_mutex);
#ifdef HAVE_COMPLEX_H
  s->fft_size = winsize/2 + 1;
  s->specdata = (fft_data_t*)fftw_malloc(sizeof(fft_data_t)*s->fft_size);
  s->pfw = fftw_plan_dft_r2c_1d(winsize, s->in,  s->specdata, FFTW_ESTIMATE);
  s->pbw = fftw_plan_dft_c2r_1d(winsize, s->specdata, s->out, FFTW_ESTIMATE);
#else
  s->fft_size = winsize;
  s->specdata = (fft_data_t*)fftw_malloc(sizeof(fft_data_t)*s->fft_size);
  s->pfw = fftw_plan_r2r_1d(winsize, s->in,  s->specdata, FFTW_R2HC, FFTW_ESTIMATE);
  s->pbw = fftw_plan_r2r_1d(winsize, s->specdata, s->out, FFTW_HC2R, FFTW_ESTIMATE);
#endif
  pthread_mutex_unlock(&aubio_fftw_mutex);
  for (i = 0; i < s->winsize; i++) {
    s->in[i] = 0.;
    s->out[i] = 0.;
  }
  for (i = 0; i < s->fft_size; i++) {
    s->specdata[i] = 0.;
  }
#else
  s->winsize = winsize;
  s->fft_size = winsize / 2 + 1;
  s->compspec = new_fvec(winsize);
  s->in    = AUBIO_ARRAY(double, s->winsize);
  s->out   = AUBIO_ARRAY(double, s->winsize);
  s->ip    = AUBIO_ARRAY(int   , s->fft_size);
  s->w     = AUBIO_ARRAY(double, s->fft_size);
  s->ip[0] = 0;
#endif
  return s;
}
コード例 #4
0
ファイル: mod_corr_fft.c プロジェクト: mcwitt/isg
void mod_corr_fft_init(mod_corr_fft *self, FILE *fp)
{
    self->cr = (double*) fftw_malloc(sizeof(double) * N);
    self->ck = (complex double*) fftw_malloc(sizeof(complex double) * N);

    self->dft = fftw_plan_dft_r2c_1d(N, self->cr, self->ck, FFTW_MEASURE);

    self->idct = fftw_plan_r2r_1d(N/2 + 1, self->cr, self->cr,
                                  FFTW_REDFT00, FFTW_MEASURE);

    print_header(fp);
}
コード例 #5
0
ファイル: fftw_test.cpp プロジェクト: TyounanMOTI/ARD
TEST(FFTWTest, DCTI1D) {
  int length = 128;
  boost::shared_array<double> buffer(static_cast<double*>(fftw_malloc(sizeof(double)*length)), fftw_free);
  fftw_plan plan = fftw_plan_r2r_1d(length, buffer.get(), buffer.get(), FFTW_REDFT00, FFTW_ESTIMATE);
  for (int i = 0; i < length; i++) {
    buffer[i] = 1.0;
  }
  fftw_execute(plan);
  EXPECT_EQ(1.0, buffer[0]/(2.0*(length-1)));

  fftw_destroy_plan(plan);
}
コード例 #6
0
ファイル: specserver.c プロジェクト: jeffkaufman/specserver
void sense(int aud_fd, struct spsv_commobj* sc)
{
   short mic_buf[WINDOW_SIZE];  /* mic output */

   double* sound; /* fft input */
   double* freq;  /* fft output */
   fftw_plan p;   /* fftw data to turn sound into freq */

   FILE* file;

   /* fft input */
   sound = (double*) fftw_malloc( sizeof(double) * WINDOW_SIZE);

   /* fft output */
   freq = (double*) fftw_malloc( sizeof(double) * WINDOW_SIZE);
   
   p = fftw_plan_r2r_1d(WINDOW_SIZE, sound, freq,
			FFTW_R2HC, FFTW_FORWARD);
   
   printf("Set up, about to process sound\n");

   char erg[256];
   sprintf(erg, "data.dat");
   file = fopen(erg, "w");

   fill_buf(aud_fd, mic_buf, WINDOW_SIZE);

   printf("About to loop.\n");

   int cycle = 0;
   while(1)
   {
      do_window(mic_buf, sound); /* convert input to doubles and
				  * window it */
      fftw_execute(p);

      send_data(sc, WINDOW_SIZE/2-1, freq);

      advance_buf(mic_buf, WINDOW_SIZE >> FRAC_READ);

      fill_buf(aud_fd, mic_buf, WINDOW_SIZE>>FRAC_READ);

      cycle ++;
   }
   
   printf("Done with sound, about to close up\n");

   fclose(file);

   fftw_destroy_plan(p);
   fftw_free(sound);
   fftw_free(freq);
}
コード例 #7
0
ファイル: dsp.c プロジェクト: KenHung/AudioVSTToolbox
void fft(double *in, double *out, int32_t N, uint8_t method)
{
	/* method :
	 * 0 = DFT
	 * 1 = IDFT
	 * 2 = DHT
	 */

	fftw_plan p = fftw_plan_r2r_1d(N, in, out, method, FFTW_ESTIMATE);
	fftw_execute(p);
	fftw_destroy_plan(p);
}
コード例 #8
0
ファイル: dct_example_2.c プロジェクト: gulkhan007/kde
int main(int argc, char** argv)
{
	int n=N;

	double in[N]={0.0545,    0.2442,    0.4026,    0.2442,    0.0545};
	double out[N],in_n[N], in2[N],in2_n[N];

	fftw_plan idct =	fftw_plan_r2r_1d(N, in, out, FFTW_REDFT01,
			FFTW_MEASURE);
	fftw_plan dct =	fftw_plan_r2r_1d(N, out, in2, FFTW_REDFT10,
			FFTW_MEASURE);


	for(int i = 0; i < n; i++)
		in_n[i]=in[i]/sqrt(2*n);

	in_n[0]*=sqrt(2);


	fftw_execute(idct);
	fftw_execute(dct);

	for(int i = 0; i < n; i++)
		in2_n[i]=in2[i]/sqrt(2*n);

	in2_n[0]/=sqrt(2);

	print_v(in,n,"in");
	print_v(in_n,n,"in_n");
	print_v(out,n,"out");
	print_v(in2,n,"in2");
	print_v(in2_n,n,"in2_n");

	fftw_destroy_plan(idct);
	fftw_destroy_plan(dct);

	return 0;
}
コード例 #9
0
ファイル: chebpack.c プロジェクト: xdavidliu/chebpack
chebpack_plan chebpack_create(int N, double a, double b)
{
     chebpack_plan p = (chebpack_plan) malloc(sizeof(struct chebpack_plan_s));

     p->N = N;
 
     p->x = (double *) malloc(sizeof(double) * (N+1));
     chebpack_set_interval(p, a, b);

     p->c = (double *) fftw_malloc(sizeof(double) * (N+1));
     p->p = fftw_plan_r2r_1d(N+1, p->c, p->c, FFTW_REDFT00, FFTW_ESTIMATE);

     return p;
}
コード例 #10
0
ファイル: init.c プロジェクト: UIKit0/eXtace
void reinit_extace(int new_nsamp)
{

  /* Stop drawing the display */
    draw_stop();
    if(data_handle != -1) /* stop if previously opened */
      { 
	input_thread_stopper(data_handle);
	close_datasource(data_handle);
      }	

  /* Free all buffers */
        mem_dealloc();
	scope_begin_l = 0;
	scope_begin_l = 0;
	/* auto shift lag slightly to maintain good sync 
	 * The idea is the shift the lag slighly so that the "on-time" data
	 * is in the MIDDLE of the window function for better eye/ear matchup
	 */
	nsamp = new_nsamp;

	convolve_factor = floor(nsamp/width) < 3 ? floor(nsamp/width) : 3 ;
	if (convolve_factor == 0)
		convolve_factor = 1;
	recalc_markers = TRUE;
	recalc_scale = TRUE;	

	mem_alloc();
	setup_datawindow(NULL,(WindowFunction)window_func);
	ring_rate_changed();
	ring_pos=0;
	
	/* only start if it has been stopped above */
	if(data_handle != -1 && (data_handle=open_datasource(data_source)) >= 0)
	  {
#ifdef USING_FFTW2
		  fftw_destroy_plan(plan);
		  plan = fftw_create_plan(nsamp, FFTW_FORWARD, FFTW_ESTIMATE);
#elif USING_FFTW3
		  fftw_cleanup();
		  plan = fftw_plan_r2r_1d(nsamp, raw_fft_in, raw_fft_out,FFTW_R2HC, FFTW_ESTIMATE);
#endif
		  input_thread_starter(data_handle);
		  ring_rate_changed(); /* Fix all gui controls that depend on
					* ring_rate (adjustments and such
					*/
		  draw_start();
	  }
}
コード例 #11
0
ファイル: fftw_test.cpp プロジェクト: TyounanMOTI/ARD
TEST(FFTWTest, DCT) {
  int size = 128;
  boost::shared_array<double> input(static_cast<double*>(fftw_malloc(sizeof(double)*size)), fftw_free);
  boost::shared_array<double> output(static_cast<double*>(fftw_malloc(sizeof(double)*size)), fftw_free);

  fftw_plan plan = fftw_plan_r2r_1d(size, input.get(), output.get(), FFTW_REDFT10, FFTW_MEASURE);
  for (int i = 0; i < size; i++) {
    input[i] = 10.0;
  }
  fftw_execute(plan);

  EXPECT_EQ(size*2*10.0, output[0]);

  fftw_destroy_plan(plan);
}
コード例 #12
0
ファイル: discrete_gauss.c プロジェクト: pearu/iocbio
int dg_convolve(double *seq, int n, double t)
{
  int k;
  double c;
  double *fseq = (double*)malloc(n*sizeof(double));
  fftw_plan plan = fftw_plan_r2r_1d(n, seq, fseq, FFTW_R2HC, FFTW_ESTIMATE);
  fftw_plan iplan = fftw_plan_r2r_1d(n, fseq, seq, FFTW_HC2R, FFTW_ESTIMATE);
  fftw_execute(plan);
  /* real part: */
  fseq[0] /= n; /* DC component */
  for (k = 1; k < (n+1)/2; ++k)  /* (k < N/2 rounded up) */
    {
      c = exp((cos((2.0*M_PI*k)/n)-1.0)*t)/n;
      fseq[k] *= c; // real part
      fseq[n-k] *= c; // imaginary part
    }
  if (n % 2 == 0) /* N is even */
    fseq[n/2] *= exp((cos((2.0*M_PI*(n/2))/n)-1.0)*t)/n;  /* Nyquist freq. */
  fftw_execute(iplan);
  fftw_destroy_plan(plan);
  fftw_destroy_plan(iplan);
  free(fseq);
  return 0;
}
コード例 #13
0
ファイル: fftlibw3_op.cpp プロジェクト: dsully/libofa
void
FFTLib_op::SetSize(int N, bool optimize, double *in, double *out)
{
	if (optimize)
		Flags = FFTW_MEASURE;
	else
		Flags = FFTW_ESTIMATE;

	if (PlanF != 0)
	{
		fftw_destroy_plan(PlanF);
		PlanF = 0;
	}

	PlanF = fftw_plan_r2r_1d(N, in, out, FFTW_R2HC, Flags);
}
コード例 #14
0
ファイル: fftwidget.cpp プロジェクト: wbt729/pure
void FFTWidget::init() {
	setTitle("FFT");
	hrBpm = 0;
	hrMarker = new QwtPlotMarker();
	hrMarker->setLineStyle(QwtPlotMarker::VLine);
	hrMarker->setLinePen(QPen(QColor(255,255,255,100), 2, Qt::SolidLine));

	QPen pen;
	pen.setWidth(2);
	pen.setColor(Qt::blue);
	QwtSymbol *symb = new QwtSymbol(QwtSymbol::Diamond);
	symb->setPen(pen);
	symb->setSize(10);

	hrMarker->setSymbol(symb);
	hrMarker->attach(this);
	hrMarker->setVisible(false);
	setAxisAutoScale(QwtPlot::yLeft, true);
	counter = 0;
	dX = QVector<double>(size, 0);
	dY = QVector<double>(size, 0);
	dYBuf = QVector<double>(size, 0);
	hamming = QVector<double>(size, 0);

	dataIn = QVector<double>(size, 0);
	sampleInterval = 1000/fS;
	p = fftw_plan_r2r_1d( size, dataIn.data(), dYBuf.data(), FFTW_DHT, FFTW_ESTIMATE );

	for(int i=0;i<size;i++) {
		dX.replace(i, i*(fS/size));
		double tmp = 0.54 - 0.46*(2*3.1415*i/size);
		hamming.replace(i, tmp);
	}

	pen.setColor(Qt::red);

	curve = new QwtPlotCurve();
	curve->setPen(pen);
	curve->setRawSamples(dX.data(), dY.data(), size/2);
	curve->setRenderHint(QwtPlotItem::RenderAntialiased);
	curve->attach(this);
}
コード例 #15
0
ファイル: fftw.c プロジェクト: 00tau/statistics
void dct(int flag, int n) {
    double* in  = malloc( n * sizeof(double));
    double* out = malloc( n * sizeof(double));
    //
    fftw_plan plan = fftw_plan_r2r_1d(n, in, out, flag, FFTW_ESTIMATE);
    for( int k = 0; k < n; k++) {
        // Init input vector
        for( int i = 0; i < n; i++)
            in[i] = 0;
        in[k] = 1;
        // Perform DFT
        fftw_execute(plan);
        // Print results
        dump_vector(n, in );
        dump_vector(n, out);
        printf("\n");
    }
    //
    free(in);
    free(out);
    fftw_destroy_plan(plan);
}
コード例 #16
0
ファイル: audio.cpp プロジェクト: ifapmzadu6/speech-analyzer
/**
 * 実データ1次元離散コサイン逆変換
 */
std::vector<double> Audio::dct_r2r_1d_reverse_vector(std::vector<double> input_vector) {
    int n = (int)input_vector.size();
    double *input = (double *)malloc(sizeof(double) * n);
    double *output = (double *)malloc(sizeof(double) * n);

    for (int i = 0; i < n; i++) {
        input[i] = input_vector[i];
    }

    fftw_plan plan = fftw_plan_r2r_1d(n, input, output, FFTW_REDFT01, FFTW_ESTIMATE);
    fftw_execute(plan);

    std::vector<double> output_vector;
    for (int i = 0; i < n; i++) {
        output_vector.push_back(output[i]);
    }

    if (plan) fftw_destroy_plan(plan);
    free(output);
    free(input);

    return output_vector;
}
コード例 #17
0
ファイル: buttons.c プロジェクト: djandruczyk/eXtace
gint set_data_source()
{

	draw_stop();
	input_thread_stopper(data_handle);
	close_datasource(data_handle);

	if ((data_handle=open_datasource(data_source)) >= 0)
	{
#ifdef USING_FFTW2
		plan = fftw_create_plan(nsamp, FFTW_FORWARD, FFTW_ESTIMATE);
#elif USING_FFTW3
		plan = fftw_plan_r2r_1d(nsamp, raw_fft_in, raw_fft_out, FFTW_R2HC, FFTW_ESTIMATE);
#endif
		ring_rate_changed(); /* Fix all gui controls that depend on
							  * ring_rate (adjustments and such
							  */
		input_thread_starter(data_handle);
		draw_start();
	}

	return TRUE;
}
コード例 #18
0
ファイル: crom_decoder.cpp プロジェクト: albert-no/CROM
void CROM_decoder::run() {
    double n = static_cast<double> (x_dim);
    double logn = log(n);
    int long_logn = static_cast<int> (logn);

    int half_len = x_dim/2;
    int x_start_idx = 0;
    int theta_start_idx = 0;
    int mat_idx;
    int x_hat_idx;

    std::vector<double> thetas_inv(half_len);
    std::vector<double> xout(x_dim);

    double scale = sqrt(n*(1-exp(-2*log(n)/n)));
    double scale_factor= exp(-log(n)/n);
    double uni_rand;

    // at i-th iterationof 
    // scale = [sqrt(n*(1-exp(-2*R/rawL))) * exp(-i*R/rawL)
    // R/L = log(n)/n
    int iter_idx;
    int theta_idx;
    int m;
    double l2norm;

    // setup scale
    scale = sqrt(n*(1-exp(-2*log(n)/n))) * exp(-(L-1)*log(n)/n);

    // Set random seed for thetas
    fftw_plan p;
    p = fftw_plan_r2r_1d(x_dim, x_hat.data(), xout.data(), FFTW_REDFT01, FFTW_MEASURE);
    for (iter_idx=L-1; iter_idx>=0; iter_idx--) {
        if (verbose) {
            printf("iteration = %d\n", iter_idx);
        }
        mat_idx = iter_idx % long_logn;

        // Decoding step
        m = m_array[iter_idx];
        step(scale, m);

        // unnormalize before idct2
        unnormalize_vector(x_hat, x_dim);

        // run idct2
        fftw_execute(p);

        // copy x_hat from xout
        copy_vector(x_hat, xout, x_dim);

        // generate thetas for decoder (sign=false) from random seed=iter_idx
        generate_theta_from_seed(thetas_inv, half_len, iter_idx, false);

        // multiply inverse butterfly matrix
        butterfly_matrix_multiplication(x_hat,
                                        thetas_inv,
                                        half_len,
                                        x_start_idx,
                                        theta_start_idx,
                                        mat_idx);
        // update scale with scale factor
        scale /= scale_factor;
        if (verbose) {
            print_vector(x_hat, x_dim);
        }
    }
    fftw_destroy_plan(p);
}
コード例 #19
0
ファイル: PortAudioSound.cpp プロジェクト: jathalls/PASound
PortAudioSound::PortAudioSound()
{
	error(Pa_Initialize());
	
	iSampleRate = 192000;
	sampleRate = (double) iSampleRate;
	framesPerBuffer = 2048;
	FFTSize = 512;
	FFTsPerBuffer = framesPerBuffer/FFTSize;
	recordflag = false;
	Processing = FALSE;
	overlap = FALSE;
	
	if (!logFile.Open(L"C:/Bat Recordings/TestFileLog.txt", CFile::modeCreate | CFile::modeWrite | CFile::typeText)){
		OutputDebugString(L"Unable to open Log File\n");
	}

	numBuffers = 16;
	ReadIndex = 0;
	WriteIndex = 0;
	currentColumn = 0;
	currentRow = 0;
	maxi = 6.0;
	mini = -6.0;
	
	FFTin = (double *) fftw_malloc(sizeof(double) * (FFTSize+2));
	FFTout = (double *) fftw_malloc(sizeof(double) * FFTSize);
	hamming = (double *) fftw_malloc(sizeof(double) * FFTSize);
	CreateHammingProfile(hamming);
	FFTplan = fftw_plan_r2r_1d(FFTSize, FFTin, FFTout, FFTW_DHT, FFTW_ESTIMATE);
	ppPowSpect = (double **) fftw_malloc(sizeof(double *) * numBuffers);
	ppShade = (BYTE **) fftw_malloc(sizeof(BYTE *) *numBuffers);
	for (int i = 0; i < numBuffers; i++){
		ppPowSpect[i] = (double *) fftw_malloc(sizeof(double) * (FFTSize+1));
		ppShade[i] = (BYTE *) fftw_malloc(sizeof(BYTE) * (FFTSize + 1));
	}
	//FFTplan = fftw_plan_dft_r2c_1d(512, FFTin, FFTout,  FFTW_ESTIMATE);
	//Pspect = (double *) fftw_malloc(sizeof(double) * 512);

	ListDevices();

	PaStreamParameters inputParameters;

	inputParameters.device = 1;
	inputParameters.channelCount = 1;
	inputParameters.sampleFormat = paInt16;
	
	inputParameters.suggestedLatency = Pa_GetDeviceInfo(inputParameters.device)->defaultHighInputLatency;
	inputParameters.hostApiSpecificStreamInfo = NULL;
	int err = Pa_IsFormatSupported(&inputParameters, NULL, sampleRate);
	if (err==0){
		logFile.WriteString(L"Input format is supported\n");
	}
	else{
		logFile.WriteString(L"Input format NOT supported\n");
	}


	
	//error(Pa_OpenStream(
	//	&pStream,
	//	&inputParameters, /* input channel*/
	//	NULL, /* output channel*/
	//	Pa_GetDeviceInfo(inputParameters.device)->defaultSampleRate,
	//	2048,
	//	paClipOff,
	//	&PortAudioSound::myPaCallback,
	//	this
	//	));
		

		error(Pa_OpenStream(
		&pStream,
		&inputParameters, /* input channel*/
		NULL, /* output channel*/
		sampleRate,
		framesPerBuffer,
		paClipOff,
		&PortAudioSound::myPaCallback,
		this
		));

	logFile.WriteString(L"Stream opened\n");
	const PaDeviceInfo* info= Pa_GetDeviceInfo(1);
	CString lf;
	lf.Format(L"Max Input Channels=%d\n", info->maxInputChannels);
	logFile.WriteString(lf);
	lf.Format(L"Default sample rate=%f\n", info->defaultSampleRate);
	logFile.WriteString(lf);
	lf.Format(L"Default input device name=%s\n", CString((info->name)));
	logFile.WriteString(lf);
	lf.Format(L"Default HostApi=%s\n\n",CString((Pa_GetHostApiInfo(info->hostApi)->name)));
	logFile.WriteString(lf);
	


}
コード例 #20
0
std::list<int> dct(arma::mat& inp, DCT_T type) {
  //level-off van pixel-blok 128 afhalen van elk element.
  arma::mat M(inp);
  for (arma::mat::iterator it = M.begin(); it != M.end(); it++)
    *it -= 128;
  //lambda functie met keuze voor type transformatie.
  auto func = [&]() {
    switch(type) {
      /** ************************************************************************
       *  doe de DCT transform gelijk als 2D, output is matrix T.
       **/
    case D2 : {
      arma::mat T(8, 8);
      plan = fftw_plan_r2r_2d(8, 8, M.memptr(), T.memptr(),
			      FFTW_REDFT10, FFTW_REDFT10, FFTW_MEASURE);
      fftw_execute(plan);
      fftw_destroy_plan(plan);
      return T;
    }
    /** *************************************************************************
     *Doe de DCT transform in 2 stappen, eerst vertical en daarna horizontaal als 1D transformaties, combineer de eindresultaten.
     **/
    case D1XD1 : {
      arma::mat Ttemp(8,8);
      for(int i = 0; i < 8; i++) {
	plan = fftw_plan_r2r_1d(8, M.colptr(i), Ttemp.colptr(i), FFTW_REDFT10, FFTW_MEASURE);
	fftw_execute(plan);
	fftw_destroy_plan(plan);
      }
      Ttemp = trans(Ttemp);
      arma::mat T(8,8);
      for(int i = 0; i < 8; i++) {
	plan = fftw_plan_r2r_1d(8, Ttemp.colptr(i), T.colptr(i), FFTW_REDFT10, FFTW_MEASURE);
	fftw_execute(plan);
	fftw_destroy_plan(plan);
      }
      Ttemp = trans(Ttemp);
      T = T + Ttemp;
      return T;
    }
    /** *************************************************************************
     *  eigen DCT.
     **/
    case EIGEN : {
      arma::mat T = compute_dct(M);
      return T;
    }
    default:
    break;
    }};
  //voer de lambda-functie uit
  arma::mat D = func();
  //geef een quantization matrix voor een bepaalde kwaliteit.
  arma::mat Q = quantisation_mat(50);
  // bouw matrix C op door af te ronden van (D/Q).
  arma::imat C(8, 8);
  arma::mat::iterator Dit = D.begin();
  arma::imat::iterator Cit = C.begin();
  for (arma::mat::iterator Qit = Q.begin(); Dit != D.end();
       Dit++ && Qit++ && Cit++) {
    *Cit = round((*Dit / *Qit));
  }
  //comprimeer matrix C door nullen op het eind weg te laten.
  std::list<int> output;
  bool first_not_zero = false;
  for(int i = 63; i >= 0; i--) { // begin aan het eind van het matrix
    if(C[comprr_ar[i]] != 0 && !first_not_zero) //is geen waarde nul
      first_not_zero = true;
    if(first_not_zero) // waardes nul gehad
      output.push_front((int)C[comprr_ar[i]]); // waardes voorin de list pushen zodat de waardes linksboven in de matrix als eerste komen.
  }
  return output;
}
コード例 #21
0
ファイル: wapp2fb.c プロジェクト: lbaehren/lofarsoft
void wapp2fb(FILE *input, FILE *output) /* includefile */
{
  FILE *bptr, *fpou, *alfa[2];
  int pixel[2];
  double pra, pdec;
  double bw, bandwidth, scale, power, hweight, tsamp_us, crate, lmst;
  double *lag, *sum, *acf, *window, jan1, days, epoch, ras,des,rahr,dede; 
  float zerolag,*block,smin,smax;
  int doit,i,j,k,two_nlags,nlags,stat,rec_size,idump,swap_bytes,ifnum,opened;
  int filesize,headersize,beam,utsecs,iymdf[4],rah,ram,ded,dem;
  unsigned char *cblock, zuc;
  unsigned short *sblock, zus; 
  unsigned int zul;
  char message[80], outfile[80];
  void *dump;
  static float realtime=0.0;

#ifdef FFTW
  fftw_plan fftplan;
#endif
  /* establish whether we need to swap bytes (WAPP is little endian) */
  swap_bytes=big_endian();

  /* initialise correlator parameters used below */
  nlags=nchans;  
  two_nlags=2*nlags;  
  bandwidth=foff*nlags;
  tsamp_us=tsamp*1.0e6;
  if (bandwidth<0.0) bandwidth *= -1.0;

#ifdef FFTW
  acf = fftw_malloc(sizeof(double) * two_nlags);
  lag = fftw_malloc(sizeof(double) * two_nlags);
  /* set up fftw table and acf array when computing power spectra */
  fftplan=fftw_plan_r2r_1d(two_nlags,acf,lag,FFTW_R2HC,FFTW_PATIENT);
#endif
#ifndef FFTW
  /* set up acf array when computing power spectra */
  acf = (double *) malloc(two_nlags * sizeof(double));
  lag = (double *) malloc(two_nlags * sizeof(double));
#endif

  if (compute_spectra) {
    /* ranges for scaling spectra */
    smin=0.0;smax=3.0;
  } else {
    /* ranges for scaling correlation functions */
    smin=-0.5;smax=1.0;
  }

  /* set up the weights for windowing of ACF to monimize FFT leakage */
  if (hanning) {
    /* Hanning window */
    hweight=0.50;
  } else if (hamming) {
    /* Hamming window */
    hweight=0.54;
  } else {
    /* no window (default) */
    hweight=1.00;
  }

  /* define the smoothing window to be applied base on the above weight */
  window = (double *) malloc(nlags * sizeof(double));
  for (j=0; j<nlags; j++) window[j]=(hweight+(1.0-hweight)*cos(PI*j/nlags));

  /* work out number of IFs to loop over */
  if (sumifs && (nifs>1)) {
    smin*=2.0;
    smax*=2.0;
    ifnum=2;
  } else {
    sumifs=0;
    ifnum=nifs;
  }

  /* calculate required record size for reading - i.e. number of bytes/dump */
  rec_size = nifs*nlags*(nbits/8);
  dump = malloc(rec_size); /* pointer to the correlator dump */

  /* correlator data rate */
  crate = 1.0/(tsamp_us-WAPP_DEAD_TIME); 
  /* scale factor to normalize correlation functions */
  if (bandwidth < 50.0) 
    bw=50.0; /* correct scaling for narrow-band use */
  else
    bw=bandwidth;

  scale = crate/bw;
  if (wapp_level==9) scale/=16.0; /* 9-level sampling */
  if (wapp_sum) scale/=2.0;  /* summed IFs (search mode) */
  scale*=pow(2.0,(double)wapp_lagtrunc); /* needed for truncation modes */

  /* now define a number of working arrays to store lags and spectra */
  block = (float *) malloc(nlags * sizeof(float));
  cblock = (unsigned char *) malloc(nlags * sizeof(unsigned char));
  sblock = (unsigned short *) malloc(nlags * sizeof(unsigned short));

  /* if the file is ALFA data --- do the demultiplexing to two files */
  if (wapp_isalfa) {

    angle_split(src_raj,&rah,&ram,&ras);
    rahr=(double)rah+(double)ram/60.0+(double)ras/3600.0;
    angle_split(src_dej,&ded,&dem,&des);
    if (ded>0)
      dede=(double)ded+(double)dem/60.0+(double)des/3600.0;
    else
      dede=(double)ded-(double)dem/60.0-(double)des/3600.0;
    /* calculate local sidereal time in hours */
    lmst=slaGmst(tstart)*12.0/4.0/atan(1.0)-4.4502051459439667;
    if (lmst<0.0) lmst+=24.0;
    slaDjcal(5,tstart,iymdf,&stat);
    slaCaldj(iymdf[0],1,1,&jan1,&stat);
    days=tstart-jan1+1.0;
    epoch=(double)iymdf[0]+days/365.25;
    utsecs=86400*(tstart-floor(tstart));

    pixel[0]=(wapp_number-1)*2;
    pixel[1]=pixel[0]+1;
    puts("opening output files for demultiplexed ALFA data...");
    for (i=0; i<2; i++) {
      if (alfa_raj[pixel[i]] == 0.0) {
      alfa_position(rahr,dede,lmst,epoch,alfa_ang,0.0,0.0,pixel[i],&pra,&pdec);
      src_raj=h2hms(pra);
      src_dej=deg2dms(pdec);
      } else {
      src_raj=h2hms(alfa_raj[pixel[i]]);
      src_dej=deg2dms(alfa_dej[pixel[i]]);
      }
      sprintf(outfile,"%s_%.0f_%05d_%04d_%s_%d.fil",
	    project,floor(tstart),utsecs,
	    scan_number,source_name,pixel[i]);
      alfa[i]=open_file(outfile,"wb");
      puts(outfile);
      filterbank_header(alfa[i]);
    }
    beam=0;
  }

  if (headerfile) {
    /* write output ASCII header file */
    fpou=open_file("head","w");  
    fprintf(fpou,"Original WAPP file: %s\n",inpfile);
    fprintf(fpou,"Sample time (us): %f\n",tsamp_us);
    fprintf(fpou,"Observation time (s): %f\n",wapp_obstime);
    fprintf(fpou,"Time stamp (MJD): %18.12f\n",tstart);
    fprintf(fpou,"Number of samples/record: %d\n",512);
    fprintf(fpou,"Center freq (MHz): %f\n",fch1+(float)nlags*foff/2.0);
    fprintf(fpou,"Channel band (kHz): %f\n",bandwidth*1000.0/nlags);
    fprintf(fpou,"Number of channels/record: %d\n",nlags);
    fprintf(fpou,"Nifs: %d\n",ifnum);
    fprintf(fpou,"RA (J2000): %f\n",src_raj);
    fprintf(fpou,"DEC (J2000):  %f\n",src_dej);
    fprintf(fpou,"Gal l: %.4f\n",srcl);
    fprintf(fpou,"Gal b: %.4f\n",srcb); 
    fprintf(fpou,"Name: %s\n",source_name);
    fprintf(fpou,"Lagformat: %d\n",wapp_lagformat);
    fprintf(fpou,"Sum: %d\n",wapp_sum);
    fprintf(fpou,"Level: %d\n",wapp_level);
    fprintf(fpou,"AZ at start: %f\n",az_start);
    fprintf(fpou,"ZA at start: %f\n",za_start);
    fprintf(fpou,"AST at start: %f\n",ast0);
    fprintf(fpou,"LST at start: %f\n",lst0);
    fprintf(fpou,"Project ID: %s\n",project);
    fprintf(fpou,"Observers: %s\n",culprits);
    filesize=sizeof_file(inpfile);
    fprintf(fpou,"File size (bytes): %d\n",filesize);
    headersize=wapp_header_size+wapp_incfile_length;
    fprintf(fpou,"Data size (bytes): %d\n",filesize-headersize);
    fprintf(fpou,"Number of samples: %d\n",nsamples(inpfile,headersize,nbits,nifs,nchans));
    fclose(fpou);
  }

  /* initialise various counters and flags */
  opened=idump=i=j=0; 

  /* main loop reading data from infile until no more left to read */
  while( (stat=read(wapp_file,dump,rec_size)) == rec_size) {

    /* calculate elapsed time and determine whether we process this record */
    realtime += (float) tsamp;
    if ( (doit=process(realtime,start_time,final_time)) == -1) break;

    if (doit) {

      /* set ALFA beam output if necessary */
      if (wapp_isalfa) {
	output=alfa[beam];       /* set output file for this loop */
	beam=!(beam);            /* flip file for next iteration */
      }

      /* clear zerolag and blocksum arrays */
      zerolag=0.0;
      for (j=0; j<nlags; j++) block[j]=0.0;

      /* loop over the IFs */
      for (i=0; i<ifnum; i++) {
	if (ifstream[i]=='Y') {
	  if (zerolagdump) {
	    /* only interested in the zero lag term for each IF */
	    switch (nbits) {
	    case 8:
	      zuc = *(((unsigned char *)dump)+i*nlags);
	      zerolag+=zuc;
	      break;
	    case 16:
	      zus = *(((unsigned short *)dump)+i*nlags);
	      if (swap_bytes) swap_short(&zus); 
	      zerolag+=zus;
	      break;
	    case 32:
	      zul = *(((unsigned int *)dump)+i*nlags);
	      if (swap_bytes) swap_int(&zul); 
	      zerolag+=zul;
	      break;
	    }
	    /* write out the data checking IF number for summed mode */
	    if ( (sumifs && (i==1)) || (!sumifs) ) {
	      if (obits==32) {
		if (swapout) swap_float(&zerolag);
		fwrite(&zerolag,sizeof(float),1,output);
	      } else {
		sprintf(message,"cannot write %d bits in zerolag mode",obits);
		error_message(message);
	      }
	    }
	  } else {
	    /* fill lag array with scaled CFs */
	    for (j=0; j<nlags; j++) {
	      switch (nbits) {
	      case 8:
		zuc = *(((unsigned char *)dump)+j+i*nlags);
		lag[j] = scale * (double) zuc - 1.0;
		break;
	      case 16:
		zus = *(((unsigned short *)dump)+j+i*nlags);
		if (swap_bytes) swap_short(&zus);
		lag[j] = scale * (double) zus - 1.0;
		break;
	      case 32:
		zul = *(((unsigned int  *)dump)+j+i*nlags);
		if (swap_bytes) swap_int(&zul);
		lag[j] = scale * (double) zul - 1.0;
		break;
	      }
	    }
	    /* calculate power and correct for finite level quantization */
	    power = inv_cerf(lag[0]);
	    power = 0.1872721836/power/power;
	    if (i<2) {
	      if (do_vanvleck) { 
		if (wapp_level==3) {
		  /* apply standard 3-level van vleck correction */
		  vanvleck3lev(lag,nlags);
		} else if (wapp_level==9) {
		  /* apply 9-level van vleck correction */
		  vanvleck9lev(lag,nlags);
		}
	      }
	    }

	    if (compute_spectra) {
	      /* form windowed even ACF in array */
	      for(j=1; j<nlags; j++) {
		acf[j]=window[j]*lag[j]*power;
		acf[two_nlags-j]=acf[j];
	      }   
	      acf[nlags]=0.0;
	      acf[0]=lag[0]*power; 
	      /* FFT the ACF (which is real and even) -> real and even FFT */
#ifdef FFTW
	      fftw_execute(fftplan);
#endif
#ifndef FFTW
	      rfft(two_nlags,acf,lag);
#endif
	      /* if the band needs to be flipped --- do it here */
	      if (wapp_flip) {
		/* use acf as temporary array */
		for (j=0;j<nlags;j++) acf[j]=lag[j]; 
		k=nlags-1;
		for (j=0;j<nlags;j++) {
		  lag[k]=acf[j];
		  k--;
		}
	      }
  	      /* add lags to block array */
	      for (j=0; j<nlags; j++) block[j]+=lag[j];
	    } else {			
	      /* just copy correlation functions into block */
	      for (j=0; j<nlags; j++) block[j]=lag[j];	
	    }
	    /* write out data block checking IF number for summed mode */
	    if ( (sumifs && (i==1)) || (!sumifs) ) {
	      if (obits==32) {
		if (swapout) for (j=0; j<nlags; j++) swap_float(&block[j]);
		fwrite(block,sizeof(float),nlags,output);
	      } else if (obits==16) {
		float2short(block,nlags,smin,smax,sblock);
		if (swapout) for (j=0; j<nlags; j++) swap_short(&sblock[j]);
		fwrite(sblock,sizeof(unsigned short),nlags,output);
	      } else if (obits==8) {
		float2char(block,nlags,smin,smax,cblock);
		fwrite(cblock,sizeof(unsigned char),nlags,output);
	      } else if (obits==4) {
		float2four(block,nlags,smin,smax,cblock);
		fwrite(cblock,sizeof(unsigned char),nlags/2,output);
	      } else {
		sprintf(message,"cannot write %d bits in wapp2fb",obits);
		error_message(message);
	      }
	    }
	  } /* end of zerolagdump if */

	  if (!sumifs) { /* reset block and zerolag if not summing */
	    zerolag=0.0;
	    for (j=0; j<nlags; j++) block[j]=0.0;
	  }
	}          /* end of IFstream if */
      }            /* end of loop over IFs */
    }              /* end of processing if */

    /* increment dump counter and update logfile every 512 dumps */
    idump++;
    if (idump%512 == 0) {
      if (!opened) {
	/* open up logfile */
	open_log("filterbank.monitor");
	opened=1;
      }
      sprintf(message,"time:%.1fs",realtime);
      update_log(message);
    }
  }                /* end of main read loop*/

    
  /* job done - free up remaining arrays */
  free(dump);free(block);free(sblock);free(cblock);free(window);
#ifdef FFTW
  fftw_destroy_plan(fftplan);
  fftw_free(acf); fftw_free(lag);
#endif
#ifndef FFTW
  free(acf); free(lag);
#endif
}
コード例 #22
0
inline void computeNumMatchesWithFFT(double *t, double *p,int n, int m,
		int transformSize,int *matches, fftw_plan *forward, fftw_plan *inverse){

   printf("USING FFT\n");

   printf("n: %d m: %d\n",n, m);

	//TODO: Should probably move these out of the function. No point allocating
	//and de-allocating the memory over and over for each character
	double *textSubString = (double *) fftw_malloc(sizeof(double) * transformSize);
	double *DFTofPattern = (double *) fftw_malloc(sizeof(double) * transformSize);
	double *DFTofText = (double *) fftw_malloc(sizeof(double) * transformSize);
	double *pTimesT = (double *) fftw_malloc(sizeof(double) * transformSize);
	double *pTimesT_PR = (double *) fftw_malloc(sizeof(double) * transformSize);
	int i;

	if(*forward==NULL){
		*forward = fftw_plan_r2r_1d(transformSize,p,DFTofPattern,FFTW_R2HC,FFTW_ESTIMATE);
		fftw_execute(*forward);
	}else{
		fftw_execute_r2r(*forward,p,DFTofPattern);
	}
	int start = 0;
	//Perform transforms on sub-strings of the text values
	while(start <= n-m){
		memcpy(textSubString,t+start,sizeof(double)*transformSize);
		fftw_execute_r2r(*forward,textSubString,DFTofText);

		/* Multiply the point representations*/

		pTimesT_PR[0] = DFTofPattern[0] * DFTofText[0];


      THE_COUNT++;
		if(transformSize % 2==0){

			for(i=1;i<transformSize/2;i++){
				pTimesT_PR[i] = DFTofPattern[i] * DFTofText[i] - DFTofPattern[transformSize-i] * DFTofText[transformSize-i];
				pTimesT_PR[transformSize-i] = DFTofPattern[transformSize-i] * DFTofText[i] + DFTofPattern[i] * DFTofText[transformSize-i];
			}
			pTimesT_PR[i] = DFTofPattern[i] * DFTofText[i];
		}else{

			for(i=1;i<=transformSize/2;i++){
				pTimesT_PR[i] = DFTofPattern[i] * DFTofText[i] - DFTofPattern[transformSize-i] * DFTofText[transformSize-i];
				pTimesT_PR[transformSize-i] = DFTofPattern[transformSize-i] * DFTofText[i] + DFTofPattern[i] * DFTofText[transformSize-i];
			}

		}

		/* Convert back to a coefficient representation */

		//On first iteration, need to create the inverse plan
		if(*inverse==NULL){
			*inverse = fftw_plan_r2r_1d(transformSize,pTimesT_PR,pTimesT,FFTW_HC2R,FFTW_ESTIMATE);
			fftw_execute(*inverse);
		}else{
			fftw_execute_r2r(*inverse,pTimesT_PR,pTimesT);
		}

		for(i=0;i<=transformSize-m && (i+start)<=n-m;i++){
			//printf("i+start: %d+%d=%d, value=%d\n",i,start,i+start,(int) ((pTimesT[m+i-1]/transformSize)+0.5));
			//plus 0.5 to allow rounding via truncation
			matches[i+start] += (int)((pTimesT[m+i-1]/transformSize)+0.5);
		}

		start +=transformSize-m +1;
	}
	fftw_free(textSubString);
	fftw_free(DFTofPattern);
	fftw_free(DFTofText);
	fftw_free(pTimesT);
	fftw_free(pTimesT_PR);
}
コード例 #23
0
arma::mat reverse_dct(std::list<int32_t>& input, DCT_T type) {
  arma::imat A(8, 8);
  //zet die shit op nul jonge!
  A.zeros();
  int count = 0;
  for(auto it = input.begin(); it != input.end(); it++) { 
    A[comprr_ar[count]] = *it;
    count++;
  }
  arma::mat Q = quantisation_mat(50);
  arma::mat C = A % Q;
  //lambda functie met keuze voor type transformatie.
  auto func = [&]() {
    switch(type) {
      /** ************************************************************************
       *  doe de DCT transform gelijk als 2D, output is matrix T.
       **/
    case D2 : {
      arma::mat T(8, 8);
      plan = fftw_plan_r2r_2d(8, 8, C.memptr(), T.memptr(),
			      FFTW_REDFT01, FFTW_REDFT01, FFTW_MEASURE);
      fftw_execute(plan);
      fftw_destroy_plan(plan);
      return T;
    }
    /** *************************************************************************
     *Doe de DCT transform in 2 stappen, eerst vertical en daarna horizontaal als 1D transformaties, combineer de eindresultaten.
     **/
    case D1XD1 : {
      arma::mat Ttemp(8,8);
      for(int i = 0; i < 8; i++) {
	plan = fftw_plan_r2r_1d(8, C.colptr(i), Ttemp.colptr(i), FFTW_REDFT01, FFTW_MEASURE);
	fftw_execute(plan);
	fftw_destroy_plan(plan);
      }
      Ttemp = trans(Ttemp);
      arma::mat T(8,8);
      for(int i = 0; i < 8; i++) {
	plan = fftw_plan_r2r_1d(8, Ttemp.colptr(i), T.colptr(i), FFTW_REDFT01, FFTW_MEASURE);
	fftw_execute(plan);
	fftw_destroy_plan(plan);
      }
      Ttemp = trans(Ttemp);
      T = T + Ttemp;
      return T;
    }
    /** *************************************************************************
     *  Deze werkt nog niet.
     **/
    // case EIGEN : {
    //   arma::mat T = compute_dct(C);
    //   return T;
    // }
    default:
    break;
    }};
  arma::mat T = func();
  //tel weer 128 bij elke waarde op, als het hoger is dan 255 zet dan de waarde op 255.
  for (arma::mat::iterator it = T.begin(); it != T.end(); it++) {
    *it += 128;
    if(*it > 255)
      *it = 255;
  }
  return T;
}
コード例 #24
0
ファイル: encoder.cpp プロジェクト: davidajulio/hx
	analysis_filter::analysis_filter() {
		plan = fftw_plan_r2r_1d(32, freq, freq, FFTW_REDFT01, FFTW_MEASURE);
	}
コード例 #25
0
ファイル: prtd.1.c プロジェクト: DartmouthSpacePhys/prtd
int main(int argc, char **argv) {
	int i, j;
	long int procid;
	char outstring1[100];
	FILE *in, *image1, *image2, *image3, *image4, *out;
	struct parsed_options options;

	umask(000);

	cmd_init_parsed_options(&options);
	cmd_parse_options(&options, argc, argv);

	/* read location for the config file if given */
	sprintf(config_filename,"%s",options.conffile);
	read_input_file();

	nice(10);

	sprintf(instring,"%s/process_rt_data_running",tmp_dir);
	out = fopen(instring, "r");
	if (out != NULL) {
		fprintf(stderr, "\nrprocess_rt_data found a lock file ... ");
		fscanf(out, "%lu", &procid);
		fprintf(stderr, "\n  PID: %lu", procid);
		fclose(out);
		sprintf(outstring1,"/proc/%lu/cmdline",procid);
		out = fopen(outstring1, "r");
		if (out != NULL) {
			fscanf(out, "%s", outstring1);
			sprintf(instring,"process_real_time_data");
			//if( strncmp(outstring1,"/home/radio",11)==0 )
			if (strstr(outstring1, instring) != NULL) {
				fprintf(stderr, "\n  Process Exists. Exiting ...\n\n");
				fclose(out);
				exit(0);
			}
			fclose(out);
		}
		sprintf(instring,"%s/process_rt_data_running",tmp_dir);
		remove(instring);
		fprintf(stderr, "\n  Process Does Not Exist. Lock File Removed\n");
	}

	sprintf(instring,"%s/process_rt_data_running",tmp_dir);

	out = fopen(instring, "w");

	if (out != NULL) {
		fprintf(out, "%lu", (long unsigned int) getpid());
		fclose(out);
	} else {
		fprintf(stderr, "Couldn't write lock file %s?!", instring);
		exit(-1);
	}

	/* initialize the images */
	for (i = 0; i < 512; i++)
		for (j = 0; j < 920; j++) {
			im1o[i][j] = 20.;
			im2o[i][j] = 20.;
			im3o[i][j] = 20.;
			im4o[i][j] = 20.;
		}

	/* initialize the fftw3 plans */
	plan_forward1 = fftw_plan_r2r_1d(1024, fft_samples1, out1, FFTW_R2HC, FFTW_MEASURE);
	plan_forward2 = fftw_plan_r2r_1d(1024, fft_samples2, out2, FFTW_R2HC, FFTW_MEASURE);
	plan_forward3 = fftw_plan_r2r_1d(1024, fft_samples3, out3, FFTW_R2HC, FFTW_MEASURE);
	plan_forward4 = fftw_plan_r2r_1d(1024, fft_samples4, out4, FFTW_R2HC, FFTW_MEASURE);


	while (1) {
		/* read in the new data */
		read_new_samples();
		/* fft the new data */
		fft_new_samples();

		sprintf(instring,"%s/hf2_display_running",tmp_dir);
		in = fopen(instring, "r");
		if (in != NULL) {
			write_data = 1;
			fclose(in);
		} else
			write_data = 0;

		sprintf(instring,"%s/levels.grayscale",tmp_dir);
		in = fopen(instring, "r");
		if (in != NULL) {
			fscanf(in, "%d %d", &gray_min, &gray_max);
			fclose(in);
		} else {
			gray_min = 0;
			gray_max = 60.;
		}
		if (old_gray_min != gray_min || old_gray_max != gray_max)
			rescale_images();
		if (write_data) {
			sprintf(instring,"%s/test.data",tmp_dir);
			out = fopen(instring, "w");
		} else {
			printf("hf2_display not running?\n");
		}

		for (i = 0; i < 512; i++) {
			x[i] = i * df;
			memcpy(*(im1+i),&im1[i][1],919);
			memcpy(*(im2+i),&im2[i][1],919);
			memcpy(*(im3+i),&im3[i][1],919);
			memcpy(*(im4+i),&im4[i][1],919);
			memcpy((im1o+i),&im1o[i][1],919*sizeof(float));
			memcpy((im2o+i),&im2o[i][1],919*sizeof(float));
			memcpy((im3o+i),&im3o[i][1],919*sizeof(float));
			memcpy((im4o+i),&im4o[i][1],919*sizeof(float));
			r1 = out1[i];
			r2 = out2[i];
			r3 = out3[i];
			r4 = out4[i];
			im1o[512 - i][919] = r1;
			im2o[512 - i][919] = r2;
			im3o[512 - i][919] = r3;
			im4o[512 - i][919] = r4;
			v1 = a + r1 * b + 0.5;
			v2 = a + r2 * b + 0.5;
			v3 = a + r3 * b + 0.5;
			v4 = a + r4 * b + 0.5;
			if (v1 < 0)
				v1 = 0;
			if (v2 < 0)
				v2 = 0;
			if (v3 < 0)
				v3 = 0;
			if (v4 < 0)
				v4 = 0;
			if (v1 > 255)
				v1 = 255;
			if (v2 > 255)
				v2 = 255;
			if (v3 > 255)
				v3 = 255;
			if (v4 > 255)
				v4 = 255;

			im1[512 - i][919] = 255 - (unsigned char) v1;
			im2[512 - i][919] = 255 - (unsigned char) v2;
			im3[512 - i][919] = 255 - (unsigned char) v3;
			im4[512 - i][919] = 255 - (unsigned char) v4;

			if (write_data)
				fprintf(out, "%.0f %.2f %.2f %.2f\n", x[i], r1, r2, r3);
		}

		if (write_data) {
			fclose(out);

			sprintf(instring,"%s/test.image1",tmp_dir);
			image1 = fopen(instring, "w");
			fprintf(image1, "P5\n920 512\n255\n");
			fwrite(im1, sizeof(im1), 1, image1);
			fclose(image1);

			sprintf(instring,"%s/test.image2",tmp_dir);
			image2 = fopen(instring, "w");
			fprintf(image2, "P5\n920 512\n255\n");
			fwrite(im2, sizeof(im2), 1, image2);
			fclose(image2);

			sprintf(instring,"%s/test.image3",tmp_dir);
			image3 = fopen(instring, "w");
			fprintf(image3, "P5\n920 512\n255\n");
			fwrite(im3, sizeof(im3), 1, image3);
			fclose(image3);

			sprintf(instring,"%s/test.image4",tmp_dir);
			image4 = fopen(instring, "w");
			fprintf(image4, "P5\n920 512\n255\n");
			fwrite(im4, sizeof(im4), 1, image4);
			fclose(image4);
		}
		usleep(1e4);
	}
	return (0);
}
コード例 #26
0
ファイル: iterS2.c プロジェクト: poulson/nfft
/**
 * The main program.
 *
 * \param argc The number of arguments
 * \param argv An array containing the arguments as C-strings
 *
 * \return Exit code
 *
 * \author Jens Keiner
 */
int main (int argc, char **argv)
{
  int T;
  int N;
  int M;
  int M2;

  int t;                       /* Index variable for testcases                */
  nfsft_plan plan;             /* NFSFT plan                                  */
  nfsft_plan plan2;            /* NFSFT plan                                  */
  solver_plan_complex iplan;           /* NFSFT plan                                  */
  int j;                       /*                                             */
  int k;                       /*                                             */
  int m;                       /*                                             */
  int use_nfsft;               /*                                             */
  int use_nfft;                /*                                             */
  int use_fpt;                 /*                                             */
  int cutoff;                  /**< The current NFFT cut-off parameter        */
  double threshold;            /**< The current NFSFT threshold parameter     */
  double re;
  double im;
  double a;
  double *scratch;
  double xs;
  double *ys;
  double *temp;
  double _Complex *temp2;
  int qlength;
  double *qweights;
  fftw_plan fplan;
  fpt_set set;
  int npt;
  int npt_exp;
  double *alpha, *beta, *gamma;

  /* Read the number of testcases. */
  fscanf(stdin,"testcases=%d\n",&T);
  fprintf(stderr,"%d\n",T);

  /* Process each testcase. */
  for (t = 0; t < T; t++)
  {
    /* Check if the fast transform shall be used. */
    fscanf(stdin,"nfsft=%d\n",&use_nfsft);
    fprintf(stderr,"%d\n",use_nfsft);
    if (use_nfsft != NO)
    {
      /* Check if the NFFT shall be used. */
      fscanf(stdin,"nfft=%d\n",&use_nfft);
      fprintf(stderr,"%d\n",use_nfsft);
      if (use_nfft != NO)
      {
        /* Read the cut-off parameter. */
        fscanf(stdin,"cutoff=%d\n",&cutoff);
        fprintf(stderr,"%d\n",cutoff);
      }
      else
      {
        /* TODO remove this */
        /* Initialize unused variable with dummy value. */
        cutoff = 1;
      }
      /* Check if the fast polynomial transform shall be used. */
      fscanf(stdin,"fpt=%d\n",&use_fpt);
      fprintf(stderr,"%d\n",use_fpt);
      if (use_fpt != NO)
      {
        /* Read the NFSFT threshold parameter. */
        fscanf(stdin,"threshold=%lf\n",&threshold);
        fprintf(stderr,"%lf\n",threshold);
      }
      else
      {
        /* TODO remove this */
        /* Initialize unused variable with dummy value. */
        threshold = 1000.0;
      }
    }
    else
    {
      /* TODO remove this */
      /* Set dummy values. */
      use_nfft = NO;
      use_fpt = NO;
      cutoff = 3;
      threshold = 1000.0;
    }

    /* Read the bandwidth. */
    fscanf(stdin,"bandwidth=%d\n",&N);
    fprintf(stderr,"%d\n",N);

    /* Do precomputation. */
    nfsft_precompute(N,threshold,
      ((use_nfsft==NO)?(NFSFT_NO_FAST_ALGORITHM):(0U/*NFSFT_NO_DIRECT_ALGORITHM*/)), 0U);

    /* Read the number of nodes. */
    fscanf(stdin,"nodes=%d\n",&M);
    fprintf(stderr,"%d\n",M);

    /* */
    if ((N+1)*(N+1) > M)
    {
      X(next_power_of_2_exp)(N, &npt, &npt_exp);
      fprintf(stderr, "npt = %d, npt_exp = %d\n", npt, npt_exp);
      fprintf(stderr,"Optimal interpolation!\n");
      scratch = (double*) nfft_malloc(4*sizeof(double));
      ys = (double*) nfft_malloc((N+1)*sizeof(double));
      temp = (double*) nfft_malloc((2*N+1)*sizeof(double));
      temp2 = (double _Complex*) nfft_malloc((N+1)*sizeof(double _Complex));

      a = 0.0;
      for (j = 0; j <= N; j++)
      {
        xs = 2.0 + (2.0*j)/(N+1);
        ys[j] = (2.0-((j == 0)?(1.0):(0.0)))*4.0*nfft_bspline(4,xs,scratch);
        //fprintf(stdout,"%3d: g(%le) = %le\n",j,xs,ys[j]);
        a += ys[j];
      }
      //fprintf(stdout,"a = %le\n",a);
      for (j = 0; j <= N; j++)
      {
        ys[j] *= 1.0/a;
      }

      qlength = 2*N+1;
      qweights = (double*) nfft_malloc(qlength*sizeof(double));

      fplan = fftw_plan_r2r_1d(N+1, qweights, qweights, FFTW_REDFT00, 0U);
      for (j = 0; j < N+1; j++)
      {
        qweights[j] = -2.0/(4*j*j-1);
      }
      fftw_execute(fplan);
      qweights[0] *= 0.5;

      for (j = 0; j < N+1; j++)
      {
        qweights[j] *= 1.0/(2.0*N+1.0);
        qweights[2*N+1-1-j] = qweights[j];
      }

      fplan = fftw_plan_r2r_1d(2*N+1, temp, temp, FFTW_REDFT00, 0U);
      for (j = 0; j <= N; j++)
      {
        temp[j] = ((j==0 || j == 2*N)?(1.0):(0.5))*ys[j];
      }
      for (j = N+1; j < 2*N+1; j++)
      {
        temp[j] = 0.0;
      }
      fftw_execute(fplan);

      for (j = 0; j < 2*N+1; j++)
      {
        temp[j] *= qweights[j];
      }

      fftw_execute(fplan);

      for (j = 0; j < 2*N+1; j++)
      {
        temp[j] *= ((j==0 || j == 2*N)?(1.0):(0.5));
        if (j <= N)
        {
          temp2[j] = temp[j];
        }
      }

      set = fpt_init(1, npt_exp, 0U);

      alpha = (double*) nfft_malloc((N+2)*sizeof(double));
      beta = (double*) nfft_malloc((N+2)*sizeof(double));
      gamma = (double*) nfft_malloc((N+2)*sizeof(double));

      alpha_al_row(alpha, N, 0);
      beta_al_row(beta, N, 0);
      gamma_al_row(gamma, N, 0);

      fpt_precompute(set, 0, alpha, beta, gamma, 0, 1000.0);

      fpt_transposed(set,0, temp2, temp2, N, 0U);

      fpt_finalize(set);

      nfft_free(alpha);
      nfft_free(beta);
      nfft_free(gamma);

      fftw_destroy_plan(fplan);

      nfft_free(scratch);
      nfft_free(qweights);
      nfft_free(ys);
      nfft_free(temp);
    }

    /* Init transform plans. */
    nfsft_init_guru(&plan, N, M,
      ((use_nfft!=0)?(0U):(NFSFT_USE_NDFT)) |
      ((use_fpt!=0)?(0U):(NFSFT_USE_DPT)) | NFSFT_MALLOC_F | NFSFT_MALLOC_X |
      NFSFT_MALLOC_F_HAT | NFSFT_NORMALIZED | NFSFT_ZERO_F_HAT,
      PRE_PHI_HUT | PRE_PSI | FFTW_INIT |
      FFT_OUT_OF_PLACE,
      cutoff);

    if ((N+1)*(N+1) > M)
    {
      solver_init_advanced_complex(&iplan, (nfft_mv_plan_complex*)(&plan), CGNE | PRECOMPUTE_DAMP);
    }
    else
    {
      solver_init_advanced_complex(&iplan, (nfft_mv_plan_complex*)(&plan), CGNR | PRECOMPUTE_WEIGHT | PRECOMPUTE_DAMP);
    }

    /* Read the nodes and function values. */
    for (j = 0; j < M; j++)
    {
      fscanf(stdin,"%le %le %le %le\n",&plan.x[2*j+1],&plan.x[2*j],&re,&im);
      plan.x[2*j+1] = plan.x[2*j+1]/(2.0*PI);
      plan.x[2*j] = plan.x[2*j]/(2.0*PI);
      if (plan.x[2*j] >= 0.5)
      {
        plan.x[2*j] = plan.x[2*j] - 1;
      }
      iplan.y[j] = re + _Complex_I * im;
      fprintf(stderr,"%le %le %le %le\n",plan.x[2*j+1],plan.x[2*j],
        creal(iplan.y[j]),cimag(iplan.y[j]));
    }

    /* Read the number of nodes. */
    fscanf(stdin,"nodes_eval=%d\n",&M2);
    fprintf(stderr,"%d\n",M2);

    /* Init transform plans. */
    nfsft_init_guru(&plan2, N, M2,
      ((use_nfft!=0)?(0U):(NFSFT_USE_NDFT)) |
      ((use_fpt!=0)?(0U):(NFSFT_USE_DPT)) | NFSFT_MALLOC_F | NFSFT_MALLOC_X |
      NFSFT_MALLOC_F_HAT | NFSFT_NORMALIZED | NFSFT_ZERO_F_HAT,
      PRE_PHI_HUT | PRE_PSI | FFTW_INIT |
      FFT_OUT_OF_PLACE,
      cutoff);

    /* Read the nodes and function values. */
    for (j = 0; j < M2; j++)
    {
      fscanf(stdin,"%le %le\n",&plan2.x[2*j+1],&plan2.x[2*j]);
      plan2.x[2*j+1] = plan2.x[2*j+1]/(2.0*PI);
      plan2.x[2*j] = plan2.x[2*j]/(2.0*PI);
      if (plan2.x[2*j] >= 0.5)
      {
        plan2.x[2*j] = plan2.x[2*j] - 1;
      }
      fprintf(stderr,"%le %le\n",plan2.x[2*j+1],plan2.x[2*j]);
    }

    nfsft_precompute_x(&plan);

    nfsft_precompute_x(&plan2);

    /* Frequency weights. */
    if ((N+1)*(N+1) > M)
    {
      /* Compute Voronoi weights. */
      //nfft_voronoi_weights_S2(iplan.w, plan.x, M);

      /* Print out Voronoi weights. */
      /*a = 0.0;
      for (j = 0; j < plan.M_total; j++)
      {
        fprintf(stderr,"%le\n",iplan.w[j]);
        a += iplan.w[j];
      }
      fprintf(stderr,"sum = %le\n",a);*/

      for (j = 0; j < plan.N_total; j++)
      {
        iplan.w_hat[j] = 0.0;
      }

      for (k = 0; k <= N; k++)
      {
        for (j = -k; j <= k; j++)
        {
          iplan.w_hat[NFSFT_INDEX(k,j,&plan)] = 1.0/(pow(k+1.0,2.0)); /*temp2[j]*/;
        }
      }
    }
    else
    {
      for (j = 0; j < plan.N_total; j++)
      {
        iplan.w_hat[j] = 0.0;
      }

      for (k = 0; k <= N; k++)
      {
        for (j = -k; j <= k; j++)
        {
          iplan.w_hat[NFSFT_INDEX(k,j,&plan)] = 1/(pow(k+1.0,2.5));
        }
      }

      /* Compute Voronoi weights. */
      nfft_voronoi_weights_S2(iplan.w, plan.x, M);

      /* Print out Voronoi weights. */
      a = 0.0;
      for (j = 0; j < plan.M_total; j++)
      {
        fprintf(stderr,"%le\n",iplan.w[j]);
        a += iplan.w[j];
      }
      fprintf(stderr,"sum = %le\n",a);
    }

    fprintf(stderr, "N_total = %d\n", plan.N_total);
    fprintf(stderr, "M_total = %d\n", plan.M_total);

    /* init some guess */
    for (k = 0; k < plan.N_total; k++)
    {
      iplan.f_hat_iter[k] = 0.0;
    }

    /* inverse trafo */
    solver_before_loop_complex(&iplan);

    /*for (k = 0; k < plan.M_total; k++)
    {
      printf("%le %le\n",creal(iplan.r_iter[k]),cimag(iplan.r_iter[k]));
    }*/

    for (m = 0; m < 29; m++)
    {
      fprintf(stderr,"Residual ||r||=%e,\n",sqrt(iplan.dot_r_iter));
      solver_loop_one_step_complex(&iplan);
    }

    /*NFFT_SWAP_complex(iplan.f_hat_iter, plan.f_hat);
    nfsft_trafo(&plan);
    NFFT_SWAP_complex(iplan.f_hat_iter, plan.f_hat);

    a = 0.0;
    b = 0.0;
    for (k = 0; k < plan.M_total; k++)
    {
      printf("%le %le %le\n",cabs(iplan.y[k]),cabs(plan.f[k]),
        cabs(iplan.y[k]-plan.f[k]));
      a += cabs(iplan.y[k]-plan.f[k])*cabs(iplan.y[k]-plan.f[k]);
      b += cabs(iplan.y[k])*cabs(iplan.y[k]);
    }

    fprintf(stderr,"relative error in 2-norm: %le\n",a/b);*/

    NFFT_SWAP_complex(iplan.f_hat_iter, plan2.f_hat);
    nfsft_trafo(&plan2);
    NFFT_SWAP_complex(iplan.f_hat_iter, plan2.f_hat);
    for (k = 0; k < plan2.M_total; k++)
    {
      fprintf(stdout,"%le\n",cabs(plan2.f[k]));
    }

    solver_finalize_complex(&iplan);

    nfsft_finalize(&plan);

    nfsft_finalize(&plan2);

    /* Delete precomputed data. */
    nfsft_forget();

    if ((N+1)*(N+1) > M)
    {
      nfft_free(temp2);
    }

  } /* Process each testcase. */

  /* Return exit code for successful run. */
  return EXIT_SUCCESS;
}
コード例 #27
0
ファイル: MZI_FFT.cpp プロジェクト: caoyuan0923/octlab
I8 mzi_fft(U32 X, U32 Y, U32 mzi_length, I8 hann_flag, I8 dB_flag,
           U32 *mzi_indexes, T1 *in, DBL *intensity, DBL *phase, DBL *Re,
           DBL *Im) {
  DBL *hann_win = static_cast<DBL *>(fftw_malloc(sizeof(DBL) * mzi_length));
  // create FFTW plan
  fftw_plan fft_p = fftw_plan_r2r_1d(mzi_length, Re, Im, FFTW_R2HC,
                                     FFTW_ESTIMATE);
  U32 width = static_cast<U32>(mzi_length/2);
  I32 j;
  // prepare Hanning window
  for (U32 i = 0; i < mzi_length; i++) {
    if (hann_flag)
      hann_win[i] = 0.5 * (1 - cos(kTwoPi * i / mzi_length));
    else
      hann_win[i] = 1.0;
  }
  // parallel run by A-lines
  #pragma omp parallel for default(shared) private(j)
  for (j = 0; j < static_cast<I32>(Y); j++) {
    DBL *tmp_fft_in = static_cast<DBL *>(fftw_malloc(sizeof(DBL) * mzi_length));
    DBL *tmp_fft_out =static_cast<DBL *>(fftw_malloc(sizeof(DBL) * mzi_length));
    I32 pos = j * width;
    // MZI filter: pick up RAW A-line values for corresponding MZI indexes
    for (U32 i = 0; i < mzi_length; i++)
      tmp_fft_in[i] = in[j * X + mzi_indexes[i]];
    // apply hanning window or just make data cast
    transform(tmp_fft_in, tmp_fft_in + mzi_length, hann_win, tmp_fft_in,
              multiplies<DBL>());
    // perform FFT using FFTW3 library
    fftw_execute_r2r(fft_p, tmp_fft_in, tmp_fft_out);
    // ZERO components
    if (dB_flag)
      intensity[pos] = 20 * log10(abs(tmp_fft_out[0]));
    else
      intensity[pos] = tmp_fft_out[0];
    Re[pos] = tmp_fft_out[0];
    phase[pos] = Im[pos] = 0.0;
    // construct intensity and phase information, Re and Im parts
    for (U32 pos1 = 1, pos2 = mzi_length - 1; pos1 < width; pos1++, pos2--) {
      // intensity
      if (dB_flag)
        intensity[pos + pos1] = 20 * log10(sqrt(tmp_fft_out[pos1] * \
                                tmp_fft_out[pos1] + tmp_fft_out[pos2] * \
                                tmp_fft_out[pos2]));
      else
        intensity[pos + pos1] = sqrt(tmp_fft_out[pos1] * tmp_fft_out[pos1] + \
                                tmp_fft_out[pos2] * tmp_fft_out[pos2]);
      // phase
      phase[pos + pos1] = atan2(tmp_fft_out[pos2], tmp_fft_out[pos1]);
      // Re part
      Re[pos + pos1] = tmp_fft_out[pos1];
      // Im part
      Im[pos + pos1] = tmp_fft_out[pos2];
    }
    fftw_free(tmp_fft_in);
    fftw_free(tmp_fft_out);
  }  // end of parallel code
  fftw_destroy_plan(fft_p);
  fftw_free(hann_win);
  return EXIT_SUCCESS;
}
コード例 #28
0
ファイル: fftw_wisdom.c プロジェクト: GeraintPratten/lalsuite
/**
 * Function used only internally, to create an FFTW plan for a specified problem (thereby adding to wisdom)
 */
int plan_problem(char type,            /**< 'r' for real or 'c' for complex transform */
		 char direc,           /**< 'f' for forward or 'b'/'r' for backward/reverse transform */
		 UINT4 transform_size, /**< Size of transform to plan */
		 int measurelvl)       /**< Level of patience in planning (0 least, 3 most) */
{
  fftw_plan genericPlan;
  void *indata, *outdata;
  int fwdflag, planning_flags;

  fwdflag = ( (direc=='f') || (direc=='F') );

  /* We call FFTW routines directly, rather than through LAL, so that if XLAL planning routines
     are changed to always read in wisdom, we can still toggle that behavior through the command line.
     In case we ever allow for aligned memory, we allocate everything with fftw_malloc().
  */

  /* If we ever allow for aligned memory, this will have to toggle depending on input: */
  planning_flags = FFTW_UNALIGNED;

  switch(measurelvl)
    {
    case 0:
      planning_flags |= FFTW_ESTIMATE;
      break;
    default:
    case 3:
      planning_flags |= FFTW_EXHAUSTIVE;
      /* Fall through: */
    case 2:
      planning_flags |= FFTW_PATIENT;
      /* Fall through */
    case 1:
      planning_flags |= FFTW_MEASURE;
      break;
    }

  /* Ugly, but makes us 'locale' independent */

  if ( (type=='r') || (type=='R') )
    {

      indata  = (double *) fftw_malloc(transform_size*sizeof(double));
      outdata = (double *) fftw_malloc(transform_size*sizeof(double));

      if ( (!indata) || (!outdata) )
	{
	  if (indata) fftw_free(indata);
	  if (outdata) fftw_free(outdata);
	  return 1;
	}

      genericPlan = fftw_plan_r2r_1d(transform_size,indata,outdata,
				      (fwdflag ? FFTW_R2HC : FFTW_HC2R),
				      planning_flags);
      if (!genericPlan)
	{
	  fftw_free(indata);
	  fftw_free(outdata);
	  return 1;
	}
      else
	{
	  fftw_free(indata);
	  fftw_free(outdata);
	  fftw_destroy_plan(genericPlan);
	  return 0;
	}
    }
  else
    {  /* type == 'c' */

      indata  = (fftw_complex *) fftw_malloc(transform_size*sizeof(fftw_complex));
      outdata = (fftw_complex *) fftw_malloc(transform_size*sizeof(fftw_complex));

      if ( (!indata) || (!outdata) )
	{
	  if (indata) fftw_free(indata);
	  if (outdata) fftw_free(outdata);
	  return 1;
	}

      genericPlan = fftw_plan_dft_1d(transform_size,indata,outdata,
				      (fwdflag ? FFTW_FORWARD : FFTW_BACKWARD),
				      planning_flags);

      if (!genericPlan)
	{
	  fftw_free(indata);
	  fftw_free(outdata);
	  return 1;
	}
      else
	{
	  fftw_free(indata);
	  fftw_free(outdata);
	  fftw_destroy_plan(genericPlan);
	  return 0;
	}
    }
}
コード例 #29
0
ファイル: s2_cospmls.c プロジェクト: artivis/soft20
void CosPmlTableGen(int bw,
		    int m,
		    double *tablespace,
		    double *workspace)
{
  double *prev, *prevprev, *temp1, *temp2, *temp3, *temp4;
  double *x_i, *eval_args;
  double *tableptr, *cosres ;
  int i, j, k;

  /* fftw stuff now */
  double fudge ;
  fftw_plan p ;

  prevprev = workspace;
  prev = prevprev + bw;
  temp1 = prev + bw;
  temp2 = temp1 + bw;
  temp3 = temp2 + bw;
  temp4 = temp3 + bw;
  x_i = temp4 + bw;
  eval_args = x_i + bw;
  cosres = eval_args + bw;

  tableptr = tablespace;

  /* make fftw plan */
  p = fftw_plan_r2r_1d( bw, temp4, cosres,
			FFTW_REDFT10, FFTW_ESTIMATE ) ;

  /* main loop */

  /* Set the initial number of evaluation points to appropriate
     amount */

  /* now get the evaluation nodes */
  EvalPts(bw,x_i);
  ArcCosEvalPts(bw,eval_args);
    
  /* set initial values of first two Pmls */
  for (i=0; i<bw; i++) 
    prevprev[i] = 0.0;

  if (m == 0)
    for (i=0; i<bw; i++)
      prev[i] = 0.707106781186547; /* sqrt(1/2) */
  else 
    Pmm_L2(m, eval_args, bw, prev);


  if ( m % 2 ) /* need to divide out sin x */
    for (i=0; i<bw; i++)
      prev[i] /= sin(eval_args[i]);
  

  /* set k to highest degree coefficient */
  if ((m % 2) == 0)
    k = m;
  else
    k = m-1;	

  /* now compute cosine transform */
  memcpy( temp4, prev, sizeof(double) * bw );
  fftw_execute( p );
  cosres[0] *= 0.707106781186547 ;
  fudge = 1. / sqrt(((double) bw ) );
  for ( i = 0 ; i < bw ; i ++ )
    cosres[i] *= fudge ;

  /* store what I've got so far */
  for (i=0; i<=k; i+=2)
    tableptr[i/2] = cosres[i];

  /* update tableptr */
  tableptr += k/2+1;

  /* now generate remaining pmls  */
  for (i=0; i<bw-m-1; i++)
    {
      vec_mul(L2_cn(m,m+i),prevprev,temp1,bw);
      vec_pt_mul(prev, x_i, temp2, bw);
      vec_mul(L2_an(m,m+i), temp2, temp3, bw);
      vec_add(temp3, temp1, temp4, bw); /* temp4 now contains P(m,m+i+1) */

      /* compute cosine transform */
      fftw_execute( p );
      cosres[0] *= 0.707106781186547 ;
      for ( j = 0 ; j < bw ; j ++ )
	cosres[j] *= fudge ;

      /* update degree counter */
      k++;

      /* now put decimated result into table */
      if ( i % 2 )
	for (j=0; j<=k; j+=2)
	  tableptr[j/2] = cosres[j];
      else
	for (j=1; j<=k; j+=2)
	  tableptr[j/2] = cosres[j];
      
      /* update tableptr */
      tableptr += k/2+1;

      /* now update Pi and P(i+1) */
      memcpy(prevprev, prev, sizeof(double) * bw);
      memcpy(prev, temp4, sizeof(double) * bw);
    }

  fftw_destroy_plan( p );

}
コード例 #30
0
ファイル: quadratureS2.c プロジェクト: andreydung/EECS468
/**
 * The main program.
 *
 * \param argc The number of arguments
 * \param argv An array containing the arguments as C-strings
 *
 * \return Exit code
 */
int main (int argc, char **argv)
{
  int tc;                      /**< The index variable for testcases          */
  int tc_max;                  /**< The number of testcases                   */

  int *NQ;                     /**< The array containing the cut-off degrees  *
                                    \f$N\f$                                   */
  int NQ_max;                  /**< The maximum cut-off degree \f$N\f$ for the*
                                    current testcase                          */
  int *SQ;                     /**< The array containing the grid size
                                    parameters                                */
  int SQ_max;                  /**< The maximum grid size parameter           */
  int *RQ;                     /**< The array containing the grid size
                                    parameters                                */
  int iNQ;                     /**< Index variable for cut-off degrees        */
  int iNQ_max;                 /**< The maximum number of cut-off degrees     */
  int testfunction;            /**< The testfunction                          */
  int N;                       /**< The test function's bandwidth             */

  int use_nfsft;               /**< Whether to use the NFSFT algorithm or not */
  int use_nfft;                /**< Whether to use the NFFT algorithm or not  */
  int use_fpt;                 /**< Whether to use the FPT algorithm or not   */
  int cutoff;                  /**< The current NFFT cut-off parameter        */
  double threshold;            /**< The current NFSFT threshold parameter     */

  int gridtype;                /**< The type of quadrature grid to be used    */
  int repetitions;             /**< The number of repetitions to be performed */
  int mode;                    /**< The number of repetitions to be performed */

  double *w;                   /**< The quadrature weights                    */
  double *x_grid;              /**< The quadrature nodes                      */
  double *x_compare;           /**< The quadrature nodes                      */
  double _Complex *f_grid;             /**< The reference function values             */
  double _Complex *f_compare;          /**< The function values                       */
  double _Complex *f;                  /**< The function values                       */
  double _Complex *f_hat_gen;         /**< The reference spherical Fourier           *
                                    coefficients                              */
  double _Complex *f_hat;              /**< The spherical Fourier coefficients        */

  nfsft_plan plan_adjoint;     /**< The NFSFT plan                            */
  nfsft_plan plan;             /**< The NFSFT plan                            */
  nfsft_plan plan_gen;         /**< The NFSFT plan                            */

  double t_avg;                /**< The average computation time needed       */
  double err_infty_avg;        /**< The average error \f$E_\infty\f$          */
  double err_2_avg;            /**< The average error \f$E_2\f$               */

  int i;                       /**< A loop variable                           */
  int k;                       /**< A loop variable                           */
  int n;                       /**< A loop variable                           */
  int d;                       /**< A loop variable                           */

  int m_theta;                 /**< The current number of different           *
                                    colatitudinal angles (for grids)          */
  int m_phi;                   /**< The current number of different           *
                                    longitudinal angles (for grids).          */
  int m_total;                 /**< The total number nodes.                   */
  double *theta;               /**< An array for saving the angles theta of a *
                                    grid                                      */
  double *phi;                 /**< An array for saving the angles phi of a   *
                                    grid                                      */
  fftw_plan fplan;             /**< An FFTW plan for computing Clenshaw-Curtis
                                    quadrature weights                        */
  //int nside;                   /**< The size parameter for the HEALPix grid   */
  int d2;
  int M;
  double theta_s;
  double x1,x2,x3,temp;
  int m_compare;
  nfsft_plan *plan_adjoint_ptr;
  nfsft_plan *plan_ptr;
  double *w_temp;
  int testmode;
  ticks t0, t1;

  /* Read the number of testcases. */
  fscanf(stdin,"testcases=%d\n",&tc_max);
  fprintf(stdout,"%d\n",tc_max);

  /* Process each testcase. */
  for (tc = 0; tc < tc_max; tc++)
  {
    /* Check if the fast transform shall be used. */
    fscanf(stdin,"nfsft=%d\n",&use_nfsft);
    fprintf(stdout,"%d\n",use_nfsft);
    if (use_nfsft != NO)
    {
      /* Check if the NFFT shall be used. */
      fscanf(stdin,"nfft=%d\n",&use_nfft);
      fprintf(stdout,"%d\n",use_nfsft);
      if (use_nfft != NO)
      {
        /* Read the cut-off parameter. */
        fscanf(stdin,"cutoff=%d\n",&cutoff);
        fprintf(stdout,"%d\n",cutoff);
      }
      else
      {
        /* TODO remove this */
        /* Initialize unused variable with dummy value. */
        cutoff = 1;
      }
      /* Check if the fast polynomial transform shall be used. */
      fscanf(stdin,"fpt=%d\n",&use_fpt);
      fprintf(stdout,"%d\n",use_fpt);
      if (use_fpt != NO)
      {
        /* Read the NFSFT threshold parameter. */
        fscanf(stdin,"threshold=%lf\n",&threshold);
        fprintf(stdout,"%lf\n",threshold);
      }
      else
      {
        /* TODO remove this */
        /* Initialize unused variable with dummy value. */
        threshold = 1000.0;
      }
    }
    else
    {
      /* TODO remove this */
      /* Set dummy values. */
      use_nfft = NO;
      use_fpt = NO;
      cutoff = 3;
      threshold = 1000.0;
    }

    /* Read the testmode type. */
    fscanf(stdin,"testmode=%d\n",&testmode);
    fprintf(stdout,"%d\n",testmode);

    if (testmode == ERROR)
    {
      /* Read the quadrature grid type. */
      fscanf(stdin,"gridtype=%d\n",&gridtype);
      fprintf(stdout,"%d\n",gridtype);

      /* Read the test function. */
      fscanf(stdin,"testfunction=%d\n",&testfunction);
      fprintf(stdout,"%d\n",testfunction);

      /* Check if random bandlimited function has been chosen. */
      if (testfunction == FUNCTION_RANDOM_BANDLIMITED)
      {
        /* Read the bandwidht. */
        fscanf(stdin,"bandlimit=%d\n",&N);
        fprintf(stdout,"%d\n",N);
      }
      else
      {
        N = 1;
      }

      /* Read the number of repetitions. */
      fscanf(stdin,"repetitions=%d\n",&repetitions);
      fprintf(stdout,"%d\n",repetitions);

      fscanf(stdin,"mode=%d\n",&mode);
      fprintf(stdout,"%d\n",mode);

      if (mode == RANDOM)
      {
        /* Read the bandwidht. */
        fscanf(stdin,"points=%d\n",&m_compare);
        fprintf(stdout,"%d\n",m_compare);
        x_compare = (double*) nfft_malloc(2*m_compare*sizeof(double));
        d = 0;
        while (d < m_compare)
        {
          x1 = 2.0*(((double)rand())/RAND_MAX) - 1.0;
          x2 = 2.0*(((double)rand())/RAND_MAX) - 1.0;
          x3 = 2.0*(((double)rand())/RAND_MAX) - 1.0;
          temp = sqrt(x1*x1+x2*x2+x3*x3);
          if (temp <= 1)
          {
            x_compare[2*d+1] = acos(x3);
            if (x_compare[2*d+1] == 0 || x_compare[2*d+1] == KPI)
            {
              x_compare[2*d] = 0.0;
            }
            else
            {
              x_compare[2*d] = atan2(x2/sin(x_compare[2*d+1]),x1/sin(x_compare[2*d+1]));
            }
            x_compare[2*d] *= 1.0/(2.0*KPI);
            x_compare[2*d+1] *= 1.0/(2.0*KPI);
            d++;
          }
        }
        f_compare = (double _Complex*) nfft_malloc(m_compare*sizeof(double _Complex));
        f = (double _Complex*) nfft_malloc(m_compare*sizeof(double _Complex));
      }
    }

    /* Initialize maximum cut-off degree and grid size parameter. */
    NQ_max = 0;
    SQ_max = 0;

    /* Read the number of cut-off degrees. */
    fscanf(stdin,"bandwidths=%d\n",&iNQ_max);
    fprintf(stdout,"%d\n",iNQ_max);

    /* Allocate memory for the cut-off degrees and grid size parameters. */
    NQ = (int*) nfft_malloc(iNQ_max*sizeof(int));
    SQ = (int*) nfft_malloc(iNQ_max*sizeof(int));
    if (testmode == TIMING)
    {
      RQ = (int*) nfft_malloc(iNQ_max*sizeof(int));
    }

    /* Read the cut-off degrees and grid size parameters. */
    for (iNQ = 0; iNQ < iNQ_max; iNQ++)
    {
      if (testmode == TIMING)
      {
        /* Read cut-off degree and grid size parameter. */
        fscanf(stdin,"%d %d %d\n",&NQ[iNQ],&SQ[iNQ],&RQ[iNQ]);
        fprintf(stdout,"%d %d %d\n",NQ[iNQ],SQ[iNQ],RQ[iNQ]);
        NQ_max = MAX(NQ_max,NQ[iNQ]);
        SQ_max = MAX(SQ_max,SQ[iNQ]);
      }
      else
      {
        /* Read cut-off degree and grid size parameter. */
        fscanf(stdin,"%d %d\n",&NQ[iNQ],&SQ[iNQ]);
        fprintf(stdout,"%d %d\n",NQ[iNQ],SQ[iNQ]);
        NQ_max = MAX(NQ_max,NQ[iNQ]);
        SQ_max = MAX(SQ_max,SQ[iNQ]);
      }
    }

    /* Do precomputation. */
    //fprintf(stderr,"NFSFT Precomputation\n");
    //fflush(stderr);
    nfsft_precompute(NQ_max, threshold,
      ((use_nfsft==NO)?(NFSFT_NO_FAST_ALGORITHM):(0U)), 0U);

    if (testmode == TIMING)
    {
      /* Allocate data structures. */
      f_hat = (double _Complex*) nfft_malloc(NFSFT_F_HAT_SIZE(NQ_max)*sizeof(double _Complex));
      f = (double _Complex*) nfft_malloc(SQ_max*sizeof(double _Complex));
      x_grid = (double*) nfft_malloc(2*SQ_max*sizeof(double));
      for (d = 0; d < SQ_max; d++)
      {
        f[d] = (((double)rand())/RAND_MAX)-0.5 + _Complex_I*((((double)rand())/RAND_MAX)-0.5);
        x_grid[2*d] = (((double)rand())/RAND_MAX) - 0.5;
        x_grid[2*d+1] = (((double)rand())/RAND_MAX) * 0.5;
      }
    }

    //fprintf(stderr,"Entering loop\n");
    //fflush(stderr);
    /* Process all cut-off bandwidths. */
    for (iNQ = 0; iNQ < iNQ_max; iNQ++)
    {
      if (testmode == TIMING)
      {
        nfsft_init_guru(&plan,NQ[iNQ],SQ[iNQ], NFSFT_NORMALIZED |
          ((use_nfft!=NO)?(0U):(NFSFT_USE_NDFT)) |
          ((use_fpt!=NO)?(0U):(NFSFT_USE_DPT)),
          PRE_PHI_HUT | PRE_PSI | FFTW_INIT | FFTW_MEASURE | FFT_OUT_OF_PLACE,
          cutoff);

        plan.f_hat = f_hat;
        plan.x = x_grid;
        plan.f = f;

        nfsft_precompute_x(&plan);

        t_avg = 0.0;

        for (i = 0; i < RQ[iNQ]; i++)
        {
          t0 = getticks();

          if (use_nfsft != NO)
          {
            /* Execute the adjoint NFSFT transformation. */
            nfsft_adjoint(&plan);
          }
          else
          {
            /* Execute the adjoint direct NDSFT transformation. */
            nfsft_adjoint_direct(&plan);
          }

          t1 = getticks();
          t_avg += nfft_elapsed_seconds(t1,t0);
        }

        t_avg = t_avg/((double)RQ[iNQ]);

        nfsft_finalize(&plan);

        fprintf(stdout,"%+le\n", t_avg);
        fprintf(stderr,"%d: %4d %4d %+le\n", tc, NQ[iNQ], SQ[iNQ], t_avg);
      }
      else
      {
        /* Determine the maximum number of nodes. */
        switch (gridtype)
        {
          case GRID_GAUSS_LEGENDRE:
            /* Calculate grid dimensions. */
            m_theta = SQ[iNQ] + 1;
            m_phi = 2*SQ[iNQ] + 2;
            m_total = m_theta*m_phi;
            break;
          case GRID_CLENSHAW_CURTIS:
            /* Calculate grid dimensions. */
            m_theta = 2*SQ[iNQ] + 1;
            m_phi = 2*SQ[iNQ] + 2;
            m_total = m_theta*m_phi;
            break;
          case GRID_HEALPIX:
            m_theta = 1;
            m_phi = 12*SQ[iNQ]*SQ[iNQ];
            m_total = m_theta * m_phi;
            //fprintf("HEALPix: SQ = %d, m_theta = %d, m_phi= %d, m");
            break;
          case GRID_EQUIDISTRIBUTION:
          case GRID_EQUIDISTRIBUTION_UNIFORM:
            m_theta = 2;
            //fprintf(stderr,"ed: m_theta = %d\n",m_theta);
            for (k = 1; k < SQ[iNQ]; k++)
            {
              m_theta += (int)floor((2*KPI)/acos((cos(KPI/(double)SQ[iNQ])-
                cos(k*KPI/(double)SQ[iNQ])*cos(k*KPI/(double)SQ[iNQ]))/
                (sin(k*KPI/(double)SQ[iNQ])*sin(k*KPI/(double)SQ[iNQ]))));
              //fprintf(stderr,"ed: m_theta = %d\n",m_theta);
            }
            //fprintf(stderr,"ed: m_theta final = %d\n",m_theta);
            m_phi = 1;
            m_total = m_theta * m_phi;
            break;
        }

        /* Allocate memory for data structures. */
        w = (double*) nfft_malloc(m_theta*sizeof(double));
        x_grid = (double*) nfft_malloc(2*m_total*sizeof(double));

        //fprintf(stderr,"NQ = %d\n",NQ[iNQ]);
        //fflush(stderr);
        switch (gridtype)
        {
          case GRID_GAUSS_LEGENDRE:
            //fprintf(stderr,"Generating grid for NQ = %d, SQ = %d\n",NQ[iNQ],SQ[iNQ]);
            //fflush(stderr);

            /* Read quadrature weights. */
            for (k = 0; k < m_theta; k++)
            {
              fscanf(stdin,"%le\n",&w[k]);
              w[k] *= (2.0*KPI)/((double)m_phi);
            }

            //fprintf(stderr,"Allocating theta and phi\n");
            //fflush(stderr);
            /* Allocate memory to store the grid's angles. */
            theta = (double*) nfft_malloc(m_theta*sizeof(double));
            phi = (double*) nfft_malloc(m_phi*sizeof(double));

            //if (theta == NULL || phi == NULL)
            //{
              //fprintf(stderr,"Couldn't allocate theta and phi\n");
              //fflush(stderr);
            //}


            /* Read angles theta. */
            for (k = 0; k < m_theta; k++)
            {
              fscanf(stdin,"%le\n",&theta[k]);
            }

            /* Generate the grid angles phi. */
            for (n = 0; n < m_phi; n++)
            {
              phi[n] = n/((double)m_phi);
              phi[n] -= ((phi[n]>=0.5)?(1.0):(0.0));
            }

            //fprintf(stderr,"Generating grid nodes\n");
            //fflush(stderr);

            /* Generate the grid's nodes. */
            d = 0;
            for (k = 0; k < m_theta; k++)
            {
              for (n = 0; n < m_phi; n++)
              {
                x_grid[2*d] = phi[n];
                x_grid[2*d+1] = theta[k];
                d++;
              }
            }

            //fprintf(stderr,"Freeing theta and phi\n");
            //fflush(stderr);
            /* Free the arrays for the grid's angles. */
            nfft_free(theta);
            nfft_free(phi);

            break;

          case GRID_CLENSHAW_CURTIS:

            /* Allocate memory to store the grid's angles. */
            theta = (double*) nfft_malloc(m_theta*sizeof(double));
            phi = (double*) nfft_malloc(m_phi*sizeof(double));

            /* Generate the grid angles theta. */
            for (k = 0; k < m_theta; k++)
            {
              theta[k] = k/((double)2*(m_theta-1));
            }

            /* Generate the grid angles phi. */
            for (n = 0; n < m_phi; n++)
            {
              phi[n] = n/((double)m_phi);
              phi[n] -= ((phi[n]>=0.5)?(1.0):(0.0));
            }

            /* Generate quadrature weights. */
            fplan = fftw_plan_r2r_1d(SQ[iNQ]+1, w, w, FFTW_REDFT00, 0U);
            for (k = 0; k < SQ[iNQ]+1; k++)
            {
              w[k] = -2.0/(4*k*k-1);
            }
            fftw_execute(fplan);
            w[0] *= 0.5;

            for (k = 0; k < SQ[iNQ]+1; k++)
            {
              w[k] *= (2.0*KPI)/((double)(m_theta-1)*m_phi);
              w[m_theta-1-k] = w[k];
            }
            fftw_destroy_plan(fplan);

            /* Generate the grid's nodes. */
            d = 0;
            for (k = 0; k < m_theta; k++)
            {
              for (n = 0; n < m_phi; n++)
              {
                x_grid[2*d] = phi[n];
                x_grid[2*d+1] = theta[k];
                d++;
              }
            }

            /* Free the arrays for the grid's angles. */
            nfft_free(theta);
            nfft_free(phi);

            break;

          case GRID_HEALPIX:

            d = 0;
            for (k = 1; k <= SQ[iNQ]-1; k++)
            {
              for (n = 0; n <= 4*k-1; n++)
              {
                x_grid[2*d+1] = 1 - (k*k)/((double)(3.0*SQ[iNQ]*SQ[iNQ]));
                x_grid[2*d] =  ((n+0.5)/(4*k));
                x_grid[2*d] -= (x_grid[2*d]>=0.5)?(1.0):(0.0);
                d++;
              }
            }

            d2 = d-1;

            for (k = SQ[iNQ]; k <= 3*SQ[iNQ]; k++)
            {
              for (n = 0; n <= 4*SQ[iNQ]-1; n++)
              {
                x_grid[2*d+1] = 2.0/(3*SQ[iNQ])*(2*SQ[iNQ]-k);
                x_grid[2*d] = (n+((k%2==0)?(0.5):(0.0)))/(4*SQ[iNQ]);
                x_grid[2*d] -= (x_grid[2*d]>=0.5)?(1.0):(0.0);
                d++;
              }
            }

            for (k = 1; k <= SQ[iNQ]-1; k++)
            {
              for (n = 0; n <= 4*k-1; n++)
              {
                x_grid[2*d+1] = -x_grid[2*d2+1];
                x_grid[2*d] =  x_grid[2*d2];
                d++;
                d2--;
              }
            }

            for (d = 0; d < m_total; d++)
            {
              x_grid[2*d+1] = acos(x_grid[2*d+1])/(2.0*KPI);
            }

            w[0] = (4.0*KPI)/(m_total);
            break;

          case GRID_EQUIDISTRIBUTION:
          case GRID_EQUIDISTRIBUTION_UNIFORM:
            /* TODO Compute the weights. */

            if (gridtype == GRID_EQUIDISTRIBUTION)
            {
              w_temp = (double*) nfft_malloc((SQ[iNQ]+1)*sizeof(double));
              fplan = fftw_plan_r2r_1d(SQ[iNQ]/2+1, w_temp, w_temp, FFTW_REDFT00, 0U);
              for (k = 0; k < SQ[iNQ]/2+1; k++)
              {
                w_temp[k] = -2.0/(4*k*k-1);
              }
              fftw_execute(fplan);
              w_temp[0] *= 0.5;

              for (k = 0; k < SQ[iNQ]/2+1; k++)
              {
                w_temp[k] *= (2.0*KPI)/((double)(SQ[iNQ]));
                w_temp[SQ[iNQ]-k] = w_temp[k];
              }
              fftw_destroy_plan(fplan);
            }

            d = 0;
            x_grid[2*d] = -0.5;
            x_grid[2*d+1] = 0.0;
            if (gridtype == GRID_EQUIDISTRIBUTION)
            {
              w[d] = w_temp[0];
            }
            else
            {
              w[d] = (4.0*KPI)/(m_total);
            }
            d = 1;
            x_grid[2*d] = -0.5;
            x_grid[2*d+1] = 0.5;
            if (gridtype == GRID_EQUIDISTRIBUTION)
            {
              w[d] = w_temp[SQ[iNQ]];
            }
            else
            {
              w[d] = (4.0*KPI)/(m_total);
            }
            d = 2;

            for (k = 1; k < SQ[iNQ]; k++)
            {
              theta_s = (double)k*KPI/(double)SQ[iNQ];
              M = (int)floor((2.0*KPI)/acos((cos(KPI/(double)SQ[iNQ])-
                cos(theta_s)*cos(theta_s))/(sin(theta_s)*sin(theta_s))));

              for (n = 0; n < M; n++)
              {
                x_grid[2*d] = (n + 0.5)/M;
                x_grid[2*d] -= (x_grid[2*d]>=0.5)?(1.0):(0.0);
                x_grid[2*d+1] = theta_s/(2.0*KPI);
                if (gridtype == GRID_EQUIDISTRIBUTION)
                {
                  w[d] = w_temp[k]/((double)(M));
                }
                else
                {
                  w[d] = (4.0*KPI)/(m_total);
                }
                d++;
              }
            }

            if (gridtype == GRID_EQUIDISTRIBUTION)
            {
              nfft_free(w_temp);
            }
            break;

          default:
            break;
        }

        /* Allocate memory for grid values. */
        f_grid = (double _Complex*) nfft_malloc(m_total*sizeof(double _Complex));

        if (mode == RANDOM)
        {
        }
        else
        {
          m_compare = m_total;
          f_compare = (double _Complex*) nfft_malloc(m_compare*sizeof(double _Complex));
          x_compare = x_grid;
          f = f_grid;
        }

        //fprintf(stderr,"Generating test function\n");
        //fflush(stderr);
        switch (testfunction)
        {
          case FUNCTION_RANDOM_BANDLIMITED:
            f_hat_gen = (double _Complex*) nfft_malloc(NFSFT_F_HAT_SIZE(N)*sizeof(double _Complex));
            //fprintf(stderr,"Generating random test function\n");
            //fflush(stderr);
            /* Generate random function samples by sampling a bandlimited
             * function. */
            nfsft_init_guru(&plan_gen,N,m_total, NFSFT_NORMALIZED |
              ((use_nfft!=NO)?(0U):(NFSFT_USE_NDFT)) |
              ((use_fpt!=NO)?(0U):(NFSFT_USE_DPT)),
              ((N>512)?(0U):(PRE_PHI_HUT | PRE_PSI)) | FFTW_INIT |
              FFT_OUT_OF_PLACE, cutoff);

            plan_gen.f_hat = f_hat_gen;
            plan_gen.x = x_grid;
            plan_gen.f = f_grid;

            nfsft_precompute_x(&plan_gen);

            for (k = 0; k < plan_gen.N_total; k++)
            {
              f_hat_gen[k] = 0.0;
            }

            for (k = 0; k <= N; k++)
            {
              for (n = -k; n <= k; n++)
              {
                f_hat_gen[NFSFT_INDEX(k,n,&plan_gen)] =
                (((double)rand())/RAND_MAX)-0.5 + _Complex_I*((((double)rand())/RAND_MAX)-0.5);
              }
            }

            if (use_nfsft != NO)
            {
              /* Execute the NFSFT transformation. */
              nfsft_trafo(&plan_gen);
            }
            else
            {
              /* Execute the direct NDSFT transformation. */
              nfsft_trafo_direct(&plan_gen);
            }

            nfsft_finalize(&plan_gen);

            if (mode == RANDOM)
            {
              nfsft_init_guru(&plan_gen,N,m_compare, NFSFT_NORMALIZED |
                ((use_nfft!=NO)?(0U):(NFSFT_USE_NDFT)) |
                ((use_fpt!=NO)?(0U):(NFSFT_USE_DPT)),
                ((N>512)?(0U):(PRE_PHI_HUT | PRE_PSI)) | FFTW_INIT |
                FFT_OUT_OF_PLACE, cutoff);

              plan_gen.f_hat = f_hat_gen;
              plan_gen.x = x_compare;
              plan_gen.f = f_compare;

              nfsft_precompute_x(&plan_gen);

              if (use_nfsft != NO)
              {
                /* Execute the NFSFT transformation. */
                nfsft_trafo(&plan_gen);
              }
              else
              {
                /* Execute the direct NDSFT transformation. */
                nfsft_trafo_direct(&plan_gen);
              }

              nfsft_finalize(&plan_gen);
            }
            else
            {
              memcpy(f_compare,f_grid,m_total*sizeof(double _Complex));
            }

            nfft_free(f_hat_gen);

            break;

          case FUNCTION_F1:
            for (d = 0; d < m_total; d++)
            {
              x1 = sin(x_grid[2*d+1]*2.0*KPI)*cos(x_grid[2*d]*2.0*KPI);
              x2 = sin(x_grid[2*d+1]*2.0*KPI)*sin(x_grid[2*d]*2.0*KPI);
              x3 = cos(x_grid[2*d+1]*2.0*KPI);
              f_grid[d] = x1*x2*x3;
            }
            if (mode == RANDOM)
            {
              for (d = 0; d < m_compare; d++)
              {
                x1 = sin(x_compare[2*d+1]*2.0*KPI)*cos(x_compare[2*d]*2.0*KPI);
                x2 = sin(x_compare[2*d+1]*2.0*KPI)*sin(x_compare[2*d]*2.0*KPI);
                x3 = cos(x_compare[2*d+1]*2.0*KPI);
                f_compare[d] = x1*x2*x3;
              }
            }
            else
            {
              memcpy(f_compare,f_grid,m_total*sizeof(double _Complex));
            }
            break;
          case FUNCTION_F2:
            for (d = 0; d < m_total; d++)
            {
              x1 = sin(x_grid[2*d+1]*2.0*KPI)*cos(x_grid[2*d]*2.0*KPI);
              x2 = sin(x_grid[2*d+1]*2.0*KPI)*sin(x_grid[2*d]*2.0*KPI);
              x3 = cos(x_grid[2*d+1]*2.0*KPI);
              f_grid[d] = 0.1*exp(x1+x2+x3);
            }
            if (mode == RANDOM)
            {
              for (d = 0; d < m_compare; d++)
              {
                x1 = sin(x_compare[2*d+1]*2.0*KPI)*cos(x_compare[2*d]*2.0*KPI);
                x2 = sin(x_compare[2*d+1]*2.0*KPI)*sin(x_compare[2*d]*2.0*KPI);
                x3 = cos(x_compare[2*d+1]*2.0*KPI);
                f_compare[d] = 0.1*exp(x1+x2+x3);
              }
            }
            else
            {
              memcpy(f_compare,f_grid,m_total*sizeof(double _Complex));
            }
            break;
          case FUNCTION_F3:
            for (d = 0; d < m_total; d++)
            {
              x1 = sin(x_grid[2*d+1]*2.0*KPI)*cos(x_grid[2*d]*2.0*KPI);
              x2 = sin(x_grid[2*d+1]*2.0*KPI)*sin(x_grid[2*d]*2.0*KPI);
              x3 = cos(x_grid[2*d+1]*2.0*KPI);
              temp = sqrt(x1*x1)+sqrt(x2*x2)+sqrt(x3*x3);
              f_grid[d] = 0.1*temp;
            }
            if (mode == RANDOM)
            {
              for (d = 0; d < m_compare; d++)
              {
                x1 = sin(x_compare[2*d+1]*2.0*KPI)*cos(x_compare[2*d]*2.0*KPI);
                x2 = sin(x_compare[2*d+1]*2.0*KPI)*sin(x_compare[2*d]*2.0*KPI);
                x3 = cos(x_compare[2*d+1]*2.0*KPI);
                temp = sqrt(x1*x1)+sqrt(x2*x2)+sqrt(x3*x3);
                f_compare[d] = 0.1*temp;
              }
            }
            else
            {
              memcpy(f_compare,f_grid,m_total*sizeof(double _Complex));
            }
            break;
          case FUNCTION_F4:
            for (d = 0; d < m_total; d++)
            {
              x1 = sin(x_grid[2*d+1]*2.0*KPI)*cos(x_grid[2*d]*2.0*KPI);
              x2 = sin(x_grid[2*d+1]*2.0*KPI)*sin(x_grid[2*d]*2.0*KPI);
              x3 = cos(x_grid[2*d+1]*2.0*KPI);
              temp = sqrt(x1*x1)+sqrt(x2*x2)+sqrt(x3*x3);
              f_grid[d] = 1.0/(temp);
            }
            if (mode == RANDOM)
            {
              for (d = 0; d < m_compare; d++)
              {
                x1 = sin(x_compare[2*d+1]*2.0*KPI)*cos(x_compare[2*d]*2.0*KPI);
                x2 = sin(x_compare[2*d+1]*2.0*KPI)*sin(x_compare[2*d]*2.0*KPI);
                x3 = cos(x_compare[2*d+1]*2.0*KPI);
                temp = sqrt(x1*x1)+sqrt(x2*x2)+sqrt(x3*x3);
                f_compare[d] = 1.0/(temp);
              }
            }
            else
            {
              memcpy(f_compare,f_grid,m_total*sizeof(double _Complex));
            }
            break;
          case FUNCTION_F5:
            for (d = 0; d < m_total; d++)
            {
              x1 = sin(x_grid[2*d+1]*2.0*KPI)*cos(x_grid[2*d]*2.0*KPI);
              x2 = sin(x_grid[2*d+1]*2.0*KPI)*sin(x_grid[2*d]*2.0*KPI);
              x3 = cos(x_grid[2*d+1]*2.0*KPI);
              temp = sqrt(x1*x1)+sqrt(x2*x2)+sqrt(x3*x3);
              f_grid[d] = 0.1*sin(1+temp)*sin(1+temp);
            }
            if (mode == RANDOM)
            {
              for (d = 0; d < m_compare; d++)
              {
                x1 = sin(x_compare[2*d+1]*2.0*KPI)*cos(x_compare[2*d]*2.0*KPI);
                x2 = sin(x_compare[2*d+1]*2.0*KPI)*sin(x_compare[2*d]*2.0*KPI);
                x3 = cos(x_compare[2*d+1]*2.0*KPI);
                temp = sqrt(x1*x1)+sqrt(x2*x2)+sqrt(x3*x3);
                f_compare[d] = 0.1*sin(1+temp)*sin(1+temp);
              }
            }
            else
            {
              memcpy(f_compare,f_grid,m_total*sizeof(double _Complex));
            }
            break;
          case FUNCTION_F6:
            for (d = 0; d < m_total; d++)
            {
              if (x_grid[2*d+1] <= 0.25)
              {
                f_grid[d] = 1.0;
              }
              else
              {
                f_grid[d] = 1.0/(sqrt(1+3*cos(2.0*KPI*x_grid[2*d+1])*cos(2.0*KPI*x_grid[2*d+1])));
              }
            }
            if (mode == RANDOM)
            {
              for (d = 0; d < m_compare; d++)
              {
                if (x_compare[2*d+1] <= 0.25)
                {
                  f_compare[d] = 1.0;
                }
                else
                {
                  f_compare[d] = 1.0/(sqrt(1+3*cos(2.0*KPI*x_compare[2*d+1])*cos(2.0*KPI*x_compare[2*d+1])));
                }
              }
            }
            else
            {
              memcpy(f_compare,f_grid,m_total*sizeof(double _Complex));
            }
            break;
          default:
            //fprintf(stderr,"Generating one function\n");
            //fflush(stderr);
            for (d = 0; d < m_total; d++)
            {
              f_grid[d] = 1.0;
            }
            if (mode == RANDOM)
            {
              for (d = 0; d < m_compare; d++)
              {
                f_compare[d] = 1.0;
              }
            }
            else
            {
              memcpy(f_compare,f_grid,m_total*sizeof(double _Complex));
            }
            break;
        }

        //fprintf(stderr,"Initializing trafo\n");
        //fflush(stderr);
        /* Init transform plan. */
        nfsft_init_guru(&plan_adjoint,NQ[iNQ],m_total, NFSFT_NORMALIZED |
          ((use_nfft!=NO)?(0U):(NFSFT_USE_NDFT)) |
          ((use_fpt!=NO)?(0U):(NFSFT_USE_DPT)),
          ((NQ[iNQ]>512)?(0U):(PRE_PHI_HUT | PRE_PSI)) | FFTW_INIT |
          FFT_OUT_OF_PLACE, cutoff);

        plan_adjoint_ptr = &plan_adjoint;

        if (mode == RANDOM)
        {
          nfsft_init_guru(&plan,NQ[iNQ],m_compare, NFSFT_NORMALIZED |
            ((use_nfft!=NO)?(0U):(NFSFT_USE_NDFT)) |
            ((use_fpt!=NO)?(0U):(NFSFT_USE_DPT)),
            ((NQ[iNQ]>512)?(0U):(PRE_PHI_HUT | PRE_PSI)) | FFTW_INIT |
            FFT_OUT_OF_PLACE, cutoff);
          plan_ptr = &plan;
        }
        else
        {
          plan_ptr = &plan_adjoint;
        }

        f_hat = (double _Complex*) nfft_malloc(NFSFT_F_HAT_SIZE(NQ[iNQ])*sizeof(double _Complex));

        plan_adjoint_ptr->f_hat = f_hat;
        plan_adjoint_ptr->x = x_grid;
        plan_adjoint_ptr->f = f_grid;

        plan_ptr->f_hat = f_hat;
        plan_ptr->x = x_compare;
        plan_ptr->f = f;

        //fprintf(stderr,"Precomputing for x\n");
        //fflush(stderr);
        nfsft_precompute_x(plan_adjoint_ptr);
        if (plan_adjoint_ptr != plan_ptr)
        {
          nfsft_precompute_x(plan_ptr);
        }

        /* Initialize cumulative time variable. */
        t_avg = 0.0;
        err_infty_avg = 0.0;
        err_2_avg = 0.0;

        /* Cycle through all runs. */
        for (i = 0; i < 1/*repetitions*/; i++)
        {
          //fprintf(stderr,"Copying original values\n");
          //fflush(stderr);
          /* Copy exact funtion values to working array. */
          //memcpy(f,f_grid,m_total*sizeof(double _Complex));

          /* Initialize time measurement. */
          t0 = getticks();

          //fprintf(stderr,"Multiplying with quadrature weights\n");
          //fflush(stderr);
          /* Multiplication with the quadrature weights. */
          /*fprintf(stderr,"\n");*/
          d = 0;
          for (k = 0; k < m_theta; k++)
          {
            for (n = 0; n < m_phi; n++)
            {
              /*fprintf(stderr,"f_ref[%d] = %le + I*%le,\t f[%d] = %le + I*%le,  \t w[%d] = %le\n",
              d,creal(f_ref[d]),cimag(f_ref[d]),d,creal(f[d]),cimag(f[d]),k,
              w[k]);*/
              f_grid[d] *= w[k];
              d++;
            }
          }

          t1 = getticks();
          t_avg += nfft_elapsed_seconds(t1,t0);

          nfft_free(w);

          t0 = getticks();

          /*fprintf(stderr,"\n");
          d = 0;
          for (d = 0; d < grid_total; d++)
          {
            fprintf(stderr,"f[%d] = %le + I*%le, theta[%d] = %le, phi[%d] = %le\n",
                    d,creal(f[d]),cimag(f[d]),d,x[2*d+1],d,x[2*d]);
          }*/

          //fprintf(stderr,"Executing adjoint\n");
          //fflush(stderr);
          /* Check if the fast NFSFT algorithm shall be tested. */
          if (use_nfsft != NO)
          {
            /* Execute the adjoint NFSFT transformation. */
            nfsft_adjoint(plan_adjoint_ptr);
          }
          else
          {
            /* Execute the adjoint direct NDSFT transformation. */
            nfsft_adjoint_direct(plan_adjoint_ptr);
          }

          /* Multiplication with the Fourier-Legendre coefficients. */
          /*for (k = 0; k <= m[im]; k++)
          {
            for (n = -k; n <= k; n++)
            {
              fprintf(stderr,"f_hat[%d,%d] = %le\t + I*%le\n",k,n,
                      creal(f_hat[NFSFT_INDEX(k,n,&plan_adjoint)]),
                      cimag(f_hat[NFSFT_INDEX(k,n,&plan_adjoint)]));
            }
          }*/

          //fprintf(stderr,"Executing trafo\n");
          //fflush(stderr);
          if (use_nfsft != NO)
          {
            /* Execute the NFSFT transformation. */
            nfsft_trafo(plan_ptr);
          }
          else
          {
            /* Execute the direct NDSFT transformation. */
            nfsft_trafo_direct(plan_ptr);
          }

          t1 = getticks();
          t_avg += nfft_elapsed_seconds(t1,t0);

          //fprintf(stderr,"Finalizing\n");
          //fflush(stderr);
          /* Finalize the NFSFT plans */
          nfsft_finalize(plan_adjoint_ptr);
          if (plan_ptr != plan_adjoint_ptr)
          {
            nfsft_finalize(plan_ptr);
          }

          /* Free data arrays. */
          nfft_free(f_hat);
          nfft_free(x_grid);

          err_infty_avg += X(error_l_infty_complex)(f, f_compare, m_compare);
          err_2_avg += X(error_l_2_complex)(f, f_compare, m_compare);

          nfft_free(f_grid);

          if (mode == RANDOM)
          {
          }
          else
          {
            nfft_free(f_compare);
          }

          /*for (d = 0; d < m_total; d++)
          {
            fprintf(stderr,"f_ref[%d] = %le + I*%le,\t f[%d] = %le + I*%le\n",
              d,creal(f_ref[d]),cimag(f_ref[d]),d,creal(f[d]),cimag(f[d]));
          }*/
        }

        //fprintf(stderr,"Calculating the error\n");
        //fflush(stderr);
        /* Calculate average time needed. */
        t_avg = t_avg/((double)repetitions);

        /* Calculate the average error. */
        err_infty_avg = err_infty_avg/((double)repetitions);

        /* Calculate the average error. */
        err_2_avg = err_2_avg/((double)repetitions);

        /* Print out the error measurements. */
        fprintf(stdout,"%+le %+le %+le\n", t_avg, err_infty_avg, err_2_avg);
        fprintf(stderr,"%d: %4d %4d %+le %+le %+le\n", tc, NQ[iNQ], SQ[iNQ],
          t_avg, err_infty_avg, err_2_avg);
      }
    } /* for (im = 0; im < im_max; im++) - Process all cut-off
       * bandwidths.*/
    fprintf(stderr,"\n");

    /* Delete precomputed data. */
    nfsft_forget();

    /* Free memory for cut-off bandwidths and grid size parameters. */
    nfft_free(NQ);
    nfft_free(SQ);
    if (testmode == TIMING)
    {
      nfft_free(RQ);
    }

    if (mode == RANDOM)
    {
      nfft_free(x_compare);
      nfft_free(f_compare);
      nfft_free(f);
    }

    if (testmode == TIMING)
    {
      /* Allocate data structures. */
      nfft_free(f_hat);
      nfft_free(f);
      nfft_free(x_grid);
    }

  } /* for (tc = 0; tc < tc_max; tc++) - Process each testcase. */

  /* Return exit code for successful run. */
  return EXIT_SUCCESS;
}