Example #1
1
/***************** read_write_streams *****************
 * inputs: char* bandSpacing
 *         char* maskNoise
 *         char* maskType
 * outputs: int (literal)
 Description:
  ...
 ****************************************************** */
int read_write_streams(char* bandSpacing, char* maskNoise, char* maskType)
{
/* DECLARATION */ 
  float den, fres, *recordsamples,*powerspec, *A, *weights, *bands, summation;
  int i, numBands, totalframes, numsamples, numbytes, y, counter; //y might cause problems 
  bool dynamic, rain, linear;

  PaStreamParameters input, output; 
  PaStream *stream_input,  *stream_output; 
  PaError error_input,error_output;
  fftw_complex *in, *out;
  fftw_plan plan;
  FILE *powerspec_file; 
  data* struct_data; 
  
/* INITIALIZE STATE VARIABLES */
  counter = 0;
  struct_data = (data*) malloc(sizeof(data));

  // Convert command line args to booleans 
  dynamic = !strcmp(maskType,"Dynamic")?   1:0;
  rain    = !strcmp(maskNoise, "Rain")?    1:0;
  linear  = !strcmp(bandSpacing, "linear")? 1:0;
  if(linear) numBands = 10;
  else       numBands = 7;

/* READ THE .WAV */
  struct_data = output_file(numBands,linear,rain);
  for(i=0; i<(2*struct_data->num_frames); i++) // is accessing num_frames bad?
  {
    summation = 0;
    for(y = 0; y <= numBands; y++)
      summation += struct_data->noise[2*y*struct_data->num_frames+i];
    
    struct_data->data[i] = summation;
  }

/* ALLOCATE MEMORY FOR DATA STRUCTURES */
  totalframes   = CHANNELS*FRAMES;//5*SAMPLE_RATE; why????
  numsamples    = FRAMES; //why totalframes is 5*sample rate change to totalframes if wrong 
  fres          = (float) SAMPLE_RATE/FRAMES;
  numbytes      = numsamples * sizeof(float);
  recordsamples = (float*) malloc(numbytes);
  powerspec     = (float*) malloc(numbytes); //malloc too much memory but i think that cool we will figure it out
  A             = (float*) malloc(numbytes);
  weights       = (float*)malloc(sizeof(float)*numBands); //final computed band weights
  bands         = (float*)malloc(sizeof(float)*numBands);  //bands specified to compute band weights
  in            = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * numsamples);
  out           = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * numsamples);
  CHECK_MALLOC(recordsamples,"read_write_streams");
  CHECK_MALLOC(powerspec,"read_write_streams"); 
  CHECK_MALLOC(weights,"read_write_streams");
  CHECK_MALLOC(bands,"read_write_streams");
  CHECK_MALLOC(in,"read_write_streams");
  CHECK_MALLOC(out,"read_write_streams");
  CHECK_MALLOC(A,"read_write_streams");
  
  
  plan                = fftw_plan_dft_1d(numsamples, in, out, FFTW_FORWARD, FFTW_MEASURE);
  struct_data->cursor = 0;


  //struct_data->num_frames = 441000;
  for (i = 0; i < numsamples; i++)
    recordsamples[i] = powerspec[i] = A[i] = 0;
  for (i = 0; i <= numBands; i++)
    weights[i]      = .75;  //init weights to 1 equal volume 
  
  if (linear)
  { bands[0] = 80;
    for (i = 1; i <= numBands; i++)
      bands[i] = i*(SAMPLE_RATE/2)/numBands;
  }
  else
  {
     bands[0] = 60;
     bands[1] = 125;
     bands[2] = 250;
     bands[3] = 500;
     bands[4] = 1000;
     bands[5] = 2000;
     bands[6] = 4000;
     bands[7] = 8000;
 }

  A_compute_coeff(numsamples/2,A,fres);

/* PORT AUDIO INIT W/ ERROR CHECKING */
  if( paNoError != (error_input = Pa_Initialize()) ) goto error;
  if( paNoError != (error_output = Pa_Initialize()) ) goto error;
  if( paNoDevice == (input.device = Pa_GetDefaultInputDevice()))
    { fprintf(stderr, "Error: No default input device. \n");  goto error; }
  if( paNoDevice == (output.device = Pa_GetDefaultOutputDevice()))
    { fprintf(stderr, "Error: No default output device. \n");  goto error; }

 
  input.channelCount              =  CHANNELS;
  input.sampleFormat              =  paFloat32;
  input.suggestedLatency          =  Pa_GetDeviceInfo( input.device )->defaultLowInputLatency;
  input.hostApiSpecificStreamInfo =  NULL;

  output.channelCount              =  CHANNELS;
  output.sampleFormat              =  paFloat32;
  output.suggestedLatency          =  Pa_GetDeviceInfo( output.device )->defaultLowInputLatency;
  output.hostApiSpecificStreamInfo =  NULL;

  // Open the port audio stream for input
  error_input = Pa_OpenStream( 
        &stream_input,
              &input,
              NULL,                  /* &outputParameters, */
              SAMPLE_RATE,
              FRAMES,
              paClipOff,      /* we won't output out of range samples so don't bother clipping them */
              NULL, /* no callback, use blocking API */
              NULL);
  if (error_input !=paNoError) goto error; 
  
  // Open the port audio stream for output
  error_output = Pa_OpenStream(
          &stream_output,
                NULL, 
              &output,
              44100,
              paFramesPerBufferUnspecified,
              paClipOff,      
              output_callback, 
              struct_data);
  if (error_output != paNoError) goto error; 
  



  error_input  = Pa_StartStream(stream_input);
  error_output = Pa_StartStream(stream_output);

  /* Intialization */

  /* Read and Write */
   while(1)
   {
      powerspec_file = fopen("../streams/powerspec.txt","w");
      if( error_output  != paNoError && 0) goto error_o;
      error_input = Pa_ReadStream(stream_input,recordsamples, FRAMES);
      if(error_input != paNoError && 0) goto error;


      /* FFT PROCESSING */
      inputsignal(in, recordsamples, CHANNELS*numsamples); //converts to fftw_complex and averages stereo to mono
      weighted_power_spectrum_fftw(numsamples,in,out,powerspec,A,den,4, plan);

      //compute bands if dynamic masking
      if (dynamic)
        compute_band_weights(numBands,linear,numsamples,powerspec,fres,weights,bands);
      

      for(i = 0;i<struct_data->num_frames*2;i++) // is accessing num_frames bad?
        {
          summation = 0;
          for(y = 0; y <= numBands;y++)
            summation +=  weights[y]*struct_data->data[y*struct_data->num_frames*2+i];
    
          struct_data->data[i] = summation;
        }
      fclose(powerspec_file);
   }

   free(recordsamples);
   free(in);
   free(out);
  //clean up other stuff fft and other malloced items

  /* Read and Write */
error:

    Pa_Terminate();
    fprintf( stderr, "An error occured while using the portaudio stream_input\n" );
    fprintf( stderr, "Error number: %d\n", error_input );
    fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( error_input) );

error_o:

    Pa_Terminate();
    fprintf( stderr, "An error occured while using the portaudio stream_input\n" );
    fprintf( stderr, "Error number: %d\n", error_output );
    fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( error_output) );
 return 0;

}
Example #2
0
void get3Draw(struct data *d,int mode,char *indir,int dataorder)
{
  char basename[MAXPATHLEN],dirname[MAXPATHLEN],filename[MAXPATHLEN];
  int dim1=0,dim2=0,dim3=0,nr=0;
  int volindex;
  int startpos,endpos;
  int ne,ns;
  int slab,image,echo;
  int i,j;

  /* This function checks the output type requested and sets the input
     filename accordingly. 3D raw data is input according to the specified
     mode using functions w3Dfdf() and wcomb3Dfdf().
     These functions output data either from individual receivers (w3Dfdf)
     or using a combination of data from all receivers (wcomb3Dfdf). */

  volindex=d->vol;

  /* Set start and end position of block */
  startpos=d->startpos; endpos=d->endpos;

  /* Set data dimensions */
  switch (dataorder) {
    case D12:
      /* If a previous block has been zero filled matrix size will be incorrect */
      d->nv2=(int)*val("nv2",&d->p);
      dim1=d->np/2; dim2=d->endpos-d->startpos; dim3=d->nv2; nr=d->nr; 
      break;
    case D3:  dim1=d->np/2; dim2=d->nv; dim3=d->endpos-d->startpos; nr=d->nr; break;
  }

  /* Allocate memory according to nr */
  if ((d->data = (fftw_complex ***)fftw_malloc(nr*sizeof(fftw_complex **))) == NULL) nomem(__FILE__,__FUNCTION__,__LINE__);

  /* Allocate memory according to block size */
  switch (dataorder) {
    case D12: /* in this case we read "D12" processing block into "D3" processing block */
      for (i=0;i<nr;i++) { /* loop over receivers and malloc for "D3" processing block */
        if ((d->data[i] = (fftw_complex **)fftw_malloc(dim1*dim2*sizeof(fftw_complex *))) == NULL) nomem(__FILE__,__FUNCTION__,__LINE__);
        for (j=0;j<dim1*dim2;j++) /* loop over dim1 and 1st phase encode block */
          if ((d->data[i][j] = (fftw_complex *)fftw_malloc(dim3*sizeof(fftw_complex))) == NULL) nomem(__FILE__,__FUNCTION__,__LINE__);
      }
      break;
    case D3: /* in this case we read "D3" processing block into "D12" processing block */
      for (i=0;i<nr;i++) { /* loop over receivers and malloc for "D12" processing block */
        if ((d->data[i] = (fftw_complex **)fftw_malloc(dim3*sizeof(fftw_complex *))) == NULL) nomem(__FILE__,__FUNCTION__,__LINE__);
        for (j=0;j<dim3;j++) /* loop over dim3 */
          if ((d->data[i][j] = (fftw_complex *)fftw_malloc(dim2*dim1*sizeof(fftw_complex))) == NULL) nomem(__FILE__,__FUNCTION__,__LINE__);
      }
      break;
  }

  /* Check for VnmrJ recon to figure if we are offline */
  if (vnmrj_recon) strcpy(basename,vnmrj_path);
  else {
    for (i=0;i<=strlen(d->file)-9;i++)
      basename[i]=d->file[i];
    basename[i]=0;
  }

  /* Number of echoes */
  ne=(int)*val("ne",&d->p);
  if (ne < 1) ne=1; /* Set ne to 1 if 'ne' does not exist */

  /* Number of slices (slabs) */
  ns=nvals("pss",&d->p);
  if (ns < 1) ns=1; /* Set ns to 1 if 'ns' does not exist */

  /* Allow for compressed multi-echo loop and multiple slabs */
  image=volindex/(ne*ns);
  slab=(volindex/ne)%ns;
  echo=volindex%ne;

  switch(mode) {
    case 'i': /* Individual input */
      for (i=0;i<d->nr;i++) {
        sprintf(dirname,"%s%s%.3d",basename,indir,i+1);
        sprintf(filename,"%s/slab%.3dimage%.3decho%.3d.raw",dirname,slab+1,image+1,echo+1);
        switch(dataorder) {
          case D12: r3Draw(filename,d,i);   break;
          case D3:  r3DrawD3(filename,d,i); break;
        }
      }
      break;
    case 's': /* Single receiver */
      sprintf(dirname,"%s%s",basename,indir);
      sprintf(filename,"%s/slab%.3dimage%.3decho%.3d.raw",dirname,slab+1,image+1,echo+1);
      switch(dataorder) {
        case D12: r3Draw(filename,d,0);   break;
        case D3:  r3DrawD3(filename,d,0); break;
      }
      break;
    default:
      fprintf(stderr,"\n%s: %s()\n",__FILE__,__FUNCTION__);
      fprintf(stderr,"  Invalid 2nd argument %s(*,'mode',*,*,*,*)\n",__FUNCTION__);
      fflush(stderr);
      break;
  } /* end mode switch */
}
Example #3
0
static void *Audio_Rx_loop()
{
	int Rx_socket;
	struct sockaddr_in Rx_addr;

	/* Socket init */
	if(Rx_socket_init(&Rx_socket, &Rx_addr, AUDIO_NET_PORT) ==0) {
		fprintf(stderr, "Rx Socket init \n");
		return NULL;
	}
	printf("Audio Rx socket init finish\n");

	ALCdevice *PlayDevice ;
	ALCcontext* PlayContext ;
	ALuint PlaySource; 
	ALuint PlayBuffer[AUDIO_Rx_PLAY_BUFFER_COUNT]; 

	PlayDevice = alcOpenDevice(NULL);
	PlayContext = alcCreateContext(PlayDevice, NULL); 

	alcMakeContextCurrent(PlayContext); 

	alGenSources(1, &PlaySource);
	alGenBuffers(AUDIO_Rx_PLAY_BUFFER_COUNT, PlayBuffer); 


	/*----------------------------*/
	/* fftw init */
	double *FT_in;
	double *IFT_in;
	fftw_complex *FT_out;
	fftw_complex *FT_out_tmp;
	fftw_plan FT_plan;
	fftw_plan IFT_plan;
	const double FOURIER_NUMBER = (floor( (double)AUDIO_SAMPLE_RATE*0.5 )+1); 

	FT_in =  (double*) fftw_malloc(sizeof(double) * (int)AUDIO_SAMPLE_RATE);
	IFT_in = (double*) fftw_malloc(sizeof(double) *(int) AUDIO_SAMPLE_RATE);
	FT_out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * (int)FOURIER_NUMBER);
	FT_plan =  fftw_plan_dft_r2c_1d(AUDIO_SAMPLE_RATE, FT_in, FT_out, (int)FFTW_ESTIMATE);
	IFT_plan = fftw_plan_dft_c2r_1d(AUDIO_SAMPLE_RATE, FT_out,IFT_in, (int)FFTW_ESTIMATE);


	int Buf_counter =0;
	unsigned short play_Audio_buf[AUDIO_SAMPLE_RATE];
	int recv_len;
	int ID;
	int remain_size = AUDIO_SAMPLE_RATE * sizeof(short);
	unsigned char Rx_Buffer[AUDIO_BUFFER_SIZE];
	int i;

	fd_set fds;
	struct timeval tv;
	int r;

	printf("Audio Tx Looping\n");
	while(sys_get_status() != SYS_STATUS_RELEASE) {
		/* start Tx Audeo */
		while(sys_get_status() == SYS_STATUS_WORK) {

			/* Timeout. */
			FD_ZERO(&fds);
			FD_SET(Rx_socket, &fds);
			tv.tv_sec = 2;
			tv.tv_usec = 0;

			r = select(Rx_socket + 1, &fds, NULL, NULL, &tv);
			if (r == -1) {
				fprintf(stderr, "select");
				goto AUDIO_RX_RELEASE;
			}
			if (r == 0) {
				//fprintf(stderr, "select timeout\n");
				/* Timeout to clear FrameBuffer */
				continue;
			}


			/*Receive Data */
			recv_len = recv(Rx_socket, (char*)&Rx_Buffer, sizeof(Rx_Buffer) , 0) ;
			if(recv_len == -1) {
				fprintf(stderr ,"Stream data recv() error\n");
				break ;
			}
			else {
				ID = *((int *)Rx_Buffer) ;
				memcpy((char *)play_Audio_buf + ID * 1024, &Rx_Buffer[4] , recv_len-4);
				remain_size -= (recv_len-4);

				/* receive finish */
				if(remain_size <= 0) {
					for(i = 0; i < AUDIO_SAMPLE_RATE; i++) {
						*(FT_in + i) = play_Audio_buf[i] * 128;
					}

					fftw_execute(FT_plan);

					for(i = 0 ; i < 300 ; i++) {
						FT_out[i][0] = 0;
						FT_out[i][1] = 0;
					}
					for(i = 7000 ; i < FOURIER_NUMBER ; i++) {
						FT_out[i][0] = 0;
						FT_out[i][1] = 0;
					}

					fftw_execute(IFT_plan);

					for(i = 0; i < AUDIO_SAMPLE_RATE; i++) {
						play_Audio_buf[i] = (IFT_in[i] /AUDIO_SAMPLE_RATE) * 10 + 15000;
						if(play_Audio_buf[i] > 32767) play_Audio_buf[i] =32767;
					}


					/* Play Audio */
					alBufferData(PlayBuffer[Buf_counter], AL_FORMAT_MONO16, (ALvoid *)play_Audio_buf ,sizeof(short) * 44100, 44100);
					alSourceStop(PlaySource);
					alSourcei(PlaySource, AL_BUFFER, PlayBuffer[Buf_counter]); 
					alSourcePlay(PlaySource);
					Buf_counter++;
					if(Buf_counter >= 10) Buf_counter = 0;
					remain_size = AUDIO_SAMPLE_RATE * sizeof(short);
				}
			}
		}
		usleep(50000);
	}

AUDIO_RX_RELEASE :
	/*------------------------------------------*/
	alcCloseDevice(PlayDevice);
	alcDestroyContext(PlayContext);
	alDeleteSources(1, &PlaySource); 
	alDeleteBuffers(AUDIO_Rx_PLAY_BUFFER_COUNT, PlayBuffer); 
	 /*------------------------------------------*/
	printf("Audio Rx finish\n");
	pthread_exit(NULL);
}
Example #4
0
void
Wavelet::WaveletReadNorsar(const std::string & fileName,
                           int               & errCode,
                           std::string       & errText)
{
  std::ifstream file;
  NRLib::OpenRead(file,fileName);
  std::string dummyStr;

  bool  lineIsComment = true;
  int   line          = 0;
  int   timeUnits;
  float milliSec;
  float samplingInt;
  float firstSample;

  NRLib::DiscardRestOfLine(file, line, false);

  // Domain
  while (lineIsComment == true) {
    if(NRLib::CheckEndOfFile(file)) {
      errText += "Error: End of file "+fileName+" premature.\n";
      errCode=1;
      return;
    }

    NRLib::ReadNextToken(file,dummyStr,line);
    if (dummyStr[0] != '*')
      lineIsComment = false;
    else
      NRLib::DiscardRestOfLine(file,line,false);
  }

  if (NRLib::Uppercase(dummyStr) != "TIME") {
    errText += "Error: The NORSAR wavelet in file "+fileName+" needs to be given in Time domain.\n";
    errCode  = 1;
    return;
  }

  timeUnits = NRLib::ReadNext<int>(file,line);
  milliSec = static_cast<float>(std::pow(10.0, 3*(1-timeUnits)));

  NRLib::DiscardRestOfLine(file,line,false); //Contains text for sample values not used by CRAVA

  // Frequency info
  lineIsComment = true;
  while( lineIsComment == true) {
    if(NRLib::CheckEndOfFile(file)) {
      errText += "Error: End of file "+fileName+" premature.\n";
      errCode=1;
      return;
    }

    NRLib::ReadNextToken(file,dummyStr,line);
    if (dummyStr[0] != '*')
      lineIsComment = false;
    else
      NRLib::DiscardRestOfLine(file,line,false);
  }

  NRLib::DiscardRestOfLine(file,line,false); //Line contains frequency information not used by CRAVA

  // Sample info
  lineIsComment = true;
  while( lineIsComment == true) {
    if(NRLib::CheckEndOfFile(file)) {
      errText += "Error: End of file "+fileName+" premature.\n";
      errCode=1;
      return;
    }

    NRLib::ReadNextToken(file,dummyStr,line);
    if (dummyStr[0] != '*')
      lineIsComment = false;
    else
      NRLib::DiscardRestOfLine(file,line,false);
  }

  nz_         = NRLib::ParseType<int>(dummyStr);
  samplingInt = NRLib::ReadNext<float>(file,line);
  firstSample = NRLib::ReadNext<float>(file,line);

  dz_   = samplingInt * milliSec;
  nzp_  = nz_;
  cnzp_ = nzp_/2+1;
  rnzp_ = 2*cnzp_;
  rAmp_ = static_cast<fftw_real*>(fftw_malloc(sizeof(float)*rnzp_));
  cAmp_ = reinterpret_cast<fftw_complex*>(rAmp_);
  norm_ = RMISSING;

  int cz_file = static_cast<int>((-firstSample / dz_) + 0.5);
  cz_         = nz_ - cz_file; //Wavelets are flipped

  // Pulse samples
  rAmp_[0] = 0.0f;
  for(int i=0; i<nz_;i++) {
    if (NRLib::CheckEndOfFile(file)) {
      errText += "Error: End of file "+fileName+" premature.\n";
      errCode=1;
      return;
    }
    NRLib::ReadNextToken(file,dummyStr,line);

    rAmp_[nz_ - i] = static_cast<fftw_real>(NRLib::ParseType<float>(dummyStr)); //Flip wavelet
  }
  file.close();
}
Example #5
0
File: smooth.c Project: POFK/Tide
/*==============================*/
int main (void)  {
    fftw_complex *deltak;
    double *deltar;
    double *deltars;
    fftw_plan plan;
    fftw_plan plans;
    int nn = 1024;    // 768 could be changed to nc
    int cn2= nn/2 + 1;
    int N  = nn*nn*nn;
    int Nc = nn*nn*cn2;

    deltak = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * Nc);
    deltar = (double *) fftw_malloc(N * sizeof(double));
    deltars= (double *) fftw_malloc(N * sizeof(double));
    plan = fftw_plan_dft_r2c_3d(nn, nn, nn, deltar, deltak, FFTW_ESTIMATE);
    plans= fftw_plan_dft_c2r_3d(nn, nn, nn, deltak, deltars,FFTW_ESTIMATE);
/*===Finishing FFTW initialization===*/

    int i, j, k, index_0;
    float input, lnd;
    FILE *DEN = fopen(path, "rb");
    printf("Reading..\n");
    for(k = 0; k < nn; k++)  {
        for(j = 0; j < nn; j++)  {
            for(i = 0; i < nn; i++)  {
                index_0 = index_f(k, j, i);
                fread(&input, 4, 1, DEN);
                deltar[index_0] = input - 1.;
            }
        }
    }
   printf("Finish reading...\n");
/*===Finishing reading data===*/

    fftw_execute(plan);
    printf("Finish fftw for the first time...\n");
/*===Finishing FFTW one===*/

    double r_part, i_part;
    int    x, y, z;
    double k2, factor, window;
    double sincx, sincy, sincz;

    for(k = 0; k < nn; k++)  {
        printf("complicate process~~~%d\n", k);
        for(j = 0; j < nn; j++)  {
            for(i = 0; i < cn2; i++)  {
                index_0 = index_k(k, j, i); //index to find that element
                r_part  = deltak[index_0][0];
                i_part  = deltak[index_0][1];
                x = i;     // index to calculating wavenumber
                if(j < cn2) y = j; else y = nn - j;
                if(k < cn2) z = k; else z = nn - k;
                k2 = x*x + y*y + z*z;
        
                if(x == 0) sincx = 1.; else sincx = sin(PI*x/nn)/(PI*x/nn);
                if(y == 0) sincy = 1.; else sincy = sin(PI*y/nn)/(PI*y/nn);
                if(z == 0) sincz = 1.; else sincz = sin(PI*z/nn)/(PI*z/nn);

                factor = (-1.)*k2*kf*kf*R*R/2.;
                window = exp(factor)/sincx/sincy/sincz;
                deltak[index_0][0] = r_part*window;
                deltak[index_0][1] = i_part*window;
           }
        }
    }

    fftw_execute(plans);
/*===Multiplying  window function===*/

    FILE *OUT1 = fopen(pathout1, "wb");
    FILE *OUT2 = fopen(pathout2, "wb");
    
    printf("Begin to output...\n");
    for(k = 0; k < nn; k++)  {
        for(j = 0; j < nn; j++)  {
            for(i = 0; i < nn; i++)  {
                index_0 = index_f(k, j, i);
                input   = deltars[index_0]/pow(nc, 3) + 1.;
                fwrite(&input, 4, 1, OUT1);
                if(input <= 0) printf("error!input=%f\n", input);
                lnd = log(input); 
                fwrite(&lnd,   4, 1, OUT2);
            }
        }
    }

/*============================*/ 
    fftw_destroy_plan(plan);
    fftw_free(deltak);
    fftw_free(deltar);

    return 0;
}
Example #6
0
/**
 * This method configures the estimator with the supplied parameters.
 * NOTE: an estimator should be configured only once.
 */
void SiEstimator::Configure( 
    int fftSize, 
    int winType, 
    int fast,
    int mbins,
    int sbins
  )
{
    int idx;

    // Get rid of any previous work space
    Cleanup();

    // Setup the resources based on approach chosen
    if( fast ) mUseFftw = 1;
    else       mUseFftw = 0;

    // Establish the common vectors and parameters
    mNfftPoints = fftSize;
    mInOut      = (double*)malloc( mNfftPoints * sizeof(double) );
    mWin        = (double*)malloc( mNfftPoints * sizeof(double) );
    mTmp        = (double*)malloc( 2*sizeof(double)*mNfftPoints );

    // Establish the window function
    if( 0==winType ){
        for(idx=0;idx<mNfftPoints;idx++){
            mWin[idx] = 1.0;
        }
        mCoherentGain = 1.0;
    }
    else if( 1==winType ){
       double x,a0,a1,a2,sum;
       a0 = 0.42659;
       a1 = 0.49656;
       a2 = 0.076849;
       sum = 0.0;
       for(idx=0;idx<mNfftPoints;idx++){
           x = (TWOPI * idx)/(mNfftPoints-1);
           mWin[idx] = a0 - a1*cos(x) + a2*cos(2*x);
           sum+=mWin[idx];
       }
       mCoherentGain = sum / mNfftPoints;
    }

    // Establish the appropriate processing vectors depending on approach
    if( mUseFftw ){
        mFftwOutput = (fftw_complex*)fftw_malloc( 
                                        sizeof(fftw_complex) * mNfftPoints);
        mFftwPlan   = fftw_plan_dft_r2c_1d(mNfftPoints,mInOut,mFftwOutput,0);
        if( mLog & M2_LOG_PLAN ){ 
            fftw_print_plan( mFftwPlan );
            printf("\n");
        }
    }
    else{
        mNrInOut = (double*)malloc( 2*sizeof(double)*mNfftPoints );
    }

    mMeasureBins = mbins;
    mSumBins     = sbins;
    mBinAve      = 0;
    // printf("CFG: mMeasureBins=%d, mSumBins=%d\n",mMeasureBins,mSumBins);
}
Example #7
0
int main(int argc, char **argv)
{
  int rows=1,columns=1;
  int nthreads=1;
  int inplace=0;
  int measure=0;
  int runs=1;
  pfft_get_args(argc,argv,"-pfft_test_runs",1,PFFT_INT,&runs); 
  pfft_get_args(argc,argv,"-pfft_omp_threads",1,PFFT_INT,&nthreads); 
  pfft_get_args(argc,argv,"-pfft_omp_rows",1,PFFT_INT,&rows); 
  pfft_get_args(argc,argv,"-pfft_omp_columns",1,PFFT_INT,&columns); 
  pfft_get_args(argc,argv,"-pfft_omp_inplace",1,PFFT_SWITCH,&inplace); 
  pfft_get_args(argc,argv,"-pfft_omp_measure",1,PFFT_SWITCH,&measure); 
  if(inplace!=1) inplace=0;

/*  printf("Enter a number:");
  scanf("%d",&nthreads);
  printf("\n");*/
  fftw_complex*m1 = (fftw_complex *) fftw_malloc(sizeof(fftw_complex)*rows*columns);
  fftw_complex*m2 = (fftw_complex *) fftw_malloc(sizeof(fftw_complex)*rows*columns);
  fftw_iodim howmany_dims[2];
  howmany_dims[0].n=rows;
  howmany_dims[0].is=columns;
  howmany_dims[0].os=1;
  howmany_dims[1].n=columns;
  howmany_dims[1].is=1;
  howmany_dims[1].os=rows;
  const int howmany_rank = 2;
  // init OMP threads for fftw
  fftw_init_threads();
  fftw_plan_with_nthreads(nthreads);
  
  fftw_plan plan_transpose_outplace,plan_transpose_inplace,plansimple2d;

  int fftw_flags=FFTW_ESTIMATE;
  if(measure==1) fftw_flags=FFTW_MEASURE;


  plan_transpose_outplace = fftw_plan_guru_dft(/*rank*/ 0,NULL,howmany_rank, howmany_dims,m1,m2,FFTW_FORWARD,fftw_flags);
  plan_transpose_inplace = fftw_plan_guru_dft(/*rank*/ 0,NULL,howmany_rank, howmany_dims,m1,m1,FFTW_FORWARD,fftw_flags);
/*  plansimple2d=fftw_plan_2d()*/
  /*plansimple2d=fftw_plan_dft_2d(rows,columns,m1,m1,FFTW_FORWARD,FFTW_ESTIMATE);*/
  
  /*printf("# rows=%d, columns=%d, threads=%d,inplace=%d, measure=%d\n",rows,columns,nthreads,inplace,measure);
  initialize_matrix(m1,rows,columns);
  printf("# start calculation...\n");*/
  /*  printf("# check");*/
  /* printmatrix(m1,rows,columns);*/
  
  struct timeval t1,t2;
  gettimeofday(&t1,NULL);
   
  int i;
  for(i=0;i<runs;i++)
  {
    if(inplace==1) fftw_execute(plan_transpose_inplace);  
    if(inplace==0) fftw_execute(plan_transpose_outplace);  
  }
  /*if(selectplan==3) fftw_execute(plansimple2d);*/
  
  gettimeofday(&t2,NULL);
  float seconds=t2.tv_sec-t1.tv_sec+(t2.tv_usec-t1.tv_usec)/1000000.0;
  printf("# output: rows,cols,inplace,,measure,threads,runs,total time,average time\n");
  printf("%d %d %d %d %d %d %.6f %6f\n",rows,columns,inplace,measure,nthreads,runs,seconds,seconds/runs);
 /* printmatrix(m1,rows,columns);*/
  free(m1);
  free(m2);
  return 0;

}
Example #8
0
void Crosscorrelation(signal_t *signal1, signal_t *signal2, char *dbg_file, int *x, double *y)
{
#ifdef TRACE_MODE
  Extrae_user_function (1);
#endif

  fftw_complex *in=NULL, *out=NULL, *in2=NULL, *out2=NULL, *product=NULL;
  fftw_plan p, p2, p3;
  int N=0, i=0, j=0, N1=0, N2=0;
  double *conj1=NULL, *conj2=NULL, max=0;

#ifdef DEBUG_MODE
  FILE *fd;
  fd = fopen (dbg_file, "w");
  if (fd == NULL)
  {
    fprintf (stderr, "\nDebug: Can't open file %s!\n", dbg_file);
    perror("fopen: ");
    exit (-1);
  }
#endif

  N1 = SIGNAL_SIZE(signal1);
  N2 = SIGNAL_SIZE(signal2);

  N = MAX(N1, N2);

  in=fftw_malloc(sizeof(fftw_complex)*N);
  out=fftw_malloc(sizeof(fftw_complex)*N);
  in2=fftw_malloc(sizeof(fftw_complex)*N);
  out2=fftw_malloc(sizeof(fftw_complex)*N);
  product=fftw_malloc(sizeof(fftw_complex)*N);
  conj1=(double *)malloc(sizeof(double)*N);
  conj2=(double *)malloc(sizeof(double)*N);

  bzero(in, sizeof(fftw_complex)*N);
  bzero(out, sizeof(fftw_complex)*N);
  bzero(in2, sizeof(fftw_complex)*N);
  bzero(out2, sizeof(fftw_complex)*N);
  bzero(conj1, sizeof(double)*N);
  bzero(conj2, sizeof(double)*N);

  p=fftw_plan_dft_1d(N, in, out, -1, FFTW_ESTIMATE);
  p2=fftw_plan_dft_1d(N, in2, out2, -1, FFTW_ESTIMATE);

  for(i=0; i<N1; i++) {
    in[i] = signal1->data[i].value;
  }

  for(i=0; i<N2; i++) {
    in2[i] = signal2->data[i].value;
  }

  fftw_execute(p); fftw_execute(p2);


  for(i=0; i<N; i++)  {
          product[i]=out[i]*conj(out2[i]);
//          product2[i]=out2[i]*conj(out[i]);
   }

  p3=fftw_plan_dft_1d(N, product, out, 1, FFTW_ESTIMATE);
  fftw_execute(p3);
//  p4=fftw_plan_dft_1d(N, product2, out2, 1, FFTW_ESTIMATE);
//  fftw_execute(p4);

/*
 *   for(i=0; i<N; i++)  {
 *        fprintf(stderr, "product_out1[%d]=%lf product_out2[%d]=%lf (equal? %d)\n",
 *                i, cabs(out[i]), i, cabs(out2[i]), ( cabs(out[i]) == cabs(out2[i]) ));
 *                  }
 *                  */
  max = 0; j = 0;

  //ULL!! N/p on p nombre d'iteracions, en aquest cas 2

  for(i=0; i<N; i++) {
        conj1[i]=(double)(pow(cabs(out[i]),2)/pow(N,3));

        if(conj1[i]>max) {
                 max=conj1[i];
                 j=i;
        }
  }

#ifdef DEBUG_MODE
  fprintf (fd, "%d %lf\n", j, max);

  for (i = 0; i < N; i++)
    {
      fprintf (fd, "%d %lf\n", i, conj1[i]);
    }
#endif

 
  fftw_destroy_plan (p);
  fftw_destroy_plan (p2);
  fftw_destroy_plan (p3);

  free(in); free(out); free(in2); free(out2); free(product); free(conj1); free(conj2);

#ifdef DEBUG_MODE
  fclose (fd);
#endif

  *x = j;
  *y = max;

#ifdef TRACE_MODE
  Extrae_user_function (0);
#endif

}
Example #9
0
void generate_PL_lines_fft(double PLindex, int nr_lines,int linelength, 
						   icl_buffer *y_buffer, //double *y, // out
						   int fielddim_z) 
{

	cufftHandle fftw_plan_transfer_fw, fftw_plan_noise_fw, fftw_plan_transfer_bw;

	// FFT preparation 
	const size_t out_size		 = sizeof(cufftDoubleComplex)*(linelength/2+1);
	const size_t in_size		 = sizeof(double)*(linelength+1);
	
	// memory allocation
	double *noise_in_host		 = (double*) malloc(in_size);  // all these allocs can technically also be done outside of the function, if performance is bad this might be a consideration	
	double *noise_in_device;
	checkCudaErrors(cudaMalloc((void **)&noise_in_device, in_size));

	cufftDoubleComplex *noise_out_host = (cufftDoubleComplex*) fftw_malloc(out_size); // check if i need 2 times +1
	cufftDoubleComplex *noise_out_device; 
	checkCudaErrors(cudaMalloc((void **)&noise_out_device, out_size));

	double *transfer_in_host 	 = (double*) malloc(in_size);  
	double *transfer_in_device;
	checkCudaErrors(cudaMalloc((void **)&transfer_in_device, in_size));
	
	cufftDoubleComplex *transfer_out_host = (cufftDoubleComplex*) fftw_malloc(out_size);	
	cufftDoubleComplex *transfer_out_device;
	checkCudaErrors(cudaMalloc((void **)&transfer_out_device, out_size));

	// plans
	cufftPlan1d(&fftw_plan_transfer_fw,	linelength, CUFFT_D2Z, 1);
	cufftPlan1d(&fftw_plan_noise_fw,	linelength, CUFFT_D2Z, 1);
	cufftPlan1d(&fftw_plan_transfer_bw,	linelength, CUFFT_Z2D, 1);	

	// XXX todo here we can potentially cufftPlanMany, to performa a batch of many plan1d fft
/*
	fftw_plan_transfer_fw = fftw_plan_dft_r2c_1d(linelength, transfer_in, transfer_out,FFTW_MEASURE); 
	fftw_plan_noise_fw    = fftw_plan_dft_r2c_1d(linelength, noise_in, noise_out,FFTW_MEASURE);     
	fftw_plan_transfer_bw = fftw_plan_dft_c2r_1d(linelength, transfer_out, transfer_in,FFTW_MEASURE);	
*/

	for(int v=0; v<nr_lines; v++){

		for(int i=0; i<linelength; i++){
			noise_in_host[i] = rand_01();
			transfer_in_host[i] = rand_01();
		}	

		Box_Mueller(linelength, noise_in_host, transfer_in_host);

		for(int i=0; i<linelength; i++){	
			noise_in_host[i] = 2*noise_in_host[i]-1; // around 0
			noise_in_host[i] = 5*noise_in_host[i];  //changes the deviation, which values need to be put will be investigated			
		}

		transfer_in_host[0]=1.0;
		for(int i=1; i<linelength; i++){
			transfer_in_host[i] = (transfer_in_host[i-1]/(i))*(i-1-(PLindex/2.0));
		}		

		/// (a) moving transfer_in and noise_in to the device
		cudaMemcpy(noise_in_device, noise_in_host, in_size, cudaMemcpyDeviceToHost);
		cudaMemcpy(transfer_in_device, transfer_in_host, in_size, cudaMemcpyDeviceToHost);
		
		//fftw_execute(fftw_plan_noise_fw);	
		//fftw_execute(fftw_plan_transfer_fw);
		cufftExecD2Z(fftw_plan_noise_fw, transfer_in_device, transfer_out_device);
		cufftExecD2Z(fftw_plan_noise_fw, noise_in_device, noise_out_device);

		/// (b) moving back transfer_out and noise out
		cudaMemcpy(transfer_out_host, transfer_out_device, out_size, cudaMemcpyHostToDevice);
		cudaMemcpy(noise_out_host, noise_out_device, out_size, cudaMemcpyHostToDevice);

		for(int i=0; i<0.5*linelength+1; i++){
			double temp = (transfer_out_host[i].x*noise_out_host[i].x+transfer_out_host[i].y*noise_out_host[i].y) / linelength;
			transfer_out_host[i].y = (transfer_out_host[i].x*noise_out_host[i].y-transfer_out_host[i].y*noise_out_host[i].x) / linelength;
			transfer_out_host[i].x = temp;
		}		

		/// (c) moving to the device transfer_out
		cudaMemcpy(transfer_out_device, transfer_out_host, out_size, cudaMemcpyDeviceToHost);

		// fftw_execute(fftw_plan_transfer_bw);	
		cufftExecZ2D(fftw_plan_transfer_bw, transfer_out_device, transfer_in_device);

		//// (d) moving back transfer_in 
		cudaMemcpy(transfer_in_host, transfer_in_device, in_size, cudaMemcpyHostToDevice);

		for(int i=0; i<linelength; i++){
			transfer_in_host[i] = transfer_in_host[i]/sqrt((double) linelength);
		}

		// xxx reduce max/avg
		double average=0;
		for(int i=0; i<linelength; i++){
			average = average + transfer_in_host[i];
		}
		average = average/linelength;


		double *y_host = (double*)malloc(sizeof(cl_double) * linelength * nr_lines + 1);
		size_t index = 0;
		for(int i=0; i<linelength; i++){
			y_host[index]=(transfer_in_host[i]-average);
			index++;
		}

		/// (e) write y_buf
		//icl_local_device* ldev = &local_devices[y_buffer->device->device_id];
		icl_local_buffer* lbuf = (icl_local_buffer*)(y_buffer->buffer_add);	
		cudaMemcpy((void*)lbuf->mem, transfer_out_host, out_size, cudaMemcpyDeviceToHost);
	}
	
	free(transfer_in_host);
	free(transfer_out_host);
	free(noise_out_host);
	free(noise_in_host);

	cudaFree(transfer_in_device);
	cudaFree(transfer_out_device);
	cudaFree(noise_out_device);
	cudaFree(noise_in_device);

	cufftDestroy(fftw_plan_transfer_fw);	
	cufftDestroy(fftw_plan_transfer_bw);
	cufftDestroy(fftw_plan_noise_fw);
//	fftw_cleanup();
}
Example #10
0
/* Generates a single wave of the low frequency (zero) and two waves
   of the high frequency (one) using FM Synthesis.

   This is what you came to see, so let's get into it. */
void make_output_audio(double **zero_audio, double **one_audio, size_t low_wavelength) {
  /* FFTW needs to make a "plan" for the best way to solve the FFT for
     particular dimensions before it can solve it. */
  fftw_plan make_waves;

  /* The harmonics we'll use to create our waves. */
  fftw_complex *harmonics; 
  size_t num_harmonics;

  /* Allocate memory for a single wave at the low wavelength.  This
   fits two waves at the higher frequency. */
  (*zero_audio) = (double*)fftw_malloc(sizeof(double)*low_wavelength);
  (*one_audio) = (double*)fftw_malloc(sizeof(double)*low_wavelength);

  /* The number of harmonics necessary to represent a wave is always
     wavelength/2+1. */
  num_harmonics = low_wavelength/2+1;
  harmonics = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*num_harmonics);

  /* Create a plan to turn the harmonics into the zero symbol audio */
  make_waves = fftw_plan_dft_c2r_1d(low_wavelength, harmonics, (*zero_audio),
				    FFTW_ESTIMATE);

  /* Initialize the harmonics */
  for (int c=0;c<num_harmonics;c++) {
    harmonics[c][0] = 0.0;
    harmonics[c][1] = 0.0;
  }

  /* Now for the tricky part. How do will fill in this array
     of harmonics to get what we want?

     We want to create one sine wave at the low wavelength with peaks at -1
     and 1.
  
     The 0th value in our array of harmonics is the part with no
     frequency (the average of the input values), so we don't want
     that. The 1st sample is exactly one wave, which is what we want.
     
     But, what's the right phase and sign?

     The "real" part of the harmonic, the first value, is the cosine
     wave, which begins at its maximum. The second value, the
     "imaginary" part is a sine wave, which begins at zero.  We want a
     pure sine wave, so we'll only set the second value.
     
     The sign of the sine wave determines whether it goes into the negative
     before going positive or vice-versa.

     It doesn't really matter which way it goes. I like waves that go up
     then come down, so I'm setting the value to negative. 

     Bonus: Why is the magnitude 0.5?
  */
  harmonics[1][1] = -0.5;

  /* Run the plan we made earlier on the harmonics we just set up
     to fill in the zero audio */
  fftw_execute(make_waves);

  
  /* Make a new plan for the one audio */
  fftw_destroy_plan(make_waves);
  make_waves = fftw_plan_dft_c2r_1d(low_wavelength, harmonics, (*one_audio),
				    FFTW_ESTIMATE);

  /* Clean up */
  for (int c=0;c<num_harmonics;c++) {
    harmonics[c][0] = 0.0;
    harmonics[c][1] = 0.0;
  }

  /* We want to create a wave with exactly twice the frequency of the
     first wave, which will create exactly two sine waves with peaks
     at -1 and 1.

     That wave is at the second position in our array.  The third value
     in our array corresponds with a wave with three times the frequency,
     the fourth four times the frequency, and so on.

     We set the phase, magnitude, and sign exactly as we did before.

     Now that you understand it, here's something to confuse you:
     In musical terms, this is the first harmonic of the wave we
     created above. It's labeled number two because musicians start
     counting from the base frequency, which mathematicians start
     counting from no frequency.
*/
  harmonics[2][1] = -0.5;

  /* Do the dirty deed */
  fftw_execute(make_waves);

  /* Free up everything we're not using */
  fftw_destroy_plan(make_waves);
  fftw_free(harmonics);
}
Example #11
0
/*************************************************************************************
NAME: potential_dot
FUNCTION: Calculates the time derivative of the potential of the 
density contrast in the k-space (from the FFT)in the grid[m] order, 
and then with an IFFT calculates the time derivative of potential in 
the position's space
INPUT: density contrast in the k-space, wave vectors, momentum field 
in k-space.
RETURN: File with the input and outputs (sorted in the grid[m] order)
*************************************************************************************/
int potential_dot()
{
  int m, i, j, k;
  double norm, alpha, pot_Re1, pot_Re2, pot_Im1, pot_Im2, factor;
  FILE *pf=NULL;


  printf("Computing time derivative of potential in k-space!\n");
  printf("-----------------------------------------------------------------\n");

  /*+++ Computing the time derivative of potential in k-space +++*/
  factor = (3.0/2.0) * (GV.H0*GV.H0) * GV.Omega_M0 / GV.a_SF;

  for( m=0; m<GV.NTOTK; m++ )
    {
      if( fabs(gp[m].k_module) > GV.ZERO ) 
	{
	  pot_Re1 = GV.Hz*gp[m].DenCon_K[0];
	  pot_Re2 = -1.0*( gp[m].k_vector[X]*gp[m].p_k[X][1] + gp[m].k_vector[Y]*gp[m].p_k[Y][1] + gp[m].k_vector[Z]*gp[m].p_k[Z][1] )/GV.a_SF;
	  
	  pot_Im1 = GV.Hz*gp[m].DenCon_K[1];
	  pot_Im2 = ( gp[m].k_vector[X]*gp[m].p_k[X][0] + gp[m].k_vector[Y]*gp[m].p_k[Y][0] + gp[m].k_vector[Z]*gp[m].p_k[Z][0] )/GV.a_SF;
	  
	  //--- Unifying ---
	  alpha = factor / (gp[m].k_module * gp[m].k_module);
	  gp[m].potDot_k[0] = alpha * ( pot_Re1 + pot_Re2 ); //Re()
	  gp[m].potDot_k[1] = alpha * ( pot_Im1 + pot_Im2 ); //Im()
	}//if
      else
	{
	  gp[m].potDot_k[0] = 0.0;
	  gp[m].potDot_k[1] = 0.0;
	}//else
      
      pot_Re1 = 0.0;
      pot_Re2 = 0.0;
      pot_Im1 = 0.0;
      pot_Im2 = 0.0;
      
    }//for m
  
  printf("Data time derivative of potential in k-space assigned!\n");
  printf("-----------------------------------------------------------------\n");

  
  /*+++++ OUT-OF-PLACE TRANSFORM +++++*/
#ifdef OUTOFPLACE
  /*+++ FFTW DEFINITIONS +++*/
  fftw_complex *in=NULL;
  double *out=NULL;
  fftw_plan plan_k2r; // FFTW from k-space to r-space
  fftw_complex *in2=NULL;
  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);

  pf = fopen("./../PotDot_k_out.dat", "w");
  fprintf(pf, "%s%3s %15s %15s\n", "#", "ID", "Re_PotDot", "Im_PotDot");
  for( m=0; m<GV.NTOTK; m++ )
    {
      in[m][0] = gp[m].potDot_k[0];
      in[m][1] = gp[m].potDot_k[1];
      fprintf(pf, 
	      "%10d %16.8lf %16.8lf\n",
	      m, gp[m].potDot_k[0], gp[m].potDot_k[1]);

    }//for m
  fclose(pf);
  
  /*+++ Making the FFT +++*/
  plan_k2r = fftw_plan_dft_c2r_3d(GV.NCELLS, GV.NCELLS, GV.NCELLS, in, out, FFTW_ESTIMATE);
  fftw_execute(plan_k2r);
  
  printf("FFT of potential derivative in r finished!\n");
  printf("-----------------------------------------\n");
  
  
  /*+++ Saving data +++*/
  pf = fopen("./../PotDot_r_out.dat", "w");
  fprintf(pf, "%s%3s %15s\n", "#", "ID", "PotDot_r");
  for( m=0; m<GV.NTOTALCELLS; m++ )
    {
      gp[m].potDot_r = out[m]/GV.NORM;
      fprintf(pf, 
	      "%10d %16.8lf\n",
	      m, gp[m].potDot_r);
    }//for m
  fclose(pf);
   
  /*Recreating input array*/
  /*
  in2 = (fftw_complex *) 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 );  
  */  

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


  /*+++++ IN-PLACE TRANSFORM +++++*/
#ifdef INPLACE
    /*+++ FFTW 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 );
    
  pf = fopen("./../PotDot_k_in.dat", "w");
  fprintf(pf, "%s%3s %15s %25s\n", "#", "ID", "Re_potDot", "Im_potDot");
  for( m=0; m<GV.NTOTK; m++ )
    {
      in[m][0] = gp[m].potDot_k[0];
      in[m][1] = gp[m].potDot_k[1]; 
      fprintf(pf, 
	      "%10d %16.8lf %16.8lf\n",
	      m, gp[m].potDot_k[0], gp[m].potDot_k[1]);
    }//for m
  fclose(pf);
  
  /*+++ Making the FFT +++*/
  plan_k2r = fftw_plan_dft_c2r_3d(GV.NCELLS, GV.NCELLS, GV.NCELLS, in, (double*)in, FFTW_ESTIMATE);
  fftw_execute(plan_k2r);
  
  printf("FFT of potential derivative in r finished!\n");
  printf("-----------------------------------------\n");
  
  
  /*+++ Saving data +++*/
  for( m=0; m<GV.NTOTALCELLS/2; m++ )
    {
      gp[2*m].potDot_r = in[m][0]/GV.NORM;
      gp[2*m+1].potDot_r = in[m][1]/GV.NORM;
    }//for m

  pf = fopen("./../PotDot_r_in.dat", "w");
  fprintf(pf, "%s%3s %15s\n", "#", "ID", "PotDot" );

  for(m=0; m<GV.NTOTALCELLS; m++)
    {
      fprintf(pf,
	      "%10d %16.8lf\n",
	      m, gp[m].potDot_r);
    }
  fclose(pf);

   
  /*Recreating input array*/
  /*
  plan_r2k = fftw_plan_dft_r2c_3d( GV.NCELLS, GV.NCELLS, GV.NCELLS, (double*)in, in, FFTW_ESTIMATE );
  fftw_execute( plan_r2k );  
  */  

  fftw_destroy_plan( plan_k2r );
  //fftw_destroy_plan( plan_r2k );
  
  free(in);
#endif


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

  return 0;
}//potential_dot
Example #12
0
int press_record(char *data_filename, char *wave_filename) {
  /* The overall goal here is to seamlessly decode as many different audio
     inputs as possible.

     There's a lot of subtlety to decoding analog input with an FFT,
     especially for a protocol like this one with a symbol that's
     half a wavelength.

     Instead of making proper hardware to amplify and filter the
     output of the TI99/4a, I made this software capable of decoding
     the weak, noisy crap obtained from connecting the microphone
     output to a line-in without any filter or amplifier.

     I perform an FFT over one wavelength once per sample. Computing
     the FFT for every sample is probably overkill, but it's
     significantly faster than realtime even on an old PowerBook G4,
     and it doesn't hurt to average out noise better.

     Using a buffer size of one wavelength means that the first and
     second harmonics are centered at exactly the frequencies we're
     looking at. I believe it's necessary to use a window function, so
     that alternating 0s and ones can be differentiated. I'm using the
     Hamming window (half a sine wave), but there may be better ones.
     
     There can be a lot of noise in the signal, so I keep a
     half-symbol size buffer of the difference between the signal
     strengths of the two frequencies and use the average.  (It it was
     a whole buffer, it would blur out the boundaries between
     symbols.)  If the difference between the low and high and low
     frequncies drops below or rises above the midpoint, it triggers a
     new signal.

*/


  void *in_file;
  FILE *out_file;
  size_t num_harmonics;
  sf_count_t samples_read;
  fftw_complex *harmonics;
  fftw_plan get_frequencies;
  size_t offset = 0;
  double *audio_samples;
  int (*read_samples)(void *device, double *buffer, size_t count);

  /* Initialize the FFT

     If the FFT is over the wavelength of the low frequency (twice the symbol size)

     sample 0 - DC
     sample 1 - wavelen of 2 symbols - "Zero"
     sample 2 - wavelen of 1 symbol - "One"

     This doesn't have a very narrow filter, so it might be susceptable to interference.     
   */
  num_harmonics = DEFAULT_WAVELENGTH/2+1;
  harmonics = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*num_harmonics);

  audio_samples = (double*) fftw_malloc(sizeof(double)*DEFAULT_WAVELENGTH);
  if (wave_filename == NULL) {
    read_samples = &read_from_mic;
    init_mic_input(&in_file);

  } else {
    read_samples = &read_from_file;
    init_file_input(&in_file,wave_filename);
  }
  init_audio_buffer(read_samples, in_file);
  init_history();
  init_window();
  if (data_filename == NULL)
    out_file = stdout;
  else
    out_file = fopen(data_filename,"wb");

  get_frequencies = fftw_plan_dft_r2c_1d(DEFAULT_WAVELENGTH, audio_samples,
					 harmonics,
					 FFTW_ESTIMATE | FFTW_DESTROY_INPUT);


  while ((samples_read = audio_at_offset(read_samples, in_file, audio_samples, offset++, DEFAULT_WAVELENGTH))>0) {
    apply_window_func(audio_samples);
    fftw_execute(get_frequencies);
    if (process_harmonics(harmonics, num_harmonics, out_file))
      break;
  }
  cosby_print("Done!\n");

  if (data_filename != NULL)    
    fclose(out_file);
 
  fftw_destroy_plan(get_frequencies);

  fftw_free(harmonics);
  fftw_free(audio_samples);
  if (wave_filename == NULL) {
  } else {
    free_audio_buffer(in_file);
  }
  free_history();
  free_window();

  return 1;
}
Example #13
0
void copy2Ddata(struct data *d1,struct data *d2)
{
  int dim1,dim2,dim3,nr;
  int i,j,k;
  double *dp1,*dp2;

#ifdef DEBUG
  struct timeval tp;
  double t1,t2;
  int rtn;
  fprintf(stdout,"\n%s: %s()\n",__FILE__,__FUNCTION__);
  rtn=gettimeofday(&tp, NULL);
  t1=(double)tp.tv_sec+(1.e-6)*tp.tv_usec;
  fflush(stdout);
#endif

  /* Data dimensions */
  dim1=d1->np/2; dim2=d1->nv; dim3=d1->endpos-d1->startpos; nr=d1->nr;

  /* Clear any data that is there */
  if (d2->data) clear2Ddata(d2);

  /* Allocate memory according to nr */
  if ((d2->data = (fftw_complex ***)fftw_malloc(nr*sizeof(fftw_complex **))) == NULL) nomem(__FILE__,__FUNCTION__,__LINE__);
  for (i=0;i<nr;i++) { /* loop over receiver blocks */
    if ((d2->data[i] = (fftw_complex **)fftw_malloc(dim3*sizeof(fftw_complex *))) == NULL) nomem(__FILE__,__FUNCTION__,__LINE__);
    for (j=0;j<dim3;j++) /* loop over slices */
      if ((d2->data[i][j] = (fftw_complex *)fftw_malloc(dim2*dim1*sizeof(fftw_complex))) == NULL) nomem(__FILE__,__FUNCTION__,__LINE__);
  }

  for (i=0;i<nr;i++) {
    for (j=0;j<dim3;j++) {
      dp1 = *d1->data[i][j];
      dp2 = *d2->data[i][j];
      for(k=0;k<dim2*d1->np;k++) *dp2++ = *dp1++;
    }
  }

  /* Set dimensions and some detail as well */
  d2->np=d1->np; d2->nv=d1->nv; d2->ns=d1->ns; d2->nr=d1->nr;
  d2->fn=d1->fn; d2->fn1=d1->fn1;

  /* Copy status of data */
  d2->ndim=d1->ndim;
  if (d1->dimstatus) {
     free(d2->dimstatus);
     if ((d2->dimstatus = malloc(d2->ndim*sizeof(*(d2->dimstatus)))) == NULL) nomem(__FILE__,__FUNCTION__,__LINE__);
     for (i=0; i<d2->ndim; i++)
       d2->dimstatus[i] = d1->dimstatus[i];
  } else
    d2->dimstatus = NULL;

  d2->datamode=d1->datamode;
  d2->vol=d1->vol;
  d2->nblocks=d1->nblocks; d2->block=d1->block;
  d2->startpos=d1->startpos; d2->endpos=d1->endpos;

#ifdef DEBUG
  rtn=gettimeofday(&tp, NULL);
  t2=(double)tp.tv_sec+(1.e-6)*tp.tv_usec;
  fprintf(stdout,"  Copying data: took  %f secs\n",t2-t1);
  fflush(stdout);
#endif

}
Example #14
0
void CBlasMath::generatePlans()
{
    unsigned int plannerMode = FFTW_EXHAUSTIVE;
    int minN = 2;
    int maxN = 1024;

    if(qApp) // test we have are in a gui env
    {
        QProgressDialog progress("CBlas Math Plugin is tuning fftw ...", "Abort", minN, maxN);
        progress.setMinimumDuration(0);
        progress.setWindowModality(Qt::WindowModal);
        progress.show();

        for(int n = minN; n <= maxN; n++)
        {
            progress.setValue(n);
            progress.setLabelText("Tuning fftw for matrix size " + QString::number(n) + " ...");
            fftw_complex *in = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * n * n);
            fftw_complex *out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * n * n);

            qApp->processEvents();
            fftw_plan pf = fftw_plan_dft_2d(n, n, in, out, FFTW_FORWARD, plannerMode);
            if (progress.wasCanceled())
                         break;

            qApp->processEvents();
            fftw_plan pb = fftw_plan_dft_2d(n, n, in, out, FFTW_BACKWARD, plannerMode);
            if (progress.wasCanceled())
                         break;

            fftw_destroy_plan(pf);
            fftw_destroy_plan(pb);
            fftw_free(in);
            fftw_free(out);
        }
    }
    else
    {
//        std::cout << "CBlas Math Plugin is tuning fftw ... (press ENTER to cancel)"  << std::endl;
//        for(int n = minN; n <= maxN; n++)
//        {
//            std::cout << '\xd' << "Tuning fftw for matrix size " << n;
//            //std::cout << std::endl << "Tuning fftw for matrix size" << n;
//            fftw_complex *in = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * n * n);
//            fftw_complex *out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * n * n);

//            if(cinThread.isFinished())
//                break;
//            fftw_plan pf = fftw_plan_dft_2d(n, n, in, out, FFTW_FORWARD, plannerMode);

//            if(cinThread.isFinished())
//                break;
//            fftw_plan pb = fftw_plan_dft_2d(n, n, in, out, FFTW_BACKWARD, plannerMode);

//            fftw_destroy_plan(pf);
//            fftw_destroy_plan(pb);
//            fftw_free(in);
//            fftw_free(out);
//        }
//        std::cout << std::endl << "Done!" << std::endl;
    }
}
Example #15
0
int main(int argc, char **argv)
{
    
    
    int         scheme_flg, nfld;
    double      *eta, *phi;
    double      *velwM, *velwM2, *velw2M, *velw2M2;
    double      t, dt, t_old;
    char        init_data_buff[INIT_DATA_BUFSIZE], init_pars_buff[INIT_DATA_BUFSIZE], subid_buff[2], dtflag[20], nfld_buff[5];
    
    fftw_complex    *heta, *hphi;
    fftw_complex    *hvelwM, *hvelwM2, *hvelw2M, *hvelw2M2;
    
    
    
    strncpy(init_pars_buff,"\0",INIT_DATA_BUFSIZE);
    //strncpy(init_pars_buff, Sim_root, strlen(Sim_root));
    strncpy(init_pars_buff,"initpars.h5", strlen("initpars.h5"));
    
    /* Read input parameters file */
    get_params(init_pars_buff);
    
    
    printf("Final time = %f\n",T);
    printf("dtsave = %f\n",dtsave);
    
    snprintf(subid_buff, 2,"%d",runsubid);
    
    strncpy(init_data_buff,"\0",INIT_DATA_BUFSIZE);
    strcat(init_data_buff,"initdata.");
    strcat(init_data_buff,subid_buff);
    strcat(init_data_buff,".h5");
   
    nfld = 0;
    strncpy(savefile_buff,"\0",SAVE_FILE_BUFSIZE);
    strcat(savefile_buff,"data");
    snprintf(nfld_buff, 5,"%d",nfld);
    strcat(savefile_buff,nfld_buff);
    strcat(savefile_buff,".");
    strcat(savefile_buff,subid_buff);
    strcat(savefile_buff,".h5");
    
    strncpy(savefile2_buff,"\0",SAVE_FILE_BUFSIZE);
    strcat(savefile2_buff,"data_extra");
    snprintf(nfld_buff, 5,"%d",nfld);
    strcat(savefile2_buff,nfld_buff);
    strcat(savefile2_buff,".");
    strcat(savefile2_buff,subid_buff);
    strcat(savefile2_buff,".h5");
    
    Nxl = 4*Nx/2;
    Nyl = 4*Ny/2;
    
    g=1;
    NLevs=M;
    
    /* Define a total size to share time-stepping routines with 1d case */
    /* N/2+1 = Nx*(Ny/2 + 1) */
    N = 2*Nx*(Ny/2+1) - 2;
    
    eta = (double*) fftw_malloc(sizeof(double)*2*Nx*Ny);
    heta = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*2*Nx*(Ny/2+1));
    
    phi = &eta[Nx*Ny];
    hphi = &heta[Nx*(Ny/2+1)];
    
    //hdummy = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*2*Nx*(Ny/2+1));
    
    //k = malloc (sizeof(double)*Nx*(Ny/2+1));
    
    f =  malloc(sizeof(double)*Nx*Ny);
    ff = malloc(sizeof(double)*Nxl*Nyl);
    hf = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*Nx*(Ny/2+1));
    hff = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*Nxl*(Nyl/2+1));
    
    velwM    =  malloc(sizeof(double)*Nx*Ny);
    velwM2   =  malloc(sizeof(double)*Nx*Ny);
    velw2M   =  malloc(sizeof(double)*Nx*Ny);
    velw2M2  =  malloc(sizeof(double)*Nx*Ny);
    hvelwM   = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*Nx*(Ny/2+1));
    hvelwM2  = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*Nx*(Ny/2+1));
    hvelw2M  = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*Nx*(Ny/2+1));
    hvelw2M2 = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*Nx*(Ny/2+1));
    
    /* Setup fft routines */
    //stat = fftw_init_threads();
    //fftw_plan_with_nthreads(4);
    
    fftp  = fftw_plan_dft_r2c_2d(Nx, Ny,  f, hf, FFTW_ESTIMATE);
    ifftp = fftw_plan_dft_c2r_2d(Nx, Ny, hf,  f, FFTW_ESTIMATE);
    
    fftp_large  = fftw_plan_dft_r2c_2d(Nxl, Nyl, ff, hff, FFTW_ESTIMATE);
    ifftp_large = fftw_plan_dft_c2r_2d(Nxl, Nyl, hff, ff, FFTW_ESTIMATE);
    
    
    /* Read initial data */
    printf("Reading initial condition from %s\n",init_data_buff);
    get_ic_2d(init_data_buff, eta, phi);
    

    /* Setup temporal scheme. */
    scheme_flg=2;
    Setup_TimeScheme(scheme_flg);
    rhs_hos_setup();
    
    t = 0;
       
    fft_2d(eta, heta, fftp);
    fft_2d(phi, hphi, fftp);
    
    ifft_2d(heta, eta, ifftp);
    ifft_2d(hphi, phi, ifftp);
  
    
    /* Dealiasing */

    int mx, my, index;
    
    mx = floor( 0.5*Nx/(1 + 0.5*NLevs) );
    my = floor( 0.5*Ny/(1 + 0.5*NLevs) );
    
    for (int i=0; i<Nx; i++) {
        
        for (int j=0; j<Ny/2+1; j++) {
            
            if ( (i>=mx && i<(Nx-mx+1)) || (j>=my) ) {
                
                index = (Ny/2+1)*i + j;
                heta[index] = 0.0;
                hphi[index] = 0.0;
            
            }
            
        }
        
    }

    
    Zvel(heta, hvelwM, hvelwM2, hvelw2M, hvelw2M2, t);
    ifft_2d(hvelwM, velwM, ifftp);
    ifft_2d(hvelwM2, velwM2, ifftp);
    
    
    /* Save initial snapshot */
    savefileid = create_file_2d(savefile_buff);
    write_header_2d(savefileid, t);
    write_field_2d(savefileid, eta, phi);
    status = close_file_2d(savefileid);
            
    savefileid2 = create_file_2d(savefile2_buff);
    write_header_2d(savefileid2, t);
    write_extra_2d(savefileid2, velwM, velwM2);
    status = close_file_2d(savefileid2);
    
    printf("Datafile written at t=%f\n",t);

    /* Time loop */
    while (t<T-0.00000001) {
        
        t_old = t;
        
        dt = 0.025;
        
        sol_update_RK(heta,&t,dt,dtflag);
        //t = t + dt;
        
        if ( floor( (t*1.000000001)/dtsave) > floor((t_old*1.000000001)/dtsave) ) {
            
            nfld = nfld + 1;
            ifft_2d(heta, eta, ifftp);
            ifft_2d(hphi, phi, ifftp);
            
            
            /* Print field in output file */
            strncpy(savefile_buff,"\0",SAVE_FILE_BUFSIZE);
            strcat(savefile_buff,"data");
            snprintf(nfld_buff, 5,"%d",nfld);
            strcat(savefile_buff,nfld_buff);
            strcat(savefile_buff,".");
            strcat(savefile_buff,subid_buff);
            strcat(savefile_buff,".h5");
    
            strncpy(savefile2_buff,"\0",SAVE_FILE_BUFSIZE);
            strcat(savefile2_buff,"data_extra");
            snprintf(nfld_buff, 5,"%d",nfld);
            strcat(savefile2_buff,nfld_buff);
            strcat(savefile2_buff,".");
            strcat(savefile2_buff,subid_buff);
            strcat(savefile2_buff,".h5");

            savefileid = create_file_2d(savefile_buff);
            write_header_2d(savefileid, t);
            write_field_2d(savefileid, eta, phi);
            status = close_file_2d(savefileid);
            
            savefileid2 = create_file_2d(savefile2_buff);
            write_header_2d(savefileid2, t);
            write_extra_2d(savefileid2, velwM, velwM2);
            status = close_file_2d(savefileid2);

            printf("Datafile written at t=%f\n",t);
            
        }
        
    }
    
    
//
//    ifft_1d(heta, eta, ifftp);
//    ifft_1d(hphi, phi, ifftp);
//    
//    
//    
    
    fftw_destroy_plan(fftp);
    fftw_destroy_plan(ifftp);
    free(eta);
    fftw_free(heta);
    
    fftw_destroy_plan(fftp_large);
    fftw_destroy_plan(ifftp_large);
    
    return 0;
    
}
Example #16
0
int main(void) {
FILE *fpw,*gnu;
int i1;
char name[50];
int INDEX;
int half_nx;
double kx, delta_kx, delta_ky;
double kx2,k2, k4;


double A = 1.0;
double delta_x = 1.0;
double delta_t = 0.2;
double alpha=1,beta=1;

int n_x;
int T=1000;
int T_write=20;

n_x= 128;
int flag=0;
/**Input the parameters**/
fpw=fopen("input.dat","r");
fscanf(fpw,"%d",&flag);//to check for the case
fscanf(fpw,"%d",&n_x);
fscanf(fpw,"%le",&delta_x);
fscanf(fpw,"%d",&T);
fscanf(fpw,"%d",&T_write);
fscanf(fpw,"%le",&delta_t);
fclose(fpw);

//checking which case is used and assigning the value to A and beta
if(flag==1)
{
	A=1;
	beta=1;
}
else if(flag==2)
{
	A=1;
	beta=4;
}
else if(flag==3)
{
	A=4;
	beta=1;
}
else
{
	printf("\nInvalid input\nExiting program......");
	exit(0);
}

fftw_complex *comp,*compDel,*g;
fftw_plan planF,planFg, planB;
fftw_plan planF_Del,planB_Del;

comp = fftw_malloc(n_x* sizeof(fftw_complex));
compDel = fftw_malloc(n_x* sizeof(fftw_complex));
g = fftw_malloc(n_x* sizeof(fftw_complex));

planF = fftw_plan_dft_1d(n_x,comp,comp,FFTW_FORWARD,FFTW_ESTIMATE);
planF_Del = fftw_plan_dft_1d(n_x,compDel,compDel,FFTW_FORWARD,FFTW_ESTIMATE);

planFg = fftw_plan_dft_1d(n_x,g,g,FFTW_FORWARD,FFTW_ESTIMATE);

planB = fftw_plan_dft_1d(n_x,comp,comp,FFTW_BACKWARD,FFTW_ESTIMATE);
planB_Del = fftw_plan_dft_1d(n_x,compDel,compDel,FFTW_BACKWARD,FFTW_ESTIMATE);

/**Initial Profile**/
for(i1=0; i1 < n_x; ++i1){
	if(i1<(n_x/4) || i1>(3*n_x/4))
	{
		__real__ comp[i1] = 0.1;
	}
	else
	{
		__real__ comp[i1] = 1;
	}
	__imag__ comp[i1] = 0.0;

}

half_nx = (int) n_x/2;
delta_kx = (2.0*M_PI)/(n_x*delta_x);

/**Make a gnu script**/

gnu=fopen("plotAnimation.gp","w");
fprintf(gnu,"set xrange[0:%d]",n_x);
fprintf(gnu,"\nset yrange[-0.1:1.1]");

/**printing the initial profile**/

sprintf(name,"./output/c_%d.dat",0);
fpw=fopen(name,"w");
for(i1=0; i1<n_x; ++i1){
	fprintf(fpw,"%le\n",__real__ comp[i1]);
	__imag__ comp[i1]=0;
}
fclose(fpw);
fprintf(gnu,"\nplot \"%s\" with lines",name);
fprintf(gnu,"\npause 1");

/**Starting the time loop**/
for(INDEX=1; INDEX<=T; ++INDEX){

	/** calculating g **/
	for(i1=0; i1 < n_x; ++i1){
		g[i1] = 2*A*(comp[i1])*(1-comp[i1])*(1-2*comp[i1]);
	}

	/** Let us take comp to the Fourier space **/
	fftw_execute_dft(planF,comp,comp);
	fftw_execute_dft(planFg,g,g);

	/** Evolve composition **/
	for(i1=0; i1 < n_x; ++i1){
		if(i1 < half_nx) kx = i1*delta_kx;
		else kx = (i1-n_x)*delta_kx;
		kx2 = kx*kx;
		k2 = kx2;
		k4= k2*k2;
		//main equation implementation take place here
		comp[i1] = (comp[i1]-alpha*k2*delta_t*g[i1])/(1+2*beta*k4*delta_t);
	}

	/** Take composition back to real space **/
	fftw_execute_dft(planB,comp,comp);

	for(i1=0; i1<n_x; ++i1){
		comp[i1] = comp[i1]/(n_x);
	}

	/**Printing the Results**/
	if(INDEX%T_write==0)
	{
		sprintf(name,"./output/c_%d.dat",INDEX);
		fpw=fopen(name,"w");
		for(i1=0; i1<n_x; ++i1){
		fprintf(fpw,"%le\n",__real__ comp[i1]);
		__imag__ comp[i1]=0;
		}
		fclose(fpw);
		fprintf(gnu,"\nplot \"%s\" with lines",name);
		fprintf(gnu,"\npause 0.4");
	}
}

sprintf(name,"output%d.dat",flag);
fpw=fopen(name,"w");
/**calculating the interface width for the final profile**/

//first find the point where the composition value just increases 0.5
int pos=1;
for(i1=0; i1<n_x/2; ++i1){
			if(__real__ comp[i1]>=0.5){
				pos=i1;
				break;
			}
		}


//now find the slope by taking a point 10 points ahead of this and 10 points before this
double m=(__real__ comp[pos]-__real__ comp[pos-1]);
//the interface width will be 1/slope
double interfaceWidth=1/m;

fprintf(fpw,"Interface Width = %le\n",interfaceWidth);

/**calculating the interfacial energy**/
//fisrt find dc/dx

for(i1=0; i1 < n_x; ++i1){
	compDel[i1] = comp[i1];
	}

/** Let us take comp to the Fourier space **/
fftw_execute_dft(planF_Del,compDel,compDel);

/** Evolve composition **/
for(i1=0; i1 < n_x; ++i1){
	if(i1 < half_nx) kx = i1*delta_kx;
	else kx = (i1-n_x)*delta_kx;
	kx2 = kx*kx;

	//main equation implementation take place here
	__real__ compDel[i1] = -kx * __imag__ compDel[i1];
	__imag__ compDel[i1] = __real__ compDel[i1] * kx;
	}

/** Take composition back to real space **/
fftw_execute_dft(planB_Del,compDel,compDel);

for(i1=0; i1<n_x; ++i1){
	compDel[i1] = compDel[i1]/(n_x);
	}

double energy=0;
for(i1=0; i1<n_x; ++i1){
		energy+=(A*comp[i1]*comp[i1]*(1-comp[i1])*(1-comp[i1]) + beta*compDel[i1]*compDel[i1])*delta_x;
		}

fprintf(fpw,"Interfacial Energy = %le\n",energy);
fclose(fpw);

/**Freeing the dynamically allocated memory**/
fftw_destroy_plan(planFg);
fftw_free(comp);
fftw_free(g);
fftw_destroy_plan(planF);
fftw_destroy_plan(planB);
fclose(gnu);
}
Example #17
0
/**
 * \brief Creates and initializes the working data for the plan
 * \param [in] plan Holds the data and memory for the plan.
 * \return int Error flag value
 * \sa parseFFT2Plan
 * \sa makeFFT2Plan
 * \sa execFFT2Plan
 * \sa perfFFT2Plan
 * \sa killFFT2Plan
 */
int initFFT2Plan(void *plan){
    int i,k;
    size_t M;
    int ret = make_error(ALLOC,generic_err);
    Plan *p;
    FFTdata *d = NULL;
    p = (Plan *)plan;

    #ifdef HAVE_PAPI
    int temp_event, j;
    int PAPI_Events [NUM_PAPI_EVENTS] = PAPI_COUNTERS;
    char *PAPI_units [NUM_PAPI_EVENTS] = PAPI_UNITS;
    #endif //HAVE_PAPI

    if(p){
        d = (FFTdata *)p->vptr;
        p->exec_count = 0;
        if(DO_PERF){
            perftimer_init(&p->timers, NUM_TIMERS);

            #ifdef HAVE_PAPI
            /* Initialize plan's PAPI data */
            p->PAPI_EventSet = PAPI_NULL;
            p->PAPI_Num_Events = 0;

            TEST_PAPI(PAPI_create_eventset(&p->PAPI_EventSet), PAPI_OK, MyRank, 9999, PRINT_SOME);

            //Add the desired events to the Event Set; ensure the dsired counters
            //  are on the system then add, ignore otherwise
            for(j = 0; j < TOTAL_PAPI_EVENTS && j < NUM_PAPI_EVENTS; j++){
                temp_event = PAPI_Events[j];
                if(PAPI_query_event(temp_event) == PAPI_OK){
                    p->PAPI_Num_Events++;
                    TEST_PAPI(PAPI_add_event(p->PAPI_EventSet, temp_event), PAPI_OK, MyRank, 9999, PRINT_SOME);
                }
            }

            PAPIRes_init(p->PAPI_Results, p->PAPI_Times);
            PAPI_set_units(p->name, PAPI_units, NUM_PAPI_EVENTS);

            TEST_PAPI(PAPI_start(p->PAPI_EventSet), PAPI_OK, MyRank, 9999, PRINT_SOME);
            #endif //HAVE_PAPI
        }         //DO_PERF
    }
    if(d){
        M = d->M;

        pthread_rwlock_wrlock(&FFTW_Lock);
        d->in_original = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * M * M);
        assert(d->in_original);
        d->out = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * M * M);
        assert(d->out);
        d->mid = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * M * M);
        assert(d->mid);
        if(d->in_original && d->out && d->mid){
            ret = make_error(0,specific_err);                                                   // Error in getting the plan set
        }
        d->forward = fftw_plan_dft_2d(M,M,d->in_original,d->mid,FFTW_FORWARD, FFTW_ESTIMATE);
        d->backward = fftw_plan_dft_2d(M,M,d->mid,d->out,FFTW_BACKWARD, FFTW_ESTIMATE);
        pthread_rwlock_unlock(&FFTW_Lock);
        if(d->forward && d->backward){
            ret = ERR_CLEAN;
        }

        srand(0);
        for(i = 0; i < M; i++){
            for(k = 0; k < M; k++){
                d->in_original[i * M + k][0] = rand();
                d->in_original[i * M + k][1] = rand();
            }
        }
    }
    return ret;
} /* initFFT2Plan */
Example #18
0
int main(int argc, char **argv)
{
  int err;
  // Error handling scheme: this function has failed until proven otherwise.
  int ret = EXIT_FAILURE;

  err = MPI_Init(&argc, &argv);
  if(err != MPI_SUCCESS) {
    // Theoretically, an error at this point will abort the program, and this
    // code path is never followed. This is here for completeness.
    fprintf(stderr, "unable to initialize MPI\n");
    goto die_immed;
  }

  // Install the MPI error handler that returns error codes, so we can perform
  // the usual process suicide ritual.
  err = MPI_Comm_set_errhandler(MPI_COMM_WORLD, MPI_ERRORS_RETURN);
  if(err != MPI_SUCCESS) {
    // Again, theoretically, the previous error handler (MPI_Abort) gets called
    // instead of reaching this fail point.
    fprintf(stderr, "unable to reset MPI error handler\n");
    goto die_finalize_mpi;
  }

  int size, rank;
  err = MPI_Comm_size(MPI_COMM_WORLD, &size);
  if(err == MPI_SUCCESS) err = MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  if(err != MPI_SUCCESS) {
    fprintf(stderr, "unable to determine rank or size\n");
    goto die_finalize_mpi;
  }

  /* Create cartestian communicator */
  int dims[2] = {0, 0};
  int periods[2] = {1, 1};
  err = MPI_Dims_create(size, 2, dims);
  if(err != MPI_SUCCESS) {
    fprintf(stderr, "unable to create a cartestian topology\n");
    goto die_finalize_mpi;
  }
  MPI_Comm cart;
  err = MPI_Cart_create(MPI_COMM_WORLD, 2, dims, periods, 1, &cart);
  if(err != MPI_SUCCESS) {
    fprintf(stderr, "unable to create cartestian communicator\n");
    goto die_finalize_mpi;
  }

  dsfmt_t *prng = malloc(sizeof(dsfmt_t));
  if(prng == NULL) {
    fprintf(stderr, "unable to allocate PRNG\n");
    goto die_free_cart_comm;
  }
  dsfmt_init_gen_rand(prng, SEED + rank);

  int const net_elems = proc_elems[0]*proc_elems[1];
  // Allocate master source array for FFT.
  double *const master = fftw_malloc(net_elems*sizeof(double));
  if(master == NULL) {
    fprintf(stderr, "unable to allocate master array\n");
    goto die_free_prng;
  }
  for(unsigned int i = 0; i < net_elems; ++i) {
    master[i] = dsfmt_genrand_open_close(prng) * 10;
  }

  /* Allocate source array for serial array. We copy the master array to this
   * array, then transform it in place, then reverse transform it. The idea is
   * that we should get the original data back, and we use this as a consistency
   * check. We need the original data to compare to.
   */
  double *const source = fftw_malloc(net_elems*sizeof(double));
  if(source == NULL) {
    fprintf(stderr, "unable to allocate source array\n");
    goto die_free_master;
  }
  for(int i = 0; i < net_elems; ++i) source[i] = master[i];

  /* Allocate the destination array */
  double complex *const dest = fftw_malloc(net_elems*sizeof(double complex));
  if(dest == NULL) {
    fprintf(stderr, "unable to allocate destination array\n");
    goto die_free_source;
  }

  /* Allocate a plan to compute the FFT */
  fft_par_plan plan = fft_par_plan_r2c(cart, proc_elems, 1, source,
      dest, &err);
  if(plan == NULL) {
    fprintf(stderr, "unable to initialize parallel FFT plan\n");
    goto die_free_dest;
  }

  /* Execute the forward plan */
  err = fft_par_execute_fwd(plan);
  if(err != MPI_SUCCESS) {
    fprintf(stderr, "error computing forward plan\n");
    goto die_free_plan;
  }

  /* Execute the reverse plan */
  err = fft_par_execute_rev(plan);
  if(err != MPI_SUCCESS) {
    fprintf(stderr, "error computing reverse plan\n");
    goto die_free_plan;
  }

  /* Compare source to master, use supremum norm */
  int norm = 0.0;
  for(int i = 0; i < net_elems; ++i) {
    /* Each FFT effectively multiplies by sqrt(net_elems*num_procs) */
    norm = fmax(norm, fabs(master[i] - source[i]/net_elems/size));
  }
  if(norm < 1.0e-6) {
    ret = EXIT_SUCCESS;
  }

die_free_plan:
  fft_par_plan_destroy(plan);
die_free_dest:
  fftw_free(dest);
die_free_source:
  fftw_free(source);
die_free_master:
  fftw_free(master);
die_free_prng:
  free(prng);
die_free_cart_comm:
  if(err == MPI_SUCCESS) err = MPI_Comm_free(&cart);
  if(err != MPI_SUCCESS) {
    fprintf(stderr, "unable to free cartestian communicator\n");
    ret = EXIT_FAILURE;
  }
die_finalize_mpi:
  if(err == MPI_SUCCESS) err = MPI_Finalize();
  if(err != MPI_SUCCESS) {
    fprintf(stderr, "unable to finalize MPI\n");
    ret = EXIT_FAILURE;
  }
die_immed:
  fftw_cleanup();
  return ret;
}
Example #19
0
int main(int argc, char ** argv){
	size_t i, j;
	size_t numThreads = 2;
	// FFT stuff
	int fftSize = 1024 * 4;
	int fftWinInc = fftSize / 4;
	// Portaudio stuff
	PaError paer;
	PaStream * stream;
	
	struct fftBuf ffts[numThreads];
	struct aBuf buf = {44100, fftSize, fftWinInc, 1.0, fftSize, 0, NULL, numThreads, ffts};
	
	buf.samples = fmalloc(buf.length * sizeof *buf.samples);
	for(j = 0; j < buf.length; j++) buf.samples[j] = 0.0;
	
	for(i = 0; i < numThreads; i++){
		ffts[i].fftIn = fmalloc(ffts[i].length * sizeof *ffts[i].samples);
		for(j = 0; j < ffts[i].length; j++) ffts[i].fftIn[j] = 0.0;
		ffts[i].fftOut = fftw_malloc(ffts[i].length * sizeof *ffts[i].fftOut);
		for(j = 0; j < ffts[i].length; j++){
			ffts[i].fftOut[j][0] = 0.0;
			ffts[i].fftOut[j][1] = 0.0;
		}
		
		ffts[i].panama = fftw_plan_dft_r2c_1d(buf.length, buf.fftIn, buf.fftOut, FFTW_ESTIMATE);
		
		ffts[i].mutex = PTHREAD_MUTEX_INITIALIZER;
		ffts[i].cond = PTHREAD_COND_INITIALIZER;
		
		ffts[i].info = &buf;
	}
	
	if(argc > 1 && ((buf.amplifier = strtod(argv[1], NULL)) < 1.0)){
		buf.amplifier = 1.0;
	}
	
	printf("---- ----\nInit done\n---- ----\n");
	
	printf("FFT-size: %i\nWindow-length: %f\nWindow-inc: %i\n", fftSize, (double)fftSize/(double)buf.samplerate, fftWinInc);
	
	pthread_create(&ffThread1, NULL, fftThread, &buf);
	//pthread_create(&ffThread2, NULL, fftThread, &buf);
	
	paer = Pa_Initialize();
	if(paer != paNoError){
		fprintf(stderr, "! Pa_Initialize failed: %s\n", Pa_GetErrorText(paer));
		return EXIT_FAILURE;
	}
	paer = Pa_OpenDefaultStream(&stream, 1, 0, paFloat32, buf.samplerate, fftWinInc, recordCallback, &buf);
	if(paer != paNoError){
		fprintf(stderr, "! Pa_OpenDefaultStream failed: %s\n", Pa_GetErrorText(paer));
		return EXIT_FAILURE;
	}
	paer = Pa_StartStream(stream);
	if(paer != paNoError){
		fprintf(stderr, "! Pa_StartStream failed: %s\n", Pa_GetErrorText(paer));
		return EXIT_FAILURE;
	}
	
	while(Pa_IsStreamActive(stream)) Pa_Sleep(100);
	
	Pa_CloseStream(stream);
	Pa_Terminate();
	free(buf.samples);
	free(buf.fftIn);
	fftw_free(buf.fftOut);
	fftw_destroy_plan(buf.panama);
	
	return 0;
}
Example #20
0
int main(int argc, char ** argv)
{
    int i = 0;
    int j = 0;
    int k = 0;
    int m = 0;

    double max = 0.0;
    int max_i = 0;

    int audio_fd = 0;
    unsigned char audio_buffer;

    int audio_format = AFMT_U8;
    int audio_stereo = 0; /* mono */
    int audio_speed = N;

    signal(SIGINT, interrupt_program);

    fftw_complex *in, *out;
    fftw_plan plan;

    if ( !fftw_init_threads() ) {
        printf ("Threads are not supported!\n");
        exit(1);
    }

    if ( (audio_fd = open(audio_dev, O_RDONLY, 0)) <= 0) {
        printf("Cannot open audio device: %s\n", audio_dev);
        perror(audio_dev);
        exit(1);
    }

    if ( ioctl(audio_fd, SNDCTL_DSP_SETFMT, &audio_format) == -1) {
        printf("Cannot select audio format.\n");
        perror(audio_dev);
        close(audio_fd);
        exit(1);
    }

    if ( ioctl(audio_fd, SNDCTL_DSP_STEREO, &audio_stereo) == -1) {
        printf("Mono recording not supported.\n");
        perror(audio_dev);
        close(audio_fd);
        exit(1);
    }

    if ( ioctl(audio_fd, SNDCTL_DSP_SPEED, &audio_speed) == -1) {
        printf("Cannot set speed on audio device.\n");
        perror(audio_dev);
        close(audio_fd);
        exit(1);
    }

    in = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * N);
    out = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * N);

    for ( j=0; j<N; ++j) {
        in[j][0] = 0.0;
        in[j][1] = 0.0;
    }

    fftw_plan_with_nthreads(2);

    plan = fftw_plan_dft_1d(N, in, out, FFTW_FORWARD, FFTW_ESTIMATE);

    while (running) {

        if ( read(audio_fd, &audio_buffer, 1) == -1) {
            printf("Cannot read data from soundcard.\n");
        } else {
            in[m][0] = (double) (audio_buffer-127)/255.0;

            if (m < N-1) {
                ++m;
            } else {
                for ( j=1; j < N; ++j) {
                    in[j-1][0] = in[j][0]/1.000032;
                }
            }

            k = (k+1) % 4;
        }

        if (k==3) {
            fftw_execute(plan);
            max = 0;
            max_i = 0;
            for ( i=1; i<1+N/2; ++i ) {
                double val = (2* sqrt(out[i][0] * out[i][0] +
                                      out[i][1] * out[i][1]) / N);
                if (val > max) {
                    max = val;
                    max_i = i;
                }
            }
            fprintf(stderr, "\rnote: %s (%03.5f [Hz])", get_note( (double) (2*max_i-1) / N * SPECTRUM + SPECT_LOW), (double) (2*max_i-1) / N * SPECTRUM + SPECT_LOW);
        }

    }


    fftw_destroy_plan(plan);

    fprintf(stderr, "\nbase: %f\n", sqrt(out[0][0] * out[0][0] +
                                         out[0][1]
                                         * out[0][1]) /SPECTRUM );
    /*
        for ( i=1; i<1+N/2; ++i ) {
            double val = (2* sqrt(out[i][0] * out[i][0] +
                                      out[i][1] * out[i][1]) / N);
            if (val > max) {
                max = val;
                max_i = i;
            }
            printf("%f %f\n", (double) (2*i-1) / N * SPECTRUM + SPECT_LOW,
                                     val );
        }
    */
    fprintf(stderr, "note: %s\n", get_note( (double) (2*max_i-1) / N * SPECTRUM + SPECT_LOW));
//    fprintf(stderr, "Max: %f [Hz] = %f\n", (double) (2*max_i-1) / N * SPECTRUM + SPECT_LOW, max);

    fftw_free(in);
    fftw_free(out);

    fftw_cleanup_threads();

    close(audio_fd);

    return 0;
}
Example #21
0
void
Wavelet::WaveletReadJason(const std::string & fileName,
                          int               & errCode,
                          fftw_real        *& rAmp,
                          fftw_complex     *& cAmp,
                          float             & dz,
                          int               & nz,
                          int               & cz,
                          int               & nzp,
                          int               & cnzp,
                          int               & rnzp,
                          float             & norm,
                          std::string       & errText) const
{
  assert(rAmp_ == NULL && cAmp_ == NULL);
  std::ifstream file;
  NRLib::OpenRead(file,fileName);
  std::string dummyStr;

  bool lineIsComment = true;
  int  line          = 0;
  int  thisLine      = 0;

  while( lineIsComment == true) {
    if(NRLib::CheckEndOfFile(file)) {
      errText += "Error: End of file "+fileName+" premature.\n";
      errCode=1;
      return;
    }

    NRLib::ReadNextToken(file,dummyStr,line);
    if (line == thisLine)
      NRLib::DiscardRestOfLine(file,line,false);
    thisLine = line;
    if((dummyStr[0]!='*') &  (dummyStr[0]!='"')) {
      lineIsComment = false;
    }
  }

  float shift = NRLib::ParseType<float>(dummyStr);

  if (NRLib::CheckEndOfFile(file))  {
    errText += "Error: End of file "+fileName+" premature.\n";
    errCode=1;
    return;
  }
  NRLib::ReadNextToken(file,dummyStr,line);
  if (line == thisLine)
    NRLib::DiscardRestOfLine(file,line,false);
  thisLine = line;

  dz  = NRLib::ParseType<float>(dummyStr);

  if (NRLib::CheckEndOfFile(file)) {
    errText += "Error: End of file "+fileName+" premature.\n";
    errCode=1;
    return;
  }
  NRLib::ReadNextToken(file,dummyStr,line);
  if (line == thisLine)
    NRLib::DiscardRestOfLine(file,line,false);
  thisLine = line;

  nz   = NRLib::ParseType<int>(dummyStr);
  nzp  = nz_;
  cnzp = nzp_/2+1;
  rnzp = 2*cnzp_;
  rAmp = static_cast<fftw_real*>(fftw_malloc(sizeof(float)*rnzp_));
  cAmp = reinterpret_cast<fftw_complex*>(rAmp);
  norm = RMISSING;

  int cz_file = static_cast<int>(floor((fabs(shift/dz_))+0.5));
  cz          = nz_ - cz_file; //Wavelets are flipped

  rAmp[0] = 0.0f;
  for(int i=0; i<nz_;i++) {
    if (NRLib::CheckEndOfFile(file)) {
      errText += "Error: End of file "+fileName+" premature.\n";
      errCode=1;
      return;
    }
    NRLib::ReadNextToken(file,dummyStr,line);
    //
    // The wavelet fill in starts at i=1 and rAmp[0] is set to zero.
    //
    // If the fill in starts at 0, a wavelet read from file gets an incorrect
    // shift of one sample. This is particular evident if a Ricker wavelet
    // read from file is compared the the wavelet given as output.
    //
    rAmp[nz_ - i] = NRLib::ParseType<float>(dummyStr); //Flip wavelet
  }
  file.close();
}
Example #22
0
void power_spectrum_init() {
	Pk_M = (double *) fftw_malloc(NUM_BINS * sizeof(double));
	k_M = (double *) fftw_malloc(NUM_BINS * sizeof(double));
	av = (int *) fftw_malloc(NUM_BINS * sizeof(int));
	F_rho = (fftw_complex*) fftw_malloc(fft_size * sizeof(fftw_complex));
}
Example #23
0
int
main (int   argc,
      char *argv[])
{
  if (argc != 1)
  {
    printf ("%s < input > output\n", argv[0]);
    printf ("input [0, %d): bytes per sample\n", (int) sizeof (int));
    printf ("input [%d, %d): number of samples\n", (int) sizeof (int), (int) (2 * sizeof (int)));
    printf ("input [%d, ...): samples\n", (int) (2 * sizeof (int)));
    printf ("output [0, %d): number of complex coefficients\n", (int) sizeof (int));
    printf ("output [%d, ...): complex coefficients\n", (int) sizeof (int));

    return 0;
  }

  int size;
  int length;

  fread (&size,   sizeof (size),   1, stdin);
  fread (&length, sizeof (length), 1, stdin);

  double       *input  = fftw_malloc (length * sizeof (double));
  fftw_complex *output = fftw_malloc ((length / 2 + 1) * sizeof (fftw_complex));

  if (size == 4)
  {
    float sample;

    int i;

    for (i = 0; i < length; i++)
    {
      fread (&sample, size, 1, stdin);

      input[i] = window (length, i) * sample;
    }
  }
  else if (size == 8)
  {
    double sample;

    int i;

    for (i = 0; i < length; i++)
    {
      fread (&sample, size, 1, stdin);

      input[i] = window (length, i) * sample;
    }
  }

  unsigned int flags = FFTW_ESTIMATE | FFTW_DESTROY_INPUT;
  fftw_plan plan = fftw_plan_dft_r2c_1d (length, input, output, flags);

  fftw_execute (plan);

  length = length / 2 + 1;

  fwrite (&length, sizeof (length), 1, stdout);
  fwrite (output, sizeof (fftw_complex), length, stdout);

  fftw_destroy_plan (plan);
  fftw_free (input);
  fftw_free (output);

  return 0;
}
Example #24
0
bool FFT::convolve(float* source, float* kernel, int xSource, int ySource, int xKernel, int yKernel)
{
  int x, y, index;
  
  // get normalization params
  float maxCurrent = 0.0f;
  for (x = 0; x < xSource * ySource; x++)
    maxCurrent = (maxCurrent < source[x]) ? source[x] : maxCurrent;
  float maxKernel = 0.0f;
  for (x = 0; x < xKernel * yKernel; x++)
    maxKernel = (maxKernel < kernel[x]) ? kernel[x] : maxKernel;
  float maxProduct = maxCurrent * maxKernel;
 
  // retrieve dimensions
  int xHalf = xKernel / 2;
  int yHalf = yKernel / 2;
  int xResPadded = xSource + xKernel;
  int yResPadded = ySource + yKernel;

  if (xResPadded != yResPadded)
    (xResPadded > yResPadded) ? yResPadded = xResPadded : xResPadded = yResPadded;

  // create padded field
  fftw_complex* padded = (fftw_complex*)fftw_malloc(sizeof(fftw_complex) * xResPadded * yResPadded);
  if (!padded)
  {
    cout << " IMAGE: Not enough memory! Try a smaller final image size." << endl;
    return false;
  }
 
  // init padded field
  for (index = 0; index < xResPadded * yResPadded; index++)
    padded[index][0] = padded[index][1] = 0.0f;
  index = 0;
  for (y = 0; y < ySource; y++)
    for (x = 0; x < xSource; x++, index++)
    {
      int paddedIndex = (x + xKernel / 2) + (y + yKernel / 2) * xResPadded;
      padded[paddedIndex][0] = source[index];
    }

  // create padded filter
  fftw_complex* filter = (fftw_complex*)fftw_malloc(sizeof(fftw_complex) * xResPadded * yResPadded);
  if (!filter)
  {
    cout << " FILTER: Not enough memory! Try a smaller final image size." << endl;
    return false;
  }

  // init padded filter
  for (index = 0; index < xResPadded * yResPadded; index++)
    filter[index][0] = filter[index][1] = 0.0f;
  
  // quadrant IV
  for (y = 0; y < (yHalf + 1); y++)
    for (x = 0; x < (xHalf + 1); x++)
    {
      int filterIndex = x + xHalf + y * xKernel;
      int fieldIndex = x + (y + yResPadded - (yHalf + 1)) * xResPadded;
      filter[fieldIndex][0] = kernel[filterIndex];
    }

  // quadrant I
  for (y = 0; y < yHalf; y++)
    for (x = 0; x < (xHalf + 1); x++)
    {
      int filterIndex = (x + xHalf) + (y + yHalf + 1) * xKernel;
      int fieldIndex = x + y * xResPadded;
      filter[fieldIndex][0] = filter[fieldIndex][1] = kernel[filterIndex];
    }
  
  // quadrant III
  for (y = 0; y < (yHalf + 1); y++)
    for (x = 0; x < xHalf; x++)
    {
      int filterIndex = x + y * xKernel;
      int fieldIndex = (x + xResPadded - xHalf) + (y + yResPadded - (yHalf + 1)) * xResPadded;
      filter[fieldIndex][0] = filter[fieldIndex][1] = kernel[filterIndex];
    }

  // quadrant II
  for (y = 0; y < yHalf; y++)
    for (x = 0; x < xHalf; x++)
    {
      int filterIndex = x + (y + yHalf + 1) * xKernel;
      int fieldIndex = (x + xResPadded - xHalf) + y * xResPadded;
      filter[fieldIndex][0] = filter[fieldIndex][1] = kernel[filterIndex];
    }
  
  // perform forward FFT on field
  fftw_complex* paddedTransformed = (fftw_complex*)fftw_malloc(sizeof(fftw_complex) * xResPadded * yResPadded);
  if (!paddedTransformed)
  {
    cout << " T-IMAGE: Not enough memory! Try a smaller final image size." << endl;
    return false;
  }
  fftw_plan forwardField = fftw_plan_dft_2d(xResPadded, yResPadded, padded, paddedTransformed, FFTW_FORWARD, FFTW_ESTIMATE);  
  fftw_execute(forwardField);

  // perform forward FFT on filter
  fftw_complex* filterTransformed = (fftw_complex*)fftw_malloc(sizeof(fftw_complex) * xResPadded * yResPadded);
  if (!filterTransformed)
  {
    cout << " T-FILTER: Not enough memory! Try a smaller final image size." << endl;
    return false;
  }
  fftw_plan forwardFilter = fftw_plan_dft_2d(xResPadded, yResPadded, filter, filterTransformed, FFTW_FORWARD, FFTW_ESTIMATE);  
  fftw_execute(forwardFilter);

  // apply frequency space filter
  for (index = 0; index < xResPadded * yResPadded; index++)
  {
    float newReal = paddedTransformed[index][0] * filterTransformed[index][0] - 
                    paddedTransformed[index][1] * filterTransformed[index][1];
    float newIm   = paddedTransformed[index][0] * filterTransformed[index][1] + 
                    paddedTransformed[index][1] * filterTransformed[index][0];
    paddedTransformed[index][0] = newReal;
    paddedTransformed[index][1] = newIm;
  }
   
  // transform back
  fftw_plan backwardField = fftw_plan_dft_2d(xResPadded, yResPadded, paddedTransformed, padded, FFTW_BACKWARD, FFTW_ESTIMATE);  
  fftw_execute(backwardField);
  
  // copy back into padded
  index = 0;
  for (y = 0; y < ySource; y++)
    for (x = 0; x < xSource; x++, index++)
    {
      int paddedIndex = (x + xKernel / 2) + (y + yKernel / 2) * xResPadded;
      source[index] = padded[paddedIndex][0];
    }

  // clean up
  fftw_free(padded);
  fftw_free(paddedTransformed);
  fftw_free(filter);
  fftw_free(filterTransformed);

  // if normalization is exceeded, renormalize
  float newMax = 0.0f;
  for (x = 0; x < xSource * ySource; x++)
    newMax = (newMax < source[x]) ? source[x] : newMax;
  if (newMax > maxProduct)
  {
    float scale = maxProduct / newMax;
    for (x = 0; x < xSource * ySource; x++)
      source[x] *= scale;
  }

  return true;
}
Example #25
0
/*
 * Create an fftwnd_plan specialized for specific arrays.  (These
 * arrays are ignored, however, if they are NULL or if the flags do
 * not include FFTW_MEASURE.)  The main advantage of being provided
 * arrays like this is that we can do runtime timing measurements of
 * our options, without worrying about allocating excessive scratch
 * space.
 */
fftwnd_plan fftwnd_create_plan_specific(int rank, const int *n,
					fftw_direction dir, int flags,
					fftw_complex *in, int istride,
					fftw_complex *out, int ostride)
{
     fftwnd_plan p;

     if (!(p = fftwnd_create_plan_aux(rank, n, dir, flags)))
	  return 0;

     if (!(flags & FFTW_MEASURE) || in == 0
	 || (!p->is_in_place && out == 0)) {

/**** use default plan ****/

	  p->plans = fftwnd_create_plans_generic(fftwnd_new_plan_array(rank),
						 rank, n, dir, flags);
	  if (!p->plans) {
	       fftwnd_destroy_plan(p);
	       return 0;
	  }
	  if (flags & FFTWND_FORCE_BUFFERED)
	       p->nbuffers = FFTWND_NBUFFERS;
	  else
	       p->nbuffers = FFTWND_DEFAULT_NBUFFERS;

	  p->nwork = fftwnd_work_size(rank, n, flags, p->nbuffers + 1);
	  if (p->nwork && !(flags & FFTW_THREADSAFE)) {
	       p->work = (fftw_complex*) fftw_malloc(p->nwork 
						     * sizeof(fftw_complex));
	       if (!p->work) {
		    fftwnd_destroy_plan(p);
		    return 0;
	       }
	  }
     } else {
/**** use runtime measurements to pick plan ****/

	  fftw_plan *plans_buf, *plans_nobuf;
	  double t_buf, t_nobuf;

	  p->nwork = fftwnd_work_size(rank, n, flags, FFTWND_NBUFFERS + 1);
	  if (p->nwork && !(flags & FFTW_THREADSAFE)) {
	       p->work = (fftw_complex*) fftw_malloc(p->nwork 
						     * sizeof(fftw_complex));
	       if (!p->work) {
		    fftwnd_destroy_plan(p);
		    return 0;
	       }
	  }
	  else
	       p->work = (fftw_complex*) NULL;

	  /* two possible sets of 1D plans: */
	  plans_buf = fftwnd_create_plans_generic(fftwnd_new_plan_array(rank),
						  rank, n, dir, flags);
	  plans_nobuf = 
	       fftwnd_create_plans_specific(fftwnd_new_plan_array(rank),
					    rank, n, p->n_after, dir,
					    flags, in, istride,
					    out, ostride);
	  if (!plans_buf || !plans_nobuf) {
	       destroy_plan_array(rank, plans_nobuf);
	       destroy_plan_array(rank, plans_buf);
	       fftwnd_destroy_plan(p);
	       return 0;
	  }
	  /* time the two possible plans */
	  p->plans = plans_nobuf;
	  p->nbuffers = 0;
	  p->nwork = fftwnd_work_size(rank, n, flags, p->nbuffers + 1);
	  t_nobuf = fftwnd_measure_runtime(p, in, istride, out, ostride);
	  p->plans = plans_buf;
	  p->nbuffers = FFTWND_NBUFFERS;
	  p->nwork = fftwnd_work_size(rank, n, flags, p->nbuffers + 1);
	  t_buf = fftwnd_measure_runtime(p, in, istride, out, ostride);

	  /* pick the better one: */
	  if (t_nobuf < t_buf) {	/* use unbuffered transform */
	       p->plans = plans_nobuf;
	       p->nbuffers = 0;

	       /* work array is unnecessarily large */
	       if (p->work)
		    fftw_free(p->work);
	       p->work = 0;

	       destroy_plan_array(rank, plans_buf);

	       /* allocate a work array of the correct size: */
	       p->nwork = fftwnd_work_size(rank, n, flags, p->nbuffers + 1);
	       if (p->nwork && !(flags & FFTW_THREADSAFE)) {
		    p->work = (fftw_complex*) fftw_malloc(p->nwork 
						       * sizeof(fftw_complex));
		    if (!p->work) {
			 fftwnd_destroy_plan(p);
			 return 0;
		    }
	       }
	  } else {		/* use buffered transform */
	       destroy_plan_array(rank, plans_nobuf);
	  }
     }

     return p;
}
Example #26
0
/**
 * Allocates aligned memory to enable SIMD
 * @param size Allocation size in Bytes
 */
void* accfft_alloc(ptrdiff_t size) {
	void * ptr = fftw_malloc(size);
	return ptr;
}
Example #27
0
PetscInt main(PetscInt argc,char **args)
{
  ptrdiff_t      N0=256,N1=256,N2=256,N3=2,dim[4];
  fftw_plan      bplan,fplan;
  fftw_complex   *out;
  double         *in1,*in2;
  ptrdiff_t      alloc_local,local_n0,local_0_start;
  ptrdiff_t      local_n1,local_1_start;
  PetscInt       i,j,indx,n1;
  PetscInt       size,rank,n,N,*in,N_factor,NM;
  PetscScalar    *data_fin,value1,one=1.57,zero=0.0;
  PetscScalar    a,*x_arr,*y_arr,*z_arr,enorm;
  Vec            fin,fout,fout1,ini,final;
  PetscRandom    rnd;
  PetscErrorCode ierr;
  VecScatter     vecscat,vecscat1;
  IS             indx1,indx2;
  PetscInt       *indx3,k,l,*indx4;
  PetscInt       low,tempindx,tempindx1;


  ierr = PetscInitialize(&argc,&args,(char*)0,help);CHKERRQ(ierr);
#if defined(PETSC_USE_COMPLEX)
  SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_SUP, "This example requires real numbers. Your current scalar type is complex");
#endif
  ierr = MPI_Comm_size(PETSC_COMM_WORLD, &size);CHKERRQ(ierr);
  ierr = MPI_Comm_rank(PETSC_COMM_WORLD, &rank);CHKERRQ(ierr);

  PetscRandomCreate(PETSC_COMM_WORLD,&rnd);


  alloc_local = fftw_mpi_local_size_3d_transposed(N0,N1,N2/2+1,PETSC_COMM_WORLD,&local_n0,&local_0_start,&local_n1,&local_1_start);

/*    printf("The value alloc_local is %ld from process %d\n",alloc_local,rank);     */
  printf("The value local_n0 is %ld from process %d\n",local_n0,rank);
/*    printf("The value local_0_start is  %ld from process %d\n",local_0_start,rank);*/
/*    printf("The value local_n1 is  %ld from process %d\n",local_n1,rank);          */
/*    printf("The value local_1_start is  %ld from process %d\n",local_1_start,rank);*/

  /* Allocate space for input and output arrays  */

  in1=(double*)fftw_malloc(sizeof(double)*alloc_local*2);
  in2=(double*)fftw_malloc(sizeof(double)*alloc_local*2);
  out=(fftw_complex*)fftw_malloc(sizeof(fftw_complex)*alloc_local);


  N=2*N0*N1*(N2/2+1);N_factor=N0*N1*N2;
  n=2*local_n0*N1*(N2/2+1);n1=local_n1*N0*2*N1;

/*    printf("The value N is  %d from process %d\n",N,rank);   */
/*    printf("The value n is  %d from process %d\n",n,rank);   */
/*    printf("The value n1 is  %d from process %d\n",n1,rank); */
  /* Creating data vector and accompanying array with VeccreateMPIWithArray */
  ierr = VecCreateMPIWithArray(PETSC_COMM_WORLD,1,n,N,(PetscScalar*)in1,&fin);CHKERRQ(ierr);
  ierr = VecCreateMPIWithArray(PETSC_COMM_WORLD,1,n,N,(PetscScalar*)out,&fout);CHKERRQ(ierr);
  ierr = VecCreateMPIWithArray(PETSC_COMM_WORLD,1,n,N,(PetscScalar*)in2,&fout1);CHKERRQ(ierr);

/*    VecGetSize(fin,&size); */
/*    printf("The size is %d\n",size); */

  VecSet(fin,one);
  VecSet(fout,zero);
  VecSet(fout1,zero);

  VecAssemblyBegin(fin);
  VecAssemblyEnd(fin);
/*    VecView(fin,PETSC_VIEWER_STDOUT_WORLD); */


  VecGetArray(fin,&x_arr);
  VecGetArray(fout1,&z_arr);
  VecGetArray(fout,&y_arr);

  fplan=fftw_mpi_plan_dft_r2c_3d(N0,N1,N2,(double*)x_arr,(fftw_complex*)y_arr,PETSC_COMM_WORLD,FFTW_ESTIMATE);
  bplan=fftw_mpi_plan_dft_c2r_3d(N0,N1,N2,(fftw_complex*)y_arr,(double*)z_arr,PETSC_COMM_WORLD,FFTW_ESTIMATE);

  fftw_execute(fplan);
  fftw_execute(bplan);

  VecRestoreArray(fin,&x_arr);
  VecRestoreArray(fout1,&z_arr);
  VecRestoreArray(fout,&y_arr);


/*    a = 1.0/(PetscReal)N_factor; */
/*    ierr = VecScale(fout1,a);CHKERRQ(ierr); */
  VecCreate(PETSC_COMM_WORLD,&ini);
  VecCreate(PETSC_COMM_WORLD,&final);
  VecSetSizes(ini,local_n0*N1*N2,N_factor);
  VecSetSizes(final,local_n0*N1*N2,N_factor);
/*    VecSetSizes(ini,PETSC_DECIDE,N_factor); */
/*    VecSetSizes(final,PETSC_DECIDE,N_factor); */
  VecSetFromOptions(ini);
  VecSetFromOptions(final);

  if (N2%2==0) NM=N2+2;
  else NM=N2+1;

  ierr = VecGetOwnershipRange(fin,&low,NULL);
  printf("The local index is %d from %d\n",low,rank);
  ierr = PetscMalloc(sizeof(PetscInt)*local_n0*N1*N2,&indx3);
  ierr = PetscMalloc(sizeof(PetscInt)*local_n0*N1*N2,&indx4);
  for (i=0; i<local_n0; i++) {
    for (j=0;j<N1;j++) {
      for (k=0;k<N2;k++) {
        tempindx  = i*N1*N2 + j*N2 + k;
        tempindx1 = i*N1*NM + j*NM + k;

        indx3[tempindx]=local_0_start*N1*N2+tempindx;
        indx4[tempindx]=low+tempindx1;
      }
      /*          printf("index3 %d from proc %d is \n",indx3[tempindx],rank); */
      /*          printf("index4 %d from proc %d is \n",indx4[tempindx],rank); */
    }
  }
  VecGetValues(fin,local_n0*N1*N2,indx4,x_arr);
  VecSetValues(ini,local_n0*N1*N2,indx3,x_arr,INSERT_VALUES);
  VecAssemblyBegin(ini);
  VecAssemblyEnd(ini);

  VecGetValues(fout1,local_n0*N1*N2,indx4,y_arr);
  VecSetValues(final,local_n0*N1*N2,indx3,y_arr,INSERT_VALUES);
  VecAssemblyBegin(final);
  VecAssemblyEnd(final);

  printf("The local index value is %ld from %d",local_n0*N1*N2,rank);
/*
  for (i=0;i<N0;i++) {
     for (j=0;j<N1;j++) {
        indx=i*N1*NM+j*NM;
        ISCreateStride(PETSC_COMM_WORLD,N2,indx,1,&indx1);
        indx=i*N1*N2+j*N2;
        ISCreateStride(PETSC_COMM_WORLD,N2,indx,1,&indx2);
        VecScatterCreate(fin,indx1,ini,indx2,&vecscat);
        VecScatterBegin(vecscat,fin,ini,INSERT_VALUES,SCATTER_FORWARD);
        VecScatterEnd(vecscat,fin,ini,INSERT_VALUES,SCATTER_FORWARD);
        VecScatterCreate(fout1,indx1,final,indx2,&vecscat1);
        VecScatterBegin(vecscat1,fout1,final,INSERT_VALUES,SCATTER_FORWARD);
        VecScatterEnd(vecscat1,fout1,final,INSERT_VALUES,SCATTER_FORWARD);
     }
  }
*/
  a    = 1.0/(PetscReal)N_factor;
  ierr = VecScale(fout1,a);CHKERRQ(ierr);
  ierr = VecScale(final,a);CHKERRQ(ierr);

  VecAssemblyBegin(ini);
  VecAssemblyEnd(ini);

  VecAssemblyBegin(final);
  VecAssemblyEnd(final);

/*    VecView(final,PETSC_VIEWER_STDOUT_WORLD); */
  ierr = VecAXPY(final,-1.0,ini);CHKERRQ(ierr);
  ierr = VecNorm(final,NORM_1,&enorm);CHKERRQ(ierr);
  ierr = PetscPrintf(PETSC_COMM_WORLD,"  Error norm of |x - z|  = %e\n",enorm);CHKERRQ(ierr);
  fftw_destroy_plan(fplan);
  fftw_destroy_plan(bplan);
  fftw_free(in1); ierr = VecDestroy(&fin);CHKERRQ(ierr);
  fftw_free(out); ierr = VecDestroy(&fout);CHKERRQ(ierr);
  fftw_free(in2); ierr = VecDestroy(&fout1);CHKERRQ(ierr);

  ierr = PetscFinalize();
  return 0;
}
int main()
{
	const unsigned int J = 32;
	const unsigned int M = 32;
	const double L = 12;
	const double R = 7.5;

	const double dt = 0.001;

	// vanishing external magnetic field
	const double Bext[3] = { 0, 0, 0 };

	unsigned int i, j, k;
	int hr;

	// enable run-time memory check for debug builds
	#if defined(_WIN32) & (defined(DEBUG) | defined(_DEBUG))
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
	#endif

	// load data from disk
	wignerV_t *W = fftw_malloc(sizeof(wignerV_t));
	for (i = 0; i < 4; i++)
	{
		char fnmame[1024];
		sprintf(fnmame, "../test/data/W%d.dat", i);
		V_RETURN(ReadData(fnmame, &W->comp[i], sizeof(double), sizeof(W->comp[i]) / sizeof(double)));
	}

	// Fourier transform
	wignerF_t *WF = fftw_malloc(sizeof(wignerF_t));

	// FFT of real data fills half the resulting complex array only
	cgrid_t *WFh = fftw_malloc(sizeof(cgrid_t));
	const double scale = 1.0 / (N_GRID * N_GRID);
	for (i = 0; i < 4; i++)
	{
		fftw_plan plan = fftw_plan_dft_r2c_2d(N_GRID, N_GRID, W->comp[i].data, WFh->data, FFTW_ESTIMATE);
		fftw_execute(plan);
		fftw_destroy_plan(plan);

		for (k = 0; k < N_GRID*(N_GRID/2+1); k++)
		{
			WFh->data[k][0] *= scale;
			WFh->data[k][1] *= scale;
		}

		// copy entries to fill complete complex array
		// FFTW uses row-major ordering
		for (j = 0; j < N_GRID; j++)
		{
			// complementary index
			unsigned int jc = (N_GRID - j) & N_MASK;

			for (k = 0; k <= N_GRID/2; k++)
			{
				WF->comp[i].data[N_GRID*j+k][0] = WFh->data[(N_GRID/2+1)*j+k][0];
				WF->comp[i].data[N_GRID*j+k][1] = WFh->data[(N_GRID/2+1)*j+k][1];
			}
			for (k = N_GRID/2 + 1; k < N_GRID; k++)
			{
				// complementary index
				unsigned int kc = N_GRID - k;
				// copy conjugate value
				WF->comp[i].data[N_GRID*j+k][0] =  WFh->data[(N_GRID/2+1)*jc+kc][0];
				WF->comp[i].data[N_GRID*j+k][1] = -WFh->data[(N_GRID/2+1)*jc+kc][1];
			}
		}
	}
	fftw_free(WFh);

	// quadrature rules
	quadI1_t quadI1;
	quadI2_t quadI2;
	quadI3_t quadI3;
	quadI1_t quadI4;
	FourierI1(J, L, R, &quadI1);
	FourierI2(J, L, R, &quadI2);
	FourierI3(J, L, R, M, &quadI3);
	FourierI4(J, L, R, &quadI4);

	// intermediate data
	collisionInterm_t interm;
	CollisionInterm_Create(&interm);

	wignerF_t *WFnext     = fftw_malloc(sizeof(wignerF_t));
	wignerF_t *WFnext_ref = fftw_malloc(sizeof(wignerF_t));

	printf("simulating a collision time step...\n");

	// start timer
	clock_t t_start = clock();

	// collision time step
	CollisionStep(WF, &quadI1, &quadI2, &quadI3, &quadI4, dt, Bext, &interm, WFnext);

	clock_t t_end = clock();
	double cpu_time = (double)(t_end - t_start) / CLOCKS_PER_SEC;
	printf("finished calculation, CPU time: %g\n\n", cpu_time);

	// example
	printf("example:\n");
	printf("WFnext->comp[0].data[5]: %g + %gi\n", WFnext->comp[0].data[5][0], WFnext->comp[0].data[5][1]);
	printf("WFnext->comp[1].data[5]: %g + %gi\n", WFnext->comp[1].data[5][0], WFnext->comp[1].data[5][1]);

	// load reference data from disk
	for (i = 0; i < 4; i++)
	{
		char fnmame[1024];
		sprintf(fnmame, "../test/data/WFnext%d_ref.dat", i);
		V_RETURN(ReadData(fnmame, &WFnext_ref->comp[i], sizeof(fftw_complex), sizeof(WFnext_ref->comp[i]) / sizeof(fftw_complex)));
	}
	printf("WFnext_ref->comp[0].data[5]: %g + %gi\n", WFnext_ref->comp[0].data[5][0], WFnext_ref->comp[0].data[5][1]);
	printf("WFnext_ref->comp[1].data[5]: %g + %gi\n", WFnext_ref->comp[1].data[5][0], WFnext_ref->comp[1].data[5][1]);

	// compare with reference
	double err = 0;
	double nrf = 0;
	for (i = 0; i < 4; i++)
	{
		for (k = 0; k < N_GRID*N_GRID; k++)
		{
			fftw_complex diff;
			Complex_Subtract(WFnext->comp[i].data[k], WFnext_ref->comp[i].data[k], diff);
			err += Complex_Abs(diff);
			nrf += Complex_Abs(WFnext_ref->comp[i].data[k]);
		}
	}
	printf("\ncumulative error: %g, relative error: %g\n", err, err / nrf);

	// clean up
	fftw_free(WFnext_ref);
	fftw_free(WFnext);
	CollisionInterm_Delete(&interm);
	QuadI1_Delete(&quadI4);
	QuadI3_Delete(&quadI3);
	QuadI2_Delete(&quadI2);
	QuadI1_Delete(&quadI1);
	fftw_free(WF);
	fftw_free(W);

	fftw_cleanup();

	return 0;
}
/*
 * get phase correlation from two images and save result to the third image
 */
void phase_correlation( IplImage *ref, IplImage *tpl, IplImage *poc )
{
	int 	i, j, k;
	double	tmp;
	
	/* get image properties */
	int width  	 = ref->width;
	int height   = ref->height;
	int step     = ref->widthStep;
	int fft_size = width * height;

	/* setup pointers to images */
	uchar 	*ref_data = ( uchar* ) ref->imageData;
	uchar 	*tpl_data = ( uchar* ) tpl->imageData;
	double 	*poc_data = ( double* )poc->imageData;
	
	/* allocate FFTW input and output arrays */
	fftw_complex *img1 = ( fftw_complex* )fftw_malloc( sizeof( fftw_complex ) * width * height );
	fftw_complex *img2 = ( fftw_complex* )fftw_malloc( sizeof( fftw_complex ) * width * height );
	fftw_complex *res  = ( fftw_complex* )fftw_malloc( sizeof( fftw_complex ) * width * height );	
	
	/* setup FFTW plans */
	fftw_plan fft_img1 = fftw_plan_dft_1d( width * height, img1, img1, FFTW_FORWARD,  FFTW_ESTIMATE );
	fftw_plan fft_img2 = fftw_plan_dft_1d( width * height, img2, img2, FFTW_FORWARD,  FFTW_ESTIMATE );
	fftw_plan ifft_res = fftw_plan_dft_1d( width * height, res,  res,  FFTW_BACKWARD, FFTW_ESTIMATE );
	
	/* load images' data to FFTW input */
	for( i = 0, k = 0 ; i < height ; i++ ) {
		for( j = 0 ; j < width ; j++, k++ ) {
			img1[k][0] = ( double )ref_data[i * step + j];
			img1[k][1] = 0.0;
			
			img2[k][0] = ( double )tpl_data[i * step + j];
			img2[k][1] = 0.0;
		}
	}
	
	/* obtain the FFT of img1 */
	fftw_execute( fft_img1 );
	
	/* obtain the FFT of img2 */
	fftw_execute( fft_img2 );
	
	/* obtain the cross power spectrum */
	for( i = 0; i < fft_size ; i++ ) {
		res[i][0] = ( img2[i][0] * img1[i][0] ) - ( img2[i][1] * ( -img1[i][1] ) );
		res[i][1] = ( img2[i][0] * ( -img1[i][1] ) ) + ( img2[i][1] * img1[i][0] );

		tmp = sqrt( pow( res[i][0], 2.0 ) + pow( res[i][1], 2.0 ) );

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

	/* obtain the phase correlation array */
	fftw_execute(ifft_res);

	/* normalize and copy to result image */
	for( i = 0 ; i < fft_size ; i++ ) {
        poc_data[i] = res[i][0] / ( double )fft_size;
	}

	/* deallocate FFTW arrays and plans */
	fftw_destroy_plan( fft_img1 );
	fftw_destroy_plan( fft_img2 );
	fftw_destroy_plan( ifft_res );
	fftw_free( img1 );
	fftw_free( img2 );
	fftw_free( res );	
}
Example #30
0
int main (int argc, char **argv)
{
	extern char *optarg;
	int	errflg = 0;
	int	c;
	int	help = 0;
	int	flag = 0;

	/* MBIO status variables */
	int	status = MB_SUCCESS;
	int	verbose = 0;
	int	error = MB_ERROR_NO_ERROR;
	char	*message;

	/* segy data */
	char	segyfile[MB_PATH_MAXLINE];
	void	*mbsegyioptr;
	struct mb_segyasciiheader_struct asciiheader;
	struct mb_segyfileheader_struct fileheader;
	struct mb_segytraceheader_struct traceheader;
	float	*trace = NULL;
	float	*worktrace = NULL;
	double	*spsd = NULL;
	double	*wpsd = NULL;
	double	*spsdtot = NULL;
	double	*wpsdtot = NULL;
	
	/* fft controls */
	int		nfft = 1024;
	fftw_plan 	plan;
	fftw_complex	*fftw_in = NULL;
	fftw_complex	*fftw_out = NULL;
	int		nsection;

	/* grid controls */
	char	fileroot[MB_PATH_MAXLINE];
	char	gridfile[MB_PATH_MAXLINE];
	char	psdfile[MB_PATH_MAXLINE];
	int	decimatex = 1;
	int	tracemode = MBSEGYPSD_USESHOT;
	int	tracestart = 0;
	int	traceend = 0;
	int	chanstart = 0;
	int	chanend = -1;
	double	timesweep = 0.0;
	double	timedelay = 0.0;
	double	sampleinterval = 0.0;
	int	windowmode = MBSEGYPSD_WINDOW_OFF;
	double	windowstart, windowend;
	int	ntraces;
	int	ngridx = 0;
	int	ngridy = 0;
	int	ngridxy = 0;
	float	*grid = NULL;
	double	xmin;
	double	xmax;
	double	ymin;
	double	ymax;
	double	dx;
	double	dy;
	double	gridmintot = 0.0;
	double	gridmaxtot = 0.0;
	char	projection[MB_PATH_MAXLINE];
	char	xlabel[MB_PATH_MAXLINE];
	char	ylabel[MB_PATH_MAXLINE];
	char	zlabel[MB_PATH_MAXLINE];
	char	title[MB_PATH_MAXLINE];
	char	plot_cmd[MB_PATH_MAXLINE];
	int	scale2distance = MB_NO;
	double	shotscale = 1.0;
	double	frequencyscale = 1.0;
	int	logscale = MB_NO;

	int	sinftracemode = MBSEGYPSD_USESHOT;
	int	sinftracestart = 0;
	int	sinftraceend = 0;
	int	sinfchanstart = 0;
	int	sinfchanend = -1;
	double	sinftimesweep = 0.0;
	double	sinftimedelay = 0.0;
	
	double	soundpressurelevel;
	
	double	sint, taper;
	double	norm, normraw, normtaper, normfft;

	FILE	*fp;
	int	nread;
	int	tracecount, tracenum, channum, traceok;
	double	tracemin, tracemax;
	double	xwidth, ywidth;
	int	ix, iy, iys;
	int	itstart, itend;
	double	factor, btime, stime, dtime;
	double	btimesave = 0.0;
	double	stimesave = 0.0;
	double	dtimesave = 0.0;
	int	plot_status;
	int	kstart, kend;
	int	i, j, k, n;

	/* set file to null */
	segyfile[0] = '\0';

	/* get NaN value */
	GMT_make_fnan(NaN);

	/* process argument list */
	while ((c = getopt(argc, argv, "A:a:D:d:I:i:LlN:n:O:o:PpS:s:T:t:VvW:w:Hh")) != -1)
	  switch (c) 
		{
		case 'H':
		case 'h':
			help++;
			break;
		case 'V':
		case 'v':
			verbose++;
			break;
		case 'A':
		case 'a':
			n = sscanf (optarg,"%lf/%lf", &shotscale, &frequencyscale);
			if (n == 2)
				scale2distance = MB_YES;
			flag++;
			break;
		case 'D':
		case 'd':
			n = sscanf (optarg,"%d", &decimatex);
			flag++;
			break;
		case 'I':
		case 'i':
			sscanf (optarg,"%s", segyfile);
			flag++;
			break;
		case 'L':
		case 'l':
			logscale = MB_YES;
			flag++;
			break;
		case 'N':
		case 'n':
			n = sscanf (optarg,"%d", &nfft);
			flag++;
			break;
		case 'G':
		case 'O':
		case 'o':
			sscanf (optarg,"%s", fileroot);
			flag++;
			break;
		case 'S':
		case 's':
			n = sscanf (optarg,"%d/%d/%d/%d/%d", &tracemode, &tracestart, &traceend, &chanstart, &chanend);
			if (n < 5)
				{
				chanstart = 0;
				chanend = -1;
				}
			if (n < 3)
				{
				tracestart = 0;
				traceend = 0;
				}
			if (n < 1)
				{
				tracemode = MBSEGYPSD_USESHOT;
				}
			flag++;
			break;
		case 'T':
		case 't':
			n = sscanf (optarg,"%lf/%lf", &timesweep, &timedelay);
			if (n < 2)
				timedelay = 0.0;
			flag++;
			break;
		case 'W':
		case 'w':
			n = sscanf (optarg,"%d/%lf/%lf", &windowmode, &windowstart, &windowend);
			flag++;
			break;
		case '?':
			errflg++;
		}

	/* set output stream to stdout or stderr */
	if (verbose >= 2)
	    outfp = stderr;
	else
	    outfp = stdout;

	/* if error flagged then print it and exit */
	if (errflg)
		{
		fprintf(outfp,"usage: %s\n", usage_message);
		fprintf(outfp,"\nProgram <%s> Terminated\n",
			program_name);
		error = MB_ERROR_BAD_USAGE;
		exit(error);
		}

	/* print starting message */
	if (verbose == 1 || help)
		{
		fprintf(outfp,"\nProgram %s\n",program_name);
		fprintf(outfp,"MB-system Version %s\n",MB_VERSION);
		}

	/* print starting debug statements */
	if (verbose >= 2)
		{
		fprintf(outfp,"\ndbg2  Program <%s>\n",program_name);
		fprintf(outfp,"dbg2  MB-system Version %s\n",MB_VERSION);
		fprintf(outfp,"dbg2  Control Parameters:\n");
		fprintf(outfp,"dbg2       verbose:        %d\n",verbose);
		fprintf(outfp,"dbg2       help:           %d\n",help);
		fprintf(outfp,"dbg2       segyfile:       %s\n",segyfile);
		fprintf(outfp,"dbg2       fileroot:       %s\n",fileroot);
		fprintf(outfp,"dbg2       nfft:           %d\n",nfft);
		fprintf(outfp,"dbg2       decimatex:      %d\n",decimatex);
		fprintf(outfp,"dbg2       tracemode:      %d\n",tracemode);
		fprintf(outfp,"dbg2       tracestart:     %d\n",tracestart);
		fprintf(outfp,"dbg2       traceend:       %d\n",traceend);
		fprintf(outfp,"dbg2       chanstart:      %d\n",chanstart);
		fprintf(outfp,"dbg2       chanend:        %d\n",chanend);
		fprintf(outfp,"dbg2       timesweep:      %f\n",timesweep);
		fprintf(outfp,"dbg2       timedelay:      %f\n",timedelay);
		fprintf(outfp,"dbg2       ngridx:         %d\n",ngridx);
		fprintf(outfp,"dbg2       ngridy:         %d\n",ngridy);
		fprintf(outfp,"dbg2       ngridxy:        %d\n",ngridxy);
		fprintf(outfp,"dbg2       windowmode:     %d\n",windowmode);
		fprintf(outfp,"dbg2       windowstart:    %f\n",windowstart);
		fprintf(outfp,"dbg2       windowend:      %f\n",windowend);
		fprintf(outfp,"dbg2       scale2distance: %d\n",scale2distance);
		fprintf(outfp,"dbg2       shotscale:      %f\n",shotscale);
		fprintf(outfp,"dbg2       frequencyscale: %f\n",frequencyscale);
		fprintf(outfp,"dbg2       logscale:       %d\n",logscale);
		}

	/* if help desired then print it and exit */
	if (help)
		{
		fprintf(outfp,"\n%s\n",help_message);
		fprintf(outfp,"\nusage: %s\n", usage_message);
		exit(error);
		}
		
	/* get segy limits if required */
	if (traceend < 1 || traceend < tracestart || timesweep <= 0.0)
		{
		get_segy_limits(verbose, 
				segyfile,  
				&sinftracemode,
				&sinftracestart,
				&sinftraceend,
				&sinfchanstart,
				&sinfchanend,
				&sinftimesweep,
				&sinftimedelay,
				&error);
		if (traceend < 1 || traceend < tracestart)
			{
			tracemode = sinftracemode;
			tracestart = sinftracestart;
			traceend = sinftraceend;
			}
		if (chanend < 1 || chanend < chanstart)
			{
			chanstart = sinfchanstart;
			chanend = sinfchanend;
			}
		if (timesweep <= 0.0)
			{
			timesweep = sinftimesweep;
			timedelay = sinftimedelay;
			}
		}
		
	/* check specified parameters */
	if (traceend < 1 || traceend < tracestart)
		{
		fprintf(outfp,"\nBad trace numbers: %d %d specified...\n", tracestart, traceend);
		fprintf(outfp,"\nProgram <%s> Terminated\n", program_name);
		exit(error);
		}
	if (timesweep <= 0.0)
		{
		fprintf(outfp,"\nBad time sweep: %f specified...\n", timesweep);
		fprintf(outfp,"\nProgram <%s> Terminated\n", program_name);
		exit(error);
		}

	/* initialize reading the segy file */
	if (mb_segy_read_init(verbose, segyfile, 
		&mbsegyioptr, &asciiheader, &fileheader, &error) != MB_SUCCESS)
		{
		mb_error(verbose,error,&message);
		fprintf(outfp,"\nMBIO Error returned from function <mb_segy_read_init>:\n%s\n",message);
		fprintf(outfp,"\nSEGY File <%s> not initialized for reading\n",segyfile);
		fprintf(outfp,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}
		
	/* calculate implied grid parameters */
	strcpy(gridfile,fileroot);
	strcat(gridfile,".grd");
	strcpy(psdfile,fileroot);
	strcat(psdfile,"_psd.txt");
	if (chanend >= chanstart)
		ntraces = (traceend - tracestart + 1) * (chanend - chanstart + 1);
	else
		ntraces = traceend - tracestart + 1;
	ngridx = ntraces / decimatex;
	sampleinterval = 0.000001 * (double) (fileheader.sample_interval);
	ngridy = nfft / 2 + 1;
	ngridxy = ngridx * ngridy;
	dx = decimatex;
	xmin = (double) tracestart - 0.5;
	xmax = (double) traceend + 0.5;
	dy = 1.0 / (2.0 * sampleinterval * ngridy);
	ymin = -0.5 * dy;
	ymax = (ngridy - 0.5) * dy;
	
	/* get start and end samples */
	if (windowmode == MBSEGYPSD_WINDOW_OFF)
		{
		itstart = 0;
		itend = ngridy - 1;
		}
	else if (windowmode == MBSEGYPSD_WINDOW_ON)
		{
		itstart = MAX((windowstart) / sampleinterval, 0);
		itend = MIN((windowend) / sampleinterval, ngridy - 1);
		}		
	
	/* allocate memory for grid array */
	status = mb_mallocd(verbose,__FILE__,__LINE__, 2 * ngridxy * sizeof(float), (void **)&grid, &error);
	status = mb_mallocd(verbose,__FILE__,__LINE__, ngridy * sizeof(double), (void **)&spsd, &error);
	status = mb_mallocd(verbose,__FILE__,__LINE__, ngridy * sizeof(double), (void **)&wpsd, &error);
	status = mb_mallocd(verbose,__FILE__,__LINE__, ngridy * sizeof(double), (void **)&spsdtot, &error);
	status = mb_mallocd(verbose,__FILE__,__LINE__, ngridy * sizeof(double), (void **)&wpsdtot, &error);

	/* zero working psd array */
	for (iy=0;iy<ngridy;iy++)
		{
		spsdtot[iy] = 0.0;
		wpsdtot[iy] = 0.0;
		}

	/* output info */
	if (verbose >= 0)
		{
		fprintf(outfp,"\nMBsegypsd Parameters:\n");
		fprintf(outfp,"Input segy file:         %s\n",segyfile);
		fprintf(outfp,"Output fileroot:         %s\n",fileroot);
		fprintf(outfp,"Input Parameters:\n");
		fprintf(outfp,"     trace mode:         %d\n",tracemode);
		fprintf(outfp,"     trace start:        %d\n",tracestart);
		fprintf(outfp,"     trace end:          %d\n",traceend);
		fprintf(outfp,"     channel start:      %d\n",chanstart);
		fprintf(outfp,"     channel end:        %d\n",chanend);
		fprintf(outfp,"     trace decimation:   %d\n",decimatex);
		fprintf(outfp,"     time sweep:         %f seconds\n",timesweep);
		fprintf(outfp,"     time delay:         %f seconds\n",timedelay);
		fprintf(outfp,"     sample interval:    %f seconds\n",sampleinterval);
		fprintf(outfp,"     window mode:        %d\n",windowmode);
		fprintf(outfp,"     window start:       %f seconds\n",windowstart);
		fprintf(outfp,"     window end:         %f seconds\n",windowend);
		fprintf(outfp,"Output Parameters:\n");
		fprintf(outfp,"     grid filename:      %s\n",gridfile);
		fprintf(outfp,"     psd filename:       %s\n",psdfile);
		fprintf(outfp,"     x grid dimension:   %d\n",ngridx);
		fprintf(outfp,"     y grid dimension:   %d\n",ngridy);
		fprintf(outfp,"     grid xmin:          %f\n",xmin);
		fprintf(outfp,"     grid xmax:          %f\n",xmax);
		fprintf(outfp,"     grid ymin:          %f\n",ymin);
		fprintf(outfp,"     grid ymax:          %f\n",ymax);
		fprintf(outfp,"     NaN values used to flag regions with no data\n");
		fprintf(outfp,"     shotscale:          %f\n",shotscale);
		fprintf(outfp,"     frequencyscale:     %f\n",frequencyscale);
		if (scale2distance == MB_YES)
			{
			fprintf(outfp,"     trace numbers scaled to distance in meters\n");
			fprintf(outfp,"     scaled grid xmin    %f\n",0.0);
			fprintf(outfp,"     scaled grid xmax:   %f\n",shotscale * (xmax - xmin));
			}
		}
	if (verbose > 0)
		fprintf(outfp,"\n");
	
	/* proceed if all ok */
	if (status == MB_SUCCESS)
		{
	
		/* fill grid with NaNs */
		for (i=0;i<ngridxy;i++)
			grid[i] = NaN;
			
		/* generate the fftw plan */
		fftw_in = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nfft);
		fftw_out = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nfft);
		plan = fftw_plan_dft_1d(nfft, fftw_in, fftw_out, FFTW_FORWARD, FFTW_MEASURE);

		/* read and print data */
		nread = 0;
		while (error <= MB_ERROR_NO_ERROR)
			{
			/* reset error */
			error = MB_ERROR_NO_ERROR;

			/* read a trace */
			status = mb_segy_read_trace(verbose, mbsegyioptr, 
					&traceheader, &trace, &error);

			/* now process the trace */
			if (status == MB_SUCCESS)
				{
				/* figure out where this trace is in the grid */
				if (tracemode == MBSEGYPSD_USESHOT)
					{
					tracenum = traceheader.shot_num;
					channum = traceheader.shot_tr;
					}
				else
					{
					tracenum = traceheader.rp_num;
					channum = traceheader.rp_tr;
					}
				if (chanend >= chanstart)
					{
					tracecount = (tracenum - tracestart) * (chanend - chanstart + 1)
							+ (channum - chanstart);
					}
				else
					{
					tracecount = tracenum - tracestart;
					}
				ix = tracecount / decimatex;
				if (traceheader.elev_scalar < 0)
					factor = 1.0 / ((float) (-traceheader.elev_scalar));
				else
					factor = (float) traceheader.elev_scalar;
				if (traceheader.src_depth > 0)
					{
					btime = factor * traceheader.src_depth / 750.0 + 0.001 * traceheader.delay_mils;
					dtime = factor * traceheader.src_depth / 750.0;
					btimesave = btime;
					dtimesave = dtime;
					}
				else if (traceheader.src_elev > 0)
					{
					btime = -factor * traceheader.src_elev / 750.0 + 0.001 * traceheader.delay_mils;
					dtime = -factor * traceheader.src_elev / 750.0;
					btimesave = btime;
					dtimesave = dtime;
					}
				else
					{
					btime = btimesave;
					dtime = dtimesave;
					}
				if (traceheader.src_wbd > 0)
					{
					stime = factor * traceheader.src_wbd / 750.0;
					stimesave = stime;
					}
				else
					{
					stime = stimesave;
					}
				iys = (btime - timedelay) / sampleinterval;
				
				/* now check if this is a trace of interest */
				traceok = MB_YES;
				if (tracenum < tracestart 
					|| tracenum > traceend)
					traceok = MB_NO;
				else if (chanend >= chanstart
						&& (channum < chanstart
							|| channum > chanend))
					traceok = MB_NO;
				else if (tracecount % decimatex != 0)
					traceok = MB_NO;

				/* get trace min and max */
				tracemin = trace[0];
				tracemax = trace[0];
				for (i=0;i<traceheader.nsamps;i++)
					{
					tracemin = MIN(tracemin, trace[i]);
					tracemax = MAX(tracemin, trace[i]);
					}	

				if ((verbose == 0 && nread % 250 == 0) || (nread % 25 == 0))
					{
					if (traceok == MB_YES) 
						fprintf(outfp,"PROCESS ");
					else 
						fprintf(outfp,"IGNORE  ");
					if (tracemode == MBSEGYPSD_USESHOT) 
						fprintf(outfp,"read:%d position:%d shot:%d channel:%d ",
							nread,tracecount,tracenum,channum);
					else 
						fprintf(outfp,"read:%d position:%d rp:%d channel:%d ",
							nread,tracecount,tracenum,channum);
					fprintf(outfp,"%4.4d/%3.3d %2.2d:%2.2d:%2.2d.%3.3d samples:%d interval:%d usec minmax: %f %f\n",
					traceheader.year,traceheader.day_of_yr,
					traceheader.hour,traceheader.min,traceheader.sec,traceheader.mils,
					traceheader.nsamps,traceheader.si_micros,
					tracemin, tracemax);
					}

				/* now actually process traces of interest */
				if (traceok == MB_YES)
					{
					/* zero working psd array */
					for (iy=0;iy<ngridy;iy++)
						{
						spsd[iy] = 0.0;
						wpsd[iy] = 0.0;
						}

					/* get bounds of trace in depth window mode */
					if (windowmode == MBSEGYPSD_WINDOW_DEPTH)
						{
						itstart = (int)((dtime + windowstart - timedelay) / sampleinterval);
						itstart = MAX(itstart, 0);
						itend = (int)((dtime + windowend - timedelay) / sampleinterval);
						itend = MIN(itend, ngridy - 1);
						}
					else if (windowmode == MBSEGYPSD_WINDOW_SEAFLOOR)
						{
						itstart = MAX((stime + windowstart - timedelay) / sampleinterval, 0);
						itend = MIN((stime + windowend - timedelay) / sampleinterval, ngridy - 1);
						}
						
					/* loop over the data calculating fft in nfft long sections */
					nsection = (itend - itstart + 1) / nfft;
					if (((itend - itstart + 1) % nfft) > 0)
						nsection++;
					for (j=0;j<nsection;j++)
						{
						/* initialize normalization factors */
						normraw = 0.0;
						normtaper = 0.0;
						normfft = 0.0;
						
						/* extract data section to be fft'd with taper */
						kstart = itstart + j * nfft;
						kend = MIN(kstart + nfft, itend);
						for (i=0;i<nfft;i++)
							{
							k = itstart + j * nfft + i;
							if (k <= kend)
								{
								sint = sin(M_PI * ((double)(k - kstart)) / ((double)(kend - kstart)));
								taper = sint * sint;
								fftw_in[i][0] = taper * trace[k]; 
								normraw += trace[k] * trace[k];
								normtaper += fftw_in[i][0] * fftw_in[i][0];
								}
							else
								fftw_in[i][0] = 0.0;
/*if (ix < 500)
fftw_in[i][0] = sin(2.0 * M_PI * 1000.0 * i * sampleinterval) 
			+ sin(2.0 * M_PI * 3000.0 * i * sampleinterval) 
			+ sin(2.0 * M_PI * 6000.0 * i * sampleinterval);*/
							fftw_in[i][1] = 0.0;
							}
						soundpressurelevel = 20.0 * log10(normraw / nfft);
/*fprintf(stderr,"Sound Pressure Level: %f dB re 1 uPa\n",soundpressurelevel);*/
							
						/* execute the fft */
						fftw_execute(plan);
						
						/* get normalization factor - require variance of transform to equal variance of input */
						for (i=1;i<nfft;i++)
							{
							normfft += fftw_out[i][0] * fftw_out[i][0] + fftw_out[i][1] * fftw_out[i][1];
							}
						norm = normraw / normfft;
						
						/* apply normalization factor */
						for (i=1;i<nfft;i++)
							{
							fftw_out[i][0] = norm * fftw_out[i][0];
							fftw_out[i][1] = norm * fftw_out[i][1];
							}
							
						/* calculate psd from result of transform */
						spsd[0] += fftw_out[0][0] * fftw_out[0][0] + fftw_out[0][1] * fftw_out[0][1];
						wpsd[0] += 1.0;
/* fprintf(stderr,"FFT result: i:%d  %f %f  %f\n",
0,fftw_out[0][0],fftw_out[0][1],fftw_out[0][0] * fftw_out[0][0] + fftw_out[0][1] * fftw_out[0][1]);*/
						for (i=1;i<nfft/2;i++)
							{
							spsd[i] += 2.0 * (fftw_out[i][0] * fftw_out[i][0] + fftw_out[i][1] * fftw_out[i][1]);
							wpsd[i] += 1.0;
/* fprintf(stderr,"FFT result: i:%d  %f %f  %f\n",
i,fftw_out[i][0],fftw_out[i][1],2.0 * fftw_out[i][0] * fftw_out[i][0] + fftw_out[i][1] * fftw_out[i][1]);*/
							}
						if (nfft % 2 == 0)
							{
							spsd[i] += fftw_out[nfft/2][0] * fftw_out[nfft/2][0] + fftw_out[nfft/2][1] * fftw_out[nfft/2][1];
							wpsd[i] += 1.0;
/* fprintf(stderr,"FFT result: i:%d  %f %f  %f\n",
nfft/2,fftw_out[nfft/2][0],fftw_out[nfft/2][1],fftw_out[nfft/2][0] * fftw_out[nfft/2][0] + fftw_out[nfft/2][1] * fftw_out[nfft/2][1]); */
							}
						}
						
					/* output psd for this trace to the grid */
/*fprintf(stderr,"N:%d Normalization: %f %f %f    ratios: %f %f     %f %f\n",
nfft,normraw,normtaper,normfft,normraw/normfft,normfft/normraw,normtaper/normfft,normfft/normtaper);*/
					for (iy=0;iy<ngridy;iy++)
						{
						k = (ngridy - 1 - iy) * ngridx + ix;
						if (wpsd[iy] > 0.0)
							{
							if (logscale == MB_NO)
								grid[k] = spsd[iy] / wpsd[iy];
							else
								grid[k] = 20.0 * log10(spsd[iy] / wpsd[iy]);
							spsdtot[iy] += grid[k];
							wpsdtot[iy] += 1.0;
/*fprintf(stderr,"ix:%d iy:%d k:%d spsd:%f wpsd:%f     f:%f p:%f\n",
ix,iy,k,spsd[iy],wpsd[iy],ymax * iy / ngridy,grid[k]);*/
							gridmintot = MIN(grid[k], gridmintot);
							gridmaxtot = MAX(grid[k], gridmaxtot);
							}
						}
					}
				}

			/* now process the trace */
			if (status == MB_SUCCESS)
				nread++;
			}
			
		/* deallocate fftw arrays and plan */
		fftw_destroy_plan(plan);
		fftw_free(fftw_in);
		fftw_free(fftw_out);
		}

	/* write out the grid */
	error = MB_ERROR_NO_ERROR;
	status = MB_SUCCESS;
	strcpy(projection, "GenericLinear");
	if (scale2distance == MB_YES)
		{
		strcpy(xlabel, "Distance (m)");
		strcpy(ylabel, "Frequency (Hz)");
		xmax *= shotscale;
		xmin *= shotscale;
		dx *= shotscale;
		}
	else
		{
		strcpy(xlabel, "Trace Number");
		strcpy(ylabel, "Frequency (Hz)");
		dx = (double) decimatex;
		}
	if (logscale == MB_YES)
		strcpy(zlabel, "dB/Hz");
	else
		strcpy(zlabel, "Intensity/Hz");
	sprintf(title, "Power Spectral Density Grid from %s", segyfile);
	status = write_cdfgrd(verbose, gridfile, grid,
		ngridx, ngridy, 
		xmin, xmax, ymin, ymax,
		gridmintot, gridmaxtot, dx, dy, 
		xlabel, ylabel, zlabel, title, 
		projection, argc, argv, &error);

	/* output average power spectra */
	if ((fp = fopen(psdfile, "w")) != NULL)
		{
		for (iy=0;iy<ngridy;iy++)
			{
			if (wpsdtot[iy] > 0.0)
				{
				spsdtot[iy] = spsdtot[iy] / wpsdtot[iy];
				}
			fprintf(fp, "%f %f\n", dy * iy, spsdtot[iy]);
			}
		fclose(fp);
		}

	/* close the segy file */
	status = mb_segy_close(verbose,&mbsegyioptr,&error);

	/* deallocate memory for grid array */
	if (worktrace != NULL)
		status = mb_freed(verbose,__FILE__,__LINE__,(void **)&worktrace, &error);	
	status = mb_freed(verbose,__FILE__,__LINE__,(void **)&grid, &error);
	status = mb_freed(verbose,__FILE__,__LINE__,(void **)&spsd, &error);
	status = mb_freed(verbose,__FILE__,__LINE__,(void **)&wpsd, &error);
	status = mb_freed(verbose,__FILE__,__LINE__,(void **)&spsdtot, &error);
	status = mb_freed(verbose,__FILE__,__LINE__,(void **)&wpsdtot, &error);
	
	/* run mbm_grdplot */
	xwidth = MIN(0.01 * (double) ngridx, 55.0);
	ywidth = MIN(0.01 * (double) ngridy, 28.0);
	sprintf(plot_cmd, "mbm_grdplot -I%s -JX%f/%f -G1 -S -V -L\"File %s - %s:%s\"", 
			gridfile, xwidth, ywidth, gridfile, title, zlabel);
	if (verbose)
		{
		fprintf(outfp, "\nexecuting mbm_grdplot...\n%s\n", 
			plot_cmd);
		}
	plot_status = system(plot_cmd);
	if (plot_status == -1)
		{
		fprintf(outfp, "\nError executing mbm_grdplot on grid file %s\n", gridfile);
		}
	
	/* run mbm_xyplot */
	xwidth = 9.0;
	ywidth = 7.0;
	sprintf(plot_cmd, "mbm_xyplot -I%s -JX%f/%f -V -L\"File %s - %s:%s\"", 
			psdfile, xwidth, ywidth, psdfile, title, zlabel);
	if (verbose)
		{
		fprintf(outfp, "\nexecuting mbm_xyplot...\n%s\n", 
			plot_cmd);
		}
	plot_status = system(plot_cmd);
	if (plot_status == -1)
		{
		fprintf(outfp, "\nError executing mbm_xyplot on psd file %s\n", psdfile);
		}

	/* check memory */
	if (verbose >= 4)
		status = mb_memory_list(verbose,&error);

	/* print output debug statements */
	if (verbose >= 2)
		{
		fprintf(outfp,"\ndbg2  Program <%s> completed\n",
			program_name);
		fprintf(outfp,"dbg2  Ending status:\n");
		fprintf(outfp,"dbg2       status:  %d\n",status);
		}

	/* end it all */
	exit(error);
}