Ejemplo n.º 1
0
void
HighPassFilter(double *z,int n,float tr,VFloat high)
{
  int i,j,nn,nc,tail;
  static double *in=NULL;
  static double *highp=NULL;
  static fftw_complex *out=NULL;
  double sharp=0.8,x,alpha;
  fftw_plan p1,p2;

  tail = n/10;
  if (tail < 50) tail = 50;
  if (tail >= n/2) tail = n/2-1;
  if (tail >= n-1) tail = n-2;
  if (tail < 0) tail = 0;

  if(n <= tail) tail = n - 2;
  nn  = n + 2*tail;

  nc  = (nn / 2) + 1;
  if (out == NULL) {
    in  = (double *) VCalloc(nn,sizeof(double));
    out = fftw_malloc (sizeof (fftw_complex ) * nc);
  }

  i = 0;
  for(j=0; j<tail; j++) in[i++] = z[tail-j];
  for(j=0; j<n; j++) in[i++] = z[j];
  j = n-2;
  while (i < n && j >= 0) in[i++] = z[j];

  /*
  for (i=0; i<n; i++) in[i] = z[i];
  */

  /* make plans */
  p1 = fftw_plan_dft_r2c_1d (nn,in,out,FFTW_ESTIMATE);
  p2 = fftw_plan_dft_c2r_1d (nn,out,in,FFTW_ESTIMATE);

  alpha = (double)n * tr;
  if (highp == NULL) highp = (double *) VCalloc(nc,sizeof(double));

  sharp = 0.8;
  for (i=1; i <nc; i++) {
    highp[i] = 1.0 / (1.0 +  exp( (alpha/high -(double)i)*sharp ));
  }

  /* forward fft */
  fftw_execute(p1);

  /* highpass */
  for (i=1; i<nc; i++) {
    x = highp[i];
    out[i][0] *= x;
    out[i][1] *= x;
  }

  /* inverse fft */
  fftw_execute(p2);
  for (i=0; i<n; i++) z[i] = in[i+tail]/(double)n;
}
Ejemplo n.º 2
0
void 
FFTLib_op::ComputeFrame(int N, double *in, double *out)
{
	fftw_execute(PlanF);
}
Ejemplo n.º 3
0
static void generate_ad_edd(void)
{
    float f;
    float offset;
    float amp;
    float phase;
    float delay;
    float pw;
#if defined(HAVE_FFTW3_H)
    double in[FFT_SIZE][2];
    double out[FFT_SIZE][2];
#else
    fftw_complex in[FFT_SIZE];
    fftw_complex out[FFT_SIZE];
#endif
    fftw_plan p;
    int i;
    int j;
    int k;
    int l;

#if defined(HAVE_FFTW3_H)
    p = fftw_plan_dft_1d(FFT_SIZE, in, out, FFTW_BACKWARD, FFTW_ESTIMATE);
#else
    p = fftw_create_plan(FFT_SIZE, FFTW_BACKWARD, FFTW_ESTIMATE);
#endif
    for (j = 0;  j < 6;  j++)
    {
        for (k = 0;  k < 3;  k++)
        {
            for (i = 0;  i < FFT_SIZE;  i++)
            {
#if defined(HAVE_FFTW3_H)
                in[i][0] =
                in[i][1] = 0.0f;
#else
                in[i].re =
                in[i].im = 0.0f;
#endif
            }
            for (i = 1;  i < FFT_SIZE/2;  i++)
            {
                f = (float) i*SAMPLE_RATE/FFT_SIZE;
                amp = 0.0f;
                for (l = 0;  l < (int) (sizeof(ad)/sizeof(ad[0]));  l++)
                {
                    if (f < ad[l].freq)
                        break;
                }
                if (l < (int) (sizeof(ad)/sizeof(ad[0])))
                {
                    offset = (f - ad[l - 1].freq)/(ad[l].freq - ad[l - 1].freq);
                    amp = (1.0 - offset)*ad[l - 1].ad[j] + offset*ad[l].ad[j];
                    amp = pow(10.0, -amp/20.0);
                }
                delay = 0.0f;
                for (l = 0;  l < (int) (sizeof(edd)/sizeof(edd[0]));  l++)
                {
                    if (f < edd[l].freq)
                        break;
                }
                if (l < (int) (sizeof(edd)/sizeof(edd[0])))
                {
                    offset = (f - edd[l - 1].freq)/(edd[l].freq - edd[l - 1].freq);
                    delay = (1.0f - offset)*edd[l - 1].edd[k] + offset*edd[l].edd[k];
                }
                phase = 2.0f*M_PI*f*delay*0.001f;
#if defined(HAVE_FFTW3_H)    
                in[i][0] = amp*cosf(phase);
                in[i][1] = amp*sinf(phase);
                in[FFT_SIZE - i][0] = in[i][0];
                in[FFT_SIZE - i][1] = -in[i][1];
#else
                in[i].re = amp*cosf(phase);
                in[i].im = amp*sinf(phase);
                in[FFT_SIZE - i].re = in[i].re;
                in[FFT_SIZE - i].im = -in[i].im;
#endif
            }
#if 0
            for (i = 0;  i < FFT_SIZE;  i++)
                fprintf(outfile, "%5d %15.5f,%15.5f\n", i, in[i].re, in[i].im);
#endif
#if defined(HAVE_FFTW3_H)    
            fftw_execute(p);
#else
            fftw_one(p, in, out);
#endif

            fprintf(outfile, "/* V.56bis AD-%d, EDD%d */\n", (j == 0)  ?  1  :  j + 4, k + 1);

            fprintf(outfile, "float ad_%d_edd_%d_model[] =\n", (j == 0)  ?  1  :  j + 4, k + 1);
            fprintf(outfile, "{\n");
            /* Normalise the filter's gain */
            pw = 0.0f;
            l = FFT_SIZE - (LINE_FILTER_SIZE - 1)/2;
            for (i = 0;  i < LINE_FILTER_SIZE;  i++)
            {
#if defined(HAVE_FFTW3_H)
                pw += out[l][0]*out[l][0];
#else
                pw += out[l].re*out[l].re;
#endif
                if (++l == FFT_SIZE)
                    l = 0;
            }
            pw = sqrt(pw);
            l = FFT_SIZE - (LINE_FILTER_SIZE - 1)/2;
            for (i = 0;  i < LINE_FILTER_SIZE;  i++)
            {
                
#if defined(HAVE_FFTW3_H)
                impulse_responses[filter_sets][i] = out[l][0]/pw;
#else
                impulse_responses[filter_sets][i] = out[l].re/pw;
#endif
                fprintf(outfile, "%15.5f,\n", impulse_responses[filter_sets][i]);
                if (++l == FFT_SIZE)
                    l = 0;
            }
            fprintf(outfile, "};\n\n");
            filter_sets++;
        }
    }
}
Ejemplo n.º 4
0
static MagickBooleanType InverseFourierTransform(FourierInfo *fourier_info,
  fftw_complex *fourier,Image *image,ExceptionInfo *exception)
{
  CacheView
    *image_view;

  double
    *source;

  fftw_plan
    fftw_c2r_plan;

  long
    y;

  register IndexPacket
    *indexes;

  register long
    i,
    x;

  register PixelPacket
    *q;

  source=(double *) AcquireQuantumMemory((size_t) fourier_info->width,
    fourier_info->height*sizeof(double));
  if (source == (double *) NULL)
    {
      (void) ThrowMagickException(exception,GetMagickModule(),
        ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
      return(MagickFalse);
    }
#if defined(MAGICKCORE_OPENMP_SUPPORT)
  #pragma omp critical (MagickCore_InverseFourierTransform)
#endif
  fftw_c2r_plan=fftw_plan_dft_c2r_2d(fourier_info->width,fourier_info->height,
    fourier,source,FFTW_ESTIMATE);
  fftw_execute(fftw_c2r_plan);
  fftw_destroy_plan(fftw_c2r_plan);
  i=0L;
  image_view=AcquireCacheView(image);
  for (y=0L; y < (long) fourier_info->height; y++)
  {
    q=GetCacheViewAuthenticPixels(image_view,0L,y,fourier_info->width,1UL,
      exception);
    if (q == (PixelPacket *) NULL)
      break;
    indexes=GetCacheViewAuthenticIndexQueue(image_view);
    for (x=0L; x < (long) fourier_info->width; x++)
    {
      switch (fourier_info->channel)
      {
        case RedChannel:
        default:
        {
          q->red=ClampToQuantum(QuantumRange*source[i]);
          break;
        }
        case GreenChannel:
        {
          q->green=ClampToQuantum(QuantumRange*source[i]);
          break;
        }
        case BlueChannel:
        {
          q->blue=ClampToQuantum(QuantumRange*source[i]);
          break;
        }
        case OpacityChannel:
        {
          q->opacity=ClampToQuantum(QuantumRange*source[i]);
          break;
        }
        case IndexChannel:
        {
          indexes[x]=ClampToQuantum(QuantumRange*source[i]);
          break;
        }
        case GrayChannels:
        {
          q->red=ClampToQuantum(QuantumRange*source[i]);
          q->green=q->red;
          q->blue=q->red;
          break;
        }
      }
      i++;
      q++;
    }
    if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
      break;
  }
  image_view=DestroyCacheView(image_view);
  source=(double *) RelinquishMagickMemory(source);
  return(MagickTrue);
}
Datum transform_eeg(PG_FUNCTION_ARGS)
{
    //the size of the array we are trying to transform
    int arraySize;
    // a Datum for the constructred and deconstructed input arrays
    Datum *intermResult;
    Datum *input_data;
    // the final result to return and the input to the function
    ArrayType *result, *input;
    Oid element_type, return_type, input_type;
    //next 6 variables are inputted into get_typlenbyvalalign() and are used for construct and deconstruct array
    //small int in postgreSQL is int16
    int16 return_typelen, input_typelen;
    bool return_typbyval, input_typbyval;
    char return_typalign, input_typalign;

    //the arrays we are transforming. Transforming array in[] into array out[]
    //fftw_complex, a data structure with real (in[i].re) and imaginary (in[i].im) floating-point components. 
    fftw_complex *in, *out;
    fftw_plan my_plan;


    // get input row
    input = PG_GETARG_ARRAYTYPE_P(0);
    // get input array element type
    input_type = ARR_ELEMTYPE(input);
    //get needed variabels
    get_typlenbyvalalign(input_type, &input_typelen, &input_typbyval, &input_typalign);
    // deconstruct inupt array and save the array as Datum input_data
    deconstruct_array(input, input_type, input_typelen, input_typbyval, input_typalign, &input_data, NULL, &arraySize);

    // get element type of return vale (Complex[])
    element_type = get_fn_expr_rettype(fcinfo->flinfo);
    // get element type of an element in the return value (Complex)
    return_type = get_element_type(element_type);
    //get needed variabels
    get_typlenbyvalalign(return_type, &return_typelen, &return_typbyval, &return_typalign);

    // in and out array and plan declarations
    in = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*arraySize);
    out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*arraySize);
    my_plan = fftw_plan_dft_1d(arraySize, in, out, FFTW_FORWARD, FFTW_ESTIMATE);
    
    // set the in variable to the array we got as input.
    // the real parts are from the input_data array
    // the imaginary part is set to 0
    for (int i = 0; i < arraySize; i++) {
        in[i][0] = (double) DatumGetInt16(input_data[i]);
        in[i][1] = 0;
    }

    // run the plan
    fftw_execute(my_plan);

    // array to store the out array (the transformed in array)
    intermResult = palloc(sizeof(Datum)*arraySize);
    
    // for each variable in the out array. 
    // Create a complex variable then set its real and imaginary party from the processed array
    // get the datum from the pointer and save it in the result array
    for(int32 i = 0; i < arraySize; i++)
    {
        Complex *temp = palloc(sizeof(Complex));
        temp->x = out[i][0];
        temp->y = out[i][1];
        intermResult[i] = PointerGetDatum(temp);
    }

    // construct a result array
    result = construct_array(intermResult, arraySize, return_type, return_typelen, return_typbyval, return_typalign);
    
    // free memory
    fftw_destroy_plan(my_plan);
    fftw_free(in);
    fftw_free(out);
    pfree(input_data);
    pfree(intermResult);

    // return result
    PG_RETURN_POINTER(result);

}
Ejemplo n.º 6
0
void M_vocoder::generateCycle() {

  int l1;  //  l1 indexes along polyphony.
  unsigned int l2;  // l2 indexes along the cycle

  inModulator = port_M_modulator->getinputdata();
  inPitchShift = port_M_pitchshift->getinputdata();
  inFreqShift = port_M_freqshift->getinputdata();
  inChannels = port_M_channels->getinputdata();
  inCarrier = port_M_carrier->getinputdata();

  //       *** Insuring continuity across FFTs  ***
  //    One problem with shifting, etc. is to insure
  //    that the output is continuous in position
  //    across FFT frames.  If *all* you do is forward and
  //    reverse FFT, then there's no problem.  However, if you
  //    do any manipulation of the FFT-format data, then you can
  //    (and usually do) get steps in output at the frame boundaries
  //    when you transform back.  This is audible as a series of
  //    signal-dependent pulses at the frame rate (about 48 Hz for
  //    a cycle size of 1024 and a 48 KHz sample rate. )
  //
  //    The hack fix we use here is to keep a buffer of the last
  //    cyclesize samples we saw, and append them together, then
  //    pick a chunk with level- and gradient-matching to use as
  //    our output.  This is turned on and off by the "Dynamic
  //    splicing" checkbox.
  //
  //    To keep the CPU load down, we stay with a power-of-two FFT
  //    size.  That is, 2 * cyclesize; compared to something not a
  //    power of two, say 1280, 2048 is actually a lot faster to
  //    execute and so what looks like more work is actually
  //    considerably less work.


  //   Did the user change the FFT windowing function?
  if (myFFTWindowFunc != whichwin) {
    whichwin = myFFTWindowFunc;
    for (l2 = 0; l2 < (unsigned int) fftsize; l2++)
      window[l2] = windowcurve (whichwin, fftsize, l2, 0.25);
  }

  //  Our outside loop is the polyphony loop.
  for (l1 = 0; l1 < synthdata->poly; l1++) {

    //  copy the modulator input into inbuf

    for (l2 = 0; l2 < fftsize - synthdata->cyclesize; l2++) {
      modbuf[l1][l2] = modbuf [l1] [l2 + synthdata->cyclesize];
    }
    for (l2 = 0; l2 < synthdata->cyclesize; l2++) {
      modbuf[l1][l2 + fftsize - synthdata->cyclesize ] = inModulator[l1][l2];
    }

    //    Copy the input buffer to modinforward
    for (l2 = 0; l2 < (unsigned int)fftsize ; l2++) {
      modinforward[l2] = modbuf[l1][l2] * window[l2];
    }

//#define QUICKCHECK
#ifdef QUICKCHECK
    for (l2 = 0; l2 < (unsigned int) synthdata->cyclesize; l2++)
      data[0][l1][l2] = creal (modinforward[l2 + fftsize/4]);
    return;
#endif
    //   and forward FFT the modulator
    fftw_execute (planmodforward);

    //    copy the FFT of the modulator to modinbackward.
    for (l2 = 0; l2 < (unsigned int)fftsize; l2++)
      modinbackward[l2] = modoutforward[l2];

    //     Send the FFT of the modulator to the output for giggles
    //     and get an approximation of the first harmonic too.
    float firstharmonicval;
    int firstharmonicindex;
    firstharmonicval = 0.0;
    firstharmonicindex = 1.0;
    for (l2 = 1; l2 < (unsigned int) synthdata->cyclesize; l2++) {
      data[2][l1][l2] = logf(fabs (creal (modoutforward[l2])) + 1.0);
      if (data[2][l1][l2] > firstharmonicval) {
	firstharmonicindex = l2;
	firstharmonicval  = data[2][l1][l2] ;
      }
    };
    data[2][l1][0] = -10.0;
    for (l2 = 0; l2 < (unsigned int) synthdata->cyclesize; l2++) {
      data[3][l1][l2] = log2 (firstharmonicindex);
    };

    //   intermediate frequency-domain munging of modulator
    //   Frequency (additive, Bode-style) shifting first
    for (l2 = 0; l2 < (unsigned int)fftsize; l2++)
      modinbackward[l2] = 0;
    int lclfrq;
    for (l2 = 0; l2 < (unsigned int)fftsize/2; l2++) {
      //   positive frequencies (first half) of the FFT result
      lclfrq = l2 + (int)freqshift + vcfreqshift * inFreqShift[l1][0];
      lclfrq = lclfrq > 0 ? lclfrq : 0;
      lclfrq = lclfrq < ((fftsize/2)-1) ? lclfrq : (fftsize/2)-1;
      modinbackward[ lclfrq ] = modoutforward [l2];
      //   Negative frequencies (second half of the fft result)
      modinbackward[fftsize - lclfrq] = modoutforward [ fftsize - l2];
    }

    //    Pitchshifting (multiplicative, harmonic-retaining) shifting.
    //    Note that we reuse the modoutforward as working space
    for (l2 = 0; l2 < (unsigned int) fftsize; l2++) {
      modoutforward[l2] = modinbackward[l2];
    };
    for (l2 = 0; l2 < (unsigned int)fftsize; l2++)
      modinbackward[l2] = 0;

    float psmod, psfactor;
    psmod = (pitchshift + vcpitch * inPitchShift[l1][0]);
    psfactor = pow (2.0, psmod);
    for (l2 = 0; l2 < (unsigned int)fftsize/2; l2++) {
      //   positive frequencies (first half) of the FFT result
      lclfrq = l2 * psfactor;
      lclfrq = lclfrq > 0 ? lclfrq : 0;
      lclfrq = lclfrq < ((fftsize/2)-1) ? lclfrq : (fftsize/2)-1;
      //   Old way to pitch shift: just move the bucket.  But this puts
      //   nulls wherever the energy is split between two buckets with
      //   a 180 degree phase difference.
      if (rtheta == 0) {
            modinbackward[lclfrq] += modoutforward [l2];
            modinbackward[fftsize - lclfrq] += modoutforward [ fftsize - l2];
      }
      else
	{
	  //
	  //   Better way: move freq. bin, multiply angle by octave motion.
	  //
	  modinbackward[lclfrq] +=
	    cabs (modoutforward [l2])
	    * cexp (I * ( carg (modoutforward [l2])
			  + (l2 * phaseshift * psfactor)));
	  modinbackward[fftsize - lclfrq] +=
	    cabs (modoutforward [ fftsize - l2])
	    * cexp (I * ( carg (modoutforward [ fftsize - l2])
			  + (l2 * phaseshift * psfactor)));
	};
    }
    //     The munged modulator is now in "inbackward"
    //     so inverse-FFT it and output it as altered modulator.
    fftw_execute (planmodbackward);

    //   renormalize the time-domain modulator output
    for (l2 = 0; l2 < (unsigned)fftsize; l2++) {
      modoutbackward [l2] = modoutbackward[l2] / float (fftsize) ;
      modoutbackward [l2] = modoutbackward[l2] / window[l2];
    }

    unsigned int i;
    float residual;
    int clomatch_index;


    //     Splicing the new output to the results
    if (dynsplice == 0.0)
      {
	//   output it as the altered modulator.
	for (l2 = 0; l2 < synthdata->cyclesize; l2++) {
	  data[0][l1][l2] = creal ( modoutbackward [l2 +
						    fftsize/2 -
						    synthdata->cyclesize/2 ]);
	}
	clomatch_index = fftsize - synthdata->cyclesize;
      }
    else
      {
	//   find where in our altered modulator output where a "close match"
	//   exists to our previous output value, then output one
	//   cyclesize worth starting there.  Note that since we start at the
	//   start, we get almost a complete fftsize worth of range to
	//   choose from.
	float clov_sofar;
	float tval, dtval;
	int searchstart;
	float spliceval, dspliceval;
	searchstart = fftsize/2 - synthdata->cyclesize;
	if (searchstart < 1) searchstart = 1;
	clomatch_index = searchstart;
	spliceval = data[0][l1][synthdata->cyclesize - 1];
	dspliceval = spliceval - data[0][l1][synthdata->cyclesize - 2];
	clov_sofar= fabs(creal(modoutbackward[clomatch_index])-spliceval );
	for (l2 = searchstart;
	     l2 < (searchstart + synthdata->cyclesize);
	     l2++)
	  {
	    tval = creal (modoutbackward[l2]);
	    dtval = tval - creal (modoutbackward [l2-1]);
	    if (
		((fabs (tval - spliceval )) < clov_sofar )
		&& ((dtval * dspliceval ) >= 0)
		 )
	      {
		clov_sofar= fabs (tval - spliceval );
		clomatch_index = l2;
		// fprintf (stderr, "%f %d ", clov_sofar, clomatch_index);
	      }
	  };
	//  fprintf (stderr, "%d %f %f ",
	//      clomatch_index, clov_sofar, clodv_sofar);
	
	//   What's our residual error, so that we can splice this
	//   with minimal "click"?
	residual = + spliceval - creal( modoutbackward[clomatch_index]);

	//  Move our wave, with the best match so far established, to
	//   the output buffer area.
	for (l2 = 0; l2 < synthdata->cyclesize; l2++) {
	  data[0][l1][l2] = creal ( modoutbackward [ clomatch_index + l2])
	    + ((1.0 - (float(l2) / float(synthdata->cyclesize))) * residual);
	};

      };

    // fprintf (stderr, "%f %d  \n", residual, clomatch_index);

    //     Now it's time to do the carrier.
    //
    for (l2 = 0; l2 < fftsize - synthdata->cyclesize; l2++) {
      carrbuf [l1][l2] = carrbuf [l1][l2 + synthdata->cyclesize];
    }
    for (l2 = 0; l2 < synthdata->cyclesize; l2++) {
      carrbuf [l1][l2 + fftsize - synthdata->cyclesize] = inCarrier[l1][l2];
    }

    for (l2 = 0; l2 <  unsigned (fftsize); l2++) {
      carrinforward [l2] = carrbuf [l1][l2] * window[l2];
    }

    fftw_execute (plancarrforward);

    for (l2 = 0; l2 < (unsigned) fftsize; l2++) {
      carrinbackward[l2] = carroutforward[l2];
    };

    //   carroutforward now has the carrier,

    //      modoutforward now has the modulator.
    //   Group the modulator into channels, and multipy the channels
    //   over the carrier.

    int localchannels;
    localchannels = channels + vcchannels * inChannels[l1][0];
    if (localchannels < 1) localchannels = 1;
    if (localchannels > fftsize - 1) localchannels = fftsize - 1;
    for (l2 = 0; l2 < (unsigned) fftsize; l2++) {
      modmap[l2] = 0;
      //       initial conditions...
      if (l2 == 0)
	for (i = 0; i < channels; i++)
	  modmap[l2] += cabs (modoutforward[l2 + i]);
      else
	modmap [l2] = modmap[l2 - 1];

      //    add the heads, subtract the tails
      i = l2 + channels;
      if (l2 < (unsigned)fftsize - 2)
	modmap[l2] += cabs( modoutforward [i] );
      i = l2 - channels;
      if (l2 >= channels)
	modmap[l2] -= cabs( modoutforward [i] );
    }

    //   Normalize the modmap
    for (l2 = 0; l2 < (unsigned) fftsize; l2++)
      modmap[l2] = modmap[l2] / localchannels;

    //   Do attack/release
    for (l2 = 0; l2 < (unsigned) fftsize; l2++) {
      if (modmap [l2] > armodmap[l2])
	armodmap [l2] += (1 - attack) * (modmap[l2] - armodmap[l2]);
      if (modmap [l2] < armodmap[l2])
	armodmap [l2] += (1 - release) * (modmap[l2] - armodmap[l2]);
    }

    //   multiply the carrier by the modulation map.
    for (l2 = 0; l2 < (unsigned) fftsize; l2++) {
      carrinbackward[l2] = carroutforward[l2] * armodmap[l2];
    }

    //   reverse transform to final output, and renormalize by 1/fftsize.
    fftw_execute (plancarrbackward);

    int offset;
    for (l2 = 0; l2 < synthdata->cyclesize; l2++) {
      offset = l2 + (fftsize/2) - (synthdata->cyclesize / 2);
      data[1][l1][l2]=
	(creal(carroutbackward[offset]/window[offset])) / (fftsize * 100);
    };
  };
}
Ejemplo n.º 7
0
/********************************************************************
NAME: potential
FUNCTION: Calculates the potential of the contrast density in the k-space (from the FFT)in the grid[m] order, and then with an IFFT calculates the potential in the real space
INPUT: density contrast in the k-space
RETURN: File with the input and outputs (sorted in the grid[m] order)
**********************************************************************/
int potential()
{
  int m, i, j, k;
  double factor;
  FILE *pf=NULL;
    
  /*+++++ Computing the potential in k-space +++++*/
  printf("Computing potential in k-space\n");
  printf("-----------------------------------------\n");

  /*----- Factor of the potential -----*/
  factor = (-3.0/2.0) * (GV.H0*GV.H0) * GV.Omega_M0 / GV.a_SF;

  for(m=0; m<GV.NTOTK; m++)
    {
      if( gp[m].k_module > GV.ZERO )
	{
	  gp[m].poten_k[0] = factor * gp[m].DenCon_K[0]/(gp[m].k_module * gp[m].k_module); //Re()
	  gp[m].poten_k[1] = factor * gp[m].DenCon_K[1]/(gp[m].k_module * gp[m].k_module); //Im()
	}//if 
      else
	{
	  gp[m].poten_k[0] = 0.0; //Re()
	  gp[m].poten_k[1] = 0.0; //Im()
	}//else 
    }//for m

  printf("Potential in k-space saved!\n");
  printf("-----------------------------------------\n");

  
#ifdef OUTOFPLACE

  /*+++++ Definitions +++++*/
  fftw_complex *in=NULL;
  double *out=NULL;
  fftw_complex *in2=NULL;
  fftw_plan plan_k2r; // FFTW from k-space to r-space
  fftw_plan plan_r2k; // FFTW from r-space to k-space
    

  /*----- Creating input/output arrays -----*/
  in  = (fftw_complex *) fftw_malloc( sizeof( fftw_complex ) * GV.NTOTK );
  out = (double *) fftw_malloc( sizeof( double ) * GV.NTOTALCELLS );
  
  /*----- Saving the potential input of the FFT -----*/
  for(m=0; m<GV.NTOTK; m++)
    {
      in[m][0] = gp[m].poten_k[0]; //Re()
      in[m][1] = gp[m].poten_k[1]; //Im()
    }//for m

  
  /*----- Making the FFT -----*/
  //plan_k2r = fftw_plan_dft_c2r_3d( GV.NCELLS, GV.NCELLS, GV.NCELLS, in, out, FFTW_ESTIMATE ); //out-of-place transform
  plan_k2r = fftw_plan_dft_c2r_3d( GV.NCELLS, GV.NCELLS, GV.NCELLS, in, out, FFTW_MEASURE ); //out-of-place transform
  fftw_execute( plan_k2r );
  
  printf("FFT potential k2r finished!\n");
  printf("---------------------------------------\n");
  
  /*----- Saving the output data for an out-of-place transform -----*/
  pf = fopen("./../Potential_r_out.dat", "w");
  fprintf(pf, "%s%14s %15s\n", "#", "ID", "Poten(r)");
  for( m=0; m<GV.NTOTALCELLS; m++ )
    {
      gp[m].poten_r = out[m]/GV.NORM; //Re()      
      fprintf(pf, 
	      "%10d %16.8lf\n",
	      m, gp[m].poten_r );
    }//for m
  fclose(pf);
    
  printf("---------------------------------------\n");
  printf("Potential in r space from an out-of-place transform saved!\n");
  printf("---------------------------------------\n");
 

  /*----- Recreating input array -----*/
  in2  = (fftw_complex *) fftw_malloc( sizeof( fftw_complex ) * GV.NTOTK );
  plan_r2k = fftw_plan_dft_r2c_3d( GV.NCELLS, GV.NCELLS, GV.NCELLS, out, in2, FFTW_ESTIMATE );
  fftw_execute( plan_r2k );

  printf("Recreated input of potential in k-space from out-of-place transform performed\n");
  printf("---------------------------------------\n");


  /*+++++ Saving recreated data +++++*/
  pf = fopen("./../Testing_potential_k_space.dat", "w");
  fprintf(pf, "%s%14s %15s %15s %15s\n", "#", "Re_Pot(k)", "Im_Pot(k)", "Reconst_Re", "Reconst_Im");

  for(m=0; m<GV.NTOTK; m++)
    {
      fprintf(pf, 
	      "%10d %20.8lf %20.8lf %20.8lf %20.8lf\n", 
	      m, 
	      gp[m].poten_k[0], gp[m].poten_k[1],
	      in2[m][0]/(GV.NORM*GV.NORM), in2[m][1]/(GV.NORM*GV.NORM));
    }//for m
  fclose(pf),

  printf("Recreated input of potential in k-space from out-of-place transform saved\n");
  printf("---------------------------------------\n");
  

  fftw_destroy_plan( plan_k2r );
  fftw_destroy_plan( plan_r2k );
  
  fftw_free( in );
  fftw_free( in2 );
  fftw_free( out );
#endif
  


#ifdef INPLACE
  /*+++++ Definitions +++++*/
  fftw_complex *in=NULL;  
  fftw_plan plan_k2r; // FFTW from k-space to r-space
  fftw_plan plan_r2k; // FFTW from r-space to k-space
    

  /*----- Creating input/output arrays -----*/
  in  = (fftw_complex *) fftw_malloc( sizeof( fftw_complex ) * GV.NTOTALCELLS );

  /*----- Saving the potential input of the FFT -----*/
  for(m=0; m<GV.NTOTK; m++)
    {
      in[m][0] = gp[m].poten_k[0]; //Re()
      in[m][1] = gp[m].poten_k[1]; //Im()
    }//for m

  /*----- Making the FFT -----*/
  //plan_k2r = fftw_plan_dft_c2r_3d( GV.NCELLS, GV.NCELLS, GV.NCELLS, in, (double *)in, FFTW_ESTIMATE ); //in-place transform  
  plan_k2r = fftw_plan_dft_c2r_3d( GV.NCELLS, GV.NCELLS, GV.NCELLS, in, (double *)in, FFTW_MEASURE ); //in-place transform  
  //plan_k2r = fftw_plan_dft_c2r_3d( GV.NCELLS, GV.NCELLS, GV.NCELLS, in, (double *)in, FFTW_IN_PLACE ); //in-place transform  
  fftw_execute( plan_k2r );

  /*----- Saving the output data for an in-place transform -----*/
  for( m=0; m<GV.NTOTALCELLS/2; m++ )
    {
      gp[2*m].poten_r = in[m][0]/GV.NORM;
      gp[2*m+1].poten_r = in[m][1]/GV.NORM;
    }//for m

  pf = fopen("./../Potential_r_in.dat", "w");
  fprintf(pf, "%s%14s %15s\n", "#", "ID", "Poten(r)");
  for( m=0; m<GV.NTOTALCELLS; m++ )
    {
      fprintf(pf,
	      "%10d %16.8lf\n", 
	      m, gp[m].poten_r );
    }//for m
  fclose(pf);

  //fftw_free( in );

  /*----- Recreating input array -----*/
  //in  = (double *) fftw_malloc( sizeof( double ) * GV.PADDING );
  plan_r2k = fftw_plan_dft_r2c_3d( GV.NCELLS, GV.NCELLS, GV.NCELLS, (double*) in, in, FFTW_ESTIMATE );
  //plan_r2k = fftw_plan_dft_r2c_3d( GV.NCELLS, GV.NCELLS, GV.NCELLS, in, (fftw_complex*)in, FFTW_IN_PLACE );
  fftw_execute( plan_r2k );
  
  printf("Recreated input of potential in k-space from out-of-place transform performed\n");
  printf("---------------------------------------\n");


  /*+++++ Saving recreated data +++++*/
  pf = fopen("./../Testing_potential_k_space_in-place.dat", "w");
  fprintf(pf, "%s%14s %15s %15s %15s\n", "#", "Re_Pot(k)", "Im_Pot(k)", "Reconst_Re", "Reconst_Im");

  for(m=0; m<GV.NTOTK; m++)
    {
      fprintf(pf, 
	      "%10d %20.8lf %20.8lf %20.8lf %20.8lf\n", 
	      m, 
	      gp[m].poten_k[0], gp[m].poten_k[1],
	      in[m][0]/(GV.NORM*GV.NORM), in[m][1]/(GV.NORM*GV.NORM));
    }//for m
  fclose(pf),

  printf("Recreated input of potential in k-space from out-of-place transform saved\n");
  printf("---------------------------------------\n");
  
  fftw_free( in );  
  fftw_destroy_plan( plan_k2r );
  fftw_destroy_plan( plan_r2k );
  
#endif

  printf("FFT_potential code finished!\n");
  printf("----------------------------\n");   

  return 0;
}//potential
Ejemplo n.º 8
0
void calc_envelope(float ** datatrace, float ** envelope, int ns, int ntr){

	/* declaration of variables */
	int i,j, nfreq, npad, k;
	float xr, yr, x, y, dump, a, *h;
	double npadd;
		
	/* declaration of variables for FFTW3*/
	fftw_complex *in, *out;
	fftw_plan p1, p2;

	/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
	/* calculation of the Hilbert transform */
	/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */


	/* calculation of the FFT */
	npad = (int)(pow(2.0, ceil(log((double)(ns))/log(2.0))+2.0) );  /* ns -> npad for usage in FFT*/
        npadd = (double)npad;
	in = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * npad);
	out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * npad);
	
	/* calculation of the vector h */
	     h = vector(1,npad);
	     if ((2*(npad/2))==npad) {
		/* npad is even */
		h[1]=1.0;
		h[npad/2+1]=1.0;
		for (i=2;i<=(npad/2);i++) {
	   	     h[i] = 2.0; }
	     } else {
		/* npad is odd */
		h[1]=1.0;
		for (i=2;i<=((npad+1)/2);i++) {
	   	     h[i]=2.0;}
	     }
	     
	for(k=1;k<=ntr;k++){
						
	     for (j=0;j<ns;j++){
	     in[j][0]=datatrace[k][j+1];
	     in[j][1]=0.0;
		     }
	     for (j=ns;j<npad;j++){
	     in[j][0]=0.0;
	     in[j][1]=0.0;
		     }
	     /* FFT */
	     p1 = fftw_plan_dft_1d(npad, in, out, 1, FFTW_ESTIMATE);
	     fftw_execute(p1);
	     fftw_destroy_plan(p1);		    

	     /* elementwise multiplication of FFT and h */
	     for (i=0;i<npad;i++){
		out[i][0] *= h[i+1];
		out[i][1] *= h[i+1];
	     }


	     /* inverse FFT */
	     p2 = fftw_plan_dft_1d(npad, out, in, -1, FFTW_ESTIMATE);
	     fftw_execute(p2);
             fftw_destroy_plan(p2);

	     /* %%%%%%%%%%%%%%%%%%%%%%% */
	     /* calculation of envelope */
	     /* %%%%%%%%%%%%%%%%%%%%%%% */
	     for (j=0;j<ns;j++){
	     	envelope[k][j+1]=(1.0/npadd)*sqrt(in[j][0]*in[j][0]+in[j][1]*in[j][1]);
	     }
	     
	}

	fftw_free(in);
	fftw_free(out);
	free_vector(h,1,npad);
	
}
Ejemplo n.º 9
0
/** computes the inverse discrete Radon transform of Rf
 *  on the grid given by gridfcn() with T angles and R offsets
 *  by a NFFT-based CG-type algorithm
 */
int Inverse_Radon_trafo(int (*gridfcn)(), int T, int S, double *Rf, int NN, double *f, int max_i)
{
  int j,k;                              /**< index for nodes and freqencies   */
  nfft_plan my_nfft_plan;               /**< plan for the nfft-2D             */
  solver_plan_complex my_infft_plan;             /**< plan for the inverse nfft        */

  fftw_complex *fft;                    /**< variable for the fftw-1Ds        */
  fftw_plan my_fftw_plan;               /**< plan for the fftw-1Ds            */

  int t,r;                              /**< index for directions and offsets */
  double *x, *w;                        /**< knots and associated weights     */
  int l;                                /**< index for iterations             */

  int N[2],n[2];
  int M=T*S;

  N[0]=NN; n[0]=2*N[0];
  N[1]=NN; n[1]=2*N[1];

  fft = (fftw_complex *)nfft_malloc(S*sizeof(fftw_complex));
  my_fftw_plan = fftw_plan_dft_1d(S,fft,fft,FFTW_FORWARD,FFTW_MEASURE);

  x = (double *)nfft_malloc(2*T*S*(sizeof(double)));
  if (x==NULL)
    return -1;

  w = (double *)nfft_malloc(T*S*(sizeof(double)));
  if (w==NULL)
    return -1;

  /** init two dimensional NFFT plan */
  nfft_init_guru(&my_nfft_plan, 2, N, M, n, 4,
                  PRE_PHI_HUT| PRE_PSI| MALLOC_X | MALLOC_F_HAT| MALLOC_F| FFTW_INIT | FFT_OUT_OF_PLACE,
                  FFTW_MEASURE| FFTW_DESTROY_INPUT);

  /** init two dimensional infft plan */
  solver_init_advanced_complex(&my_infft_plan,(nfft_mv_plan_complex*)(&my_nfft_plan), CGNR | PRECOMPUTE_WEIGHT);

  /** init nodes and weights of grid*/
  gridfcn(T,S,x,w);
  for(j=0;j<my_nfft_plan.M_total;j++)
  {
    my_nfft_plan.x[2*j+0] = x[2*j+0];
    my_nfft_plan.x[2*j+1] = x[2*j+1];
    if (j%S)
      my_infft_plan.w[j]    = w[j];
    else
      my_infft_plan.w[j]    = 0.0;
  }

  /** precompute psi, the entries of the matrix B */
  if(my_nfft_plan.nfft_flags & PRE_LIN_PSI)
    nfft_precompute_lin_psi(&my_nfft_plan);

  if(my_nfft_plan.nfft_flags & PRE_PSI)
    nfft_precompute_psi(&my_nfft_plan);

  if(my_nfft_plan.nfft_flags & PRE_FULL_PSI)
    nfft_precompute_full_psi(&my_nfft_plan);

  /** compute 1D-ffts and init given samples and weights */
  for(t=0; t<T; t++)
  {
/*    for(r=0; r<R/2; r++)
       fft[r] = cexp(I*KPI*r)*Rf[t*R+(r+R/2)];
      for(r=0; r<R/2; r++)
       fft[r+R/2] = cexp(I*KPI*r)*Rf[t*R+r];
 */

    for(r=0; r<S; r++)
      fft[r] = Rf[t*S+r] + _Complex_I*0.0;

    nfft_fftshift_complex(fft, 1, &S);
    fftw_execute(my_fftw_plan);
    nfft_fftshift_complex(fft, 1, &S);

    my_infft_plan.y[t*S] = 0.0;
    for(r=-S/2+1; r<S/2; r++)
      my_infft_plan.y[t*S+(r+S/2)] = fft[r+S/2]/KERNEL(r);
  }

  /** initialise some guess f_hat_0 */
  for(k=0;k<my_nfft_plan.N_total;k++)
    my_infft_plan.f_hat_iter[k] = 0.0 + _Complex_I*0.0;

  /** solve the system */
  solver_before_loop_complex(&my_infft_plan);

  if (max_i<1)
  {
    l=1;
    for(k=0;k<my_nfft_plan.N_total;k++)
      my_infft_plan.f_hat_iter[k] = my_infft_plan.p_hat_iter[k];
  }
  else
  {
    for(l=1;l<=max_i;l++)
    {
      solver_loop_one_step_complex(&my_infft_plan);
      /*if (sqrt(my_infft_plan.dot_r_iter)<=1e-12) break;*/
    }
  }
  /*printf("after %d iteration(s): weighted 2-norm of original residual vector = %g\n",l-1,sqrt(my_infft_plan.dot_r_iter));*/

  /** copy result */
  for(k=0;k<my_nfft_plan.N_total;k++)
    f[k] = creal(my_infft_plan.f_hat_iter[k]);

  /** finalise the plans and free the variables */
  fftw_destroy_plan(my_fftw_plan);
  nfft_free(fft);
  solver_finalize_complex(&my_infft_plan);
  nfft_finalize(&my_nfft_plan);
  nfft_free(x);
  nfft_free(w);
  return 0;
}
Ejemplo n.º 10
0
/* Called by jack when new data ist available */
int process (jack_nframes_t nframes, void *arg) {
  static uint8_t cnt = 0;
  jack_default_audio_sample_t *in, *out;

  int i;
  in = jack_port_get_buffer(input_port, nframes);

  /* Copy samples to fft input vector and window them with a hamming window */
  for (i = 0; i < nframes; ++i){
    in_cplx[i][0] = in[i]*(0.54-0.46*sin(2*M_PI*i/(nframes-1)));
    in_cplx[i][1] = 0.0;
  }

  /* Do the fft */
  fftw_execute(p);

  double acc = 0;
  double acc_i = 0;
  double acc_r = 0;
  //int log_idx = 0;
  double f = 0;
  int z = 0;

  gg_set_frame_color(frame, 0, 0, 0);

  /*  */
  /* Lowpass filter the spectrum */
  /*  */

  /* Move old amplitudes */
  int k, l;
  for (k = 0; k < LP_LEN-1; ++k) {
    for (l = 0; l < COLS; ++l) {
      old_amplitudes[k][l] = old_amplitudes[k+1][l];
    }
  }

  /* Calculate boxcar mean */
  for (l = 0; l < COLS; ++l) {
    for (k = 0; k < LP_LEN; ++k) {    
      filtered_amplitudes[l] += old_amplitudes[k][l];
    }
    filtered_amplitudes[l] /= LP_LEN;
  }

  for (i = 0; i < 512; ++i){
    //double val = out_cplx[i][0]*out_cplx[i][0] + out_cplx[i][1]*out_cplx[i][1];
    double val_i = out_cplx[i][0];
    double val_r = out_cplx[i][1];
    acc_i += val_i;
    acc_r += val_r;

    /* Sampled frequency to physical frequency */
    f = i/512.0*22.05e3;

    /* If we are in a new bark band, we need to start integrating the
     * spectrum */
    if (f > z_to_f(z)) {
      acc = sqrt(acc_i*acc_i + acc_r*acc_r);

      /* Set current amplitude */
      old_amplitudes[LP_LEN-1][z] = acc;

      printf("\e[%dm%1d\e[0m", (int)(acc+30), 0);

      /* Calculate bar height from amplitude */
      int bar_height = 0;
      bar_height = (int)round(4*atan(filtered_amplitudes[z]/40.0)/(M_PI/2.0));
      if (bar_height > 4) bar_height = 4;
      
      /* Do the coloring of current bar from amplitude */
      draw_spectrum_column(frame, z, bar_height);

      ++z;
      acc = 0;
      acc_i = 0;
      acc_r = 0;
    }
  }
Ejemplo n.º 11
0
int CallBack(const void *input, void *output, unsigned long frameCount, const PaStreamCallbackTimeInfo *timeInfo, PaStreamCallbackFlags statusFlags, void *userData)
{
    short *in = (short *)input;
    short *out = (short *)output;

    for (int i = 0; i < frameCount; i++) {
        *out++ = *in++;
//        *out++ = 0;
    }

    fft_out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * fft_num);
    double double_in[fft_num];
    
    for (int i = 0; i < fft_num; i++) {
        if (i < (int)frameCount) {
            double_in[i] = (double)in[i];
        } else {
            double_in[i] = 0.0;
        }
    }

    p = fftw_plan_dft_r2c_1d(fft_num, double_in, fft_out, FFTW_ESTIMATE); 
    fftw_execute(p);

    double max_power = 0.0;
    int max_idx = 0;
    for (int i = 0; i < fft_num / 2; i++) {
        double s = fft_out[i][0] * fft_out[i][0] + fft_out[i][1] * fft_out[i][1];
        if (s > max_power) {
            max_power = s;
            max_idx = i;
        }
    }

    double freq = (44100 / (double)fft_num) * max_idx;

    double min_distance = 1000.0;
    int min_idx = 0;
    for (int i = 0; i < 128; i++) {
        double distance = (midi_freqs[i] - freq) * (midi_freqs[i] - freq);
        if (distance < min_distance) {
            min_distance = distance;
            min_idx = i;
        }
    }

    std::string current_midi_key = midi_keys[min_idx];

//    printf("%.0lf:", freq);
//    std::cout << current_midi_key << ", ";

    if (prev_midi_key == "C-1" || prev_midi_key == "") {
        prev_midi_key = current_midi_key;
        sound_length = 0;
    } else if (prev_midi_key != current_midi_key) {
//        std::cout << std::endl << std::endl << prev_midi_key << ":" << sound_length << "ms, " << std::endl;
        if (sound_length >= 50) {
            std::cout << std::endl << std::endl << sound_length << "/" << prev_midi_key << std::endl;
            std::stringstream ss;
            ss << sound_length;
//            std::string output = "./soxclient '" + ss.str() + "/" + prev_midi_key + " " + prev_output + "'";
//            prev_output = ss.str() + "/" + prev_midi_key;
//            std::string output = "./soxclient '50/" + prev_midi_key + prev_output + "'";
            std::string output = "./soxclient '50/" + prev_midi_key + " " + prev_output + "'";
            prev_output = "50/" + prev_midi_key;

            int BUF = 256;
            char buf[BUF];
            std::string hoge = output.c_str();
            if (hoge != "./soxclient '50/C2 50/C3'") {
            std::cout << "zzz" << output.c_str() << std::endl;
            if ((file_p = popen(output.c_str(), "r")) == NULL) {
                err(EXIT_FAILURE, "%s", output.c_str());
            }
            while (fgets(buf, BUF, file_p) != NULL) {
                (void) fputs(buf, stdout);
            }
            if (strlen(buf) >= 4) {
                std::string str = buf;
                str.pop_back();
                std::cout << "|||" << str << "|||" << std::endl;
                if (str != "20/S") {
                    PlaySox ps = PlaySox(str);
                    if (sound != NULL && prev_sound != NULL) {
                        ps.play(sound);
                    }
                    sound = prev_sound;
                    prev_sound = ps.chooseSound();
                }
            }
            }
        }
        prev_midi_key = current_midi_key;
        sound_length = 0;
    } else {
        sound_length += 20;
    }
    
    return (int)paContinue;
}
Ejemplo n.º 12
0
void fft(int N, double *in, int stride) {
	fftw_plan p;
	p = fftw_plan_many_dft(1,&N, 1, (fftw_complex *)in, NULL, stride, 0, (fftw_complex *)in, NULL, stride, 0, FFTW_FORWARD, FFTW_ESTIMATE);
	fftw_execute(p);
	fftw_destroy_plan(p);	
}
Ejemplo n.º 13
0
/*
  run_all_fft

  This routine converts a wavepacket propagation from |f(x,y,t)> to |f(x,y,E)> , from a previously calculated cubic spline representation, using the fftw library routines

  main input: bcoefre, bcoefim. real and complex part spline matrices of |f(x,y,t)>
  main output: WPERe, WPEIm. real and complex part vectors of |f(x,y,E)>

 */
int run_all_fft(double *bcoefre,double *bcoefim, double *X, double *Y,double *xknot, double *yknot, double *tknot, int kx,double ti,double tf,double steptspl,int *np,int nf,int NTG, double width,double *WPERe,double *WPEIm, char *windtype, char *dim){
  int i,j,l,ll,k,nE;
  double x,y,E,ke,norm,stepxspl;
  fftw_complex *workin,*workout, *workin_b,*workout_b;
  fftw_plan p,p_b;
  double Ei,stepE;
  FILE *filin=fopen("fft_check_in.dat","w");
  FILE *filout=fopen("fft_check_out.dat","w");

  stepE = 2*M_PI/(NTG*steptspl);
  Ei = -NTG*stepE/(2.0E+0);
  nE =  NTG; //NTG/2
  printf("\nEnergy step: %E \n\n",stepE);

  //--- allocating work vectors
  workin = fftw_malloc(sizeof(fftw_complex) * NTG);
  workout = fftw_malloc(sizeof(fftw_complex) * NTG);
  workin_b = fftw_malloc(sizeof(fftw_complex) * NTG);
  workout_b = fftw_malloc(sizeof(fftw_complex) * NTG);


  for(i=0;i<np[1];i++){
    for(j=0;j<np[0];j++){
      //generates data set from spline coeff.
      gendata_Psic(workin,bcoefre,bcoefim,xknot,yknot,tknot,kx,np,nf,X[i],Y[j],ti,tf,steptspl,NTG,width,windtype,dim);
      gendata_Psic_bar(workin_b,bcoefre,bcoefim,xknot,yknot,tknot,kx,np,nf,X[i],Y[j],ti,tf,steptspl,NTG,width,windtype,dim);
      //centers t=0 at the zero frequency position of the fft input vector(first) due to periodicity requirement of fft
      center_fft(workin,NTG);
      center_fft(workin_b,NTG);

      //--- do forward fft
      // FFTW_BACKWARD -> sign in the exponent = 1.
      p = fftw_plan_dft_1d(NTG,workin,workout,FFTW_BACKWARD,FFTW_ESTIMATE);
      p_b = fftw_plan_dft_1d(NTG,workin_b,workout_b,FFTW_BACKWARD,FFTW_ESTIMATE);

      fftw_execute(p);  
      fftw_execute(p_b);  

      //shifts the fft result back to the center of the array
      center_fft(workout,NTG);
      center_fft(workout_b,NTG);

      //debug ---
      if(j==26){
	//center_fft(workin,NTG);
	fprintf(filin,"# %E %E\n",X[i],Y[j]);
	for(k=0;k<NTG;k++)fprintf(filin,"%E %E %E %E %E\n",-tf + k*steptspl,workin[k][0],workin[k][1],workin_b[k][0],workin_b[k][1]);
	fprintf(filout,"# %E %E\n",X[i],Y[j]);
	//for(k=0;k<NTG;k++)fprintf(filout,"%E %E %E\n",Ei + k*stepE,steptspl*workout[k][0],steptspl*workout[k][1]);
	for(k=0;k<NTG;k++)fprintf(filout,"%E %E %E %E %E\n",Ei + k*stepE,steptspl*workout[k][0],steptspl*workout[k][1],steptspl*workout_b[k][0],steptspl*workout_b[k][1]);
      }
      //----------
      
      //copies fft results to permanent array
      for(l=0;l<NTG;l++){ 
	//result of discrete FT must be multiplied by the time step (see num. recipes)
	ll = j + i*np[0] + l*np[1]*np[0];
	//printf("%d %d %d -> %d \n",j,i,k,ll);
	//fprintf(fil," %E %E %E\n",Ei + l*stepE,steptspl*workout[l][0],steptspl*workout[l][1]);
	//WPERe[ll] = (1.0/sqrt(2*M_PI))*steptspl*workout[l][0];
	//WPEIm[ll] = (1.0/sqrt(2*M_PI))*steptspl*workout[l][1];
	WPERe[ll] = steptspl*workout[l][0] + steptspl*workout_b[l][0];
	WPEIm[ll] = steptspl*workout[l][1] + steptspl*workout_b[l][1];
      }
      //fprintf(fil,"\n");
    }
  }
  //----------


  fftw_destroy_plan(p);
  fftw_destroy_plan(p_b);
  fftw_free(workin); 
  fftw_free(workout);
  fftw_free(workin_b); 
  fftw_free(workout_b);
  return 0;
}
Ejemplo n.º 14
0
int
main(int argc,char** argv){
  BMP fin (argv[1]);
  BMP fout;fout.init(fin.w,fin.h);
  
  double  (*in  )[8];
  double  (*out )[8];
  double  (*out2)[8];
  fftw_plan p ;
  int i,j,idx;
 
  in  = (double (*)[8])fftw_malloc( sizeof(double) * 8*8);
  out = (double (*)[8])fftw_malloc( sizeof(double) * 8*8);
  out2= (double (*)[8])fftw_malloc( sizeof(double) * 8*8);

 
  for(int c=0;c<3;c++){
    for(int by=0;by<fin.h/8;by++)
      for(int bx=0;bx<fin.w/8;bx++){
	for(int dy=0;dy<8;dy++)
	  for(int dx=0;dx<8;dx++){
	    int x=bx*8+dx;
	    int y=by*8+dy;
	    in[   dy][   dx]=fin(x,y)[c];
	  }


	p = fftw_plan_r2r_2d( 8,8,
			      (double*)in, (double*)out,
			      FFTW_REDFT10,FFTW_REDFT10,
			      FFTW_ESTIMATE );
      
	fftw_execute(p);


	for(int dy=0;dy<8;dy++)
	  for(int dx=0;dx<8;dx++){
	    out[   dy][   dx]/=8*8*4;
	  }
      
	for(int dy=0;dy<8;dy++)
	  for(int dx=0;dx<8;dx++){
	    //	    out[   dy][   dx]=round(out[   dy][   dx]/(qt[dy][dx]*quality));
	    out[   dy][   dx]=round(out[   dy][   dx]/2);
	  }

	for(int dy=0;dy<8;dy++)
	  for(int dx=0;dx<8;dx++){
	    //	    out[   dy][   dx]*=qt[dy][dx]*quality;
	    out[   dy][   dx]*=2;
	  }

      
	// for(int dy=0;dy<8;dy++)
	//   for(int dx=0;dx<8;dx++){
	//     printf("%04d\n",(int)out[   dy][   dx]);
	//   }
      
	p = fftw_plan_r2r_2d( 8,8,
			      (double*)out, (double*)out2,
			      FFTW_REDFT01,FFTW_REDFT01,
			      FFTW_ESTIMATE );
	fftw_execute(p);

      


	for(int dy=0;dy<8;dy++)
	  for(int dx=0;dx<8;dx++){
	    int x=bx*8+dx;
	    int y=by*8+dy;
	    fout(x,y)[c]=lmt(out2[   dy][   dx]);
	  }



      }
  }

  fout.write(argv[2]);
 
  fftw_destroy_plan(p);
  fftw_free(in);
  fftw_free(out);
  fftw_free(out2);
 
  return true;
}
Ejemplo n.º 15
0
void fourier(const int N, dcomplex* fw, dcomplex* ft){
    fftw_plan p;
    p = fftw_plan_dft_1d(N, reinterpret_cast<fftw_complex*>(fw), reinterpret_cast<fftw_complex*>(ft), FFTW_FORWARD, FFTW_ESTIMATE);
    fftw_execute(p);
    fftw_destroy_plan(p);
}
Ejemplo n.º 16
0
void test02 ( void )

/******************************************************************************/
/*
  Purpose:

    TEST02: apply FFT to real 1D data.

  Modified:

    23 October 2005

  Author:

    John Burkardt
*/
{
  int i;
  double *in;
  double *in2;
  int n = 100;
  int nc;
  fftw_complex *out;
  fftw_plan plan_backward;
  fftw_plan plan_forward;
  unsigned int seed = 123456789;

  printf ( "\n" );
  printf ( "TEST02\n" );
  printf ( "  Demonstrate FFTW3 on a single vector of real data.\n" );
  printf ( "\n" );
  printf ( "  Transform data to FFT coefficients.\n" );
  printf ( "  Backtransform FFT coefficients to recover data.\n" );
  printf ( "  Compare recovered data to original data.\n" );
/*
  Set up an array to hold the data, and assign the data.
*/
  in = fftw_malloc ( sizeof ( double ) * n );

  srand ( seed );

  for ( i = 0; i < n; i++ )
  {
    in[i] = frand ( );
  }

  printf ( "\n" );
  printf ( "  Input Data:\n" );
  printf ( "\n" );

  for ( i = 0; i < n; i++ )
  {
    printf ( "  %4d  %12f\n", i, in[i] );
  }
/*
  Set up an array to hold the transformed data,
  get a "plan", and execute the plan to transform the IN data to
  the OUT FFT coefficients.
*/
  nc = ( n / 2 ) + 1;

  out = fftw_malloc ( sizeof ( fftw_complex ) * nc );

  plan_forward = fftw_plan_dft_r2c_1d ( n, in, out, FFTW_ESTIMATE );

  fftw_execute ( plan_forward );

  printf ( "\n" );
  printf ( "  Output FFT Coefficients:\n" );
  printf ( "\n" );

  for ( i = 0; i < nc; i++ )
  {
    printf ( "  %4d  %12f  %12f\n", i, out[i][0], out[i][1] );
  }
/*
  Set up an arrray to hold the backtransformed data IN2,
  get a "plan", and execute the plan to backtransform the OUT
  FFT coefficients to IN2.
*/
  in2 = fftw_malloc ( sizeof ( double ) * n );

  plan_backward = fftw_plan_dft_c2r_1d ( n, out, in2, FFTW_ESTIMATE );

  fftw_execute ( plan_backward );

  printf ( "\n" );
  printf ( "  Recovered input data divided by N:\n" );
  printf ( "\n" );

  for ( i = 0; i < n; i++ )
  {
    printf ( "  %4d  %12f\n", i, in2[i] / ( double ) ( n ) );
  }
/*
  Release the memory associated with the plans.
*/
  fftw_destroy_plan ( plan_forward );
  fftw_destroy_plan ( plan_backward );

  fftw_free ( in );
  fftw_free ( in2 );
  fftw_free ( out );

  return;
}
Ejemplo n.º 17
0
int fftw3_test(GPU_INFO *gpu_info,CUFFT_INFO *cufft_info){

	
	int i,j,k;
	double *array;
	int Nx=cufft_info->Nx;
	int Ny=cufft_info->Ny;
	int Nz=cufft_info->Nz;
	array=(double *)malloc(sizeof(double)*cufft_info->NxNyNz);
	
	double *in;
	fftw_complex *in_one;
	fftw_complex *out,*out_one;

	in=(double *)malloc(sizeof(double)*cufft_info->NxNyNz);
	out=(fftw_complex *)malloc(sizeof(fftw_complex)*cufft_info->NxNyNz);

	in_one=(fftw_complex *)malloc(sizeof(fftw_complex)*cufft_info->NxNyNz);
	out_one=(fftw_complex *)malloc(sizeof(fftw_complex)*cufft_info->NxNyNz);

	fftw_plan plan_forward;
	int temp;

	int rank=3;int n[3];
	n[0]=cufft_info->Nx;n[1]=cufft_info->Ny;n[2]=cufft_info->Nz;
	unsigned flags;
	
	for(long ijk=0;ijk<cufft_info->NxNyNz;ijk++) {
		
				
		array[ijk]=ijk;
		
		in[ijk]=ijk;
		
	}
	int Nxh1=Nx/2+1;
	cufft_info->Nxh1NyNz=Nxh1*Ny*Nz;
	long ijk,ijkr;
	/*fftw_plan fftw_plan_dft_2d(int n0, int n1,
                                fftw_complex *in, fftw_complex *out,
                                int sign, unsigned flags);*/
	
	
	for(i=0;i<cufft_info->Nz;i++){
		plan_forward=fftw_plan_dft_r2c_3d(1, Ny, Nx, in+Nx*Ny*i, out+Nx*Ny*i, FFTW_ESTIMATE);
		
		fftw_execute ( plan_forward );
	}
	
	
	for(i=0;i<Nxh1;i++){
		for(j=0;j<cufft_info->Ny;j++){
			
			for(k=0;k<Nz;k++) {in_one[k][0]=out[i+j*Nxh1+k*Nx*Ny][0];in_one[k][1]=out[i+j*Nxh1+k*Nx*Ny][1];}
			//if(i==0&&j==0) for(k=0;k<Nz;k++)  printf("%g %g\n",in_one[k][0],in_one[k][1]);
			plan_forward=fftw_plan_dft_1d(Nz, in_one, out_one,FFTW_FORWARD, FFTW_ESTIMATE);
			fftw_execute ( plan_forward );
			for(k=0;k<Nz;k++) {out[i+j*Nxh1+k*Nx*Ny][0]=out_one[k][0];out[i+j*Nxh1+k*Nx*Ny][1]=out_one[k][1];}
		}
	}
	
	FILE *dp;
	dp=fopen("fftw3_compare.dat","w");

	for(k=0;k<Nz;k++)
	for(j=0;j<Ny;j++)
	for(i=0;i<Nx;i++){
		ijkr=(long)((k*Ny+j)*Nx+i);
		ijk=(long)(i+Nx*j+Nxh1*Ny*k);
		if(abs(out[ijkr][0])>0.0000001||abs(out[ijkr][1])>0.0000001)
		fprintf(dp,"%d %g %g\n",ijk,out[ijkr][0],out[ijkr][1]);
	}
	fclose(dp);
	
	for(i=0;i<Nxh1;i++){
		for(j=0;j<cufft_info->Ny;j++){
			for(k=0;k<Nz;k++) {in_one[k][0]=out[i+j*Nxh1+k*Nx*Ny][0];in_one[k][1]=out[i+j*Nxh1+k*Nx*Ny][1];}
			// for(k=0;k<Nz;k++)  printf("%g %g\n",in_one[k][0],in_one[k][1]);
			plan_forward=fftw_plan_dft_1d(Nz, in_one, out_one,FFTW_BACKWARD, FFTW_ESTIMATE);
			fftw_execute ( plan_forward );
			//for(k=0;k<Nz;k++)  printf("%g %g\n",out_one[k][0],out_one[k][1]);
			for(k=0;k<Nz;k++) {out[i+j*Nxh1+k*Nx*Ny][0]=out_one[k][0];out[i+j*Nxh1+k*Nx*Ny][1]=out_one[k][1];}
			//for(k=0;k<Nz;k++)  printf("%g %g\n",out_one[k][0],out_one[k][1]);
		}
	}
	for(i=0;i<16;i++) {out[i][0]=i;out[i][1]=0;}
	plan_forward=fftw_plan_dft_c2r_3d(2, 8, 1,  out,in, FFTW_ESTIMATE);
	fftw_execute ( plan_forward );
	/*
	for(i=0;i<cufft_info->Nz;i++){
		//for(k=0;k<8;k++)  printf("%g %g\n",out[k+8*i][0],out[k+8*i][1]);
		plan_forward=fftw_plan_dft_c2r_3d(1, 8, 1,  out+Nx*Ny*i,in+Nx*Ny*i, FFTW_ESTIMATE);
		
		fftw_execute ( plan_forward );
	}
	*/
	//for(i=0;i<16;i++) {printf("%g\n",in[i]);}
	/*	
	for(k=0;k<Nz;k++)
	for(j=0;j<Ny;j++)
	for(i=0;i<Nxh1;i++){
		
		//ijk=(long)((k*Ny+j)*Nxh1+i);
		ijkr=(long)((k*Ny+j)*Nx+i);
		ijk=(long)(k*Nx*Ny+j*Nxh1+i);
		if(abs(out[ijk][0])>=0.00000000001||abs(out[ijk][1])>=0.00000000001){
			
			fprintf(dp,"%d %g %g %g\n",ijkr,out[ijk][0],out[ijk][1],in[ijkr]/512);
		}
		
	}
	*/
	
	printf("finish writiing\n");
	
	free(array);
	free(in);
	free(out);
	return 1;
}
Ejemplo n.º 18
0
void test03 ( void )

/******************************************************************************/
/*
  Purpose:

    TEST03: apply FFT to complex 2D data.

  Discussion:

    In this example, we generate NX=8 by NY=10 random complex values 
    stored as an NX by NY array of type FFTW_COMPLEX named "IN".

    We have FFTW3 compute the Fourier transform of this data named "OUT".

    We have FFTW3 compute the inverse Fourier transform of "OUT" to get
    "IN2", which should be the original input data, scaled by NX * NY.

    For a 2D complex NX by NY array used by FFTW, we need to access elements
    as follows:

      a[i*ny+j][0] is the real      part of A(I,J).
      a[i*ny+j][1] is the imaginary part of A(I,J)..

  Modified:

    05 November 2007

  Author:

    John Burkardt
*/
{
  int i;
  fftw_complex *in;
  fftw_complex *in2;
  int j;
  int nx = 8;
  int ny = 10;
  fftw_complex *out;
  fftw_plan plan_backward;
  fftw_plan plan_forward;
  unsigned int seed = 123456789;

  printf ( "\n" );
  printf ( "TEST03\n" );
  printf ( "  Demonstrate FFTW3 on a %d by %d array of complex data.\n",
    nx, ny );
  printf ( "\n" );
  printf ( "  Transform data to FFT coefficients.\n" );
  printf ( "  Backtransform FFT coefficients to recover data.\n" );
  printf ( "  Compare recovered data to original data.\n" );
/*
  Create the input array.
*/
  in = fftw_malloc ( sizeof ( fftw_complex ) * nx * ny );

  srand ( seed );

  for ( i = 0; i < nx; i++ )
  {
    for ( j = 0; j < ny; j++ )
    {
      in[i*ny+j][0] = frand ( );
      in[i*ny+j][1] = frand ( );
    }
  }

  printf ( "\n" );
  printf ( "  Input Data:\n" );
  printf ( "\n" );

  for ( i = 0; i < nx; i++ )
  {
    for ( j = 0; j < ny; j++ )
    {
      printf ( "  %4d  %4d  %12f  %12f\n", i, j, in[i*ny+j][0], in[i*ny+j][1] );
    }
  }
/*
  Create the output array.
*/
  out = fftw_malloc ( sizeof ( fftw_complex ) * nx * ny );

  plan_forward = fftw_plan_dft_2d ( nx, ny, in, out, FFTW_FORWARD, 
    FFTW_ESTIMATE );

  fftw_execute ( plan_forward );

  printf ( "\n" );
  printf ( "  Output FFT Coefficients:\n" );
  printf ( "\n" );

  for ( i = 0; i < nx; i++ )
  {
    for ( j = 0; j < ny; j++ )
    {
      printf ( "  %4d  %4d  %12f  %12f\n", i, j, out[i*ny+j][0], out[i*ny+j][1] );
    }
  }
/*
  Recreate the input array.
*/
  in2 = fftw_malloc ( sizeof ( fftw_complex ) * nx * ny );

  plan_backward = fftw_plan_dft_2d ( nx, ny, out, in2, FFTW_BACKWARD, 
    FFTW_ESTIMATE );

  fftw_execute ( plan_backward );

  printf ( "\n" );
  printf ( "  Recovered input data divided by NX * NY:\n" );
  printf ( "\n" );

  for ( i = 0; i < nx; i++ )
  {
    for ( j = 0; j < ny; j++ )
    {
      printf ( "  %4d  %4d  %12f  %12f\n",  i, j,
      in2[i*ny+j][0] / ( double ) ( nx * ny ),
      in2[i*ny+j][1] / ( double ) ( nx * ny ) );
    }
  }
/*
  Free up the allocated memory.
*/
  fftw_destroy_plan ( plan_forward );
  fftw_destroy_plan ( plan_backward );

  fftw_free ( in );
  fftw_free ( in2 );
  fftw_free ( out );

  return;
}
Ejemplo n.º 19
0
int main(void)
{
  int j, jj;
  int sleep_sec=2;
  char buf[128];
  int ind, Mcount;
  int M=50;
  int plan;

  pg_id = cpgopen("/XSERVE");
  cpgpap(7.75, 0.8);

  timedata = fftw_malloc(sizeof(double) * N);
  freqdata = fftw_malloc(sizeof(fftw_complex) * N);
  read_count=N*M;
 
  if ((fp=fopen("SatPosData","w"))==NULL)
    {
      printf("Cannot open file. \n");
      exit(1);
    }

  for (j=1; j<=max_scans; j++)
    {
      printf("\n\nAcquisition %d\n",j);
      fprintf(fp,"\nAcquisition: %d\n",j);
      strcpy(buf, send_command0("Apollo","GET_TIME$"));
      printf("Universal Time: %s",buf);
      fprintf(fp, "UT: %s",buf);
      acquire_data();
      printf("Satellites above local horizon:\n");
      getSatInfo0();
      getSatInfo1();
      transfer_and_scale((U16*)ai_buf, channel+1);
      for (k=0; k<(N/2)+1; k++) accumFreqData[k]=0;      
	      printf("Integrating ... %i %i-blocks",M,N);
      for (Mcount=1; Mcount<=M; Mcount++)
	{
	  for (ind=0; ind<N; ind++)
	    {
	      timedata[ind]=voltarray[ind+(N*(Mcount-1))];
	    }
	  //	      printf("%i ",Mcount);
	      plan=(j==1)&(Mcount==1);
	      if (plan)
	    {
	      p=fftw_plan_dft_r2c_1d(N, timedata, freqdata, FFTW_FORWARD);
	    }

	  fftw_execute(p);


	  for (k=0; k<(N/2)+1; k++)
	    {
	      accumFreqData[k]+=(sqrt(freqdata[k][0]*freqdata[k][0]+freqdata[k][1]*freqdata[k][1])/(M*256));	  
	    } 

	}
      fprintf(fp, "Bin Voltages \n");
      for (jj=0; jj<=240; jj+=10)
	{
	  for (k=jj; k<(jj+10); k++) fprintf(fp, "%f ", accumFreqData[k]);
	  fprintf(fp, "\n");
	}

      //      plot_channel_data();
      plot_freq_data();
      free( ai_buf );
      printf("\nPause %d seconds ...",sleep_sec);
     sleep(sleep_sec);
     }
  int fclose(FILE *fp);
      postfft();
  printf("\n\nEnd of program. "); 
  //getch(); 
  putchar('\n');
  return 0;
}
Ejemplo n.º 20
0
void test04 ( void )

/******************************************************************************/
/*
  Purpose:

    TEST04: apply FFT to real 2D data.

  Discussion:

    In this example, we generate NX=8 by NY=10 random real values 
    stored as an NX by NY array of type DOUBLE named "IN".

    We have FFTW3 compute the Fourier transform of this data named "OUT".

    We have FFTW3 compute the inverse Fourier transform of "OUT" to get
    "IN2", which should be the original input data, scaled by NX * NY.

    The Fourier coefficients are stored in an NX by NYH array where
    NYH = (NY/2) + 1.  We only compute about half the data because
    of real data implies symmetric FFT coefficients.

      a[i*nyh+j][0] is the real      part of A(I,J).
      a[i*nyh+j][1] is the imaginary part of A(I,J)..

  Modified:

    05 November 2007

  Author:

    John Burkardt
*/
{
  int i;
  double *in;
  double *in2;
  int j;
  int nx = 8;
  int ny = 10;
  int nyh;
  fftw_complex *out;
  fftw_plan plan_backward;
  fftw_plan plan_forward;
  unsigned int seed = 123456789;

  printf ( "\n" );
  printf ( "TEST04\n" );
  printf ( "  Demonstrate FFTW3 on a %d by %d array of real data.\n",
    nx, ny );
  printf ( "\n" );
  printf ( "  Transform data to FFT coefficients.\n" );
  printf ( "  Backtransform FFT coefficients to recover data.\n" );
  printf ( "  Compare recovered data to original data.\n" );
/*
  Create the input array, an NX by NY array of doubles.
*/
  in = malloc ( sizeof ( double ) * nx * ny );

  srand ( seed );

  for ( i = 0; i < nx; i++ )
  {
    for ( j = 0; j < ny; j++ )
    {
      in[i*ny+j] = frand ( );
    }
  }

  printf ( "\n" );
  printf ( "  Input Data:\n" );
  printf ( "\n" );

  for ( i = 0; i < nx; i++ )
  {
    for ( j = 0; j < ny; j++ )
    {
      printf ( "  %4d  %4d  %12f\n", i, j, in[i*ny+j] );
    }
  }
/*
  Create the output array OUT, which is of type FFTW_COMPLEX,
  and of a size NX * NYH that is roughly half the dimension of the input data
  (ignoring the fact that the input data is real, and the FFT
  coefficients are complex).
*/
  nyh = ( ny / 2 ) + 1;

  out = fftw_malloc ( sizeof ( fftw_complex ) * nx * nyh );

  plan_forward = fftw_plan_dft_r2c_2d ( nx, ny, in, out, FFTW_ESTIMATE );

  fftw_execute ( plan_forward );

  printf ( "\n" );
  printf ( "  Output FFT Coefficients:\n" );
  printf ( "\n" );

  for ( i = 0; i < nx; i++ )
  {
    for ( j = 0; j < nyh; j++ )
    {
      printf ( "  %4d  %4d  %12f  %12f\n", 
      i, j, out[i*nyh+j][0], out[i*nyh+j][1] );
    }
  }
/*
  Recreate the input array.
*/
  in2 = malloc ( sizeof ( double ) * nx * ny );

  plan_backward = fftw_plan_dft_c2r_2d ( nx, ny, out, in2, FFTW_ESTIMATE );

  fftw_execute ( plan_backward );

  printf ( "\n" );
  printf ( "  Recovered input data divided by NX * NY:\n" );
  printf ( "\n" );

  for ( i = 0; i < nx; i++ )
  {
    for ( j = 0; j < ny; j++ )
    {
      printf ( "  %4d  %4d  %12f\n",  
        i, j, in2[i*ny+j] / ( double ) ( nx * ny ) );
    }
  }
/*
  Free up the allocated memory.
*/
  fftw_destroy_plan ( plan_forward );
  fftw_destroy_plan ( plan_backward );

  free ( in );
  free ( in2 );
  fftw_free ( out );

  return;
}
Ejemplo n.º 21
0
static MagickBooleanType ForwardFourierTransform(FourierInfo *fourier_info,
  const Image *image,double *magnitude,double *phase,ExceptionInfo *exception)
{
  CacheView
    *image_view;

  double
    n,
    *source;

  fftw_complex
    *fourier;

  fftw_plan
    fftw_r2c_plan;

  long
    y;

  register const IndexPacket
    *indexes;

  register const PixelPacket
    *p;

  register long
    i,
    x;

  /*
    Generate the forward Fourier transform.
  */
  source=(double *) AcquireQuantumMemory((size_t) fourier_info->height,
    fourier_info->width*sizeof(*source));
  if (source == (double *) NULL)
    {
      (void) ThrowMagickException(exception,GetMagickModule(),
        ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
      return(MagickFalse);
    }
  ResetMagickMemory(source,0,fourier_info->width*fourier_info->height*
    sizeof(*source));
  i=0L;
  image_view=AcquireCacheView(image);
  for (y=0L; y < (long) fourier_info->height; y++)
  {
    p=GetCacheViewVirtualPixels(image_view,0L,y,fourier_info->width,1UL,
      exception);
    if (p == (const PixelPacket *) NULL)
      break;
    indexes=GetCacheViewVirtualIndexQueue(image_view);
    for (x=0L; x < (long) fourier_info->width; x++)
    {
      switch (fourier_info->channel)
      {
        case RedChannel:
        default:
        {
          source[i]=QuantumScale*GetRedPixelComponent(p);
          break;
        }
        case GreenChannel:
        {
          source[i]=QuantumScale*GetGreenPixelComponent(p);
          break;
        }
        case BlueChannel:
        {
          source[i]=QuantumScale*GetBluePixelComponent(p);
          break;
        }
        case OpacityChannel:
        {
          source[i]=QuantumScale*GetOpacityPixelComponent(p);
          break;
        }
        case IndexChannel:
        {
          source[i]=QuantumScale*indexes[x];
          break;
        }
        case GrayChannels:
        {
          source[i]=QuantumScale*GetRedPixelComponent(p);
          break;
        }
      }
      i++;
      p++;
    }
  }
  image_view=DestroyCacheView(image_view);
  fourier=(fftw_complex *) AcquireAlignedMemory((size_t) fourier_info->height,
    fourier_info->center*sizeof(*fourier));
  if (fourier == (fftw_complex *) NULL)
    {
      (void) ThrowMagickException(exception,GetMagickModule(),
        ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
      source=(double *) RelinquishMagickMemory(source);
      return(MagickFalse);
    }
#if defined(MAGICKCORE_OPENMP_SUPPORT)
  #pragma omp critical (MagickCore_ForwardFourierTransform)
#endif
  fftw_r2c_plan=fftw_plan_dft_r2c_2d(fourier_info->width,fourier_info->width,
    source,fourier,FFTW_ESTIMATE);
  fftw_execute(fftw_r2c_plan);
  fftw_destroy_plan(fftw_r2c_plan);
  source=(double *) RelinquishMagickMemory(source);
  /*
    Normalize Fourier transform.
  */
  n=(double) fourier_info->width*(double) fourier_info->width;
  i=0L;
  for (y=0L; y < (long) fourier_info->height; y++)
    for (x=0L; x < (long) fourier_info->center; x++)
      fourier[i++]/=n;
  /*
    Generate magnitude and phase (or real and imaginary).
  */
  i=0L;
  if (fourier_info->modulus != MagickFalse)
    for (y=0L; y < (long) fourier_info->height; y++)
      for (x=0L; x < (long) fourier_info->center; x++)
      {
        magnitude[i]=cabs(fourier[i]);
        phase[i]=carg(fourier[i]);
        i++;
      }
  else
    for (y=0L; y < (long) fourier_info->height; y++)
      for (x=0L; x < (long) fourier_info->center; x++)
      {
        magnitude[i]=creal(fourier[i]);
        phase[i]=cimag(fourier[i]);
        i++;
      }
  fourier=(fftw_complex *) RelinquishAlignedMemory(fourier);
  return(MagickTrue);
}
Ejemplo n.º 22
0
void test01 ( void )

/******************************************************************************/
/*
  Purpose:

    TEST01: apply FFT to complex 1D data.

  Discussion:

    In this example, we generate N=100 random complex values stored as
    a vector of type FFTW_COMPLEX named "IN".

    We have FFTW3 compute the Fourier transform of this data named "OUT".

    We have FFTW3 compute the inverse Fourier transform of "OUT" to get
    "IN2", which should be the original input data, scaled by N.

  Modified:

    04 November 2007

  Author:

    John Burkardt
*/
{
  int i;
  fftw_complex *in;
  fftw_complex *in2;
  int n = 100;
  fftw_complex *out;
  fftw_plan plan_backward;
  fftw_plan plan_forward;
  unsigned int seed = 123456789;

  printf ( "\n" );
  printf ( "TEST01\n" );
  printf ( "  Demonstrate FFTW3 on a single vector of complex data.\n" );
  printf ( "\n" );
  printf ( "  Transform data to FFT coefficients.\n" );
  printf ( "  Backtransform FFT coefficients to recover data.\n" );
  printf ( "  Compare recovered data to original data.\n" );
/*
  Create the input array.
*/
  in = fftw_malloc ( sizeof ( fftw_complex ) * n );

  srand ( seed );

  for ( i = 0; i < n; i++ )
  {
    in[i][0] = frand ( );
    in[i][1] = frand ( );
  }

  printf ( "\n" );
  printf ( "  Input Data:\n" );
  printf ( "\n" );

  for ( i = 0; i < n; i++ )
  {
    printf ( "  %3d  %12f  %12f\n", i, in[i][0], in[i][1] );
  }
/*
  Create the output array.
*/
  out = fftw_malloc ( sizeof ( fftw_complex ) * n );

  plan_forward = fftw_plan_dft_1d ( n, in, out, FFTW_FORWARD, FFTW_ESTIMATE );

  fftw_execute ( plan_forward );

  printf ( "\n" );
  printf ( "  Output FFT Coefficients:\n" );
  printf ( "\n" );

  for ( i = 0; i < n; i++ )
  {
    printf ( "  %3d  %12f  %12f\n", i, out[i][0], out[i][1] );
  }
/*
  Recreate the input array.
*/
  in2 = fftw_malloc ( sizeof ( fftw_complex ) * n );

  plan_backward = fftw_plan_dft_1d ( n, out, in2, FFTW_BACKWARD, FFTW_ESTIMATE );

  fftw_execute ( plan_backward );

  printf ( "\n" );
  printf ( "  Recovered input data:\n" );
  printf ( "\n" );

  for ( i = 0; i < n; i++ )
  {
    printf ( "  %3d  %12f  %12f\n", i, in2[i][0], in2[i][1] );
  }

  printf ( "\n" );
  printf ( "  Recovered input data divided by N:\n" );
  printf ( "\n" );

  for ( i = 0; i < n; i++ )
  {
    printf ( "  %3d  %12f  %12f\n", i, 
      in2[i][0] / ( double ) ( n ), in2[i][1] / ( double ) ( n ) );
  }
/*
  Free up the allocated memory.
*/
  fftw_destroy_plan ( plan_forward );
  fftw_destroy_plan ( plan_backward );

  fftw_free ( in );
  fftw_free ( in2 );
  fftw_free ( out );

  return;
}
Ejemplo n.º 23
0
struct Peak Find_FFT(IplImage* src, IplImage* tpl, int hamming)
{
	int i, j, k = 0;
	double tmp; //To store the modulus temporarily

	//src and tpl must be the same size
	assert(src->width == tpl->width);
	assert(src->height == tpl->height);

	// Get image properties
	int width    = src->width;
	int height   = src->height;
	int step     = src->widthStep;
	int fft_size = width * height;
	
	fftw_init_threads(); //Initialize FFTW for multithreading with a max number of 2 threads (more is not efficient)
	fftw_plan_with_nthreads(2);
	
	//Allocate arrays for FFT of src and tpl
	fftw_complex *src_spatial = ( fftw_complex* )fftw_malloc( sizeof( fftw_complex ) * width * height );
	fftw_complex *src_freq = ( fftw_complex* )fftw_malloc( sizeof( fftw_complex ) * width * height );
	
	fftw_complex *tpl_spatial = ( fftw_complex* )fftw_malloc( sizeof( fftw_complex ) * width * height );
	fftw_complex *tpl_freq = ( fftw_complex* )fftw_malloc( sizeof( fftw_complex ) * width * height );

	fftw_complex *res_spatial = ( fftw_complex* )fftw_malloc( sizeof( fftw_complex ) * width * height ); //Result = Cross correlation
	fftw_complex *res_freq = ( fftw_complex* )fftw_malloc( sizeof( fftw_complex ) * width * height );

	// Setup pointers to images
	uchar *src_data = (uchar*) src->imageData;
	uchar *tpl_data = (uchar*) tpl->imageData;

	// Fill the structure that will be used by fftw
	for(i = 0; i < height; i++)
	{
		for(j = 0 ; j < width ; j++, k++)
		{
			src_spatial[k][0] = (double) src_data[i * step + j];
			src_spatial[k][1] =  0.0;

			tpl_spatial[k][0] = (double) tpl_data[i * step + j];
			tpl_spatial[k][1] =  0.0;
		}
	}
	
	// Hamming window to improve FFT (but slightly slower to compute)
	if(hamming == 1)
	{
		double omega = 2.0*M_PI/(fft_size-1);
		double A= 0.54;
		double B= 0.46;
		for(i=0,k=0;i<height;i++)
		{
			for(j=0;j<width;j++,k++)
			{
			    src_spatial[k][0]= (src_spatial[k][0])*(A-B*cos(omega*k));
			    tpl_spatial[k][0]= (tpl_spatial[k][0])*(A-B*cos(omega*k));
			}
		}
	}

	// Setup FFTW plans
	fftw_plan plan_src = fftw_plan_dft_2d(height, width, src_spatial, src_freq, FFTW_FORWARD, FFTW_ESTIMATE);
	fftw_plan plan_tpl = fftw_plan_dft_2d(height, width, tpl_spatial, tpl_freq, FFTW_FORWARD, FFTW_ESTIMATE);
	fftw_plan plan_res = fftw_plan_dft_2d(height, width, res_freq,  res_spatial,  FFTW_BACKWARD, FFTW_ESTIMATE);

	// Execute the FFT of the images
	fftw_execute(plan_src);
	fftw_execute(plan_tpl);

	// Compute the cross-correlation
	for(i = 0; i < fft_size ; i++ )
	{
		res_freq[i][0] = tpl_freq[i][0] * src_freq[i][0] + tpl_freq[i][1] * src_freq[i][1];
		res_freq[i][1] = tpl_freq[i][0] * src_freq[i][1] - tpl_freq[i][1] * src_freq[i][0];
		
		tmp = sqrt(pow(res_freq[i][0], 2.0) + pow(res_freq[i][1], 2.0));

		res_freq[i][0] /= tmp;
		res_freq[i][1] /= tmp;
	}

	// Get the phase correlation array = compute inverse fft
	fftw_execute(plan_res);

	// Find the peak
	struct Peak pk;	
	IplImage* peak_find = cvCreateImage(cvSize(tpl->width,tpl->height ), IPL_DEPTH_64F, 1);
	double  *peak_find_data = (double*) peak_find->imageData;
	
	for( i = 0 ; i < fft_size ; i++ )
	{
        peak_find_data[i] = res_spatial[i][0] / (double) fft_size;
    }
    
    CvPoint minloc, maxloc;
    double  minval, maxval;
    
    cvMinMaxLoc(peak_find, &minval, &maxval, &minloc, &maxloc, 0);
    
	pk.pt = maxloc;
	pk.maxval = maxval;

	// Clear memory
	fftw_destroy_plan(plan_src);
	fftw_destroy_plan(plan_tpl);
	fftw_destroy_plan(plan_res);
	fftw_free(src_spatial);
	fftw_free(tpl_spatial);
	fftw_free(src_freq);
	fftw_free(tpl_freq);
	fftw_free(res_spatial);
	fftw_free(res_freq);
	cvReleaseImage(&peak_find);
	
	fftw_cleanup_threads(); //Cleanup everything else related to FFTW
	
	return pk;
}
Ejemplo n.º 24
0
void AudioCapture::processData()
{
#ifdef HAS_FFTW3
    unsigned int i;
    quint64 pwrSum = 0;

    // 1 ********* Initialize FFTW
    fftw_plan plan_forward;
    plan_forward = fftw_plan_dft_r2c_1d(m_captureSize, m_fftInputBuffer, (fftw_complex*)m_fftOutputBuffer , 0);

    // 2 ********* Apply a window to audio data
    // *********** and convert it to doubles

    for (i = 0; i < m_captureSize; i++)
    {
        if(m_audioBuffer[i] < 0)
            pwrSum += -1 * m_audioBuffer[i];
        else
            pwrSum += m_audioBuffer[i];

#ifdef USE_BLACKMAN
        double a0 = (1-0.16)/2;
        double a1 = 0.5;
        double a2 = 0.16/2;
        m_fftInputBuffer[i] = m_audioBuffer[i]  * (a0 - a1 * qCos((M_2PI * i) / (m_captureSize - 1)) +
                              a2 * qCos((2 * M_2PI * i) / (m_captureSize - 1)));
#endif
#ifdef USE_HANNING
        m_fftInputBuffer[i] = m_audioBuffer[i] * (0.5 * (1.00 - qCos((M_2PI * i) / (m_captureSize - 1))));
#endif
#ifdef USE_NO_WINDOW
        m_fftInputBuffer[i] = (double)m_audioBuffer[i];
#endif
    }

    // 3 ********* Perform FFT
    fftw_execute(plan_forward);
    fftw_destroy_plan(plan_forward);

    // 4 ********* Clear FFT noise
#ifdef CLEAR_FFT_NOISE
    //We delete some values since these will ruin our output
    for (int n = 0; n < 5; n++)
    {
        ((fftw_complex*)m_fftOutputBuffer)[n][0] = 0;
        ((fftw_complex*)m_fftOutputBuffer)[n][1] = 0;
    }
#endif

    // 5 ********* Calculate the average signal power
    m_signalPower = pwrSum / m_captureSize;

    // 6 ********* Calculate vector magnitude
    foreach(int barsNumber, m_fftMagnitudeMap.keys())
    {
        double maxMagnitude = fillBandsData(barsNumber);
        emit dataProcessed(m_fftMagnitudeMap[barsNumber].m_fftMagnitudeBuffer.data(),
                           m_fftMagnitudeMap[barsNumber].m_fftMagnitudeBuffer.size(),
                           maxMagnitude, m_signalPower);
    }
#endif
}
Ejemplo n.º 25
0
/**
   This code computes the integtated autocorrelation time :

   It expects a file of length N double precision measurements

   Defining c(t) = ( Y(t) - \bar{Y} )

   C(T) = \sum_{t=0}^{N} ( c(t) c(t+T) )

   R(T) = C(T) / C(0)

   Setting a cutoff point "n"

   Tau(n) = 0.5 + Nsep * \sum_{T}^{n} R(T)

   We estimate the error on Tau(T) by

   S_E(n) = n * \sqrt( ( 0.5 + \sum_{t}^{n} R(T) ) / N ) 

   The computation of C(T) is performed by convolution with FFTs

   The autocorrelation time is written to the file specified
 */
int
autocorrelation( const struct resampled RAW ,
		 const int NSEP ,
		 const char *output )
{
  // openmp'd fftws
  parallel_ffts( ) ;

  if( RAW.restype != RAWDATA ) {
    printf( "Resampled data is not RAW ... Cannot compute autocorrelation\n" ) ;
    return FAILURE ;
  }

  // some constants
  const int N = RAW.NSAMPLES ;
  const int N2 = 2 * N ;

  printf( "RAWDATA has %d samples\n" , N ) ;

  printf( "Measurement separation %d\n\n" , NSEP ) ;

  // allocate memory
  double complex *in  = calloc( N2 , sizeof( double complex ) ) ;
  double complex *out = calloc( N2 , sizeof( double complex ) ) ;

  // subtract the average from each data point
  int i ;
#pragma omp parallel for private(i)
  for( i = 0 ; i < N ; i++ ) {
    in[ i ] = ( RAW.resampled[ i ] - RAW.avg ) ;
  }

  message( "FFT planning" ) ;

  // are we doing this using openmp ffts?
#if ( defined OMP_FFTW ) && ( defined HAVE_OMP_H )
  if( parallel_ffts( ) == FAILURE ) {
    printf( "Parallel FFT setting failed \n" ) ;
    return FAILURE ;
  }
#endif
  
  // create the plans
  const fftw_plan forward = fftw_plan_dft_1d( N2 , in , out , 
					      FFTW_FORWARD , FFTW_ESTIMATE ) ; 

  const fftw_plan backward = fftw_plan_dft_1d( N2 , out , in , 
					       FFTW_BACKWARD , FFTW_ESTIMATE ) ;
  
  fftw_execute( forward ) ;

  // convolve
#pragma omp parallel for private(i)
  for( i = 0 ; i < N2 ; i++ ) {
    out[i] = creal( out[i] ) * creal( out[i] ) + 
             cimag( out[i] ) * cimag( out[i] ) ;
  }

  fftw_execute( backward ) ;

  // normalise
  const double zeropoint = 1.0 / in[ 0 ] ;
#pragma omp parallel for private(i)
  for( i = 0 ; i < N2 ; i++ ) {
    in[ i ] *= zeropoint ;
  }

  // summy the lags
  message( "Computing tau(n)" ) ;

  FILE *output_file = fopen( output , "w" ) ;

  printf( "Writing tau(n) to file %s \n" , output ) ;

  int n ;
  for( n = 0 ; n < 30 ; n++ ) {
    register double sum = 0.5 ;
    int j ;
    for( j = 0 ; j < n ; j++ ) {
      sum += NSEP * in[j] ;
    }
    // simple error estimate
    const double err = n * sqrt( ( sum ) / N ) ;
    fprintf( output_file , "%d %e %e \n" , n * NSEP , sum , err ) ;
  }

  fclose( output_file ) ;

  // memory free
  free( in ) ;
  free( out ) ;
  fftw_destroy_plan(forward ) ;
  fftw_destroy_plan( backward ) ;
#ifdef OMP_FFTW
  // parallel
  fftw_cleanup_threads( ) ;
#endif  
  fftw_cleanup( ) ;

  return SUCCESS ;
}
Ejemplo n.º 26
0
int main(int argc, char *argv[]) {
    /* Declare some variables */
    SNDFILE *music_file = NULL;
    SF_INFO sfinfo;
    sfinfo.format = 0;

    printf("Audio visualizer for Comp 467\n");
    printf("By: Jorenz Paragas, Carlos Henriquez, Joshua Licudo\n");
    printf("----\n");

    /* Check if the user provided a .wav file */
    if (argc < 2) {
        fprintf(stderr, "Error: a .wav file was not provided.\n");
        fprintf(stderr, "Usage: %s input.wav\n", argv[0]);
        return EXIT_FAILURE;
    }

    /* Open the .wav file */
    music_file = sf_open(argv[1], SFM_READ, &sfinfo);
    if (music_file == NULL) {
        fprintf(stderr, "Cannot open .wav file: %s\n", argv[1]);
        return EXIT_FAILURE;
    }

    printf("Name of file: %s\n", argv[1]);
    printf("Sample rate: %d\n", sfinfo.samplerate);
    printf("Channels: %d\n", sfinfo.channels);

    /* The buffer size for libsndfile must be as large as the product of
     * the number of channels and the number of samples to be read */ 
    const int buffer_size = SAMPLE_COUNT * sfinfo.channels;

    /* For a real-to-complex transform, according to the FFTW docs,
     * the expected size of the array is n / 2 + 1 */
    const int out_buffer_size = buffer_size / 2 + 1;

    /* Declare the two buffers to hold the data and tell
     * FFTW how to calculate the frequencies */
    double samples[buffer_size];
    memset(&samples, 0, buffer_size);

    fftw_complex output[out_buffer_size];
    fftw_plan plan = fftw_plan_dft_r2c_1d(buffer_size, samples, 
        output, FFTW_ESTIMATE);

    if (plan == NULL) {
        fprintf(stderr, "Plan cannot be created.\n");
        sf_close(music_file);
        return EXIT_FAILURE;
    }

    /* Start SDL */
    if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
        fprintf(stderr, "SDL_Init error: %s\n", SDL_GetError());
        return EXIT_FAILURE;
    }
    atexit(SDL_Quit);

    /* Create the window */
    SDL_Window *window = SDL_CreateWindow("Comp 467 Project", 10, 10, 
        WINDOW_WIDTH, WINDOW_HEIGHT, 0);
    if (window == NULL) {
        fprintf(stderr, "SDL_CreateWindow error: %s\n", SDL_GetError());
        return EXIT_FAILURE;
    }
    
    /* Get the window's surface */
    SDL_Surface *surface = SDL_GetWindowSurface(window);
    
    /* Initialize the random number generator */
    srand(time(NULL));

    /* Open the music file */
    Mix_OpenAudio(sfinfo.samplerate, MIX_DEFAULT_FORMAT, 
        sfinfo.channels, 4096);
    Mix_Music *music = Mix_LoadMUS(argv[1]);
    if (music == NULL) {
        fprintf(stderr, "Mix_LoadMUS error: %s\n", Mix_GetError());
    }
    
    /* Start playing it */
    Mix_PlayMusic(music, 0);

    /* Timer-related variables */
    unsigned int start_time = SDL_GetTicks();
    unsigned int last_time = start_time;
    unsigned int current_time = start_time;

    /* The main loop */
    bool running = true;
    while (running) {
        /* Obtain any user input */
        SDL_Event event;
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) {
                running = false;
            }
        }

        /* Based on the sample rate and the current time,
         * figure out what position to read the audio file from */
        double seconds = (current_time - start_time) / 1000.0; 
        //printf("Current time: %.2f\n", seconds);

        sf_count_t sample_pos = (int) sfinfo.samplerate * seconds; 
        int result = sf_seek(music_file, sample_pos, SEEK_SET);
        if (result == -1) {
            running = false;
        }

        /* Read the samples */
        int samples_read = sf_readf_double(music_file, samples, 
            SAMPLE_COUNT); 
        if (samples_read <= 0) {
            running = false;        
        }
    
        /* Calculate the FFT */
        fftw_execute(plan);

        /* Fill the screen with black first */
        SDL_Rect surf_rect;
        
        surf_rect.w = WINDOW_WIDTH;
        surf_rect.h = WINDOW_HEIGHT;

        surf_rect.x = 0;
        surf_rect.y = 0;

        SDL_FillRect(surface, &surf_rect, SDL_MapRGB(surface->format,
                     0, 0, 0));

        /* Draw all the rectangles */
        int x_pos;
        for (x_pos = 0; x_pos < WINDOW_WIDTH; x_pos += 1) {
            SDL_Rect rect;

            /* Based on the rectangle's position, get a different
             * frequency; the second half of the buffer is useless
             * data, so ignore that portion */
            double relative_pos = x_pos * 1.0f / WINDOW_WIDTH; 
            int buf_range_max = out_buffer_size / 2;
            int index = (int) (relative_pos * buf_range_max);

            /* Figure out the normalized magnitude of the frequency */
            double mag = sqrt(output[index][0] * output[index][0] +
                              output[index][1] * output[index][1]);
            double norm_mag = mag * (1 / sqrt(buffer_size)); 
            //printf("%d: %f\n", index, norm_mag);

            /* Set the rectangle's size */
            rect.w = 1;
            rect.h = norm_mag * WINDOW_HEIGHT;

            /* Set the rectangle's lower left corner */
            rect.x = x_pos;
            rect.y = WINDOW_HEIGHT - rect.h;

            /* Draw the rectangle to the screen */
            SDL_FillRect(surface, &rect, SDL_MapRGB(surface->format,
                         0, 0, 255));
        }

        /* Update the display */
        SDL_UpdateWindowSurface(window);

        /* Ensure that it runs around 30 FPS and also update the
         * timer variables */ 
        current_time = SDL_GetTicks();
        int delta = current_time - last_time;
        if (delta <= 33) {
            SDL_Delay(33 - delta);
        }
        last_time = current_time;
    }

    /* Stop the music and free its memory */
    Mix_HaltMusic();
    Mix_FreeMusic(music);

    /* Clean up and exit */
    SDL_FreeSurface(surface);
    SDL_DestroyWindow(window);

    fftw_destroy_plan(plan);
    sf_close(music_file);

    return EXIT_SUCCESS;
}
Ejemplo n.º 27
0
Archivo: fftw.hpp Proyecto: mroja/empi
	/**
	 * Execute plan.
     */
	inline void execute() const {
		fftw_execute(plan);
	}
Ejemplo n.º 28
0
///
/// Make SFTs from given REAL8TimeSeries at given timestamps, potentially applying a time-domain window on each timestretch first
///
SFTVector *
XLALMakeSFTsFromREAL8TimeSeries ( const REAL8TimeSeries *timeseries,	//!< input time-series
                                  const LIGOTimeGPSVector *timestamps, 	//!< timestamps to produce SFTs for (can be NULL), if given must all lies within timeseries' time-span
                                  const char *windowType,		//!< optional time-domain window function to apply before FFTing
                                  REAL8 windowBeta			//!< window parameter, if any
                                  )
{
  XLAL_CHECK_NULL ( timeseries != NULL, XLAL_EINVAL, "Invalid NULL input 'timeseries'\n");
  XLAL_CHECK_NULL ( timestamps != NULL, XLAL_EINVAL, "Invalid NULL input 'timestamps'\n");

  REAL8 dt = timeseries->deltaT;	// timeseries timestep */
  REAL8 Tsft = timestamps->deltaT;
  REAL8 df = 1.0 / Tsft;		// SFT frequency spacing

  // make sure that number of timesamples/SFT is an integer (up to possible rounding error 'eps')
  REAL8 timestepsSFT0 = Tsft / dt;
  UINT4 timestepsSFT  = lround ( timestepsSFT0 );
  XLAL_CHECK_NULL ( fabs ( timestepsSFT0 - timestepsSFT ) / timestepsSFT0 < eps, XLAL_ETOL,
                    "Inconsistent sampling-step (dt=%g) and Tsft=%g: must be integer multiple Tsft/dt = %g >= %g\n",
                    dt, Tsft, timestepsSFT0, eps );

  // prepare window function if requested
  REAL8Window *window = NULL;
  if ( windowType != NULL ) {
    XLAL_CHECK_NULL ( (window = XLALCreateNamedREAL8Window ( windowType, windowBeta, timestepsSFT )) != NULL, XLAL_EFUNC );
  }

  // ---------- Prepare FFT ----------
  REAL8Vector *timeStretchCopy;	// input array of length N
  XLAL_CHECK_NULL ( (timeStretchCopy = XLALCreateREAL8Vector ( timestepsSFT )) != NULL, XLAL_EFUNC, "XLALCreateREAL4Vector(%d) failed.\n", timestepsSFT );
  UINT4 numSFTBins = timestepsSFT / 2 + 1;	// number of positive frequency-bins + 'DC' to be stored in SFT
  fftw_complex *fftOut;	// output array of length N/2 + 1
  XLAL_CHECK_NULL ( (fftOut = fftw_malloc ( numSFTBins * sizeof(fftOut[0]) )) != NULL, XLAL_ENOMEM, "fftw_malloc(%d*sizeof(complex)) failed\n", numSFTBins );
  fftw_plan fftplan;	// FFTW plan
  LAL_FFTW_WISDOM_LOCK;
  XLAL_CHECK_NULL ( (fftplan = fftw_plan_dft_r2c_1d ( timestepsSFT, timeStretchCopy->data, fftOut, FFTW_ESTIMATE)) != NULL, XLAL_EFUNC );	// FIXME: or try FFTW_MEASURE
  LAL_FFTW_WISDOM_UNLOCK;

  LIGOTimeGPS tStart = timeseries->epoch;

  // get last possible start-time for an SFT
  REAL8 duration =  round ( timeseries->data->length * dt ); // rounded to seconds
  LIGOTimeGPS tLast = tStart;
  XLALGPSAdd( &tLast, duration - Tsft );

  // check that all timestamps lie within [tStart, tLast]
  for ( UINT4 i = 0; i < timestamps->length; i ++ )
    {
      char buf1[256], buf2[256];
      XLAL_CHECK_NULL ( XLALGPSDiff ( &tStart, &(timestamps->data[i]) ) <= 0, XLAL_EDOM, "Timestamp i=%d: %s before start-time %s\n",
                        i, XLALGPSToStr ( buf1, &(timestamps->data[i]) ), XLALGPSToStr ( buf2, &tStart ) );
      XLAL_CHECK_NULL ( XLALGPSDiff ( &tLast,   &(timestamps->data[i]) ) >=0, XLAL_EDOM, "Timestamp i=%d: %s after last start-time %s\n",
                        i, XLALGPSToStr ( buf1, &(timestamps->data[i]) ), XLALGPSToStr ( buf2, &tLast ) );
    }

  UINT4 numSFTs = timestamps->length;

  // prepare output SFT-vector
  SFTVector *sftvect;
  XLAL_CHECK_NULL ( (sftvect = XLALCreateSFTVector ( numSFTs, numSFTBins )) != NULL, XLAL_EFUNC,
                    "XLALCreateSFTVector(numSFTs=%d, numBins=%d) failed.\n", numSFTs, numSFTBins );

  // main loop: apply FFT to the requested time-stretches and store in output SFTs
  for ( UINT4 iSFT = 0; iSFT < numSFTs; iSFT++ )
    {
      SFTtype *thisSFT = &(sftvect->data[iSFT]);	// point to current SFT-slot to store output in

      // find the start-bin for this SFT in the time-series
      REAL8 offset = XLALGPSDiff ( &(timestamps->data[iSFT]), &tStart );
      INT4 offsetBins = lround ( offset / dt );

      // copy timeseries-data for that SFT into local buffer
      memcpy ( timeStretchCopy->data, timeseries->data->data + offsetBins, timeStretchCopy->length * sizeof(timeStretchCopy->data[0]) );

      // window the current time series stretch if required
      REAL8 sigma_window = 1;
      if ( window != NULL )
        {
	  sigma_window = sqrt ( window->sumofsquares / window->data->length );
	  for( UINT4 iBin = 0; iBin < timeStretchCopy->length; iBin++ ) {
            timeStretchCopy->data[iBin] *= window->data->data[iBin];
          }
        } // if window

      // FFT this time-stretch
      fftw_execute ( fftplan );

      // fill the header of the i'th output SFT */
      strcpy ( thisSFT->name, timeseries->name );
      thisSFT->epoch = timestamps->data[iSFT];
      thisSFT->f0 = timeseries->f0;			// SFT starts at heterodyning frequency
      thisSFT->deltaF = df;

      // normalize DFT-data to conform to v2 specification ==> multiply DFT by (dt/sigma{window})
      // the SFT normalization in case of windowing follows the conventions detailed in the SFTv2 specification,
      // namely LIGO-T040164, and in particular Eqs.(3),(4) and (6) in T010095-00.pdf
      // https://dcc.ligo.org/cgi-bin/private/DocDB/ShowDocument?.submit=Number&docid=T010095
      // https://dcc.ligo.org/DocDB/0026/T010095/000/T010095-00.pdf
      REAL8 norm = dt / sigma_window;
      for ( UINT4 k = 0; k < numSFTBins ; k ++ ) {
        thisSFT->data->data[k] = (COMPLEX8) ( norm * fftOut[k] );
      }

      // correct heterodyning-phase, IF NECESSARY: ie if (fHet * tStart) is not an integer, such that phase-corr = multiple of 2pi
      if ( ( (INT4)timeseries->f0 != timeseries->f0  ) || (timeseries->epoch.gpsNanoSeconds != 0) || (thisSFT->epoch.gpsNanoSeconds != 0) ) {
        XLAL_CHECK_NULL ( XLALcorrect_phase ( thisSFT, timeseries->epoch) == XLAL_SUCCESS, XLAL_EFUNC );
      }

    } // for iSFT < numSFTs

  // free memory
  fftw_free ( fftOut );
  LAL_FFTW_WISDOM_LOCK;
  fftw_destroy_plan ( fftplan );
  LAL_FFTW_WISDOM_UNLOCK;
  XLALDestroyREAL8Vector ( timeStretchCopy );
  XLALDestroyREAL8Window ( window );

  return sftvect;

} // XLALMakeSFTsFromREAL8TimeSeries()
Ejemplo n.º 29
0
static void generate_proakis(void)
{
    float f;
    float f1;
    float offset;
    float amp;
    float phase;
    float delay;
    float pw;
    int index;
    int i;
    int l;
#if defined(HAVE_FFTW3_H)
    double in[FFT_SIZE][2];
    double out[FFT_SIZE][2];
#else
    fftw_complex in[FFT_SIZE];
    fftw_complex out[FFT_SIZE];
#endif
    fftw_plan p;

#if defined(HAVE_FFTW3_H)
    p = fftw_plan_dft_1d(FFT_SIZE, in, out, FFTW_BACKWARD, FFTW_ESTIMATE);
#else
    p = fftw_create_plan(FFT_SIZE, FFTW_BACKWARD, FFTW_ESTIMATE);
#endif
    for (i = 0;  i < FFT_SIZE;  i++)
    {
#if defined(HAVE_FFTW3_H)
        in[i][0] =
        in[i][1] = 0.0f;
#else
        in[i].re =
        in[i].im = 0.0f;
#endif
    }
    for (i = 1;  i < FFT_SIZE/2;  i++)
    {
        f = (float) i*SAMPLE_RATE/FFT_SIZE;
        f1 = f/200.0f;
        offset = f1 - floor(f1);
        index = (int) floor(f1);

        /* Linear interpolation */
        amp = ((1.0f - offset)*proakis[index].amp + offset*proakis[index + 1].amp)/2.3f;
        delay = (1.0f - offset)*proakis[index].delay + offset*proakis[index + 1].delay;
        phase = 2.0f*M_PI*f*delay*0.001f;
#if defined(HAVE_FFTW3_H)
        in[i][0] = amp*cosf(phase);
        in[i][1] = amp*sinf(phase);
        in[FFT_SIZE - i][0] = in[i][0];
        in[FFT_SIZE - i][1] = -in[i][1];
#else
        in[i].re = amp*cosf(phase);
        in[i].im = amp*sinf(phase);
        in[FFT_SIZE - i].re = in[i].re;
        in[FFT_SIZE - i].im = -in[i].im;
#endif
    }

#if defined(HAVE_FFTW3_H)
    fftw_execute(p);
#else
    fftw_one(p, in, out);
#endif

    fprintf(outfile, "/* Medium range telephone line response\n");
    fprintf(outfile, "   (from p 537, Digital Communication, John G. Proakis */\n");

    fprintf(outfile, "float proakis_line_model[] =\n");
    fprintf(outfile, "{\n");
    /* Normalise the filter's gain */
    pw = 0.0f;
    l = FFT_SIZE - (LINE_FILTER_SIZE - 1)/2;
    for (i = 0;  i < LINE_FILTER_SIZE;  i++)
    {
#if defined(HAVE_FFTW3_H)
        pw += out[l][0]*out[l][0];
#else
        pw += out[l].re*out[l].re;
#endif
        if (++l == FFT_SIZE)
            l = 0;
    }
    pw = sqrt(pw);
    l = FFT_SIZE - (LINE_FILTER_SIZE - 1)/2;
    for (i = 0;  i < LINE_FILTER_SIZE;  i++)
    {
#if defined(HAVE_FFTW3_H)
        impulse_responses[filter_sets][i] = out[l][0]/pw;
#else
        impulse_responses[filter_sets][i] = out[l].re/pw;
#endif
        fprintf(outfile, "%15.5f,\n", impulse_responses[filter_sets][i]);
        if (++l == FFT_SIZE)
            l = 0;
    }
    fprintf(outfile, "};\n\n");
    filter_sets++;
}
Ejemplo n.º 30
0
int main(void)
{
  /* This example shows the use of the fast polynomial transform to evaluate a
   * finite expansion in Legendre polynomials,
   *
   *   f(x) = a_0 P_0(x) + a_1 P_1(x) + ... + a_N P_N(x)                     (1)
   *
   * at the Chebyshev nodes x_j = cos(j*pi/N), j=0,1,...,N. */
  const int N = 8;

  /* An fpt_set is a data structure that contains precomputed data for a number
   * of different polynomial transforms. Here, we need only one transform. the
   * second parameter (t) is the exponent of the maximum transform size desired
   * (2^t), i.e., t = 3 means that N in (1) can be at most N = 8. */
  fpt_set set = fpt_init(1,lrint(ceil(log2((double)N))),0U);

  /* Three-term recurrence coefficients for Legendre polynomials */
  double *alpha = malloc((N+2)*sizeof(double)),
    *beta = malloc((N+2)*sizeof(double)),
    *gamma = malloc((N+2)*sizeof(double));

  /* alpha[0] and beta[0] are not referenced. */
  alpha[0] = beta[0] = 0.0;
  /* gamma[0] contains the value of P_0(x) (which is a constant). */
  gamma[0] = 1.0;

  /* Actual three-term recurrence coefficients for Legendre polynomials */
  {
    int k;
    for (k = 0; k <= N; k++)
    {
      alpha[k+1] = ((double)(2*k+1))/((double)(k+1));
      beta[k+1] = 0.0;
      gamma[k+1] = -((double)(k))/((double)(k+1));
    }
  }

  printf(
    "Computing a fast polynomial transform (FPT) and a fast discrete cosine \n"
    "transform (DCT) to evaluate\n\n"
    "  f_j = a_0 P_0(x_j) + a_1 P_1(x_j) + ... + a_N P_N(x_j), j=0,1,...,N,\n\n"
    "with N=%d, x_j = cos(j*pi/N), j=0,1,...N, the Chebyshev nodes, a_k,\n"
    "k=0,1,...,N, random Fourier coefficients in [-1,1]x[-1,1]*I, and P_k,\n"
    "k=0,1,...,N, the Legendre polynomials.",N
  );

  /* Random seed, makes things reproducible. */
  nfft_srand48(314);

  /* The function fpt_repcompute actually does the precomputation for a single
   * transform. It needs arrays alpha, beta, and gamma, containing the three-
   * term recurrence coefficients, here of the Legendre polynomials. The format
   * is explained above. The sixth parameter (k_start) is where the index in the
   * linear combination (1) starts, here k_start=0. The seventh parameter
   * (kappa) is the threshold which has an influence on the accuracy of the fast
   * polynomial transform. Usually, kappa = 1000 is a good choice. */
  fpt_precompute(set,0,alpha,beta,gamma,0,1000.0);


  {
    /* Arrays for Fourier coefficients and function values. */
    double _Complex *a = malloc((N+1)*sizeof(double _Complex));
    double _Complex *b = malloc((N+1)*sizeof(double _Complex));
    double *f = malloc((N+1)*sizeof(double _Complex));

    /* Plan for discrete cosine transform */
    const int NP1 = N + 1;
    fftw_r2r_kind kind = FFTW_REDFT00;
    fftw_plan p = fftw_plan_many_r2r(1, &NP1, 1, (double*)b, NULL, 2, 1,
      (double*)f, NULL, 1, 1, &kind, 0U);

    /* random Fourier coefficients */
    {
      int k;
      printf("\n2) Random Fourier coefficients a_k, k=0,1,...,N:\n");
      for (k = 0; k <= N; k++)
      {
        a[k] = 2.0*X(drand48)() - 1.0; /* for debugging: use k+1 */
        printf("   a_%-2d = %+5.3lE\n",k,creal(a[k]));
      }
    }

    /* fast polynomial transform */
    fpt_trafo(set,0,a,b,N,0U);

    /* Renormalize coefficients b_j, j=1,2,...,N-1 owing to how FFTW defines a
     * DCT-I; see
     * http://www.fftw.org/fftw3_doc/1d-Real_002deven-DFTs-_0028DCTs_0029.html
     * for details */
    {
      int j;
      for (j = 1; j < N; j++)
        b[j] *= 0.5;
    }

    /* discrete cosine transform */
    fftw_execute(p);

    {
      int j;
      printf("\n3) Function values f_j, j=1,1,...,M:\n");
      for (j = 0; j <= N; j++)
        printf("   f_%-2d = %+5.3lE\n",j,f[j]);
    }

    /* cleanup */
    free(a);
    free(b);
    free(f);

    /* cleanup */
    fftw_destroy_plan(p);
  }

  /* cleanup */
  fpt_finalize(set);
  free(alpha);
  free(beta);
  free(gamma);

  return EXIT_SUCCESS;
}