示例#1
0
 int findPeakElement(vector<int>& nums) {
     int len = nums.size();
     if(!len)
         return -1;
     return find_peak(nums, 0, len-1);
     
 }
示例#2
0
static double
find_attenuation (double freq, int converter, int verbose)
{	static float input	[BUFFER_LEN] ;
	static float output [2 * BUFFER_LEN] ;

	SRC_DATA	src_data ;
	double 		output_peak ;
	int			error ;

	gen_windowed_sines (input, BUFFER_LEN, &freq, 1) ;

	src_data.end_of_input = 1 ; /* Only one buffer worth of input. */

	src_data.data_in = input ;
	src_data.input_frames = BUFFER_LEN ;

	src_data.src_ratio = 1.999 ;

	src_data.data_out = output ;
	src_data.output_frames = ARRAY_LEN (output) ;

	if ((error = src_simple (&src_data, converter, 1)))
	{	printf ("\n\nLine %d : %s\n\n", __LINE__, src_strerror (error)) ;
		exit (1) ;
		} ;

	output_peak = find_peak (output, ARRAY_LEN (output)) ;

	if (verbose)
		printf ("\tFreq : %6f   InPeak : %6f    OutPeak : %6f   Atten : %6.2f dB\n",
				freq, 1.0, output_peak, 20.0 * log10 (1.0 / output_peak)) ;

	return 20.0 * log10 (1.0 / output_peak) ;
} /* find_attenuation */
示例#3
0
文件: llsm.c 项目: Icenowy/libllsm
static void find_harmonic_trajectory(llsm_parameters param, FP_TYPE** spectrogram, FP_TYPE** phasegram,
  int nfft, int fs, FP_TYPE* f0, int nf0, int idx, FP_TYPE* freq, FP_TYPE* ampl, FP_TYPE* phse) {
  const FP_TYPE hardev = 0.3;
  FP_TYPE cand_bin[20];
  int cand_bin_n = 0;
  for(int i = 0; i < nf0; i ++) {
    freq[i] = 0;
    ampl[i] = 0;
    phse[i] = 0;
    if(f0[i] < 50 || f0[i] * idx > param.a_mvf)
      continue;

    int l_idx = round(f0[i] * (idx - hardev) / fs * nfft);
    int u_idx = round(f0[i] * (idx + hardev) / fs * nfft);
    l_idx = l_idx < 1 ? 1 : l_idx;
    u_idx = u_idx > nfft / 2 - 1 ? nfft / 2 - 1 : u_idx;

    cand_bin_n = find_peak_cand(cand_bin, spectrogram[i], nfft / 2, l_idx, u_idx, 0.0, 20);
    int peak_bin;
    if(cand_bin_n > 0)
      peak_bin = cand_bin[select_nearest_cand(cand_bin, cand_bin_n, f0[i] * idx / fs * nfft)];
    else
      peak_bin = find_peak(spectrogram[i], l_idx, u_idx, 1);
    
    FP_TYPE peak_freq, peak_ampl;
    interp_peak(& peak_freq, & peak_ampl, spectrogram[i], peak_bin);
    freq[i] = peak_freq * fs / nfft;
    ampl[i] = exp(peak_ampl);
    phse[i] = linterp(phasegram[i][(int)peak_freq], phasegram[i][(int)peak_freq + 1], fmod(peak_freq, 1.0));
    
    if(isnan(ampl[i])) // peak amplitude goes nan if one of the bins = -INF
      ampl[i] = 0;
  }
}
示例#4
0
 int find_peak(vector<int>& nums, int left, int right)
 {
     int mid = (left+right)/2;
     int len = nums.size();
     bool l_lar = false;
     bool r_lar = false;
     if(mid -1<0 || nums[mid]>nums[mid-1])
         l_lar = true;
     if(mid+1>=len || nums[mid]>nums[mid+1])
         r_lar = true;
     if(l_lar && r_lar)
         return mid;
     if(l_lar)
         return find_peak(nums, mid+1, right);
     else
         return find_peak(nums, left, mid);
 }
示例#5
0
void print_dominant(double xs[], int len) {
    double upper_limit = INFINITY;
    for(int i = 0; i < 20; i++) {
        struct peak p = find_peak(xs, len, upper_limit);
        printf("%d ", NUM_BLOCKS * p.ix);
        upper_limit = p.value;
    }
    printf("\n");
}
示例#6
0
文件: fdt.c 项目: shidai/ptimeD
int InitialGuess (double *s, double *p, int nphase, int nchn, int *chn) 
{
	int index;
	double frac_off = 0.05;  // set to be 0.05

	double ptemp[nphase];
	double temp[nchn];
	int i, h;
	for (i = 0; i < nchn; i++)
	{
		for (h = 0; h < nphase; h++)
		{
			ptemp[h] = p[i*nphase+h];
		}
		int x;
		x = def_off_pulse (nphase, ptemp, frac_off);

		double ptemp_out[nphase];
		pre_diff (ptemp, nphase, x, frac_off, ptemp_out);

		temp[i] = find_peak_value(nphase,ptemp_out);
	}

	int peak;
	find_peak (0, nchn, temp, &peak);
	//printf ("%d\n",peak);
	(*chn) = peak;

	double p_use[nphase];
	double s_use[nphase];
	for (h = 0; h < nphase; h++)
	{
		p_use[h] = p[peak*nphase+h];
		s_use[h] = s[peak*nphase+h];
	}

	// remove the baseline of template
	index = def_off_pulse (nphase, s_use, frac_off);

	double s_out[nphase];
	pre_diff (s_use, nphase, index, frac_off, s_out);

	// remove the baseline of profile
	index = def_off_pulse (nphase, p_use, frac_off);

	double p_out[nphase];
	pre_diff (p_use, nphase, index, frac_off, p_out);

	// Guess the phase shift
	int d;
	d = corr (s_out, p_out, nphase);

	return d;
}
/*--------------------------------------------------------------------------------*/
size_t find_peak_wrapper(float *data, int nchan, int ndata, float *peak_snr, int *peak_channel, int *peak_sample, int *peak_duration)
{
  Data dat;
  float **mat=(float **)malloc(sizeof(float *)*nchan);
  for (int i=0;i<nchan;i++)
    mat[i]=data+i*ndata;
  dat.data=mat;
  dat.ndata=ndata;
  dat.nchan=nchan;
  Peak best=find_peak(&dat);
  free(dat.data); //get rid of the pointer array
  *peak_snr=best.snr;
  *peak_channel=best.dm_channel;
  //starting sample of the burst
  *peak_sample=best.ind*(1<<best.depth);
  *peak_duration=best.duration*(1<<best.depth);
  return 0;
  
}
示例#8
0
文件: fdt.c 项目: shidai/ptimeD
int get_toa (double *s, double *p, double *phasex, double *errphasex, double psrfreq, int nphase, double *rms, double *bx)
// calculate the phase shift between template and simulated (or real) data 
// error of phase can be calculated
// initial guess of phase shift is added
// try to do two-dim template matching
{
    //int nphase=1024;
    int nchn=1;

	// read a std
	
	//puts(argv[1]);
	//puts(argv[2]);
	//double t[nphase*nchn],s[nphase*nchn];
	//int n;

	//readfile(name,&n,t,s);
	//printf ("%d\n", n);
	//puts(argv[1]);

	//////////////////////////////////////////////////////////////////////////
	// simulate data

	//double p[nphase*nchn];
	//double SNR=atof(argv[2]);
	//simulate(n,SNR,s,p);//*/
	
	/////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////
	// dft profile and template
	
	//nchn = n/nphase;
	//printf ("%d\n", nchn);
	int k;  // k=nphase/2

	//double amp_s[nchn][nphase/2],amp_p[nchn][nphase/2];  // elements for calculating A7
	//double phi_s[nchn][nphase/2],phi_p[nchn][nphase/2];
	params param;
	allocateMemoryPtime (&param, nchn, nphase);
	//double amp_s[nchn][NP],amp_p[nchn][NP];  // elements for calculating A7
	//double phi_s[nchn][NP],phi_p[nchn][NP];  // the second dim should be NP, which is large enough for different observations

	preA7(s, p, nphase, nchn, &param);
	//preA7(&k, amp_s, amp_p, phi_s, phi_p, s, p, nphase, nchn);
	//printf ("%d\n", nchn);
	
	// initial guess of the phase
	int peak_s, peak_p;	

	find_peak(0, nphase,s,&peak_s);
	find_peak(0, nphase,p,&peak_p);

	int d, chn;
	double step;
	double ini_phase,up_phase,low_phase;

	d = InitialGuess (s, p, nphase, 1, &chn);
	//d=peak_p-peak_s;
	//printf ("Initial guess: %d\n",d);
	step=2.0*M_PI/(10.0*nphase);

	if (d>=nphase/2)
	{
		if (d>0)
		{
			ini_phase=2.0*M_PI*(nphase-1-d)/nphase;
		}
		else
		{
			ini_phase=-2.0*M_PI*(nphase-1+d)/nphase;
		}
		up_phase=ini_phase+step;
		low_phase=ini_phase-step;
		while (A7(up_phase, param)*A7(low_phase, param)>0.0)
		{
		    up_phase+=step;
		    low_phase-=step;
		}
	}
	else
	{
		ini_phase=-2.0*M_PI*d/nphase;
		up_phase=ini_phase+step;
		low_phase=ini_phase-step;
		while (A7(up_phase, param)*A7(low_phase, param)>0.0)
		{
		    up_phase+=step;
		    low_phase-=step;
		}
	}

  // calculate phase shift, a and b
  double phase,b;
  phase=zbrent(A7, low_phase, up_phase, 1.0e-16, param);
  //phase=zbrent(A7, -1.0, 1.0, 1.0e-16);
  //phase=zbrent(A7, -0.005, 0.005, 1.0e-16);
  b=A9(phase, param);
  //a=A4(b);
	(*bx) = b;

		
	//printf ("Phase shift: %.10lf\n", phase/(2.0*M_PI));
	//printf ("%.10lf %.10lf\n", phase, A7(phase));
	//printf ("%.10lf \n", ((phase/3.1415926)*5.75/2.0)*1.0e+3);  // microseconds
	//printf ("%.10lf \n", b);
	//printf ("%.10lf \n", a);
	//printf ("///////////////////////// \n");
		
	
	// calculate the errors of phase and b
    double errphase, errb;	

	error(phase,b,&errphase,&errb, param);
	//printf ("%.10lf %.10lf\n", ((phase/3.1415926)/(psrfreq*2.0))*1.0e+6, ((errphase/3.1415926)/(psrfreq*2.0))*1.0e+6);  // microseconds
	//printf ("%.10lf %.10lf\n", ((phase/3.1415926)*4.569651/2.0)*1.0e+3, ((errphase/3.1415926)*4.569651/2.0)*1.0e+3);  // microseconds
	//printf ("errphase %.10lf \n", ((errphase/3.1415926)*5.75/2.0)*1.0e+6);
	//printf ("errb %.10lf \n", errb);
	
	(*phasex) = phase;
	(*errphasex) = errphase;

	// calculate the rms
	cal_rms(phase,b,rms, param);

	deallocateMemoryPtime (&param, nchn);
	return 0;
}
示例#9
0
文件: fdt.c 项目: shidai/ptimeD
int corr (double *s, double *p, int nphase)
{
	/*
	FILE *fp1, *fp2;

	if ((fp1 = fopen(argv[1], "r")) == NULL)
	{
		fprintf (stdout, "Can't open file\n");
		exit(1);
	}

	if ((fp2 = fopen(argv[2], "r")) == NULL)
	{
		fprintf (stdout, "Can't open file\n");
		exit(1);
	}

	float x1[1024], x2[1024];
	int i = 0;
	while (fscanf (fp1, "%f", &x1[i]) == 1)
	{
		i++;
	}

	i = 0;
	while (fscanf (fp2, "%f", &x2[i]) == 1)
	{
		i++;
	}
	*/

	double r[nphase];
	int i, j;
	for (j = 0; j < nphase; j++)
	{
		r[j] = 0.0;
		for (i = 0; i < nphase; i++)
		{
			if ((i+j) > (nphase-1))
			{
				r[j] += p[i]*s[i+j-(nphase-1)];
			}
			else
			{
				r[j] += p[i]*s[i+j];
			}
			//printf ("%f %f\n", x1[i], x2[i]);
		}
	}

	int shift;
	find_peak (0, nphase, r,  &shift);
	/*
	for (j = 0; j < 1024; j++)
	{
		printf ("%f\n", r[j]);
	}
	*/

	return -shift;
}
int main(int argc, char *argv[])
{
  //int nchan=4096;
  //int ndat=12000;
  int nchan=1024;
  int ndat=327680;

  int nrep=1;

  if (argc>1)
    nchan=atoi(argv[1]);
  if (argc>2)
    ndat=atoi(argv[2]);
  if (argc>3)
    nrep=atoi(argv[3]);

  float **dat=matrix(nchan,ndat+nchan);
  float **dat2=matrix(nchan,ndat+nchan);
  if (1)
    for (int i=0;i<nchan;i++)
      dat[i][(int)(0.8317*i+160.2)]=1;
  else
    for (int i=0;i<nchan;i++)
      dat[i][ndat/2]=1;
  
#if 0
  write_mat(dat,nchan,ndat,"dat_starting.dat");
  dedisperse_kernel(dat,dat2,nchan,ndat);
  write_mat(dat2,nchan,ndat,"dat_1pass.dat");
  dedisperse_2pass(dat,dat2,nchan,ndat);
  write_mat(dat,nchan,ndat,"dat_2pass.dat");  
#endif



  double t1=omp_get_wtime();
  //dedisperse(dat,dat2,nchan,ndat);
  //dedisperse_blocked(dat,dat2,nchan,ndat);
  dedisperse_blocked_cached(dat,dat2,nchan,ndat);
  double t2=omp_get_wtime();
  printf("took %12.4f seconds.\n",t2-t1);
  int ichan,idat;
  find_peak(dat,nchan,ndat,&ichan,&idat);
  t1=omp_get_wtime();
  printf("took %12.4f seconds to find peak.\n",t1-t2);


  
  for (int i=0;i<10;i++) {
    
    t1=omp_get_wtime();
    for (int j=0;j<nrep;j++) {
      dedisperse_blocked_cached(dat,dat2,nchan,ndat);
      //dedisperse(dat,dat2,nchan,ndat);
    }
    t2=omp_get_wtime();
    double nops=get_npass(nchan)*(nchan+0.0)*(ndat+0.0)*(nrep+0.0);
    printf("took %12.6f seconds at rate %12.6f.\n",t2-t1,nops/(t2-t1)/1024/1024);

    //printf("took %12.4f seconds.\n",t2-t1);
  
  }
  
  //write_mat(dat,nchan,ndat,"dat_final1.dat");

  //write_mat(dat2,nchan,ndat,"dat_final2.dat");
}
示例#11
0
int main(int argc, char *argv[])
{
   float maxpow = 0.0, inx = 0.0, iny = 0.0;
   double centerr, offsetf;
   int zoomlevel, maxzoom, minzoom, xid, psid;
   char *rootfilenm, inchar;
   fftpart *lofp;
   fftview *fv;

   if (argc == 1) {
      printf("\nusage:  explorefft fftfilename\n\n");
      exit(0);
   }

   printf("\n\n");
   printf("      Interactive FFT Explorer\n");
   printf("         by Scott M. Ransom\n");
   printf("            October, 2001\n");
   print_help();

   {
      int hassuffix = 0;
      char *suffix;

      hassuffix = split_root_suffix(argv[1], &rootfilenm, &suffix);
      if (hassuffix) {
         if (strcmp(suffix, "fft") != 0) {
            printf("\nInput file ('%s') must be a FFT file ('.fft')!\n\n", argv[1]);
            free(suffix);
            exit(0);
         }
         free(suffix);
      } else {
         printf("\nInput file ('%s') must be a FFT file ('.fft')!\n\n", argv[1]);
         exit(0);
      }
   }

   /* Read the info file */

   readinf(&idata, rootfilenm);
   if (strlen(remove_whitespace(idata.object)) > 0) {
      printf("Examining %s data from '%s'.\n\n",
             remove_whitespace(idata.object), argv[1]);
   } else {
      printf("Examining data from '%s'.\n\n", argv[1]);
   }
   N = idata.N;
   T = idata.dt * idata.N;
#ifdef USEMMAP
   printf("Memory mapping the input FFT.  This may take a while...\n");
   mmap_file = open(argv[1], O_RDONLY);
   {
      int rt;
      struct stat buf;

      rt = fstat(mmap_file, &buf);
      if (rt == -1) {
         perror("\nError in fstat() in explorefft.c");
         printf("\n");
         exit(-1);
      }
      Nfft = buf.st_size / sizeof(fcomplex);
   }
   lofp = get_fftpart(0, Nfft);
#else
   {
      int numamps;

      fftfile = chkfopen(argv[1], "rb");
      Nfft = chkfilelen(fftfile, sizeof(fcomplex));
      numamps = (Nfft > MAXBINS) ? (int) MAXBINS : (int) Nfft;
      lofp = get_fftpart(0, numamps);
   }
#endif

   /* Plot the initial data */

   {
      int initnumbins = INITIALNUMBINS;

      if (initnumbins > Nfft) {
         initnumbins = next2_to_n(Nfft) / 2;
         zoomlevel = LOGDISPLAYNUM - (int) (log(initnumbins) / log(2.0));
         minzoom = zoomlevel;
      } else {
         zoomlevel = LOGDISPLAYNUM - LOGINITIALNUMBINS;
         minzoom = LOGDISPLAYNUM - LOGMAXBINS;
      }
      maxzoom = LOGDISPLAYNUM - LOGMINBINS;
      centerr = initnumbins / 2;
   }
   fv = get_fftview(centerr, zoomlevel, lofp);

   /* Prep the XWIN device for PGPLOT */

   xid = cpgopen("/XWIN");
   if (xid <= 0) {
      free(fv);
#ifdef USEMMAP
      close(mmap_file);
#else
      fclose(fftfile);
#endif
      free_fftpart(lofp);
      exit(EXIT_FAILURE);
   }
   cpgscr(15, 0.4, 0.4, 0.4);
   cpgask(0);
   cpgpage();
   offsetf = plot_fftview(fv, maxpow, 1.0, 0.0, 0);

   do {
      cpgcurs(&inx, &iny, &inchar);
      if (DEBUGOUT)
         printf("You pressed '%c'\n", inchar);

      switch (inchar) {
      case 'A':                /* Zoom in */
      case 'a':
         centerr = (inx + offsetf) * T;
      case 'I':
      case 'i':
         if (DEBUGOUT)
            printf("  Zooming in  (zoomlevel = %d)...\n", zoomlevel);
         if (zoomlevel < maxzoom) {
            zoomlevel++;
            free(fv);
            fv = get_fftview(centerr, zoomlevel, lofp);
            cpgpage();
            offsetf = plot_fftview(fv, maxpow, 1.0, 0.0, 0);
         } else
            printf("  Already at maximum zoom level (%d).\n", zoomlevel);
         break;
      case 'X':                /* Zoom out */
      case 'x':
      case 'O':
      case 'o':
         if (DEBUGOUT)
            printf("  Zooming out  (zoomlevel = %d)...\n", zoomlevel);
         if (zoomlevel > minzoom) {
            zoomlevel--;
            free(fv);
            fv = get_fftview(centerr, zoomlevel, lofp);
            cpgpage();
            offsetf = plot_fftview(fv, maxpow, 1.0, 0.0, 0);
         } else
            printf("  Already at minimum zoom level (%d).\n", zoomlevel);
         break;
      case '<':                /* Shift left 1 full screen */
         centerr -= fv->numbins + fv->numbins / 8;
      case ',':                /* Shift left 1/8 screen */
         if (DEBUGOUT)
            printf("  Shifting left...\n");
         centerr -= fv->numbins / 8;
         {                      /* Should probably get the previous chunk from the fftfile... */
            double lowestr;

            lowestr = 0.5 * fv->numbins;
            if (centerr < lowestr)
               centerr = lowestr;
         }
         free(fv);
         fv = get_fftview(centerr, zoomlevel, lofp);
         cpgpage();
         offsetf = plot_fftview(fv, maxpow, 1.0, 0.0, 0);
         break;
      case '>':                /* Shift right 1 full screen */
         centerr += fv->numbins - fv->numbins / 8;
      case '.':                /* Shift right 1/8 screen */
         if (DEBUGOUT)
            printf("  Shifting right...\n");
         centerr += fv->numbins / 8;
         {                      /* Should probably get the next chunk from the fftfile... */
            double highestr;

            highestr = lofp->rlo + lofp->numamps - 0.5 * fv->numbins;
            if (centerr > highestr)
               centerr = highestr;
         }
         free(fv);
         fv = get_fftview(centerr, zoomlevel, lofp);
         cpgpage();
         offsetf = plot_fftview(fv, maxpow, 1.0, 0.0, 0);
         break;
      case '+':                /* Increase height of powers */
      case '=':
         if (maxpow == 0.0) {
            printf("  Auto-scaling is off.\n");
            maxpow = 1.1 * fv->maxpow;
         }
         maxpow = 3.0 / 4.0 * maxpow;
         cpgpage();
         offsetf = plot_fftview(fv, maxpow, 1.0, 0.0, 0);
         break;
      case '-':                /* Decrease height of powers */
      case '_':
         if (maxpow == 0.0) {
            printf("  Auto-scaling is off.\n");
            maxpow = 1.1 * fv->maxpow;
         }
         maxpow = 4.0 / 3.0 * maxpow;
         cpgpage();
         offsetf = plot_fftview(fv, maxpow, 1.0, 0.0, 0);
         break;
      case 'S':                /* Auto-scale */
      case 's':
         if (maxpow == 0.0)
            break;
         else {
            printf("  Auto-scaling is on.\n");
            maxpow = 0.0;
            cpgpage();
            offsetf = plot_fftview(fv, maxpow, 1.0, 0.0, 0);
            break;
         }
      case 'G':                /* Goto a frequency */
      case 'g':
         {
            char freqstr[50];
            double freq = -1.0;

            while (freq < 0.0) {
               printf("  Enter the frequency (Hz) to go to:\n");
               fgets(freqstr, 50, stdin);
               freqstr[strlen(freqstr) - 1] = '\0';
               freq = atof(freqstr);
            }
            offsetf = 0.0;
            centerr = freq * T;
            printf("  Moving to frequency %.15g.\n", freq);
            free(fv);
            fv = get_fftview(centerr, zoomlevel, lofp);
            cpgpage();
            offsetf = plot_fftview(fv, maxpow, 1.0, centerr, 2);
         }
         break;
      case 'H':                /* Show harmonics */
      case 'h':
         {
            double retval;

            retval = harmonic_loop(xid, centerr, zoomlevel, lofp);
            if (retval > 0.0) {
               offsetf = 0.0;
               centerr = retval;
               free(fv);
               fv = get_fftview(centerr, zoomlevel, lofp);
               cpgpage();
               offsetf = plot_fftview(fv, maxpow, 1.0, centerr, 2);
            }
         }
         break;
      case '?':                /* Print help screen */
         print_help();
         break;
      case 'D':                /* Show details about a selected point  */
      case 'd':
         {
            double newr;

            printf("  Searching for peak near freq = %.7g Hz...\n", (inx + offsetf));
            newr = find_peak(inx + offsetf, fv, lofp);
            centerr = newr;
            free(fv);
            fv = get_fftview(centerr, zoomlevel, lofp);
            cpgpage();
            offsetf = plot_fftview(fv, maxpow, 1.0, centerr, 2);
         }
         break;
      case 'L':                /* Load a zaplist */
      case 'l':
         {
            int ii, len;
            char filename[200];
            double *lobins, *hibins;

            printf("  Enter the filename containing the zaplist to load:\n");
            fgets(filename, 199, stdin);
            len = strlen(filename) - 1;
            filename[len] = '\0';
            numzaplist = get_birdies(filename, T, 0.0, &lobins, &hibins);
            lenzaplist = numzaplist + 20;       /* Allow some room to add more */
            if (lenzaplist)
               free(zaplist);
            zaplist = (bird *) malloc(sizeof(bird) * lenzaplist);
            for (ii = 0; ii < numzaplist; ii++) {
               zaplist[ii].lobin = lobins[ii];
               zaplist[ii].hibin = hibins[ii];
            }
            vect_free(lobins);
            vect_free(hibins);
            printf("\n");
            cpgpage();
            offsetf = plot_fftview(fv, maxpow, 1.0, 0.0, 0);
         }
         break;
      case 'Z':                /* Add a birdie to a zaplist */
      case 'z':
         {
            int badchoice = 2;
            float lox, hix, loy, hiy;
            double rs[2];
            char choice;

            if (numzaplist + 1 > lenzaplist) {
               lenzaplist += 10;
               zaplist = (bird *) realloc(zaplist, sizeof(bird) * lenzaplist);
            }
            cpgqwin(&lox, &hix, &loy, &hiy);
            printf("  Click the left mouse button on the first frequency limit.\n");
            while (badchoice) {
               cpgcurs(&inx, &iny, &choice);
               if (choice == 'A' || choice == 'a') {
                  rs[2 - badchoice] = ((double) inx + offsetf) * T;
                  cpgsave();
                  cpgsci(7);
                  cpgmove(inx, 0.0);
                  cpgdraw(inx, hiy);
                  cpgunsa();
                  badchoice--;
                  if (badchoice == 1)
                     printf
                         ("  Click the left mouse button on the second frequency limit.\n");
               } else {
                  printf("  Option not recognized.\n");
               }
            };
            if (rs[1] > rs[0]) {
               zaplist[numzaplist].lobin = rs[0];
               zaplist[numzaplist].hibin = rs[1];
            } else {
               zaplist[numzaplist].lobin = rs[1];
               zaplist[numzaplist].hibin = rs[0];
            }
            printf("    The new birdie has:  f_avg = %.15g  f_width = %.15g\n\n",
                   0.5 * (zaplist[numzaplist].hibin + zaplist[numzaplist].lobin) / T,
                   (zaplist[numzaplist].hibin - zaplist[numzaplist].lobin) / T);
            numzaplist++;
            qsort(zaplist, numzaplist, sizeof(bird), compare_birds);
            cpgpage();
            offsetf = plot_fftview(fv, maxpow, 1.0, 0.0, 0);
         }
         break;
      case 'P':                /* Print the current plot */
      case 'p':
         {
            int len;
            char filename[200];

            printf("  Enter the filename to save the plot as:\n");
            fgets(filename, 196, stdin);
            len = strlen(filename) - 1;
            filename[len + 0] = '/';
            filename[len + 1] = 'P';
            filename[len + 2] = 'S';
            filename[len + 3] = '\0';
            psid = cpgopen(filename);
            cpgslct(psid);
            cpgpap(10.25, 8.5 / 11.0);
            cpgiden();
            cpgscr(15, 0.8, 0.8, 0.8);
            offsetf = plot_fftview(fv, maxpow, 1.0, 0.0, 0);
            cpgclos();
            cpgslct(xid);
            cpgscr(15, 0.4, 0.4, 0.4);
            filename[len] = '\0';
            printf("  Wrote the plot to the file '%s'.\n", filename);
         }
         break;
      case 'N':                /* Changing power normalization */
      case 'n':
         {
            float inx2 = 0.0, iny2 = 0.0;
            char choice;
            unsigned char badchoice = 1;

            printf("  Specify the type of power normalization:\n"
                   "       m,M  :  Median values determined locally\n"
                   "       d,D  :  DC frequency amplitude\n"
                   "       r,R  :  Raw powers (i.e. no normalization)\n"
                   "       u,U  :  User specified interval (the average powers)\n");
            while (badchoice) {
               cpgcurs(&inx2, &iny2, &choice);
               switch (choice) {
               case 'M':
               case 'm':
                  norm_const = 0.0;
                  maxpow = 0.0;
                  badchoice = 0;
                  printf
                      ("  Using local median normalization.  Autoscaling is on.\n");
                  break;
               case 'D':
               case 'd':
                  norm_const = 1.0 / r0;
                  maxpow = 0.0;
                  badchoice = 0;
                  printf
                      ("  Using DC frequency (%f) normalization.  Autoscaling is on.\n",
                       r0);
                  break;
               case 'R':
               case 'r':
                  norm_const = 1.0;
                  maxpow = 0.0;
                  badchoice = 0;
                  printf
                      ("  Using raw powers (i.e. no normalization).  Autoscaling is on.\n");
                  break;
               case 'U':
               case 'u':
                  {
                     char choice2;
                     float xx = inx, yy = iny;
                     int lor, hir, numr;
                     double avg, var;

                     printf
                         ("  Use the left mouse button to select a left and right boundary\n"
                          "  of a region to calculate the average power.\n");
                     do {
                        cpgcurs(&xx, &yy, &choice2);
                     } while (choice2 != 'A' && choice2 != 'a');
                     lor = (int) ((xx + offsetf) * T);
                     cpgsci(7);
                     cpgmove(xx, 0.0);
                     cpgdraw(xx, 10.0 * fv->maxpow);
                     do {
                        cpgcurs(&xx, &yy, &choice2);
                     } while (choice2 != 'A' && choice2 != 'a');
                     hir = (int) ((xx + offsetf) * T);
                     cpgmove(xx, 0.0);
                     cpgdraw(xx, 10.0 * fv->maxpow);
                     cpgsci(1);
                     if (lor > hir) {
                        int tempr;
                        tempr = hir;
                        hir = lor;
                        lor = tempr;
                     }
                     numr = hir - lor + 1;
                     avg_var(lofp->rawpowers + lor - lofp->rlo, numr, &avg, &var);
                     printf("  Selection has:  average = %.5g\n"
                            "                  std dev = %.5g\n", avg, sqrt(var));
                     norm_const = 1.0 / avg;
                     maxpow = 0.0;
                     badchoice = 0;
                     printf
                         ("  Using %.5g as the normalization constant.  Autoscaling is on.\n",
                          avg);
                     break;
                  }
               default:
                  printf("  Unrecognized choice '%c'.\n", choice);
                  break;
               }
            }
            free(fv);
            fv = get_fftview(centerr, zoomlevel, lofp);
            cpgpage();
            offsetf = plot_fftview(fv, maxpow, 1.0, 0.0, 0);
         }
         break;
      case 'Q':                /* Quit */
      case 'q':
         printf("  Quitting...\n");
         free(fv);
         cpgclos();
         break;
      default:
         printf("  Unrecognized option '%c'.\n", inchar);
         break;
      }
   } while (inchar != 'Q' && inchar != 'q');

   free_fftpart(lofp);
#ifdef USEMMAP
   close(mmap_file);
#else
   fclose(fftfile);
#endif
   if (lenzaplist)
      free(zaplist);
   printf("Done\n\n");
   return 0;
}
示例#12
0
/*  circles with radii inner and outer */
double
aperture(FITS_IMAGE *sl, double x0, double y0, double inner, double outer, 
    double *sx, double *sy)

{
  double v,  background, ball;
  double bx = 0.0, by = 0.0;
  int x, y;
  double sg;
  int inarea, outarea;
  double i, j, i2;
  int k;
  int rmax, imin, imax, jmin, jmax;
  double dist[4];
  int size;
  static int bsize = 0;
  static PIXEL *backg = NULL;
  double o2 = outer * outer;
  double sv;
  int above_thresh;
  double thresh;
  OBJEKT obj;

  /*  radius of the circle to be examined  */
  rmax = outer + 0.5;
  /*  areas of the inner circle and of the outer minus inner circle  */
  inarea = outarea = 0;
  /*  range of x coordinates to be examined  */
  imin = x0 - rmax;
  imax = x0 + rmax;
  /*  Calculate the size needed for the storage of the background pixels */
  size = M_PI * o2;
  if (size > bsize) {
    if (backg) {
      backg = (PIXEL *) realloc(backg, sizeof(PIXEL) * size);
      if (!backg) {
	fprintf(stderr, "Out of memory, function aperture, backg.\n");
	exit(1);
      }
    }
    else {
      backg = (PIXEL *) myalloc(sizeof(PIXEL) * size, "aperture", "backg");
    }
    bsize = size;
  }
  for (i = imin; i <= imax; i++) {
    i2 = i - x0;
    i2 *= i2;
    jmax = (int) (sqrt(o2 - i2) + 0.5);
    jmin = y0 - jmax;
    jmax += y0;
    for (j = jmin; j <= jmax; j++) {
      if (inside(x0, y0, inner, i, j, dist) > 0) {
	v = video_point(sl, (int) i, (int) j);
	/* this pixel is inside the inner circle with at least one vertex */
	inarea++;
      }
	/* this pixel is inside the outer circle with at least one vertex */
      else if (inside(x0, y0, outer, i, j, dist) > 0) {
	v = video_point(sl, (int) i, (int) j);
	/*  This pixel is between the inner and outer circle  */
	backg[outarea] = v;
	outarea++;
	if (outarea == bsize) {
	  bsize += 100;	
	  backg = (PIXEL *) realloc(backg, sizeof(PIXEL) * bsize);
	  if (!backg) {
	    fprintf(stderr, "Out of memory, function aperture, backg.\n");
	    exit(1);
	  }
	}
      }
    }
  }
  /*  Calculate the median of the background pixels  */
  qsort(backg, outarea, sizeof(PIXEL), cmppixel);
  /*  Calculate the sigma  */
  sg = 0;
  i2 = 0;
  background = 0;
  for (k = 0.1 * outarea; k < outarea * 0.9; k++) {
    background += backg[k];
    sg += backg[k] * backg[k];
    i2++;
  }
  background /= i2;
  sg = sqrt(sg / i2 - background * background);
  thresh = background + sl->sg_num * sg;
  /*  Calculate the intensity and centroid of the pixel larger than background  */
  /*  for sg_num * sigma  */
  find_peak(sl, (double) x0, (double) y0, inner, &x, &y);
  aperture_visit(sl, (double) x, (double) y, inner, thresh, background, sg, &obj);
  above_thresh = obj.area;
  sv = obj.grey;
  *sx = obj.xt;
  *sy = obj.yt;
  bx = obj.x1;
  by = obj.y1;
  if (above_thresh > 0) {
    ball =  background * above_thresh;
    /*  Subtract the background from the signal  */
    sv -= ball;
    *sx = (*sx - bx * background) / sv;
    *sy = (*sy - by * background) / sv;
  }
  else {
    sv = video_point(sl, (int) x0, (int) y0) - background;
    *sx = x0;
    *sy = y0;
  }
  return sv;
}
示例#13
0
static double
snr_test (SINGLE_TEST *test_data, int number, int converter, int verbose, double *conversion_rate)
{	static float data [BUFFER_LEN + 1] ;
	static float output [MAX_SPEC_LEN] ;

	SRC_STATE	*src_state ;
	SRC_DATA	src_data ;

	clock_t start_clock, clock_time ;

	double		output_peak, snr ;
	int 		k, output_len, input_len, error ;

	if (verbose != 0)
	{	printf ("\tSignal-to-Noise Ratio Test %d.\n"
				"\t=====================================\n", number) ;
		printf ("\tFrequencies : [ ") ;
		for (k = 0 ; k < test_data->freq_count ; k++)
			printf ("%6.4f ", test_data->freqs [k]) ;

		printf ("]\n\tSRC Ratio   : %8.4f\n", test_data->src_ratio) ;
		}
	else
	{	printf ("\tSignal-to-Noise Ratio Test %d : ", number) ;
		fflush (stdout) ;
		} ;

	/* Set up the output array. */
	if (test_data->src_ratio >= 1.0)
	{	output_len = MAX_SPEC_LEN ;
		input_len = (int) ceil (MAX_SPEC_LEN / test_data->src_ratio) ;
		if (input_len > BUFFER_LEN)
			input_len = BUFFER_LEN ;
		}
	else
	{	input_len = BUFFER_LEN ;
		output_len = (int) ceil (BUFFER_LEN * test_data->src_ratio) ;
		output_len &= ((-1) << 4) ;
		if (output_len > MAX_SPEC_LEN)
			output_len = MAX_SPEC_LEN ;
		input_len = (int) ceil (output_len / test_data->src_ratio) ;
		} ;

	memset (output, 0, sizeof (output)) ;

	/* Generate input data array. */
	gen_windowed_sines (data, input_len, test_data->freqs, test_data->freq_count) ;

	/* Perform sample rate conversion. */
	if ((src_state = src_new (converter, 1, &error)) == NULL)
	{	printf ("\n\nLine %d : src_new() failed : %s.\n\n", __LINE__, src_strerror (error)) ;
		exit (1) ;
		} ;

	src_data.end_of_input = 1 ; /* Only one buffer worth of input. */

	src_data.data_in = data ;
	src_data.input_frames = input_len ;

	src_data.src_ratio = test_data->src_ratio ;

	src_data.data_out = output ;
	src_data.output_frames = output_len ;

	start_clock = clock () ;
	if ((error = src_process (src_state, &src_data)))
	{	printf ("\n\nLine %d : %s\n\n", __LINE__, src_strerror (error)) ;
		exit (1) ;
		} ;

	clock_time = clock () - start_clock ;

	src_state = src_delete (src_state) ;

	if (clock_time <= 0)
		clock_time = 1 ;

	*conversion_rate = (1.0 * output_len * CLOCKS_PER_SEC) / clock_time ;
	if (test_data->src_ratio < 1.0)
		*conversion_rate /= test_data->src_ratio ;

	if (verbose != 0)
	{	printf ("\tOutput Rate :   %.0f samples/sec\n", *conversion_rate) ;

		printf ("\tOutput Len  :   %ld\n", src_data.output_frames_gen) ;
		} ;

	if (abs (src_data.output_frames_gen - output_len) > 4)
	{	printf ("\n\nLine %d : output data length should be %d.\n\n", __LINE__, output_len) ;
		exit (1) ;
		} ;

	/* Check output peak. */
	output_peak = find_peak (output, src_data.output_frames_gen) ;

	if (verbose != 0)
		printf ("\tOutput Peak :   %6.4f\n", output_peak) ;

	if (fabs (output_peak - test_data->peak_value) > 0.01)
	{	printf ("\n\nLine %d : output peak (%6.4f) should be %6.4f\n\n", __LINE__, output_peak, test_data->peak_value) ;
		save_oct_data ("snr_test.dat", data, BUFFER_LEN, output, output_len) ;
		exit (1) ;
		} ;

	/* Calculate signal-to-noise ratio. */
	snr = calculate_snr (output, src_data.output_frames_gen) ;

	if (snr < 0.0)
	{	/* An error occurred. */
		save_oct_data ("snr_test.dat", data, BUFFER_LEN, output, src_data.output_frames_gen) ;
		exit (1) ;
		} ;

	if (verbose != 0)
		printf ("\tSNR Ratio   :   %.2f dB\n", snr) ;

	if (snr < test_data->snr)
	{	printf ("\n\nLine %d : SNR (%5.2f) should be > %6.2f dB\n\n", __LINE__, snr, test_data->snr) ;
		exit (1) ;
		} ;

	if (verbose != 0)
		puts ("\t-------------------------------------\n\tPass\n") ;
	else
		puts ("Pass") ;

	return snr ;
} /* snr_test */
void EBGM_FeatureVectors(double Gabor_Respone[][Height][Width][2],double Gabor_Respone_Mean_Value[][2],int *feature_count,double Each_Feature_Vectors[][41][2])
{
	int j,k,m;
	int row_index,column_index;
	int Row_Window=20;
	int Column_Window=20;
	int Threshold=2;
	double EachImage_Filter_Respone[Height][Width][2]={0.0};
	double local_peak=0.0;
	char Gabor_peak_count[Height][Width]={0};
	int row_position; 
	int column_position;
	int count=0;

	for (j=0;j<Filter_Num;j++)
	{
		memcpy(EachImage_Filter_Respone,Gabor_Respone[j],Height*Width*2*8);
		for (row_index=0;row_index<(int)Height/Row_Window+1;row_index++)
		{
			for (column_index=0;column_index<(int)Width/Column_Window+1;column_index++)
			{
				if (((row_index+1)*Row_Window<Height)&&((column_index+1)*Column_Window<Width))
				{
					find_peak(EachImage_Filter_Respone,row_index*Row_Window,(row_index+1)*Row_Window,column_index*Column_Window,(column_index+1)*Column_Window,&row_position,&column_position);
				}
				else if(((row_index+1)*Row_Window>Height)&&((column_index+1)*Column_Window<Width))
				{
					find_peak(EachImage_Filter_Respone,row_index*Row_Window,Height,column_index*Column_Window,(column_index+1)*Column_Window,&row_position,&column_position);
				}
				else if(((row_index+1)*Row_Window<Height)&&((column_index+1)*Column_Window>Width))
				{
					find_peak(EachImage_Filter_Respone,row_index*Row_Window,(row_index+1)*Row_Window,column_index*Column_Window,Width,&row_position,&column_position);
				}
				else if(((row_index+1)*Row_Window>Height)&&((column_index+1)*Column_Window>Width))
				{
					find_peak(EachImage_Filter_Respone,row_index*Row_Window,Height,column_index*Column_Window,Width,&row_position,&column_position);
				}
				
				if (EachImage_Filter_Respone[row_position][column_position][0]>Gabor_Respone_Mean_Value[j][0])
				{
					Gabor_peak_count[row_position][column_position]++;
				}
			}
		}

	}
	
	count=(*feature_count);
	for (j=0;j<Height;j++)
	{
		for (k=0;k<Width;k++)
		{
			if (Gabor_peak_count[j][k]>Threshold)
			{
				for (m=0;m<41;m++)
				{
					if (m==0)
					{
						Each_Feature_Vectors[count][0][0]=j;
						Each_Feature_Vectors[count][0][1]=k;
					}
					else
					{
						Each_Feature_Vectors[count][m][0]=Gabor_Respone[m-1][j][k][0];
						Each_Feature_Vectors[count][m][1]=Gabor_Respone[m-1][j][k][1];
					}
				}
				count++;  
			}
			else
			{
				Gabor_peak_count[j][k]=0;
			}
		}
	}
	*feature_count=count;
}