Example #1
0
void rc1_fft(REAL *data, complex *cdata, int n, int sign)
{
	int    j;
	double *datft;

	if (NINT(pow(2.0, (double)NINT(log((double)n)/log(2.0)))) != n) {
		if (npfar(n) == n) pfarc(sign,n,data,cdata);
		else rcdft(data,cdata,n,sign);
	}
	else {
		datft = (double *)malloc(n*sizeof(double));
		if (datft == NULL) fprintf(stderr,"rc1_fft: memory allocation error\n");
	
		for (j = 0; j < n; j++) datft[j] = (double)data[j];
		realfft(n, datft);
		cdata[0].i = 0.0;
		for (j = 0; j < n/2; j++) {
			cdata[j].r = (REAL)datft[j]; 
			cdata[j+1].i = sign*(REAL)datft[n-j-1]; 
		}
		cdata[n/2].r = datft[n/2];
		cdata[n/2].i = 0.0; 
	
		free(datft);
	}

	return;
}
Example #2
0
Var* ff_realfft(vfuncptr func, Var* arg)
{
	Var* obj = NULL;
	int i, n;
	double *in, *out;

	Alist alist[3];
	alist[0]      = make_alist("obj", ID_VAL, NULL, &obj);
	alist[1].name = NULL;

	if (parse_args(func, arg, alist) == 0) return (NULL);

	if (obj == NULL) {
		parse_error("%s: No object specified\n", func->name);
		return (NULL);
	}

	n   = V_DSIZE(obj);
	in  = (double*)calloc(n, sizeof(double));
	out = (double*)calloc(n, sizeof(double));

	for (i = 0; i < n; i++) {
		in[i] = extract_double(obj, i);
	}

	if (func->fdata == (void*)1) {
		realfft(in, n, out);
	} else {
		realrft(in, n, out);
	}
	return (newVal(BSQ, 1, n, 1, DV_DOUBLE, out));
}
Example #3
0
int fft_waveform( doublewf_t *w, complexwf_t *fft ) {

  if ( ! w || ! fft ) {
    bpm_error( "Invalid waveform pointers in fft_waveform(...)",
	       __FILE__, __LINE__ );
    return BPM_FAILURE;
  }

  return realfft( w, FFT_FORWARD, fft );
}
Example #4
0
/*{{{  raw_fft(transform_info_ptr tinfo) {*/
METHODDEF DATATYPE *
raw_fft(transform_info_ptr tinfo) {
 int i;
 array myarray, fftarray;
 long datasize, fftsize;

 if (tinfo->itemsize==2) {
  /*{{{  Do the inverse transform*/
  if (tinfo->data_type==TIME_DATA) {
   tinfo->nroffreq=tinfo->nr_of_points;
   tinfo->nrofshifts=1;
  }
  datasize=tinfo->nroffreq;
  fftsize=datasize-3;
  for (i=0; fftsize>>=1; i++);
  fftsize=1<<(i+2);
  if (datasize!=fftsize/2+1 || tinfo->nrofshifts!=1) {
   ERREXIT(tinfo->emethods, "raw_fft: Input spectra must have 2^n+1 frequencies, 2 items and 1 shift\n");
  }

  fftarray.nr_of_elements=fftsize;
  fftarray.element_skip=1;
  fftarray.nr_of_vectors=tinfo->nr_of_channels;
  if (array_allocate(&fftarray)==NULL) {
   ERREXIT(tinfo->emethods, "raw_fft: Error allocating memory\n");
  }

  /* We access tsdata as 1-item data already now (this makes copying easier) */
  tinfo->itemsize=1;
  tinfo->nr_of_points*=2;
  tinfo->data_type=TIME_DATA;
  tinfo_array(tinfo, &myarray);
  do {
   myarray.current_element=0;
   myarray.current_vector=fftarray.current_vector;
   realfft(ARRAY_ELEMENT(&myarray), fftsize, -1);
   do {
    array_write(&fftarray, array_scan(&myarray));
   } while (fftarray.message==ARRAY_CONTINUE);
  } while (fftarray.message==ARRAY_ENDOFVECTOR);
  tinfo->nr_of_points=fftarray.nr_of_elements;
  /*}}}  */
 } else {
Example #5
0
void rcm_fft(REAL *data, complex *cdata, int n1, int n2, int ldr, int ldc, int sign)
{
	int    j, i;
	double *datft;

	if (NINT(pow(2.0, (double)NINT(log((double)n1)/log(2.0)))) != n1) {
		if (npfar(n1) == n1) {
			if (ldr == n1 && ldc == n2) {
				pfa2rc(sign, 1, n1, n2, data, cdata);
			}
			else {
				for (i = 0; i < n2; i++) {
					pfarc(sign, n1, &data[i*ldr], &cdata[i*ldc]);
				}
			}
		}
		else {
			for (i = 0; i < n2; i++) {
				rcdft(&data[i*ldr], &cdata[i*ldc], n1, sign);
			}
		}
	}
	else {
		datft = (double *)malloc(n1*sizeof(double));
		if (datft == NULL) fprintf(stderr,"rcm_fft: memory allocation error\n");
	
		for (i = 0; i < n2; i++) {
			for (j = 0; j < n1; j++) datft[j] = (double)data[i*ldr+j];
			realfft(n1, datft);
			cdata[i*ldc].i = 0.0;
			for (j = 0; j < n1/2; j++) {
				cdata[i*ldc+j].r = (REAL)datft[j]; 
				cdata[i*ldc+j+1].i = sign*(REAL)datft[n1-j-1]; 
			}
			cdata[i*ldc+n1/2].r = (REAL)datft[n1/2]; 
			cdata[i*ldc+n1/2].i = 0.0; 
		}
	
		free(datft);
	}

	return;
}
Example #6
0
static void decibelspec(double *from, double *to)
{
    double p, hr;
    int i, j;
    static double *w_table = NULL;

    if(w_table == NULL)
    {
	double t;

	w_table = (double *)safe_malloc(FFTSIZE * sizeof(double));
	t = -M_PI;
	for(i = 0; i < FFTSIZE; i++)
	{
	    w_table[i] = 0.50 + 0.50 * cos(t);
	    t += 2.0 * M_PI / FFTSIZE;
	}
    }
    for(i = 0; i < FFTSIZE; i++)
	from[i] *= w_table[i];
    realfft(from, FFTSIZE);

    hr = AMP * NCOLOR;
    if(from[0] >= 0)
	p = from[0];
    else
	p = -from[0];
    to[0] = log(1.0 + (128.0 / FFTSIZE) * p) * hr;
    for(i = 1, j = FFTSIZE - 1; i < FFTSIZE/2; i++, j--)
    {
	double t, u;

	t = from[i];
	u = from[j];
	to[i] = log(1.0 + (128.0 / FFTSIZE) * sqrt(t*t + u*u)) * hr;
    }
    p = from[FFTSIZE/2];
    to[FFTSIZE/2] = log(1.0 + (128.0 / FFTSIZE) * sqrt(2 * p*p)) * hr;
}
Example #7
0
void open_soundspec(void)
{
    static int initflag = 0;

	if( win.show){
		ShowWindow(win.ref);
	}

    if(disp != NULL)
    {		//already opened
	ring_index = 0;
	next_wakeup_samples = outcnt;
	memset(ring_buffer, 0, ring_buffer_len * sizeof(int32));
	view_soundspec_flag = 1;
	return;
    }

    if(soundspec_update_interval == 0)
	soundspec_update_interval = (int32)(DEFAULT_UPDATE * play_mode->rate);

	disp=true;
	
    if(!initflag)
    {
	ring_buffer = (long*)safe_malloc(ring_buffer_len * sizeof(int32));
	realfft(NULL, FFTSIZE);
	initialize_exp_hz_table(DEFAULT_ZOOM);
	initflag = 1;
    }

    set_color_ring();

    ring_index = 0;
    next_wakeup_samples = outcnt;
    memset(ring_buffer, 0, sizeof(int32));
    view_soundspec_flag = 1;
}
Example #8
0
int main(int argc, char *argv[])
{
   FILE *bytemaskfile;
   float **dataavg = NULL, **datastd = NULL, **datapow = NULL;
   float *chandata = NULL, powavg, powstd, powmax;
   float inttime, norm, fracterror = RFI_FRACTERROR;
   float *rawdata = NULL;
   unsigned char **bytemask = NULL;
   short *srawdata = NULL;
   char *outfilenm, *statsfilenm, *maskfilenm;
   char *bytemaskfilenm, *rfifilenm;
   int numchan = 0, numint = 0, newper = 0, oldper = 0, good_padvals = 0;
   int blocksperint, ptsperint = 0, ptsperblock = 0, padding = 0;
   int numcands, candnum, numrfi = 0, numrfivect = NUM_RFI_VECT;
   int ii, jj, kk, slen, numread = 0, insubs = 0;
   int harmsum = RFI_NUMHARMSUM, lobin = RFI_LOBIN, numbetween = RFI_NUMBETWEEN;
   double davg, dvar, freq;
   struct spectra_info s;
   presto_interptype interptype;
   rfi *rfivect = NULL;
   mask oldmask, newmask;
   fftcand *cands;
   infodata idata;
   Cmdline *cmd;

   /* Call usage() if we have no command line arguments */

   if (argc == 1) {
      Program = argv[0];
      printf("\n");
      usage();
      exit(0);
   }

   /* Parse the command line using the excellent program Clig */

   cmd = parseCmdline(argc, argv);
   spectra_info_set_defaults(&s);
   s.filenames = cmd->argv;
   s.num_files = cmd->argc;
   s.clip_sigma = cmd->clip;
   // -1 causes the data to determine if we use weights, scales, & 
   // offsets for PSRFITS or flip the band for any data type where
   // we can figure that out with the data
   s.apply_flipband = (cmd->invertP) ? 1 : -1;
   s.apply_weight = (cmd->noweightsP) ? 0 : -1;
   s.apply_scale  = (cmd->noscalesP) ? 0 : -1;
   s.apply_offset = (cmd->nooffsetsP) ? 0 : -1;
   s.remove_zerodm = (cmd->zerodmP) ? 1 : 0;
   if (cmd->noclipP) {
       cmd->clip = 0.0;
       s.clip_sigma = 0.0;
   }
   if (cmd->ifsP) {
       // 0 = default or summed, 1-4 are possible also
       s.use_poln = cmd->ifs;
   }
   slen = strlen(cmd->outfile) + 20;

#ifdef DEBUG
   showOptionValues();
#endif

   printf("\n\n");
   printf("               Pulsar Data RFI Finder\n");
   printf("                 by Scott M. Ransom\n\n");

   /* The following is the root of all the output files */

   outfilenm = (char *) calloc(slen, sizeof(char));
   sprintf(outfilenm, "%s_rfifind", cmd->outfile);

   /* And here are the output file names */

   maskfilenm = (char *) calloc(slen, sizeof(char));
   sprintf(maskfilenm, "%s.mask", outfilenm);
   bytemaskfilenm = (char *) calloc(slen, sizeof(char));
   sprintf(bytemaskfilenm, "%s.bytemask", outfilenm);
   rfifilenm = (char *) calloc(slen, sizeof(char));
   sprintf(rfifilenm, "%s.rfi", outfilenm);
   statsfilenm = (char *) calloc(slen, sizeof(char));
   sprintf(statsfilenm, "%s.stats", outfilenm);
   sprintf(idata.name, "%s", outfilenm);

   if (RAWDATA) {
       if (cmd->filterbankP) s.datatype = SIGPROCFB;
       else if (cmd->psrfitsP) s.datatype = PSRFITS;
       else if (cmd->pkmbP) s.datatype = SCAMP;
       else if (cmd->bcpmP) s.datatype = BPP;
       else if (cmd->wappP) s.datatype = WAPP;
       else if (cmd->spigotP) s.datatype = SPIGOT;
   } else {  // Attempt to auto-identify the data
       identify_psrdatatype(&s, 1);
       if (s.datatype==SIGPROCFB) cmd->filterbankP = 1;
       else if (s.datatype==PSRFITS) cmd->psrfitsP = 1;
       else if (s.datatype==SCAMP) cmd->pkmbP = 1;
       else if (s.datatype==BPP) cmd->bcpmP = 1;
       else if (s.datatype==WAPP) cmd->wappP = 1;
       else if (s.datatype==SPIGOT) cmd->spigotP = 1;
       else if (s.datatype==SUBBAND) insubs = 1;
       else {
           printf("Error:  Unable to identify input data files.  Please specify type.\n\n");
           exit(1);
       }
   }

   if (!cmd->nocomputeP) {

       if (RAWDATA || insubs) {
           char description[40];
           psrdatatype_description(description, s.datatype);
           if (s.num_files > 1)
               printf("Reading %s data from %d files:\n", description, s.num_files);
           else
               printf("Reading %s data from 1 file:\n", description);
           if (insubs) s.files = (FILE **)malloc(sizeof(FILE *) * s.num_files);
           for (ii = 0; ii < s.num_files; ii++) {
               printf("  '%s'\n", cmd->argv[ii]);
               if (insubs) s.files[ii] = chkfopen(cmd->argv[ii], "rb");
           }
           printf("\n");
       }           

       if (RAWDATA) {
           read_rawdata_files(&s);
           print_spectra_info_summary(&s);
           spectra_info_to_inf(&s, &idata);
           ptsperblock = s.spectra_per_subint;
           numchan = s.num_channels;
           idata.dm = 0.0;
       }
       
       if (insubs) {
           /* Set-up values if we are using subbands */
           char *tmpname, *root, *suffix;
           if (split_root_suffix(s.filenames[0], &root, &suffix) == 0) {
               printf("Error:  The input filename (%s) must have a suffix!\n\n", s.filenames[0]);
               exit(1);
           }
           if (strncmp(suffix, "sub", 3) == 0) {
               tmpname = calloc(strlen(root) + 6, 1);
               sprintf(tmpname, "%s.sub", root);
               readinf(&idata, tmpname);
               free(tmpname);
           } else {
               printf("\nThe input files (%s) must be subbands!  (i.e. *.sub##)\n\n",
                      s.filenames[0]);
               exit(1);
           }
           free(root);
           free(suffix);
           ptsperblock = 1;
           /* Compensate for the fact that we have subbands and not channels */
           idata.freq = idata.freq - 0.5 * idata.chan_wid +
               0.5 * idata.chan_wid * (idata.num_chan / s.num_files);
           idata.chan_wid = idata.num_chan / s.num_files * idata.chan_wid;
           idata.num_chan = numchan = s.num_files;
           idata.dm = 0.0;
           sprintf(idata.name, "%s", outfilenm);
           writeinf(&idata);
           s.padvals = gen_fvect(s.num_files);
           for (ii = 0 ; ii < s.num_files ; ii++)
               s.padvals[ii] = 0.0;
       }

       /* Read an input mask if wanted */
       if (cmd->maskfileP) {
           read_mask(cmd->maskfile, &oldmask);
           printf("Read old mask information from '%s'\n\n", cmd->maskfile);
           good_padvals = determine_padvals(cmd->maskfile, &oldmask, s.padvals);
       } else {
           oldmask.numchan = oldmask.numint = 0;
       }

      /* The number of data points and blocks to work with at a time */

      if (cmd->blocksP) {
         blocksperint = cmd->blocks;
         cmd->time = blocksperint * ptsperblock * idata.dt;
      } else {
         blocksperint = (int) (cmd->time / (ptsperblock * idata.dt) + 0.5);
      }
      ptsperint = blocksperint * ptsperblock;
      numint = (long long) idata.N / ptsperint;
      if ((long long) idata.N % ptsperint)
         numint++;
      inttime = ptsperint * idata.dt;
      printf("Analyzing data sections of length %d points (%.6g sec).\n",
             ptsperint, inttime);
      {
         int *factors, numfactors;

         factors = get_prime_factors(ptsperint, &numfactors);
         printf("  Prime factors are:  ");
         for (ii = 0; ii < numfactors; ii++)
            printf("%d ", factors[ii]);
         printf("\n");
         if (factors[numfactors - 1] > 13) {
            printf("  WARNING:  The largest prime factor is pretty big!  This will\n"
                   "            cause the FFTs to take a long time to compute.  I\n"
                   "            recommend choosing a different -time value.\n");
         }
         printf("\n");
         free(factors);
      }

      /* Allocate our workarrays */

      if (RAWDATA)
          rawdata = gen_fvect(idata.num_chan * ptsperblock * blocksperint);
      else if (insubs)
          srawdata = gen_svect(idata.num_chan * ptsperblock * blocksperint);
      dataavg = gen_fmatrix(numint, numchan);
      datastd = gen_fmatrix(numint, numchan);
      datapow = gen_fmatrix(numint, numchan);
      chandata = gen_fvect(ptsperint);
      bytemask = gen_bmatrix(numint, numchan);
      for (ii = 0; ii < numint; ii++)
         for (jj = 0; jj < numchan; jj++)
            bytemask[ii][jj] = GOODDATA;
      rfivect = rfi_vector(rfivect, numchan, numint, 0, numrfivect);
      if (numbetween == 2)
         interptype = INTERBIN;
      else
         interptype = INTERPOLATE;

      /* Main loop */

      printf("Writing mask data  to '%s'.\n", maskfilenm);
      printf("Writing  RFI data  to '%s'.\n", rfifilenm);
      printf("Writing statistics to '%s'.\n\n", statsfilenm);
      printf("Massaging the data ...\n\n");
      printf("Amount Complete = %3d%%", oldper);
      fflush(stdout);

      for (ii = 0; ii < numint; ii++) { /* Loop over the intervals */
         newper = (int) ((float) ii / numint * 100.0 + 0.5);
         if (newper > oldper) {
            printf("\rAmount Complete = %3d%%", newper);
            fflush(stdout);
            oldper = newper;
         }

         /* Read a chunk of data */

         if (RAWDATA)
             numread = read_rawblocks(rawdata, blocksperint, &s, &padding);
         else if (insubs)
             numread = read_subband_rawblocks(s.files, s.num_files,
                                              srawdata, blocksperint, &padding);

         if (padding)
            for (jj = 0; jj < numchan; jj++)
               bytemask[ii][jj] |= PADDING;

         for (jj = 0; jj < numchan; jj++) {     /* Loop over the channels */

             if (RAWDATA)
                 get_channel(chandata, jj, blocksperint, rawdata, &s);
             else if (insubs)
                 get_subband(jj, chandata, srawdata, blocksperint);

            /* Calculate the averages and standard deviations */
            /* for each point in time.                        */

            if (padding) {
                dataavg[ii][jj] = 0.0;
                datastd[ii][jj] = 0.0;
                datapow[ii][jj] = 1.0;
            } else {
               avg_var(chandata, ptsperint, &davg, &dvar);
               dataavg[ii][jj] = davg;
               datastd[ii][jj] = sqrt(dvar);
               realfft(chandata, ptsperint, -1);
               numcands = 0;
               norm = datastd[ii][jj] * datastd[ii][jj] * ptsperint;
               if (norm == 0.0)
                  norm = (chandata[0] == 0.0) ? 1.0 : chandata[0];
               cands = search_fft((fcomplex *) chandata, ptsperint / 2,
                                  lobin, ptsperint / 2, harmsum,
                                  numbetween, interptype, norm, cmd->freqsigma,
                                  &numcands, &powavg, &powstd, &powmax);
               datapow[ii][jj] = powmax;

               /* Record the birdies */

               if (numcands) {
                  for (kk = 0; kk < numcands; kk++) {
                     freq = cands[kk].r / inttime;
                     candnum = find_rfi(rfivect, numrfi, freq, RFI_FRACTERROR);
                     if (candnum >= 0) {
                        update_rfi(rfivect + candnum, freq, cands[kk].sig, jj, ii);
                     } else {
                        update_rfi(rfivect + numrfi, freq, cands[kk].sig, jj, ii);
                        numrfi++;
                        if (numrfi == numrfivect) {
                           numrfivect *= 2;
                           rfivect = rfi_vector(rfivect, numchan, numint,
                                                numrfivect / 2, numrfivect);
                        }
                     }
                  }
                  free(cands);
               }
            }
         }
      }
      printf("\rAmount Complete = 100%%\n");

      /* Write the data to the output files */

      write_rfifile(rfifilenm, rfivect, numrfi, numchan, numint,
                    ptsperint, lobin, numbetween, harmsum,
                    fracterror, cmd->freqsigma);
      write_statsfile(statsfilenm, datapow[0], dataavg[0], datastd[0],
                      numchan, numint, ptsperint, lobin, numbetween);

   } else {                     /* If "-nocompute" */
      float freqsigma;

      /* Read the data from the output files */

      printf("Reading  RFI data  from '%s'.\n", rfifilenm);
      printf("Reading statistics from '%s'.\n", statsfilenm);
      readinf(&idata, outfilenm);
      read_rfifile(rfifilenm, &rfivect, &numrfi, &numchan, &numint,
                   &ptsperint, &lobin, &numbetween, &harmsum,
                   &fracterror, &freqsigma);
      numrfivect = numrfi;
      read_statsfile(statsfilenm, &datapow, &dataavg, &datastd,
                     &numchan, &numint, &ptsperint, &lobin, &numbetween);
      bytemask = gen_bmatrix(numint, numchan);
      printf("Reading  bytemask  from '%s'.\n\n", bytemaskfilenm);
      bytemaskfile = chkfopen(bytemaskfilenm, "rb");
      chkfread(bytemask[0], numint * numchan, 1, bytemaskfile);
      fclose(bytemaskfile);
      for (ii = 0; ii < numint; ii++)
         for (jj = 0; jj < numchan; jj++)
            bytemask[ii][jj] &= PADDING;        /* Clear all but the PADDING bits */
      inttime = ptsperint * idata.dt;
   }

   /* Make the plots and set the mask */

   {
      int *zapints, *zapchan;
      int numzapints = 0, numzapchan = 0;

      if (cmd->zapintsstrP) {
         zapints = ranges_to_ivect(cmd->zapintsstr, 0, numint - 1, &numzapints);
         zapints = (int *) realloc(zapints, (size_t) (sizeof(int) * numint));
      } else {
         zapints = gen_ivect(numint);
      }
      if (cmd->zapchanstrP) {
         zapchan = ranges_to_ivect(cmd->zapchanstr, 0, numchan - 1, &numzapchan);
         zapchan = (int *) realloc(zapchan, (size_t) (sizeof(int) * numchan));
      } else {
         zapchan = gen_ivect(numchan);
      }
      rfifind_plot(numchan, numint, ptsperint, cmd->timesigma, cmd->freqsigma,
                   cmd->inttrigfrac, cmd->chantrigfrac,
                   dataavg, datastd, datapow, zapchan, numzapchan,
                   zapints, numzapints, &idata, bytemask,
                   &oldmask, &newmask, rfivect, numrfi,
                   cmd->rfixwinP, cmd->rfipsP, cmd->xwinP);

      vect_free(zapints);
      vect_free(zapchan);
   }

   /* Write the new mask and bytemask to the file */

   write_mask(maskfilenm, &newmask);
   bytemaskfile = chkfopen(bytemaskfilenm, "wb");
   chkfwrite(bytemask[0], numint * numchan, 1, bytemaskfile);
   fclose(bytemaskfile);

   /* Determine the percent of good and bad data */

   {
      int numpad = 0, numbad = 0, numgood = 0;

      for (ii = 0; ii < numint; ii++) {
         for (jj = 0; jj < numchan; jj++) {
            if (bytemask[ii][jj] == GOODDATA) {
               numgood++;
            } else {
               if (bytemask[ii][jj] & PADDING)
                  numpad++;
               else
                  numbad++;
            }
         }
      }
      printf("\nTotal number of intervals in the data:  %d\n\n", numint * numchan);
      printf("  Number of padded intervals:  %7d  (%6.3f%%)\n",
             numpad, (float) numpad / (float) (numint * numchan) * 100.0);
      printf("  Number of  good  intervals:  %7d  (%6.3f%%)\n",
             numgood, (float) numgood / (float) (numint * numchan) * 100.0);
      printf("  Number of  bad   intervals:  %7d  (%6.3f%%)\n\n",
             numbad, (float) numbad / (float) (numint * numchan) * 100.0);
      qsort(rfivect, numrfi, sizeof(rfi), compare_rfi_sigma);
      printf("  Ten most significant birdies:\n");
      printf("#  Sigma     Period(ms)      Freq(Hz)       Number \n");
      printf("----------------------------------------------------\n");
      for (ii = 0; ii < 10; ii++) {
         double pperr;
         char temp1[40], temp2[40];

         if (rfivect[ii].freq_var == 0.0) {
            pperr = 0.0;
            sprintf(temp1, " %-14g", rfivect[ii].freq_avg);
            sprintf(temp2, " %-14g", 1000.0 / rfivect[ii].freq_avg);
         } else {
            pperr = 1000.0 * sqrt(rfivect[ii].freq_var) /
                (rfivect[ii].freq_avg * rfivect[ii].freq_avg);
            nice_output_2(temp1, rfivect[ii].freq_avg, sqrt(rfivect[ii].freq_var),
                          -15);
            nice_output_2(temp2, 1000.0 / rfivect[ii].freq_avg, pperr, -15);
         }
         printf("%-2d %-8.2f %13s %13s %-8d\n", ii + 1, rfivect[ii].sigma_avg,
                temp2, temp1, rfivect[ii].numobs);
      }
      qsort(rfivect, numrfi, sizeof(rfi), compare_rfi_numobs);
      printf("\n  Ten most numerous birdies:\n");
      printf("#  Number    Period(ms)      Freq(Hz)       Sigma \n");
      printf("----------------------------------------------------\n");
      for (ii = 0; ii < 10; ii++) {
         double pperr;
         char temp1[40], temp2[40];

         if (rfivect[ii].freq_var == 0.0) {
            pperr = 0.0;
            sprintf(temp1, " %-14g", rfivect[ii].freq_avg);
            sprintf(temp2, " %-14g", 1000.0 / rfivect[ii].freq_avg);
         } else {
            pperr = 1000.0 * sqrt(rfivect[ii].freq_var) /
                (rfivect[ii].freq_avg * rfivect[ii].freq_avg);
            nice_output_2(temp1, rfivect[ii].freq_avg, sqrt(rfivect[ii].freq_var),
                          -15);
            nice_output_2(temp2, 1000.0 / rfivect[ii].freq_avg, pperr, -15);
         }
         printf("%-2d %-8d %13s %13s %-8.2f\n", ii + 1, rfivect[ii].numobs,
                temp2, temp1, rfivect[ii].sigma_avg);
      }
      printf("\nDone.\n\n");
   }

   /* Close the files and cleanup */

   free_rfi_vector(rfivect, numrfivect);
   free_mask(newmask);
   if (cmd->maskfileP)
      free_mask(oldmask);
   free(outfilenm);
   free(statsfilenm);
   free(bytemaskfilenm);
   free(maskfilenm);
   free(rfifilenm);
   vect_free(dataavg[0]);
   vect_free(dataavg);
   vect_free(datastd[0]);
   vect_free(datastd);
   vect_free(datapow[0]);
   vect_free(datapow);
   vect_free(bytemask[0]);
   vect_free(bytemask);
   if (!cmd->nocomputeP) {
       //  Close all the raw files and free their vectors
       close_rawfiles(&s);
       vect_free(chandata);
       if (insubs)
           vect_free(srawdata);
       else
           vect_free(rawdata);
   }
   return (0);
}
Example #9
0
t_int *stft_perform(t_int *w)
{
	t_stft *x = (t_stft *)(w[1]);
	float *inreal = (float *)(w[2]);
	float *outreal = (float *)(w[3]);
	int n = w[4];
	int i, m, np, count;
	long pts = x->x_fftsize;
	long hop = x->x_hop;
	float *b;
	float *ei = x->x_in + pts; // indicates end pointer of buffer
	float *eo = x->x_out + pts;	
	//float mult = x->x_1overpts;
	float *wind = x->x_window;
	
	if (x->x_obj.z_disabled)
		goto exit;
	if (n > pts) {  // if sigvect > fftsize
		np = pts;
		count = n / pts;
	} else {
		np = n;
		count = 1;
	}
	m = np;
	set_zero(outreal, n);
	while (count--) { // do big loop just once if sigvect < fftsize

		b = x->x_inptr;  // copy signal into input buffer
		BlockMove(inreal,b, np * sizeof(float));
		b += np; 	// increment temp input pointer by sigvs
					// we will increment input pointer later
		
		if (b == ei) { // if temp input pointer is at end
			float *real = x->x_out;
			float *freal = x->x_out;
			t_complex *frame = x->x_sdifbuf;
			long wpts = pts;
			long fpts = x->x_sdifbufsize -1;
			
			// copy input buffer into oputput buffer and fft the outbuffer
			BlockMove(x->x_in,x->x_out,pts * sizeof(float));
			
			while (wpts--) 
				*real++ *= *wind++; // do windowing
	
			realfft(pts, x->x_out); // perform mayer FFT	
			//fftRealfast(pts, x->x_out, x->x_twiddle); // REALFAST FFT		
			*outreal = 1.0; //send just a click out
			
			// fill sdifbuf
			for (i=1; i< fpts; i++) {
				x->x_sdifbuf[i].re = x->x_out[i];
				x->x_sdifbuf[i].im = x->x_out[i+fpts];
			}
			x->x_sdifbuf[0].re = x->x_out[0];		
			x->x_sdifbuf[fpts].re = x->x_out[fpts];
			x->x_sdifbuf[0].im = x->x_sdifbuf[fpts].im = 0.;
		
			// shift and reset i/o buffer pointers
			BlockMove(x->x_in+hop,x->x_in,(pts-hop) * sizeof(float));
			x->x_inptr = x->x_in +pts-hop;

		} else if (b) { // otherwise just increment input pointer
			x->x_inptr += np;
		}
	}
exit:
	return (w + 5);
}
Example #10
0
int main(int argc, char *argv[])
{
   float *data;
   int status, isign;
   unsigned long numdata;
/*   unsigned long next2ton; */
   FILE *datafile, *scratchfile;
   char datafilenm[100], scratchfilenm[100], resultfilenm[100];
   char command[80];
   struct tms runtimes;
   double ttim, stim, utim, tott;

   tott = times(&runtimes) / (double) CLK_TCK;
   printf("\n\n");
   printf("   Real-Valued Data FFT Program v2.0\n");
   printf("        by Scott M. Ransom\n");
   printf("           8 June, 1997\n\n");

   if ((argc > 1) && (argc < 7)) {

      /*      Open and check data file.    */

      if (argc == 3) {
         sprintf(datafilenm, "%s.", argv[2]);
         sprintf(scratchfilenm, "%s.tmp", argv[2]);
         sprintf(resultfilenm, "%s.", argv[2]);
      }
      if (argc == 4) {
         sprintf(datafilenm, "%s/%s.", argv[3], argv[2]);
         sprintf(scratchfilenm, "%s/%s.tmp", argv[3], argv[2]);
         sprintf(resultfilenm, "%s/%s.", argv[3], argv[2]);
      }
      if (argc == 5) {
         sprintf(datafilenm, "%s/%s.", argv[3], argv[2]);
         sprintf(scratchfilenm, "%s/%s.tmp", argv[4], argv[2]);
         sprintf(resultfilenm, "%s/%s.", argv[3], argv[2]);
      }
      isign = atoi(argv[1]);

      /*  Add the appropriate suffix to the filenames. */

      if (isign == 1) {
         strcat(datafilenm, "fft");
         strcat(resultfilenm, "dat");
      } else {
         strcat(datafilenm, "dat");
         strcat(resultfilenm, "fft");
      }

      /*  Check the input data set...  */

      printf("Checking data in \"%s\".\n", datafilenm);
      datafile = chkfopen(datafilenm, "rb");

      /* # of real data points */

      numdata = chkfilelen(datafile, sizeof(float));
/*     next2ton = next2_to_n(numdata); */
/*     if (numdata != next2ton) { */
/*       printf("\nNumber of data pts must be an integer power of two,\n"); */
/*       printf("     or data must be single precision floats.\n"); */
/*       printf("Exiting.\n\n"); */
/*       fclose(datafile); */
/*       exit(1); */
/*     } */
      printf("Data OK.  There are %ld points.\n\n", numdata);
      fclose(datafile);
   } else {
      printf("\nUsage:  realfft sign datafilename [ data path] ");
      printf("[scratch path]\n\n");
      printf("  This program calculates the FFT of a file containing\n");
      printf("  a power-of-two number of floats representing\n");
      printf("  real numbers.  (i.e. a normal time series)\n\n");
      printf("  THE INPUT FILE WILL BE OVERWRITTEN.\n\n");
      printf("  \"sign\" is the sign of the exponential during the FFT. \n");
      printf("  (i.e. -1 is the standard forward transform, 1 is the\n");
      printf("  inverse transform times N (the number of floats))\n");
      printf("  If both paths are omitted, the data is assumed to be\n");
      printf("  located in the working directory, and the scratch space\n");
      printf("  if needed will be located there. If only one path is\n");
      printf("  given, both input and scratch files will reside there.\n\n");
      printf("  Notes:\n");
      printf("    - datafilename must not include \".dat\" or \".fft\"\n");
      printf("        suffix. It will be added by the program.\n");
      printf("    - Do not end paths in \"/\".\n");
      printf("    - The scratch file is the same size as the input file.\n");
      printf("    - If \"sign\"=1, the file to be transformed should end\n");
      printf("        with \".fft\".  Otherwise, it should end with\n");
      printf("        \".dat\".\n\n");
      exit(0);
   }

   /*     Start the transform sequence               */

   if (numdata > MAXREALFFT) {

      /*  Perform Two-Pass, Out-of-Core, FFT  */

      printf("Performing Out-of-Core Two-Pass FFT on data.\n\n");
      printf("Result will be stored in the file \"%s\".\n", resultfilenm);

      /*  Initialize files. */

      datafile = chkfopen(datafilenm, "rb+");
      scratchfile = chkfopen(scratchfilenm, "wb+");

      printf("\nTransforming...\n");

      /*     Call Two-Pass routine  */

      if (isign == 1) {
         realfft_scratch_inv(datafile, scratchfile, numdata);
      } else {
         realfft_scratch_fwd(datafile, scratchfile, numdata);
      }

      fclose(scratchfile);

      sprintf(command, "rm -f %s\n", scratchfilenm);
      if ((status = (system(command))) == -1 || status == 127) {
         perror("\nSystem call (rm) failed");
         printf("\n");
         exit(1);
      }
      printf("Finished.\n\n");

      printf("Timing summary:\n");
      tott = times(&runtimes) / (double) CLK_TCK - tott;
      utim = runtimes.tms_utime / (double) CLK_TCK;
      stim = runtimes.tms_stime / (double) CLK_TCK;
      ttim = utim + stim;
      printf("CPU usage: %.3f sec total (%.3f sec user, %.3f sec system)\n",
             ttim, utim, stim);
      printf("Total time elapsed:  %.3f sec.\n\n", tott);

   } else {

      /* Perform standard FFT for real functions  */

      printf("Performing in-core FFT for real functions on data.\n\n");
      printf("FFT will be stored in the file \"%s\".\n\n", resultfilenm);

      /* Open the data and fft results files.    */

      datafile = chkfopen(datafilenm, "rb+");

      /* Read data from file to data array   */

      printf("Reading data.\n\n");
      data = gen_fvect(numdata);
      chkfread(data, sizeof(float), (unsigned long) numdata, datafile);
      chkfileseek(datafile, 0L, sizeof(char), SEEK_SET);

      /* Start and time the transform   */

      printf("Transforming...\n");
      realfft(data, numdata, isign);
      printf("Finished.\n\n");

      /* Write data from FFT array to file  */

      printf("Writing FFT data.\n\n");
      chkfwrite(data, sizeof(float), (unsigned long) numdata, datafile);
      vect_free(data);

      /* Output the timing information */

      printf("Timing summary:\n");
      tott = times(&runtimes) / (double) CLK_TCK - tott;
      utim = runtimes.tms_utime / (double) CLK_TCK;
      stim = runtimes.tms_stime / (double) CLK_TCK;
      ttim = utim + stim;
      printf("CPU usage: %.3f sec total (%.3f sec user, %.3f sec system)\n",
             ttim, utim, stim);
      printf("Total time elapsed:  %.3f sec.\n\n", tott);

   }

   sprintf(command, "mv %s %s\n", datafilenm, resultfilenm);
   if ((status = (system(command))) == -1 || status == 127) {
      perror("\nSystem call (mv) failed");
      printf("\n");
      exit(1);
   }
   fclose(datafile);
   /*
      fftw_print_max_memory_usage();
      fftw_check_memory_leaks();
    */
   exit(0);
}
Example #11
0
float *real_corr_conv(float *data, float *kernel, int numdata,
                      presto_ffts ffts, presto_optype type)
  /* Perform and return a real-valued correlation or convolution.   */
  /* Arguments:                                                     */
  /*   'data' is the complex array to correlate/convolve.           */
  /*   'kernel' is the correlation/convolution kernel.              */
  /*   'numdata' is the length of 'data', 'kernel' and the result.  */
  /*   'ffts' describes how to perform the convolution/correlation. */
  /*      'ffts' = FFTDK:  FFT both the 'data' and the 'kernel'.    */
  /*      'ffts' = FFTD:  FFT only the 'data' not the 'kernel'.     */
  /*      'ffts' = FFTK:  FFT only the 'kernel' not the 'data'.     */
  /*      'ffts' = NOFFTS:  Don't FFT the 'data' or the 'kernel'.   */
  /*   'type' is the type of operation to perform.                  */
  /*      'type' = CONV:  return a convolution in a new vector.     */
  /*      'type' = CORR:  return a correlation in a new vector.     */
  /*      'type' = INPLACE_CONV:  convolution over-writes 'data'.   */
  /*      'type' = INPLACE_CORR:  correlation over-writes 'data'.   */
{
   int ii;
   float normal, tmpd, tmpk, *tmpdat;
   fcomplex *fcdata, *fckern;

   /* Get the normalization factor */

   normal = 2.0 / numdata;

   /* Set up all our parameters */

   if (ffts > 3) {
      printf("\nIllegal 'ffts' option (%d) in real_corr_conv().\n", ffts);
      printf("Exiting\n\n");
      exit(1);
   }
   if (type > 3) {
      printf("\nIllegal 'type' option (%d) in real_corr_conv().\n", ffts);
      printf("Exiting\n\n");
      exit(1);
   }
   if (type == INPLACE_CONV || type == INPLACE_CORR) {
      tmpdat = data;
   } else {
      tmpdat = gen_fvect(numdata);
      memcpy(tmpdat, data, sizeof(float) * numdata);
   }
   if (ffts == FFTDK || ffts == FFTD) {
      realfft(tmpdat, numdata, -1);
   }
   if (ffts == FFTDK || ffts == FFTK) {
      realfft(kernel, numdata, -1);
   }

   // Act like our packed-complex floats are really fcomplex values

   fcdata = (fcomplex *)tmpdat;
   fckern = (fcomplex *)kernel;

   // Do the complex multiplications

   if (type == CORR || type == INPLACE_CORR) {
      for (ii = 1; ii < numdata / 2; ii++) {
         tmpd = fcdata[ii].r;
         tmpk = fckern[ii].r;
         fcdata[ii].r = (tmpd * tmpk + fcdata[ii].i * fckern[ii].i)
             * normal;
         fcdata[ii].i = (fcdata[ii].i * tmpk - fckern[ii].i * tmpd)
             * normal;
      }
   } else {
      for (ii = 1; ii < numdata / 2; ii++) {
         tmpd = fcdata[ii].r;
         tmpk = fckern[ii].r;
         fcdata[ii].r = (tmpd * tmpk - fcdata[ii].i * fckern[ii].i)
             * normal;
         fcdata[ii].i = (fcdata[ii].i * tmpk + fckern[ii].i * tmpd)
             * normal;
      }
   }

   // Now handle bin zero

   fcdata[0].r *= fckern[0].r * normal;
   fcdata[0].i *= fckern[0].i * normal;

   // Perform the inverse FFT on the result and return

   realfft(tmpdat, numdata, 1);
   return tmpdat;
}
Example #12
0
int main(int argc, char *argv[])
{
    FILE *fftfile, *candfile = NULL, *psfile = NULL;
    char filenm[100], candnm[100], psfilenm[120];
    float locpow, norm, powargr, powargi;
    float *powr, *spreadpow, *minizoompow, *freqs;
    fcomplex *data, *minifft, *minizoom, *spread;
    fcomplex *resp, *kernel;
    double T, dr, ftobinp;
    int ii, nbins, ncands, candnum, lofreq = 0, nzoom, numsumpow = 1;
    int numbetween, numkern, kern_half_width;
    binaryprops binprops;
    infodata idata;

    if (argc < 3 || argc > 6) {
        usage();
        exit(1);
    }
    printf("\n\n");
    printf("         Binary Candidate Display Routine\n");
    printf("              by Scott M. Ransom\n\n");

    /* Initialize the filenames: */

    sprintf(filenm, "%s.fft", argv[1]);
    sprintf(candnm, "%s_bin.cand", argv[1]);

    /* Read the info file */

    readinf(&idata, argv[1]);
    if (idata.object) {
        printf("Plotting a %s candidate from '%s'.\n", idata.object, filenm);
    } else {
        printf("Plotting a candidate from '%s'.\n", filenm);
    }
    T = idata.N * idata.dt;

    /* Open the FFT file and get its length */

    fftfile = chkfopen(filenm, "rb");
    nbins = chkfilelen(fftfile, sizeof(fcomplex));

    /* Open the candidate file and get its length */

    candfile = chkfopen(candnm, "rb");
    ncands = chkfilelen(candfile, sizeof(binaryprops));

    /* The candidate number to examine */

    candnum = atoi(argv[2]);

    /* Check that candnum is in range */

    if ((candnum < 1) || (candnum > ncands)) {
        printf("\nThe candidate number is out of range.\n\n");
        exit(1);
    }
    /* The lowest freq present in the FFT file */

    if (argc >= 4) {
        lofreq = atoi(argv[3]);
        if ((lofreq < 0) || (lofreq > nbins - 1)) {
            printf("\n'lofreq' is out of range.\n\n");
            exit(1);
        }
    }
    /* Is the original FFT a sum of other FFTs with the amplitudes added */
    /* in quadrature?  (i.e. an incoherent sum)                          */

    if (argc >= 5) {
        numsumpow = atoi(argv[4]);
        if (numsumpow < 1) {
            printf("\nNumber of summed powers must be at least one.\n\n");
            exit(1);
        }
    }
    /* Initialize PGPLOT using Postscript if requested  */

    if ((argc == 6) && (!strcmp(argv[5], "ps"))) {
        sprintf(psfilenm, "%s_bin_cand_%d.ps", argv[1], candnum);
        cpgstart_ps(psfilenm, "landscape");
    } else {
        cpgstart_x("landscape");
    }

    /* Read the binary candidate */

    chkfileseek(candfile, (long) (candnum - 1), sizeof(binaryprops), SEEK_SET);
    chkfread(&binprops, sizeof(binaryprops), 1, candfile);
    fclose(candfile);

    /* Output the binary candidate */

    print_bin_candidate(&binprops, 2);

    /* Allocate some memory */

    powr = gen_fvect(binprops.nfftbins);
    minifft = gen_cvect(binprops.nfftbins / 2);
    spread = gen_cvect(binprops.nfftbins);
    spreadpow = gen_fvect(binprops.nfftbins);
    nzoom = 2 * ZOOMFACT * ZOOMNEIGHBORS;
    minizoom = gen_cvect(nzoom);
    minizoompow = gen_fvect(nzoom);

    /* Allocate and initialize our interpolation kernel */

    numbetween = 2;
    kern_half_width = r_resp_halfwidth(LOWACC);
    numkern = 2 * numbetween * kern_half_width;
    resp = gen_r_response(0.0, numbetween, numkern);
    kernel = gen_cvect(binprops.nfftbins);
    place_complex_kernel(resp, numkern, kernel, binprops.nfftbins);
    COMPLEXFFT(kernel, binprops.nfftbins, -1);

    /* Read the data from the FFT file */

    data = read_fcomplex_file(fftfile, binprops.lowbin - lofreq, binprops.nfftbins);

    /* Turn the Fourier amplitudes into powers */

    for (ii = 0; ii < binprops.nfftbins; ii++)
        powr[ii] = POWER(data[ii].r, data[ii].i);

    /* Chop the powers that are way above the median level */

    prune_powers(powr, binprops.nfftbins, numsumpow);

    /* Perform the minifft */

    memcpy((float *) minifft, powr, sizeof(float) * binprops.nfftbins);
    realfft((float *) minifft, binprops.nfftbins, -1);

    /* Calculate the normalization constant */

    norm = sqrt((double) binprops.nfftbins * (double) numsumpow) / minifft[0].r;
    locpow = minifft[0].r / binprops.nfftbins;

    /* Divide the original power spectrum by the local power level */

    for (ii = 0; ii < binprops.nfftbins; ii++)
        powr[ii] /= locpow;

    /* Now normalize the miniFFT */

    minifft[0].r = 1.0;
    minifft[0].i = 1.0;
    for (ii = 1; ii < binprops.nfftbins / 2; ii++) {
        minifft[ii].r *= norm;
        minifft[ii].i *= norm;
    }

    /* Interpolate the minifft and convert to power spectrum */

    corr_complex(minifft, binprops.nfftbins / 2, RAW,
                 kernel, binprops.nfftbins, FFT,
                 spread, binprops.nfftbins, kern_half_width,
                 numbetween, kern_half_width, CORR);
    for (ii = 0; ii < binprops.nfftbins; ii++)
        spreadpow[ii] = POWER(spread[ii].r, spread[ii].i);

    /* Plot the initial data set */

    freqs = gen_freqs(binprops.nfftbins, binprops.lowbin / T, 1.0 / T);
    xyline(binprops.nfftbins, freqs, powr, "Pulsar Frequency (hz)",
           "Power / Local Power", 1);
    vect_free(freqs);
    printf("The initial data set (with high power outliers removed):\n\n");

    /* Plot the miniFFT */

    freqs = gen_freqs(binprops.nfftbins, 0.0, T / (2 * binprops.nfftbins));
    xyline(binprops.nfftbins, freqs, spreadpow, "Binary Period (sec)",
           "Normalized Power", 1);
    vect_free(freqs);
    printf("The miniFFT:\n\n");

    /* Interpolate and plot the actual candidate peak */

    ftobinp = T / binprops.nfftbins;
    freqs = gen_freqs(nzoom, (binprops.rdetect - ZOOMNEIGHBORS) *
                      ftobinp, ftobinp / (double) ZOOMFACT);
    for (ii = 0; ii < nzoom; ii++) {
        dr = -ZOOMNEIGHBORS + (double) ii / ZOOMFACT;
        rz_interp(minifft, binprops.nfftbins / 2, binprops.rdetect + dr,
                  0.0, kern_half_width, &minizoom[ii]);
        minizoompow[ii] = POWER(minizoom[ii].r, minizoom[ii].i);
    }
    xyline(nzoom, freqs, minizoompow, "Binary Period (sec)", "Normalized Power", 1);
    vect_free(freqs);
    printf("The candidate itself:\n\n");
    printf("Done.\n\n");

    /* Cleanup */

    cpgend();
    vect_free(data);
    vect_free(powr);
    vect_free(resp);
    vect_free(kernel);
    vect_free(minifft);
    vect_free(spread);
    vect_free(spreadpow);
    vect_free(minizoom);
    vect_free(minizoompow);
    fclose(fftfile);
    if ((argc == 6) && (!strcmp(argv[5], "ps"))) {
        fclose(psfile);
    }
    return (0);
}
Example #13
0
t_int *fft_real_perform(t_int *w)
{
	t_fft *x = (t_fft *)(w[1]);
	float *in = (float *)(w[2]);
	float *out = (float *)(w[3]);
	float *outsync = (float *)(w[4]);
	int n = w[5],m,np,count;
	long pts = x->f_points, interval = x->f_interval;
	float *b, *ei = x->f_realin + pts, *eo = x->f_realout + pts;
	float mult = x->f_1overpts;
	
	if (x->f_obj.z_disabled)
		goto out;
	
	if (n > pts) {
		np = pts;
		count = n / pts;
	} else {
		np = n;
		count = 1;
	}
	m = np;
	while (count--) {
#ifdef USING_PHASE
		if (x->f_start) {
			long phase = x->f_phase % interval;
			if (phase < pts)
				x->f_realoutptr = x->f_realout + phase;
			else
				x->f_realoutptr = x->f_realout + pts;
			if (pts + phase >= interval) {
				x->f_countdown = 0;
				x->f_realinptr = x->f_realin + (pts + phase - interval);
			} else {
				x->f_countdown = (interval - phase - pts) / np;
				x->f_realinptr = x->f_realin;
			}
			x->f_start = 0;
		}
#endif
		if (x->f_countdown) {
			x->f_countdown--;
			b = 0;
		} else {
			b = x->f_realinptr;
			BlockMove(in,b, np * sizeof(float));
			b += np;
		}
		if (x->f_realoutptr != eo) {
			double q = (int)(x->f_realoutptr - x->f_realout);
			BlockMove(x->f_realoutptr,out,np * sizeof(float));
			x->f_realoutptr += np;
			if (!fts_mode) {
				while (m--) {
					*outsync++ = q;
					q += 1.0;
				}
			}
		} else {
			if (!fts_mode) {
				while (m--)
					*outsync++ = 0.;
			}
		}
		if (b == ei) {
			BlockMove(x->f_realin,x->f_realout,pts * sizeof(float));
			if (x->f_inverse) {
				float *real = x->f_realout;
				float mult = x->f_1overpts;
				realifft(pts, real);
				while (pts--)
					*real++ *= mult;
			} else
				realfft(pts, x->f_realout);
			x->f_realoutptr = x->f_realout;
			x->f_realinptr = x->f_realin;
			x->f_countdown = (interval - x->f_points) / np;
			if (fts_mode)
				clock_delay(x->f_clock, 0L);
		} else if (b) {
			x->f_realinptr += np;
		}
	}
out:
	return (w + 6);
}
Example #14
0
void soundspec_update_wave(int32 *buff, int samples)
{
    int i;

    if(buff == NULL) /* Initialize */
    {
	ring_index = 0;
	if(samples == 0)
	{
	    outcnt = 0;
	    next_wakeup_samples = 0;
	}
	if(ring_buffer != NULL)
	    memset(ring_buffer, 0, sizeof(int32));
	return;
    }

    if(!view_soundspec_flag && !ctl_speana_flag)
    {
	outcnt += samples;
	return;
    }

    if(ring_buffer == NULL)
    {
	ring_buffer = safe_malloc(ring_buffer_len * sizeof(int32));
	memset(ring_buffer, 0, sizeof(int32));
	if(soundspec_update_interval == 0)
	    soundspec_update_interval =
		(int32)(DEFAULT_UPDATE * play_mode->rate);
	realfft(NULL, FFTSIZE);
	initialize_exp_hz_table(soundspec_zoom);
    }

    if(ring_index + samples > ring_buffer_len)
    {
	int d;

	d = ring_buffer_len - ring_index;
	if(play_mode->encoding & PE_MONO)
	    memcpy(ring_buffer + ring_index, buff, d * 4);
	else
	{
	    int32 *p;
	    int n;

	    p = ring_buffer + ring_index;
	    n = d * 2;
	    for(i = 0; i < n; i += 2)
		*p++ = (buff[i] + buff[i + 1]) / 2;
	}
	ring_index = 0;
	outcnt += d;
	samples -= d;
    }

    if(play_mode->encoding & PE_MONO)
	memcpy(ring_buffer + ring_index, buff, samples * 4);
    else
    {
	int32 *p;
	int n;

	p = ring_buffer + ring_index;
	n = samples * 2;
	for(i = 0; i < n; i += 2)
	    *p++ = (buff[i] + buff[i + 1]) / 2;
    }

    ring_index += samples;
    outcnt += samples;
    if(ring_index == ring_buffer_len)
	ring_index = 0;

    if(next_wakeup_samples < outcnt - (ring_buffer_len - FFTSIZE))
    {
	/* next_wakeup_samples is too small */
	next_wakeup_samples = outcnt - (ring_buffer_len - FFTSIZE);
    }

    while(next_wakeup_samples < outcnt - FFTSIZE)
    {
	double x[FFTSIZE];
	struct drawing_queue *q;

	ringsamples(x, next_wakeup_samples % ring_buffer_len, FFTSIZE);
	q = new_queue();
	decibelspec(x, q->values);
	push_midi_time_vp(midi_trace.offset + next_wakeup_samples,
			  trace_draw_scope,
			  q);
	next_wakeup_samples += soundspec_update_interval;
    }
}
float TramaParametriza(Ttrastero *trastero,TTrastero2 *trastero2,int32 nframes, Tparamet *paramet)
	{
   float total;
   FILE *fp;
   static int gendatos = 0;

   if (gendatos == 0)
     {
     fp = fopen("datospar.sal", "wt");
     fprintf(fp, "Coef preenf:          %f\n", __coef_preenf);
     fprintf(fp, "Coef rasta :          %f\n", __coef_rasta);
     fprintf(fp, "Coef preenf rasta:    %f\n", trastero->preenf);
     fclose(fp);
     }
   else
     gendatos = 1;

	VectorImprimir("jlpc.dep",nframes,trastero->a,__long_ventana,"antes preenf...");
	//VectorImprimir("jlpc.dep",nframes,trastero->hamwei,__long_ventana,"hamwei");
	Hamm_Preenf(trastero->a, trastero->hamwei,__coef_preenf);
	VectorImprimir("jlpc.dep",nframes,trastero->a,__long_ventana,"tras preenf...");

	/* CÁLCULO DE LA FFT PARA CADA TRAMA */
   realfft(__fft_points,trastero->a);

   Energia(trastero->a,trastero->c,__fft_points/2,trastero->y);
	VectorImprimir("jlpc.dep",nframes,trastero->c,__fft_points/2,"FFT");

   total=Promedio(trastero->c,__fft_points/2);
   total=10*LOG10(total);

  __energias[nframes]=paramet->mfc[0][nframes][__numParam-1]=trastero->nmfc[nframes][__numParam-1]=total;
  //__ErrMsg(stderr,"mfcc y energ'ia\n");

	/* ENERGÍA EN CADA FILTRO */
	plp(trastero->pptr.nfilts, trastero->filwei, trastero->ibegen, trastero->c,
       trastero->sp, trastero->splog, nframes, trastero->filtertype);
	VectorImprimir("jlpc.dep",nframes,trastero->splog[nframes],
                  trastero->pptr.nfilts,"LogEnergBand tras PLP");
  //__ErrMsg(stderr,"plp\n");
  /* RASTA FILTERING AND RASTA MEL */

  rasta_trama (trastero->pptr.nfilts, trastero->preenf, trastero->sp,
               trastero->splog, trastero->spfilt, nframes, paramet->mfc,
               trastero->nmfc,trastero->filtertype, trastero->_melNum,&(trastero->pptr));
  if (nframes>=4)
  		{
		VectorImprimir("jlpc.dep",nframes-4,trastero->splog[nframes-4],trastero->pptr.nfilts,"LogEnergBand2 tras PLP");
		VectorImprimir("jlpc.dep",nframes-3,trastero->splog[nframes-3],trastero->pptr.nfilts,"LogEnergBand2 tras PLP");
		VectorImprimir("jlpc.dep",nframes-2,trastero->splog[nframes-2],trastero->pptr.nfilts,"LogEnergBand2 tras PLP");
		VectorImprimir("jlpc.dep",nframes-1,trastero->splog[nframes-1],trastero->pptr.nfilts,"LogEnergBand2 tras PLP");
		VectorImprimir("jlpc.dep",nframes,trastero->splog[nframes],trastero->pptr.nfilts,"LogEnergBand2 tras PLP");
		VectorImprimir("jlpc.dep",nframes,trastero->spfilt[nframes],trastero->pptr.nfilts,"LogEnergBand tras rasta");
      VectorImprimir("jlpc.dep",nframes,paramet->mfc[0][nframes],trastero->_melNum,"parrasta");
      }
  if (paramet->n_codeBooks > 1)
  	{
   __CalculaDelta_trama (paramet, nframes-DELTA,trastero2);
  if (nframes>=DELTA)
      VectorImprimir("jlpc.dep",nframes-DELTA,paramet->mfc[1][nframes-DELTA],trastero->_melNum,"delta parrasta");
   }
	//falta un factor 2 PI? parece que no
  return total;
  }
Example #16
0
void create_accelobs(accelobs * obs, infodata * idata, Cmdline * cmd, int usemmap)
{
   int ii, rootlen, input_shorts = 0;

   {
      int hassuffix = 0;
      char *suffix;

      hassuffix = split_root_suffix(cmd->argv[0], &(obs->rootfilenm), &suffix);
      if (hassuffix) {
         if (strcmp(suffix, "fft") != 0 &&
             strcmp(suffix, "dat") != 0 && strcmp(suffix, "sdat") != 0) {
            printf("\nInput file ('%s') must be an '.fft' or '.[s]dat' file!\n\n",
                   cmd->argv[0]);
            free(suffix);
            exit(0);
         }
         /* If the input file is a time series */
         if (strcmp(suffix, "dat") == 0 || strcmp(suffix, "sdat") == 0) {
            obs->dat_input = 1;
            obs->mmap_file = 0;
            if (strcmp(suffix, "sdat") == 0)
               input_shorts = 1;
         } else {
            obs->dat_input = 0;
         }
         free(suffix);
      } else {
         printf("\nInput file ('%s') must be an '.fft' or '.[s]dat' file!\n\n",
                cmd->argv[0]);
         exit(0);
      }
   }

   if (cmd->noharmpolishP)
       obs->use_harmonic_polishing = 0;
   else
       obs->use_harmonic_polishing = 1;  // now default

   /* Read the info file */

   readinf(idata, obs->rootfilenm);
   if (idata->object) {
      printf("Analyzing %s data from '%s'.\n\n",
             remove_whitespace(idata->object), cmd->argv[0]);
   } else {
      printf("Analyzing data from '%s'.\n\n", cmd->argv[0]);
   }

   /* Prepare the input time series if required */

   if (obs->dat_input) {
      FILE *datfile;
      long long filelen;
      float *ftmp;

      printf("Reading and FFTing the time series...");
      fflush(NULL);
      datfile = chkfopen(cmd->argv[0], "rb");

      /* Check the length of the file to see if we can handle it */
      filelen = chkfilelen(datfile, sizeof(float));
      if (input_shorts)
         filelen *= 2;
      if (filelen > 67108864) { /* Small since we need memory for the templates */
         printf("\nThe input time series is too large.  Use 'realfft' first.\n\n");
         exit(0);
      }

      /* Read the time series into a temporary buffer */
      /* Note:  The padding allows us to search very short time series */
      /*        using correlations without having to worry about       */
      /*        accessing data before or after the valid FFT freqs.    */
      if (input_shorts) {
         short *stmp = gen_svect(filelen);
         ftmp = gen_fvect(filelen+2*ACCEL_PADDING);
         for (ii = 0; ii < ACCEL_PADDING; ii++) {
             ftmp[ii] = 0.0;
             ftmp[ii+filelen+ACCEL_PADDING] = 0.0;
         }
         chkfread(stmp, sizeof(short), filelen, datfile);
         for (ii = 0; ii < filelen; ii++)
            ftmp[ii+ACCEL_PADDING] = (float) stmp[ii];
         free(stmp);
      } else {
         ftmp = read_float_file(datfile, -ACCEL_PADDING, filelen+2*ACCEL_PADDING);
      }
      /* Now, offset the pointer so that we are pointing at the first */
      /* bits of valid data.                                          */
      ftmp += ACCEL_PADDING;
      fclose(datfile);

      /* FFT it */
      realfft(ftmp, filelen, -1);
      obs->fftfile = NULL;
      obs->fft = (fcomplex *) ftmp;
      obs->numbins = filelen / 2;
      printf("done.\n");

      /* De-redden it */
      printf("Removing red-noise...");
      deredden(obs->fft, obs->numbins);
      printf("done.\n\n");
   }

   /* Determine the output filenames */

   rootlen = strlen(obs->rootfilenm) + 25;
   obs->candnm = (char *) calloc(rootlen, 1);
   obs->accelnm = (char *) calloc(rootlen, 1);
   obs->workfilenm = (char *) calloc(rootlen, 1);
   sprintf(obs->candnm, "%s_ACCEL_%d.cand", obs->rootfilenm, cmd->zmax);
   sprintf(obs->accelnm, "%s_ACCEL_%d", obs->rootfilenm, cmd->zmax);
   sprintf(obs->workfilenm, "%s_ACCEL_%d.txtcand", obs->rootfilenm, cmd->zmax);

   /* Open the FFT file if it exists appropriately */
   if (!obs->dat_input) {
      obs->fftfile = chkfopen(cmd->argv[0], "rb");
      obs->numbins = chkfilelen(obs->fftfile, sizeof(fcomplex));
      if (usemmap) {
         fclose(obs->fftfile);
         obs->fftfile = NULL;
         printf("Memory mapping the input FFT.  This may take a while...\n");
         obs->mmap_file = open(cmd->argv[0], O_RDONLY);
         if (obs->mmap_file == -1) {
            perror("\nError in open() in accel_utils.c");
            printf("\n");
            exit(-1);
         }
         obs->fft = (fcomplex *) mmap(0, sizeof(fcomplex) * obs->numbins, PROT_READ,
                                      MAP_SHARED, obs->mmap_file, 0);
         if (obs->fft == MAP_FAILED) {
            perror("\nError in mmap() in accel_utils.c");
            printf("Falling back to a non-mmaped approach\n");
            obs->fftfile = chkfopen(cmd->argv[0], "rb");
            obs->mmap_file = 0;
         }
      } else {
         obs->mmap_file = 0;
      }
   }

   /* Determine the other parameters */

   if (cmd->zmax % ACCEL_DZ)
      cmd->zmax = (cmd->zmax / ACCEL_DZ + 1) * ACCEL_DZ;
   if (!obs->dat_input)
      obs->workfile = chkfopen(obs->workfilenm, "w");
   obs->N = (long long) idata->N;
   if (cmd->photonP) {
      if (obs->mmap_file || obs->dat_input) {
         obs->nph = obs->fft[0].r;
      } else {
         obs->nph = get_numphotons(obs->fftfile);
      }
      printf("Normalizing powers using %.0f photons.\n\n", obs->nph);
   } else {
      obs->nph = 0.0;
      /* For short FFTs insure that we don't pick up the DC */
      /* or Nyquist component as part of the interpolation  */
      /* for higher frequencies.                            */
      if (cmd->locpowP) {
          obs->norm_type = 1;
          printf("Normalizing powers using local-power determination.\n\n");
      } else if (cmd->medianP) {
          obs->norm_type = 0;
          printf("Normalizing powers using median-blocks.\n\n");
      } else {
          obs->norm_type = 0;
          printf("Normalizing powers using median-blocks (default).\n\n");
      }
      if (obs->dat_input) {
         obs->fft[0].r = 1.0;
         obs->fft[0].i = 1.0;
      }
   }
   obs->lobin = cmd->lobin;
   if (obs->lobin > 0) {
      obs->nph = 0.0;
      if (cmd->lobin > obs->numbins - 1) {
         printf("\n'lobin' is greater than the total number of\n");
         printf("   frequencies in the data set.  Exiting.\n\n");
         exit(1);
      }
   }
   if (cmd->numharm != 1 &&
       cmd->numharm != 2 &&
       cmd->numharm != 4 && cmd->numharm != 8 && cmd->numharm != 16) {
      printf("\n'numharm' = %d must be a power-of-two!  Exiting\n\n", cmd->numharm);
      exit(1);
   }
   obs->numharmstages = twon_to_index(cmd->numharm) + 1;
   obs->dz = ACCEL_DZ;
   obs->numz = cmd->zmax * 2 + 1;
   obs->numbetween = ACCEL_NUMBETWEEN;
   obs->dt = idata->dt;
   obs->T = idata->dt * idata->N;
   if (cmd->floP) {
      obs->rlo = floor(cmd->flo * obs->T);
      if (obs->rlo < obs->lobin)
         obs->rlo = obs->lobin;
      if (obs->rlo > obs->numbins - 1) {
         printf("\nLow frequency to search 'flo' is greater than\n");
         printf("   the highest available frequency.  Exiting.\n\n");
         exit(1);
      }
   } else {
      if (cmd->rloP)
         obs->rlo = cmd->rlo;
      else
         obs->rlo = 1.0;
      if (obs->rlo < obs->lobin)
         obs->rlo = obs->lobin;
      if (obs->rlo > obs->numbins - 1) {
         printf("\nLow frequency to search 'rlo' is greater than\n");
         printf("   the available number of points.  Exiting.\n\n");
         exit(1);
      }
   }
   obs->highestbin = obs->numbins - 1;
   if (cmd->fhiP) {
      obs->highestbin = ceil(cmd->fhi * obs->T);
      if (obs->highestbin > obs->numbins - 1)
         obs->highestbin = obs->numbins - 1;
      obs->rhi = obs->highestbin;
      if (obs->highestbin < obs->rlo) {
         printf("\nHigh frequency to search 'fhi' is less than\n");
         printf("   the lowest frequency to search 'flo'.  Exiting.\n\n");
         exit(1);
      }
   } else if (cmd->rhiP) {
      obs->highestbin = cmd->rhi;
      if (obs->highestbin > obs->numbins - 1)
         obs->highestbin = obs->numbins - 1;
      obs->rhi = obs->highestbin;
      if (obs->highestbin < obs->rlo) {
         printf("\nHigh frequency to search 'rhi' is less than\n");
         printf("   the lowest frequency to search 'rlo'.  Exiting.\n\n");
         exit(1);
      }
   }
   obs->dr = ACCEL_DR;
   obs->zhi = cmd->zmax;
   obs->zlo = -cmd->zmax;
   obs->sigma = cmd->sigma;
   obs->powcut = (float *) malloc(obs->numharmstages * sizeof(float));
   obs->numindep = (long long *) malloc(obs->numharmstages * sizeof(long long));
   for (ii = 0; ii < obs->numharmstages; ii++) {
      if (obs->numz == 1)
         obs->numindep[ii] = (obs->rhi - obs->rlo) / index_to_twon(ii);
      else
         /* The numz+1 takes care of the small amount of  */
         /* search we get above zmax and below zmin.      */
         obs->numindep[ii] = (obs->rhi - obs->rlo) * (obs->numz + 1) *
             (obs->dz / 6.95) / index_to_twon(ii);
      obs->powcut[ii] = power_for_sigma(obs->sigma,
                                        index_to_twon(ii), obs->numindep[ii]);
   }
   obs->numzap = 0;
   /*
      if (zapfile!=NULL)
      obs->numzap = get_birdies(cmd->zapfile, obs->T, obs->baryv, 
      &(obs->lobins), &(obs->hibins));
      else
      obs->numzap = 0;
    */
}
Example #17
0
void output_fundamentals(fourierprops * props, GSList * list,
                         accelobs * obs, infodata * idata)
{
   double accel = 0.0, accelerr = 0.0, coherent_pow;
   int ii, jj, numcols = 12, numcands, *width, *error;
   int widths[12] = { 4, 5, 6, 8, 4, 16, 15, 15, 15, 11, 15, 20 };
   int errors[12] = { 0, 0, 0, 0, 0, 1, 1, 2, 1, 2, 2, 0 };
   char tmpstr[30], ctrstr[30], *notes;
   accelcand *cand;
   GSList *listptr;
   rzwerrs errs;
   static char **title;
   static char *titles1[] = { "", "", "Summed", "Coherent", "Num", "Period",
      "Frequency", "FFT 'r'", "Freq Deriv", "FFT 'z'",
      "Accel", ""
   };
   static char *titles2[] = { "Cand", "Sigma", "Power", "Power", "Harm", "(ms)",
      "(Hz)", "(bin)", "(Hz/s)", "(bins)",
      "(m/s^2)", "Notes"
   };

   numcands = g_slist_length(list);
   listptr = list;

   /* Close the old work file and open the cand file */

   if (!obs->dat_input)
      fclose(obs->workfile); /* Why is this here? -A */
   obs->workfile = chkfopen(obs->accelnm, "w");

   /* Set our candidate notes to all spaces */

   notes = (char *) malloc(numcands * widths[numcols - 1]);
   memset(notes, ' ', numcands * widths[numcols - 1]);

   /* Compare the candidates with the pulsar database */

   if (dms2rad(idata->ra_h, idata->ra_m, idata->ra_s) != 0.0 &&
       hms2rad(idata->dec_d, idata->dec_m, idata->dec_s) != 0.0) {
      for (ii = 0; ii < numcands; ii++) {
         comp_psr_to_cand(props + ii, idata, notes + ii * 20, 0);
      }
   }

   /* Compare the candidates with themselves */

   compare_rzw_cands(props, numcands, notes);

   /* Print the header */

   width = widths;
   title = titles1;
   for (ii = 0; ii < numcols - 1; ii++) {
      center_string(ctrstr, *title++, *width++);
      fprintf(obs->workfile, "%s  ", ctrstr);
   }
   center_string(ctrstr, *title++, *width++);
   fprintf(obs->workfile, "%s\n", ctrstr);

   width = widths;
   title = titles2;
   for (ii = 0; ii < numcols - 1; ii++) {
      center_string(ctrstr, *title++, *width++);
      fprintf(obs->workfile, "%s  ", ctrstr);
   }
   center_string(ctrstr, *title++, *width++);
   fprintf(obs->workfile, "%s\n", ctrstr);

   width = widths;
   for (ii = 0; ii < numcols - 1; ii++) {
      memset(tmpstr, '-', *width);
      tmpstr[*width++] = '\0';
      fprintf(obs->workfile, "%s--", tmpstr);
   }
   memset(tmpstr, '-', *width++);
   tmpstr[widths[ii]] = '\0';
   fprintf(obs->workfile, "%s\n", tmpstr);

   /* Print the fundamentals */

   for (ii = 0; ii < numcands; ii++) {
      width = widths;
      error = errors;
      cand = (accelcand *) (listptr->data);
      calc_rzwerrs(props + ii, obs->T, &errs);

      {                         /* Calculate the coherently summed power */
         double coherent_r = 0.0, coherent_i = 0.0;
         double phs0, phscorr, amp;
         rderivs harm;
         double ifft_peak;

         /* These phase calculations assume the fundamental is best */
         /* Better to irfft them and check the amplitude */
         phs0 = cand->derivs[0].phs;
         if (obs->use_new_coherent_power) {
             float* profile;
             double amp;
             const int upsample=4;
             profile = gen_fvect(cand->numharm*upsample*2);
             for(jj=0;jj<cand->numharm*upsample*2;jj++)
                 profile[jj]=0;

             for(jj=0; jj<cand->numharm; jj++) {
                 harm = cand->derivs[jj];
                 if (obs->nph > 0.0)
                     amp = sqrt(harm.pow / obs->nph);
                 else
                     amp = sqrt(harm.pow / harm.locpow);
                 phscorr = - fmod((jj + 1.0) * phs0, TWOPI);
                 profile[2*jj+2] = amp*cos(harm.phs+phscorr);
                 profile[2*jj+3] = amp*sin(harm.phs+phscorr);
             }
             realfft(profile, cand->numharm*upsample*2, 1);
             ifft_peak = 0;
             for(jj=0;jj<cand->numharm*upsample*2;jj++) {
                 if (profile[jj]>ifft_peak) {
                     ifft_peak = profile[jj];
                 }
             }
             ifft_peak *= cand->numharm*upsample;
             coherent_pow = ifft_peak*ifft_peak;
             free(profile);
         } else {
             /* These phase calculations assume the fundamental is best */
             /* Better to irfft them and check the amplitude */
             for (jj = 0; jj < cand->numharm; jj++) {
                harm = cand->derivs[jj];
                if (obs->nph > 0.0)
                   amp = sqrt(harm.pow / obs->nph);
                else
                   amp = sqrt(harm.pow / harm.locpow);
                phscorr = - fmod((jj + 1.0) * phs0, TWOPI);
                coherent_r += amp * cos(harm.phs + phscorr);
                coherent_i += amp * sin(harm.phs + phscorr);
             }
             coherent_pow = coherent_r * coherent_r + coherent_i * coherent_i;
         }
      }

      sprintf(tmpstr, "%-4d", ii + 1);
      center_string(ctrstr, tmpstr, *width++);
      error++;
      fprintf(obs->workfile, "%s  ", ctrstr);

      sprintf(tmpstr, "%.2f", cand->sigma);
      center_string(ctrstr, tmpstr, *width++);
      error++;
      fprintf(obs->workfile, "%s  ", ctrstr);

      sprintf(tmpstr, "%.2f", cand->power);
      center_string(ctrstr, tmpstr, *width++);
      error++;
      fprintf(obs->workfile, "%s  ", ctrstr);

      sprintf(tmpstr, "%.2f", coherent_pow);
      center_string(ctrstr, tmpstr, *width++);
      error++;
      fprintf(obs->workfile, "%s  ", ctrstr);

      sprintf(tmpstr, "%d", cand->numharm);
      center_string(ctrstr, tmpstr, *width++);
      error++;
      fprintf(obs->workfile, "%s  ", ctrstr);

      write_val_with_err(obs->workfile, errs.p * 1000.0, errs.perr * 1000.0,
                         *error++, *width++);
      write_val_with_err(obs->workfile, errs.f, errs.ferr, *error++, *width++);
      write_val_with_err(obs->workfile, props[ii].r, props[ii].rerr,
                         *error++, *width++);
      write_val_with_err(obs->workfile, errs.fd, errs.fderr, *error++, *width++);
      write_val_with_err(obs->workfile, props[ii].z, props[ii].zerr,
                         *error++, *width++);
      accel = props[ii].z * SOL / (obs->T * obs->T * errs.f);
      accelerr = props[ii].zerr * SOL / (obs->T * obs->T * errs.f);
      write_val_with_err(obs->workfile, accel, accelerr, *error++, *width++);
      fprintf(obs->workfile, "  %.20s\n", notes + ii * 20);
      fflush(obs->workfile);
      listptr = listptr->next;
   }
   fprintf(obs->workfile, "\n\n");
   free(notes);
}