Esempio n. 1
0
double get_localpower3d(fcomplex * data, int numdata, double r, double z, double w)
  /* Return the local power level around a specific FFT           */
  /* frequency, f-dot, and f-dotdot.                              */
  /* Arguments:                                                   */
  /*   'data' is a pointer to a complex FFT.                      */
  /*   'numdata' is the number of complex points in 'data'.       */
  /*   'r' is the Fourier frequency in data that we want to       */
  /*      interpolate.                                            */
  /*   'z' is the Fourier Frequency derivative (# of bins the     */
  /*       signal smears over during the observation).            */
  /*   'w' is the Fourier Frequency 2nd derivative (change in the */
  /*       Fourier f-dot during the observation).                 */
{
    double powargr, powargi, sum = 0.0;
    double lo1, lo2, hi1, hi2, freq;
    int binsperside, kern_half_width;
    fcomplex ans;

    binsperside = NUMLOCPOWAVG / 2;
    kern_half_width = w_resp_halfwidth(z, w, LOWACC);

    /* Set the bounds of our summation */

    lo1 = r - DELTAAVGBINS - binsperside;
    hi1 = lo1 + binsperside;
    lo2 = r + DELTAAVGBINS;
    hi2 = lo2 + binsperside;

    /* Make sure we don't try to read non-existant data */

    if (lo1 < 0.0)
        lo1 = 0.0;
    if (lo2 < 0.0)
        lo2 = 0.0;
    if (hi1 < 0.0)
        hi1 = 0.0;
    if (hi2 < 0.0)
        hi2 = 0.0;
    if (lo1 > numdata)
        lo1 = (double) numdata;
    if (lo2 > numdata)
        lo2 = (double) numdata;
    if (hi1 > numdata)
        hi1 = (double) numdata;
    if (hi2 > numdata)
        hi2 = (double) numdata;

    /* Perform the summation */

    for (freq = lo1; freq < hi1; freq += 1.0) {
        rzw_interp(data, numdata, freq, z, w, kern_half_width, &ans);
        sum += POWER(ans.r, ans.i);
    }
    for (freq = lo2; freq < hi2; freq += 1.0) {
        rzw_interp(data, numdata, freq, z, w, kern_half_width, &ans);
        sum += POWER(ans.r, ans.i);
    }
    sum /= (double) NUMLOCPOWAVG;
    return sum;
}
Esempio n. 2
0
double get_localpower(fcomplex * data, int numdata, double r)
  /* Return the local power level at specific FFT frequency.  */
  /* Arguments:                                               */
  /*   'data' is a pointer to a complex FFT.                  */
  /*   'numdata' is the number of complex points in 'data'.   */
  /*   'r' is the Fourier frequency in data that we want to   */
  /*      interpolate.                                        */
{
    double powargr, powargi, sum = 0.0;
    int ii, binsperside, lo1, lo2, hi1, hi2, intfreq;

    intfreq = (long) floor(r);
    binsperside = NUMLOCPOWAVG / 2;

    /* Set the bounds of our summation */

    lo1 = intfreq - DELTAAVGBINS - binsperside + 1;
    hi1 = lo1 + binsperside;
    lo2 = intfreq + DELTAAVGBINS + 1;
    hi2 = lo2 + binsperside;

    /* Make sure we don't try to read non-existant data */

    if (lo1 < 0)
        lo1 = 0;
    if (lo2 < 0)
        lo2 = 0;
    if (hi1 < 0)
        hi1 = 0;
    if (hi2 < 0)
        hi2 = 0;
    if (lo1 > numdata)
        lo1 = numdata;
    if (lo2 > numdata)
        lo2 = numdata;
    if (hi1 > numdata)
        hi1 = numdata;
    if (hi2 > numdata)
        hi2 = numdata;

    /* Perform the summation */

    for (ii = lo1; ii < hi1; ii++)
        sum += POWER(data[ii].r, data[ii].i);
    for (ii = lo2; ii < hi2; ii++)
        sum += POWER(data[ii].r, data[ii].i);
    sum /= (double) NUMLOCPOWAVG;
    return sum;
}
Esempio n. 3
0
void init_predictor()
{
	//bhr = (sizeof(short) * 8);
	bhr = (mask(BBHR) / 2);
	//bhr = RESET;
	ghr = (mask(BGHR) / 2);
	chr = (mask(BCHR) / 2);

	for(int i=0; i<(POWER(BGHR)/2); i++)
	{
		ght[i] = TSTATE;
	}

	for(int i=(POWER(BGHR)/2); i<POWER(BGHR); i++)
	{
		ght[i] = NSTATE;
	}

	for(int i=0; i<POWER(BBHR); i++)
	{
		pht[i] = bhr;
	}

	for(int i=0; i<(POWER(BPHT)/2); i++)
	{
		bht[i] = TSTATE;
	}

	for(int i=(POWER(BPHT)/2); i<POWER(BPHT); i++)
	{
		bht[i] = NSTATE;
	}

	for(int i=0; i<(POWER(BCHR)/2); i++)
	{
		cht[i] = TSTATE;
	}

	for(int i=(POWER(BCHR)/2); i<POWER(BCHR); i++)
	{
		cht[i] = NSTATE;
	}
}
Esempio n. 4
0
static double power_call_rz(double rz[])
/* f-fdot plane power function */
{
   double powargr, powargi;
   fcomplex ans;

   /* num_funct_calls++; */
   rz_interp(maxdata, nummaxdata, rz[0], rz[1] * ZSCALE, max_kern_half_width, &ans);
   return -POWER(ans.r, ans.i);
}
Esempio n. 5
0
static float *
recur_bin_complex(RecurAudioBinner *ab, GstFFTF32Complex *f)
{
  int i, j;
  float mul;
  float sum_left = 0.0f;
  float sum_right;
  float power;
  RecurAudioBinSlope *slope;
  /*first slope is left side only, last slope is right only*/
  for (i = 0; i <= ab->n_bins; i++){
    slope = &ab->slopes[i];
    j = slope->left;
    /*left fractional part*/
    mul = slope->slope * slope->left_fraction;
    power = POWER(f[j]) * slope->left_fraction;

    sum_right = sum_left + (1.0f - mul) * power;
    /*Note sum_right is old sum_left */
    sum_left = mul * power;

    if (slope->left != slope->right){
      /*centre */
      for (j = slope->left + 1; j < slope->right; j++){
        mul += slope->slope;
        power = POWER(f[j]);
        sum_left += mul * power;
        sum_right += (1.0f - mul) * power;
      }
    }
    /*right fraction */
    mul += slope->slope * slope->right_fraction;
    power = POWER(f[j]) * slope->right_fraction;
    sum_left += mul * power;
    sum_right += (1.0f - mul) * power;

    if (i){
      ab->fft_bins[i - 1] = logf(sum_right + 1);// - slope->log_scale;
    }
  }
  return ab->fft_bins;
}
Esempio n. 6
0
float			ft_cos(float angle)
{
	float		ret;
	int			n;
	float		angle2;

	angle = ft_check_angle(angle);
	angle2 = angle * 3.14 / 180;
	n = 1;
	ret = 1;
	while (n < 5)
	{
		ret += POWER(-1, n) * ((POWER(angle2, n + n) / FACTO(n + n)));
		n++;
	}
	if (ret > 1)
		return (EXIT_SUCCES);
	if (ret < -1)
		return (EXIT_FAIL);
	return (ret);
}
Esempio n. 7
0
void get_derivs3d(fcomplex * data, int numdata, double r,
                  double z, double w, double localpower, rderivs * result)
  /* Return an rderives structure that contains the power,      */
  /* phase, and their first and second derivatives at a point   */
  /* in the F/F-dot/F-dortdot volume.                           */
  /* Arguments:                                                 */
  /*   'data' is a pointer to a complex FFT.                    */
  /*   'numdata' is the number of complex points in 'data'.     */
  /*   'r' is the Fourier frequency in data that we want to     */
  /*      interpolate.                                          */
  /*   'z' is the Fourier Frequency derivative (# of bins the   */
  /*       signal smears over during the observation).          */
  /*   'w' is the Fourier Frequency 2nd derivative (change in   */
  /*       the Fourier f-dot during the observation).           */
  /*   'localpower' is the local power level around the signal. */
  /*   'result' is a pointer to an rderivs structure that will  */
  /*       contain the results.                                 */
{
    /* h = Length of delta for derivatives (See Num Recip p. 186)  */
    /* This is optimized for single precision powers and phases.   */

    double h = 0.003, twoh = 0.006, twohsqrd = 0.000036, f;
    double powargr, powargi, radargr, radargi, radtmp, pwr[5], phs[5];
    int ii, kern_half_width;
    fcomplex ans;

    /* Read the powers and phases: */

    kern_half_width = w_resp_halfwidth(z, w, HIGHACC);
    for (ii = 0, f = r - twoh; ii < 5; ii++, f += h) {
        rzw_interp(data, numdata, f, z, w, kern_half_width, &ans);
        pwr[ii] = POWER(ans.r, ans.i);
        phs[ii] = RADIAN_PHASE(ans.r, ans.i);
    }

    /* Ensure there are no discontinuities in the phase values: */

    for (ii = 0; ii < 4; ii++) {
        if (fabs(phs[ii + 1] - phs[ii]) > PI)
            phs[ii + 1] -= TWOPI;
    }

    /* Calculate the derivatives */

    result->pow = pwr[2];
    result->phs = phs[2];
    result->dpow = (pwr[3] - pwr[1]) / twoh;
    result->dphs = (phs[3] - phs[1]) / twoh;
    result->d2pow = (pwr[4] - 2.0 * pwr[2] + pwr[0]) / twohsqrd;
    result->d2phs = (phs[4] - 2.0 * phs[2] + phs[0]) / twohsqrd;
    result->locpow = localpower;
}
Esempio n. 8
0
static double power_call_rz_harmonics(double rz[])
{
    int i;
    double total_power = 0.;
    double powargr, powargi;
    fcomplex ans;

    for(i=1; i<=max_num_harmonics; i++) {
       rz_interp(maxdata_harmonics[i-1], nummaxdata, 
               (maxr_offset[i-1]+rz[0])*i-maxr_offset[i-1], rz[1] * ZSCALE * i, 
               max_kern_half_width, &ans);
       total_power += POWER(ans.r, ans.i)/maxlocpow[i-1];
    }
    return -total_power;
}
Esempio n. 9
0
static fftpart *get_fftpart(int rlo, int numr)
{
   int ii, jj, index;
   float powargr, powargi, tmppwr, chunk[LOCALCHUNK];
   fftpart *fp;

   if (rlo + numr > Nfft) {
      return NULL;
   } else {
      fp = (fftpart *) malloc(sizeof(fftpart));
      fp->rlo = rlo;
      fp->numamps = numr;
#ifdef USEMMAP
      fp->amps = (fcomplex *) mmap(0, sizeof(fcomplex) * numr, PROT_READ,
                                   MAP_SHARED, mmap_file, 0);
#else
      fp->amps = read_fcomplex_file(fftfile, rlo, numr);
#endif
      if (rlo == 0)
         r0 = fp->amps[0].r;
      fp->rawpowers = gen_fvect(fp->numamps);
      fp->medians = gen_fvect(fp->numamps / LOCALCHUNK);
      fp->normvals = gen_fvect(fp->numamps / LOCALCHUNK);
      fp->maxrawpow = 0.0;
      for (ii = 0; ii < fp->numamps / LOCALCHUNK; ii++) {
         index = ii * LOCALCHUNK;
         for (jj = 0; jj < LOCALCHUNK; jj++, index++) {
            tmppwr = POWER(fp->amps[index].r, fp->amps[index].i);
            if (tmppwr > fp->maxrawpow)
               if (rlo || (rlo == 0 && index > 0))
                  fp->maxrawpow = tmppwr;
            fp->rawpowers[index] = tmppwr;
            chunk[jj] = tmppwr;
         }
         if (rlo == 0 && ii == 0) {
            chunk[0] = 1.0;
            fp->rawpowers[0] = 1.0;
         }
         fp->medians[ii] = median(chunk, LOCALCHUNK);
         fp->normvals[ii] = 1.0 / (1.4426950408889634 * fp->medians[ii]);
      }
      return fp;
   }
}
Esempio n. 10
0
int kport(CSOUND *csound, KPORT *p)
{
    /* Set up variables local to this instance of the port ugen, if
     * khtim has changed.
     *
     * onedkr = one divided by k rate.
     *
     * c2 = sqrt 1 / kr * half time
     * c1 = 1 - c2
     *
     */
    /* This previous comment is WRONG;  do not be misled -- JPff */

    if (UNLIKELY(p->prvhtim != *p->khtim)) {
      p->c2 = POWER(FL(0.5), CS_ONEDKR / *p->khtim);
      p->c1 = FL(1.0) - p->c2;
      p->prvhtim = *p->khtim;
    }
    /* New state =   (c2 * old state) + (c1 * input value)       */
    *p->kr = p->yt1 = p->c1 * *p->ksig + p->c2 * p->yt1;
    return OK;
}
Esempio n. 11
0
void DownstreamPowerChange(void) {

	LoadCorePacket(&downstreamPacketTemp);
	POWER(&downstreamPacketTemp);

	downstreamPacketTemp.use.data[2] = GetRawVoltageCode(0);
	downstreamPacketTemp.use.data[3] = GetRawVoltageCode(1);

	if (downstreamPacketTemp.use.data[0] == bankA
			&& downstreamPacketTemp.use.data[1] == bankB
			&& downstreamPacketTemp.use.data[2] == batteryCode0
			&& downstreamPacketTemp.use.data[3] == batteryCode1)
		return;
	bankA = downstreamPacketTemp.use.data[0];
	bankB = downstreamPacketTemp.use.data[1];
	batteryCode0 = downstreamPacketTemp.use.data[2];
	batteryCode1 = downstreamPacketTemp.use.data[3];

	SendPacketToCoProc(&downstreamPacketTemp);
	UpstreamPushPowerChange(bankA, bankB, GetRawVoltage(), getPowerOverRide());

}
Esempio n. 12
0
void On_remind_me(double pTime, int pData)
//***************************************
// VMLAB notifies about a previouly sent REMIND_ME() function.
// Read the next voltage sample from the WAV file, set the analog voltage on the
// output pin, and schedule another output update based on the sampling rate of
// the input wav file.
{
   char strBuffer[MAXBUF];

   // Do nothing if the wav file is closed due to an error
   if(!VAR(File)) {
      return;
   }
   
   // Read the next voltage sample from the wav file. If an error occurs or
   // EOF is reached, then the wav file is closed, the output voltage remains
   // set to the previous value and no more output updates are scheduled.
   if(sf_readf_double(VAR(File), VAR(Sample_buffer), 1) != 1) {
      // Break with an error message if an actual I/O or decode error occurred
      if(sf_error(VAR(File))) {
         snprintf(strBuffer, MAXBUF, "Error reading \"%s.wav\" file: %s",
            GET_INSTANCE(), sf_strerror(VAR(File)));
         BREAK(strBuffer);         
      }
      
      // Close the file on either an error or a normal end-of-file
      Close_file();
      return;
   }

   // The voltage in VMLAB ranges from 0 to POWER(), while the sample that
   // libsndfile returns ranges from -1 to +1. Only the sample from the
   // first (left) channel is used here. Samples from additional channels
   // are simply discarded.
   SET_VOLTAGE(DATA, (*VAR(Sample_buffer) + 1) * 0.5 * POWER());

   // Schedule the next On_remind_me() based on the sampling rate
   REMIND_ME(1.0 / VAR(File_info).samplerate);
}
Esempio n. 13
0
/**
 * Select the 'best' charge port, as defined by the supplier heirarchy and the
 * ability of the port to provide power.
 */
static void charge_manager_get_best_charge_port(int *new_port,
						int *new_supplier)
{
	int supplier = CHARGE_SUPPLIER_NONE;
	int port = CHARGE_PORT_NONE;
	int best_port_power = -1, candidate_port_power;
	int i, j;

	/* Skip port selection on OVERRIDE_DONT_CHARGE. */
	if (override_port != OVERRIDE_DONT_CHARGE) {
		/*
		 * Charge supplier selection logic:
		 * 1. Prefer higher priority supply.
		 * 2. Prefer higher power over lower in case priority is tied.
		 * 3. Prefer current charge port over new port in case (1)
		 *    and (2) are tied.
		 * available_charge can be changed at any time by other tasks,
		 * so make no assumptions about its consistency.
		 */
		for (i = 0; i < CHARGE_SUPPLIER_COUNT; ++i)
			for (j = 0; j < CONFIG_USB_PD_PORT_COUNT; ++j) {
				/*
				 * Skip this supplier if there is no
				 * available charge.
				 */
				if (available_charge[i][j].current == 0 ||
				    available_charge[i][j].voltage == 0)
					continue;

				/*
				 * Don't select this port if we have a
				 * charge on another override port.
				 */
				if (override_port != OVERRIDE_OFF &&
				    override_port == port &&
				    override_port != j)
					continue;

#ifndef CONFIG_CHARGE_MANAGER_DRP_CHARGING
				/*
				 * Don't charge from a dual-role port unless
				 * it is our override port.
				 */
				if (dualrole_capability[j] != CAP_DEDICATED &&
				    override_port != j)
					continue;
#endif

				candidate_port_power =
					POWER(available_charge[i][j]);

				/* Select if no supplier chosen yet. */
				if (supplier == CHARGE_SUPPLIER_NONE ||
				/* ..or if supplier priority is higher. */
				    supplier_priority[i] <
				    supplier_priority[supplier] ||
				/* ..or if this is our override port. */
				   (j == override_port &&
				    port != override_port) ||
				/* ..or if priority is tied and.. */
				   (supplier_priority[i] ==
				    supplier_priority[supplier] &&
				/* candidate port can supply more power or.. */
				   (candidate_port_power > best_port_power ||
				/*
				 * candidate port is the active port and can
				 * supply the same amount of power.
				 */
				   (candidate_port_power == best_port_power &&
				    charge_port == j)))) {
					supplier = i;
					port = j;
					best_port_power = candidate_port_power;
				}
			}

	}

	*new_port = port;
	*new_supplier = supplier;
}
Esempio n. 14
0
/**
 * Fills passed power_info structure with current info about the passed port.
 */
static void charge_manager_fill_power_info(int port,
	struct ec_response_usb_pd_power_info *r)
{
	int sup = CHARGE_SUPPLIER_NONE;
	int i;

	/* Determine supplier information to show. */
	if (port == charge_port)
		sup = charge_supplier;
	else
		/* Find highest priority supplier */
		for (i = 0; i < CHARGE_SUPPLIER_COUNT; ++i)
			if (available_charge[i][port].current > 0 &&
			    available_charge[i][port].voltage > 0 &&
			    (sup == CHARGE_SUPPLIER_NONE ||
			     supplier_priority[i] <
			     supplier_priority[sup] ||
			    (supplier_priority[i] ==
			     supplier_priority[sup] &&
			     POWER(available_charge[i][port]) >
			     POWER(available_charge[sup]
						   [port]))))
				sup = i;

	/* Fill in power role */
	if (charge_port == port)
		r->role = USB_PD_PORT_POWER_SINK;
	else if (pd_is_connected(port) && pd_get_role(port) == PD_ROLE_SOURCE)
		r->role = USB_PD_PORT_POWER_SOURCE;
	else if (sup != CHARGE_SUPPLIER_NONE)
		r->role = USB_PD_PORT_POWER_SINK_NOT_CHARGING;
	else
		r->role = USB_PD_PORT_POWER_DISCONNECTED;

	/* Is port partner dual-role capable */
	r->dualrole = (dualrole_capability[port] == CAP_DUALROLE);

	if (sup == CHARGE_SUPPLIER_NONE ||
	    r->role == USB_PD_PORT_POWER_SOURCE) {
		r->type = USB_CHG_TYPE_NONE;
		r->meas.voltage_max = 0;
		r->meas.voltage_now = r->role == USB_PD_PORT_POWER_SOURCE ? 5000
									  : 0;
		r->meas.current_max = 0;
		r->max_power = 0;
	} else {
#if defined(HAS_TASK_CHG_RAMP) || defined(CONFIG_CHARGE_RAMP_HW)
		/* Read ramped current if active charging port */
		int use_ramp_current = (charge_port == port);
#else
		const int use_ramp_current = 0;
#endif

		switch (sup) {
		case CHARGE_SUPPLIER_PD:
			r->type = USB_CHG_TYPE_PD;
			break;
		case CHARGE_SUPPLIER_TYPEC:
			r->type = USB_CHG_TYPE_C;
			break;
		case CHARGE_SUPPLIER_PROPRIETARY:
			r->type = USB_CHG_TYPE_PROPRIETARY;
			break;
		case CHARGE_SUPPLIER_BC12_DCP:
			r->type = USB_CHG_TYPE_BC12_DCP;
			break;
		case CHARGE_SUPPLIER_BC12_CDP:
			r->type = USB_CHG_TYPE_BC12_CDP;
			break;
		case CHARGE_SUPPLIER_BC12_SDP:
			r->type = USB_CHG_TYPE_BC12_SDP;
			break;
		case CHARGE_SUPPLIER_VBUS:
			r->type = USB_CHG_TYPE_VBUS;
			break;
		default:
			r->type = USB_CHG_TYPE_OTHER;
		}
		r->meas.voltage_max = available_charge[sup][port].voltage;

		if (use_ramp_current) {
			/*
			 * If charge_ramp has not detected charger yet,
			 * then charger type is unknown.
			 */
			if (!chg_ramp_is_detected())
				r->type = USB_CHG_TYPE_UNKNOWN;

			/* Current limit is output of ramp module */
			r->meas.current_lim = chg_ramp_get_current_limit();

			/*
			 * If ramp is allowed, then the max current depends
			 * on if ramp is stable. If ramp is stable, then
			 * max current is same as input current limit. If
			 * ramp is not stable, then we report the maximum
			 * current we could ramp up to for this supplier.
			 * If ramp is not allowed, max current is just the
			 * available charge current.
			 */
			if (board_is_ramp_allowed(sup)) {
				r->meas.current_max = chg_ramp_is_stable() ?
					r->meas.current_lim :
					board_get_ramp_current_limit(
					  sup,
					  available_charge[sup][port].current);
			} else {
				r->meas.current_max =
					available_charge[sup][port].current;
			}

			r->max_power =
				r->meas.current_max * r->meas.voltage_max;
		} else {
			r->meas.current_max = r->meas.current_lim =
				available_charge[sup][port].current;
			r->max_power = POWER(available_charge[sup][port]);
		}

		/*
		 * If we are sourcing power, or sinking but not charging, then
		 * VBUS must be 5V. If we are charging, then read VBUS ADC.
		 */
		if (r->role == USB_PD_PORT_POWER_SINK_NOT_CHARGING)
			r->meas.voltage_now = 5000;
		else
			if (ADC_VBUS >= 0)
				r->meas.voltage_now =
					adc_read_channel(ADC_VBUS);
			else
				/* No VBUS ADC channel - voltage is unknown */
				r->meas.voltage_now = 0;
	}
}
Esempio n. 15
0
int main(int argc, char *argv[])
/* dftfold:  Does complex plane vector addition of a DFT freq */
/* Written by Scott Ransom on 31 Aug 00 based on Ransom and   */
/* Eikenberry paper I (to be completed sometime...).          */
{
   FILE *infile;
   char infilenm[200], outfilenm[200];
   int dataperread;
   unsigned long N;
   double T, rr = 0.0, norm = 1.0;
   dftvector dftvec;
   infodata idata;
   Cmdline *cmd;

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

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

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

   cmd = parseCmdline(argc, argv);

#ifdef DEBUG
   showOptionValues();
#endif

   printf("\n\n");
   printf("        DFT Vector Folding Routine\n");
   printf("            by Scott M. Ransom\n");
   printf("              31 August, 2000\n\n");

   /* Open the datafile and read the info file */

   sprintf(infilenm, "%s.dat", cmd->argv[0]);
   infile = chkfopen(infilenm, "rb");
   readinf(&idata, cmd->argv[0]);

   /* The number of points in datafile */

   N = chkfilelen(infile, sizeof(float));
   dataperread = N / cmd->numvect;
/*   N = cmd->numvect * dataperread; */
   T = N * idata.dt;

   /* Calculate the Fourier frequency */

   if (!cmd->rrP) {
      if (cmd->ffP)
         rr = cmd->ff;
      else if (cmd->ppP)
         rr = T / cmd->pp;
      else {
         printf("\n  You must specify a frequency to fold!  Exiting.\n\n");
      }
   } else
      rr = cmd->rr;

   /* Calculate the amplitude normalization if required */

   if (cmd->normP)
      norm = 1.0 / sqrt(cmd->norm);
   else if (cmd->fftnormP) {
      FILE *fftfile;
      int kern_half_width, fftdatalen, startbin;
      double rrfrac, rrint;
      char fftfilenm[200];
      fcomplex *fftdata;

      sprintf(fftfilenm, "%s.fft", cmd->argv[0]);
      fftfile = chkfopen(fftfilenm, "rb");
      kern_half_width = r_resp_halfwidth(HIGHACC);
      fftdatalen = 2 * kern_half_width + 10;
      rrfrac = modf(rr, &rrint);
      startbin = (int) rrint - fftdatalen / 2;
      fftdata = read_fcomplex_file(fftfile, startbin, fftdatalen);
      norm = 1.0 / sqrt(get_localpower3d(fftdata, fftdatalen,
                                         rrfrac + fftdatalen / 2, 0.0, 0.0));
      vect_free(fftdata);
      fclose(fftfile);
   }

   /* Initialize the dftvector */

   init_dftvector(&dftvec, dataperread, cmd->numvect, idata.dt, rr, norm, T);

   /* Show our folding values */

   printf("\nFolding data from '%s':\n", infilenm);
   printf("   Folding Fourier Freq = %.5f\n", rr);
   printf("      Folding Freq (Hz) = %-.11f\n", rr / T);
   printf("     Folding Period (s) = %-.14f\n", T / rr);
   printf("  Points per sub-vector = %d\n", dftvec.n);
   printf("  Number of sub-vectors = %d\n", dftvec.numvect);
   printf(" Normalization constant = %g\n", norm * norm);

   /* Perform the actual vector addition */

   {
      int ii, jj;
      float *data;
      double real, imag, sumreal = 0.0, sumimag = 0.0;
      double theta, aa, bb, cc, ss, dtmp;
      double powargr, powargi, phsargr, phsargi, phstmp;

      data = gen_fvect(dftvec.n);
      theta = -TWOPI * rr / (double) N;
      dtmp = sin(0.5 * theta);
      aa = -2.0 * dtmp * dtmp;
      bb = sin(theta);
      cc = 1.0;
      ss = 0.0;
      for (ii = 0; ii < dftvec.numvect; ii++) {
         chkfread(data, sizeof(float), dftvec.n, infile);
         real = 0.0;
         imag = 0.0;
         for (jj = 0; jj < dftvec.n; jj++) {
            real += data[jj] * cc;
            imag += data[jj] * ss;
            cc = aa * (dtmp = cc) - bb * ss + cc;
            ss = aa * ss + bb * dtmp + ss;
         }
         dftvec.vector[ii].r = norm * real;
         dftvec.vector[ii].i = norm * imag;
         sumreal += dftvec.vector[ii].r;
         sumimag += dftvec.vector[ii].i;
      }
      vect_free(data);
      printf("\nDone:\n");
      printf("             Vector sum = %.3f + %.3fi\n", sumreal, sumimag);
      printf("      Total phase (deg) = %.2f\n", PHASE(sumreal, sumimag));
      printf("            Total power = %.2f\n", POWER(sumreal, sumimag));
      printf("\n");
   }
   fclose(infile);

   /* Write the output structure */

   sprintf(outfilenm, "%s_%.3f.dftvec", cmd->argv[0], rr);
   write_dftvector(&dftvec, outfilenm);

   /* Free our vector and return */

   free_dftvector(&dftvec);
   return (0);
}
Esempio n. 16
0
fftcand *search_fft(fcomplex * fft, int numfft, int lobin, int hibin,
                    int numharmsum, int numbetween,
                    presto_interptype interptype,
                    float norm, float sigmacutoff, int *numcands,
                    float *powavg, float *powvar, float *powmax)
/* This routine searches a short FFT of 'numfft' complex freqs      */
/* and returns a candidate vector of fftcand structures containing  */
/* information about the best candidates found.                     */
/* The routine uses either interbinning or interpolation as well    */
/* as harmonic summing during the search.                           */
/* The number of candidates returned is either 'numcands' if != 0,  */
/* or is determined automatically by 'sigmacutoff' -- which         */
/* takes into account the number of bins searched.                  */
/* The returned vector is sorted in order of decreasing power.      */
/* Arguments:                                                       */
/*   'fft' is the FFT to search (complex valued)                    */
/*   'numfft' is the number of complex points in 'fft'              */
/*   'lobin' is the lowest Fourier freq to search                   */
/*   'hibin' is the highest Fourier freq to search                  */
/*   'numharmsum' the number of harmonics to sum during the search  */
/*   'numbetween' the points to interpolate per bin                 */
/*   'interptype' is either INTERBIN or INTERPOLATE.                */
/*      INTERBIN = (interbinning) is fast but less sensitive.       */
/*         NOTE:  INTERBINNING is conducted by this routine!        */
/*      INTERPOLATE = (Fourier interpolation) is slower but more    */
/*        sensitive.                                                */
/*         NOTE:  The interpolation is assumed to ALREADY have been */
/*                completed by the calling function!  The easiest   */
/*                way is by zero-padding to 2*numfft and FFTing.    */
/*                If you use this method, make sure numfft is the   */
/*                original length rather than the interpolated      */
/*                length and also make sure numbetween is correct.  */
/*   'norm' is the normalization constant to multiply each power by */
/*   'sigmacutoff' if the number of candidates will be determined   */
/*      automatically, is the minimum Gaussian significance of      */
/*      candidates to keep -- taking into account the number of     */
/*      bins searched                                               */
/*   'numcands' if !0, is the number of candates to return.         */
/*      if 0, is a return value giving the number of candidates.    */
/*   'powavg' is a return value giving the average power level      */
/*   'powvar' is a return value giving the power level variance     */
/*   'powmax' is a return value giving the maximum power            */
{
   int ii, jj, offset, numtosearch, dynamic = 0;
   int numspread = 0, nc = 0, startnc = 10;
   float powargr, powargi, *fullpows = NULL, *sumpows, ftmp;
   double twobypi, minpow = 0.0, tmpminsig = 0.0, dr, davg, dvar;
   fftcand *cands, newcand;
   fcomplex *spread;

   /* Override the value of numbetween if interbinning */

   if (interptype == INTERBIN)
      numbetween = 2;
   norm = 1.0 / norm;
   *powmax = 0.0;

   /* Decide if we will manage the number of candidates */

   if (*numcands > 0)
      startnc = *numcands;
   else {
      dynamic = 1;
      minpow = power_for_sigma(sigmacutoff, 1, hibin - lobin);
   }
   cands = (fftcand *) malloc(startnc * sizeof(fftcand));
   for (ii = 0; ii < startnc; ii++)
      cands[ii].sig = 0.0;

   /* Prep some other values we will need */

   dr = 1.0 / (double) numbetween;
   twobypi = 2.0 / PI;
   numtosearch = numfft * numbetween;

   /* Spread and interpolate the fft */

   numspread = numfft * numbetween + 1;
   if (interptype == INTERPOLATE) {     /* INTERPOLATE */
      spread = fft;
   } else {                     /* INTERBIN */
      spread = gen_cvect(numspread);
      spread_with_pad(fft, numfft, spread, numspread, numbetween, 0);
      for (ii = 1; ii < numtosearch; ii += 2) {
         spread[ii].r = twobypi * (spread[ii - 1].r - spread[ii + 1].r);
         spread[ii].i = twobypi * (spread[ii - 1].i - spread[ii + 1].i);
      }
   }
   spread[0].r = spread[numtosearch].r = 1.0;
   spread[0].i = spread[numtosearch].i = 0.0;

   /* First generate the original powers in order to         */
   /* calculate the statistics.  Yes, this is inefficient... */

   fullpows = gen_fvect(numtosearch);
   for (ii = lobin, jj = 0; ii < hibin; ii++, jj++) {
      ftmp = POWER(fft[ii].r, fft[ii].i) * norm;
      fullpows[jj] = ftmp;
      if (ftmp > *powmax)
         *powmax = ftmp;
   }
   avg_var(fullpows, hibin - lobin, &davg, &dvar);
   *powavg = davg;
   *powvar = dvar;
   fullpows[0] = 1.0;
   for (ii = 1; ii < numtosearch; ii++)
      fullpows[ii] = POWER(spread[ii].r, spread[ii].i) * norm;
   if (interptype == INTERBIN)
      vect_free(spread);

   /* Search the raw powers */

   for (ii = lobin * numbetween; ii < hibin * numbetween; ii++) {
      if (fullpows[ii] > minpow) {
         newcand.r = dr * (double) ii;
         newcand.p = fullpows[ii];
         newcand.sig = candidate_sigma(fullpows[ii], 1, hibin - lobin);
         newcand.nsum = 1;
         cands[startnc - 1] = newcand;
         tmpminsig = percolate_fftcands(cands, startnc);
         if (dynamic) {
            nc++;
            if (nc == startnc) {
               startnc *= 2;
               cands = (fftcand *) realloc(cands, startnc * sizeof(fftcand));
               for (jj = nc; jj < startnc; jj++)
                  cands[jj].sig = 0.0;
            }
         } else {
            minpow = cands[startnc - 1].p;
            if (nc < startnc)
               nc++;
         }
      }
   }

   /* If needed, sum and search the harmonics */

   if (numharmsum > 1) {
      sumpows = gen_fvect(numtosearch);
      memcpy(sumpows, fullpows, sizeof(float) * numtosearch);
      for (ii = 2; ii <= numharmsum; ii++) {
         offset = ii / 2;
         if (dynamic)
            minpow = power_for_sigma(sigmacutoff, ii, hibin - lobin);
         else
            minpow = power_for_sigma(tmpminsig, ii, hibin - lobin);
         for (jj = lobin * numbetween; jj < numtosearch; jj++) {
            sumpows[jj] += fullpows[(jj + offset) / ii];
            if (sumpows[jj] > minpow) {
               newcand.r = dr * (double) jj;
               newcand.p = sumpows[jj];
               newcand.sig = candidate_sigma(sumpows[jj], ii, hibin - lobin);
               newcand.nsum = ii;
               cands[startnc - 1] = newcand;
               tmpminsig = percolate_fftcands(cands, startnc);
               if (dynamic) {
                  nc++;
                  if (nc == startnc) {
                     startnc *= 2;
                     cands = (fftcand *) realloc(cands, startnc * sizeof(fftcand));
                     for (jj = nc; jj < startnc; jj++)
                        cands[jj].sig = 0.0;
                  }
               } else {
                  minpow = power_for_sigma(tmpminsig, ii, hibin - lobin);
                  if (nc < startnc)
                     nc++;
               }
            }
         }
      }
      vect_free(sumpows);
   }
   vect_free(fullpows);

   /* Chop off the unused parts of the dynamic array */

   if (dynamic)
      cands = (fftcand *) realloc(cands, nc * sizeof(fftcand));
   *numcands = nc;
   return cands;
}
Esempio n. 17
0
void On_time_step(double pTime)
//*****************************
// The analysis at the given time has finished. DO NOT place further actions
// on pins (unless they are delayed). Pins values are stable at this point.
{
   LOGIC newData;

   // Do nothing if the log file could not be opened by the first instance
   if(!File) {
      return;
   }

   // Record the total elapsed simulation time for use in On_simulation_end()
   Total_time = pTime;
   
   // Since we're expecting a digital input, the input voltage should be either
   // 0, POWER(), or POWER()/2 to designate logic 0, 1, and UNKNOWN. To allow
   // for round off-errors or perhaps input passed though an analog RC filter,
   // the 0 to POWER() voltage range is divided into 3 equal sections. Input
   // voltages in the lower third are considered to be logic 0, the upper third
   // to be logic 1, and the middle third to be UNKNOWN.
   double voltage = GET_VOLTAGE(DATA);
   if(voltage < (1.0/3.0) * POWER()) {
      newData = 0;
   } else if(voltage > (2.0/3.0) * POWER()) {
      newData = 1;
   } else {
      newData = UNKNOWN;
   }

   // The first component to enter On_time_step(0) at the beginning of the
   // simulation is responsible for finishing the VCD header section.
   if(Log_time == -1 && pTime == 0) {
      Log_printf("$upscope $end\n");
      Log_printf("$enddefinitions $end\n");
      Log_time = 0;
   }
   
   // If the current state of the input pin is different from the previous
   // state in the last time step, then the new state needs to be logged
   if(newData != VAR(Log_data)) {
      char id = VAR(Instance_number) + MIN_ID;

      // If this component instance is the first to log something at the
      // current "pTime" then also write the current elapsed time to the file
      if(pTime > Log_time) {
         // The elapsed time (in seconds) is logged as an integer number of
         // nanoseconds. To avoid any floating point round off errors, the
         // fprintf() is used to round up the result to the closest integer
         // instead of using an integer cast.
         Log_printf("#%.0lf\n", pTime * TIME_MULT);
         Log_time = pTime;
      }

      // Write the new changed pin state to the log file
      if(newData == 0) {
         Log_printf("0%c\n", id);
      } else if(newData == 1) {
         Log_printf("1%c\n", id);
      } else {
         Log_printf("x%c\n", id);
      }
      
      VAR(Log_data) = newData;
   } 
}
Esempio n. 18
0
void search_minifft(fcomplex * minifft, int numminifft,
                    double min_orb_p, double max_orb_p,
                    rawbincand * cands, int numcands, int numharmsum,
                    int numbetween, double numfullfft, double timefullfft,
                    double lorfullfft, presto_interptype interptype,
                    presto_checkaliased checkaliased)
  /* This routine searches a short FFT (usually produced using the   */
  /* MiniFFT binary search method) and returns a candidte vector     */
  /* containing information about the best binary candidates found.  */
  /* The routine uses either interbinning or interpolation as well   */
  /* as harmonic summing during the search.                          */
  /* Arguments:                                                      */
  /*   'minifft' is the FFT to search (complex valued)               */
  /*   'numminifft' is the number of complex points in 'minifft'     */
  /*   'min_orb_p' is the minimum orbital period (s) to search       */
  /*   'max_orb_p' is the maximum orbital period (s) to search       */
  /*   'cands' is a pre-allocated vector of rawbincand type in which */
  /*      the sorted (in decreasing sigma) candidates are returned   */
  /*   'numcands' is the length of the 'cands' vector                */
  /*   'numharmsum' the number of harmonics to sum during the search */
  /*   'numbetween' the points to interpolate per bin                */
  /*   'numfullfft' the number of points in the original long FFT    */
  /*   'timefullfft' the duration of the original time series (s)    */
  /*   'lorfullfft' the 1st bin of the long FFT that was miniFFT'd   */
  /*   'interptype' is either INTERBIN or INTERPOLATE.               */
/*      INTERBIN = (interbinning) is fast but less sensitive.        */
/*         NOTE:  INTERBINNING is conducted by this routine!         */
/*      INTERPOLATE = (Fourier interpolation) is slower but more     */
/*        sensitive.                                                 */
/*         NOTE:  The interpolation is assumed to ALREADY have been  */
/*                completed by the calling function!  The easiest    */
/*                way is by zero-padding to 2*numminifft and FFTing. */
/*                If you use this method, make sure numminifft is the*/
/*                original length rather than the interpolated       */
/*                length and also make sure numbetween is correct.   */
  /*   'checkaliased' is either CHECK_ALIASED or NO_CHECK_ALIASED.   */
  /*      NO_CHECK_ALIASED = harmonic summing does not include       */
  /*        aliased freqs making it faster but less sensitive.       */
  /*      CHECK_ALIASED = harmonic summing includes aliased freqs    */
  /*        making it slower but more sensitive.                     */
{
   int ii, jj, fftlen, offset, numtosearch = 0, lobin, hibin, numspread = 0;
   float powargr, powargi, *fullpows = NULL, *sumpows;
   double twobypi, minpow, minsig, dr, numindep;
   fcomplex *spread;

   /* Override the value of numbetween if interbinning */

   if (interptype == INTERBIN)
      numbetween = 2;

   /* Prep some other values we will need */

   dr = 1.0 / (double) numbetween;
   twobypi = 2.0 / PI;
   fftlen = numminifft * numbetween;
   for (ii = 0; ii < numcands; ii++) {
      cands[ii].mini_sigma = 0.0;
      cands[ii].mini_power = 0.0;
   }
   lobin = ceil(2 * numminifft * min_orb_p / timefullfft);
   if (lobin <= 0)
      lobin = 1;
   hibin = floor(2 * numminifft * max_orb_p / timefullfft);
   if (hibin >= 2 * numminifft)
      hibin = 2 * numminifft - 1;
   lobin *= numbetween;
   hibin *= numbetween;

   /* Spread and interpolate the fft */

   numtosearch = (checkaliased == CHECK_ALIASED) ? 2 * fftlen : fftlen;
   numspread = numminifft * numbetween + 1;
   if (interptype == INTERPOLATE) {     /* INTERPOLATE */
      spread = minifft;
   } else {                     /* INTERBIN */
      spread = gen_cvect(numspread);
      spread_with_pad(minifft, numminifft, spread, numspread, numbetween, 0);
      for (ii = 1; ii < fftlen; ii += 2) {
         spread[ii].r = twobypi * (spread[ii - 1].r - spread[ii + 1].r);
         spread[ii].i = twobypi * (spread[ii - 1].i - spread[ii + 1].i);
      }
   }
   spread[0].r = spread[fftlen].r = 1.0;
   spread[0].i = spread[fftlen].i = 0.0;

   fullpows = gen_fvect(numtosearch);
   fullpows[0] = 1.0;
   if (checkaliased == CHECK_ALIASED)
      fullpows[fftlen] = 1.0;   /* used to be nyquist^2 */

   /* The following wraps the data around the Nyquist freq such that */
   /* we consider aliased frequencies as well (If CHECK_ALIASED).    */

   if (checkaliased == CHECK_ALIASED)
      for (ii = 1, jj = numtosearch - 1; ii < fftlen; ii++, jj--)
         fullpows[ii] = fullpows[jj] = POWER(spread[ii].r, spread[ii].i);
   else
      for (ii = 1; ii < numtosearch; ii++)
         fullpows[ii] = POWER(spread[ii].r, spread[ii].i);
   if (interptype == INTERBIN)
      vect_free(spread);

   /* Search the raw powers */

   numindep = hibin - lobin + 1.0;
   minpow = power_for_sigma(MINRETURNSIG, 1, numindep);
   for (ii = lobin; ii < hibin; ii++) {
      if (fullpows[ii] > minpow) {
         cands[numcands - 1].mini_r = dr * (double) ii;
         cands[numcands - 1].mini_power = fullpows[ii];
         cands[numcands - 1].mini_numsum = 1.0;
         cands[numcands - 1].mini_sigma = candidate_sigma(fullpows[ii], 1, numindep);
         minsig = percolate_rawbincands(cands, numcands);
         if (cands[numcands - 1].mini_power > minpow)
            minpow = cands[numcands - 1].mini_power;
      }
   }

   /* If needed, sum and search the harmonics */

   if (numharmsum > 1) {
      sumpows = gen_fvect(numtosearch);
      memcpy(sumpows, fullpows, sizeof(float) * numtosearch);
      for (ii = 2; ii <= numharmsum; ii++) {
         offset = ii / 2;
         numindep = (hibin - lobin + 1.0) / (double) ii;
         if (cands[numcands - 1].mini_sigma < MINRETURNSIG)
            minsig = MINRETURNSIG;
         else
            minsig = cands[numcands - 1].mini_sigma;
         minpow = power_for_sigma(minsig, ii, numindep);
         for (jj = lobin * ii; jj < hibin; jj++) {
            sumpows[jj] += fullpows[(jj + offset) / ii];
            if (sumpows[jj] > minpow) {
               cands[numcands - 1].mini_r = (dr * (double) jj) / ii;
               cands[numcands - 1].mini_power = sumpows[jj];
               cands[numcands - 1].mini_numsum = (double) ii;
               cands[numcands - 1].mini_sigma =
                   candidate_sigma(sumpows[jj], ii, numindep);
               minsig = percolate_rawbincands(cands, numcands);
               if (minsig > MINRETURNSIG)
                  minpow = power_for_sigma(minsig, ii, numindep);
            }
         }
      }
      vect_free(sumpows);
   }
   vect_free(fullpows);

   /* Add the rest of the rawbincand data to the candidate array */

   for (ii = 0; ii < numcands; ii++) {
      cands[ii].full_N = numfullfft;
      cands[ii].full_T = timefullfft;
      cands[ii].full_lo_r = lorfullfft;
      cands[ii].mini_N = 2 * numminifft;        /* # of real points */
      cands[ii].psr_p = timefullfft / (lorfullfft + numminifft);
      cands[ii].orb_p = timefullfft * cands[ii].mini_r / cands[ii].mini_N;
   }
}
Esempio n. 19
0
int main(int argc, char *argv[])
{
	// promenne		
	//char buffer[BUFFER_SIZE]; // pole znaku
	int i = 0;
	int j = 0;
	char ch;
	float fl = 0;
	double dbl = 15.3;

	const int pole[] = {1, 2, 3, 4, 5, 6, 7};
	int velikostPole = 0;
	
	int a = 5;
	int x = 0;
	int y = 0;

	int prvni = 0;
	int druhe = 0;
	int result = 0;

	//-----------------------------------------------------------------------------------------------------------------------------------
	setCmdTextColor(TEXT_RED);
	printf("VITEJTE V CVICENI C. 3!\n\n");
	setCmdTextColor(TEXT_WHITE);

	// operatory	
	i = !i;
	printf("i = %d \n", i); 

	i = 10;

	i++; 
	printf("i = %d \n", i);
	++i; 
	printf("i = %d \n", i);

	i--;
	printf("i = %d \n", i);
	--i;
	printf("i = %d \n", i);

	i = i + 1;
	i = i - 1;

	printf("i / 2 = %d \n", i / 2);
	printf("i * 2 = %d \n", i * 2);
	printf("Zbytek po deleni = %d \n", i % 3);

	i += 1;
	i -= 1;

	if ( i > 0 && i <= 15 )
		printf("Od peti do patnacti... \n");

	if ( i == 10 ) 
		printf("Deset \n");

	j = 5;
	if ( i == 10 || j > 1)
		printf("Podminka splnena \n");

	j *= 2;
	printf("j = %d \n", j );

	j /= 2;
	printf("j = %d \n", j );

	printf("sizeof int = %d \n", sizeof(j));
	printf("sizeof char = %d \n", sizeof(ch));
	printf("sizeof float = %d \n", sizeof(fl));
	printf("sizeof double = %d \n", sizeof(dbl));
		
	printf("velikost pole = %d \n", sizeof(pole) / sizeof(pole[0]));
	velikostPole = sizeof(pole) / sizeof(pole[0]);

	printf("a = %d \n", a);
	a = a++ + ++a; // nedefinovany stav
	printf("a = %d \n", a);

	//-----------------------------------------------------------------------------------------------------------------------------------
	// ternarni operatory
	x = (x == 0) ? 1:11;
	printf("x = %d \n", x);
	
	// slozeny ternarni operator -> tohle neni dobry napad
	y=x>0?x<10?x:x>9000?9001:0:0;
	printf("y = %d\n",y);
	
	if(x>0 && x < 10)
		y = x;
	else if (x > 9000)
		y = 9001;
	else
		y = 0;
	
	// operator carky
	for(x=0, y=0; x<5; x++, ++y){
		printf("x = %d, y = %d \n", x, y);
	}
	
	//-----------------------------------------------------------------------------------------------------------------------------------
	// makra
	printf("%s \n", AHOJ);
	NAZDAR;
	printf("%d \n", POWER(10));
	SOUCET(x, y);

	//-----------------------------------------------------------------------------------------------------------------------------------
	// funkce

	printf("Zadej prvni cislo: ");
	scanf("%d", &prvni);

	printf("Zadej druhe cislo: ");
	while (!scanf("%d", &druhe))
	{
		fflush(stdin); 
		printf("Zadej cislo: ");	
	}
	result = secti(prvni, druhe);
	printf("A+B = %d  \n", result);

	printPole(pole, velikostPole);

	//-----------------------------------------------------------------------------------------------------------------------------------
	// podmineny preklad

	setCmdTextColor(TEXT_YELLOW);
#ifndef NDEBUG
	printf("DEBUG \n");
#else
	printf("RELEASE \n");
#endif
	setCmdTextColor(TEXT_WHITE);

	//-----------------------------------------------------------------------------------------------------------------------------------
	// booleovska algebra
	for(i = 0; i <= 15; i++){
		printf("i = %2d --> ", i);

		if((i >= 5) && (i <= 10)){
			printf("AND True , ");
		}else{
			printf("AND False, ");
		}

		if((i < 5) || (i > 10)){
			printf("OR True  \n");
		}else{
			printf("OR False \n");
		}
	}

	return 0;
}
Esempio n. 20
0
static fftview *get_fftview(double centerr, int zoomlevel, fftpart * fp)
{
   int ii;
   double split = 1.0 / (double) LOCALCHUNK;
   float powargr, powargi;
   fftview *fv;

   fv = (fftview *) malloc(sizeof(fftview));
   fv->zoomlevel = zoomlevel;
   fv->centerr = centerr;
   if (zoomlevel > 0) {         /* Magnified power spectrum */
      int numbetween, nextbin, index;
      fcomplex *interp;

      numbetween = (1 << zoomlevel);
      fv->numbins = DISPLAYNUM / numbetween;
      fv->dr = 1.0 / (double) numbetween;
      fv->lor = centerr - fv->numbins / 2;
      if (fv->lor + fv->numbins > Nfft) {
         fv->lor = Nfft - fv->numbins;
         fv->centerr = fv->lor + fv->numbins / 2;
      }
      if (fv->lor < 0)
         fv->lor = 0;
      interp = corr_rz_interp(fp->amps, fp->numamps, numbetween,
                              fv->lor - fp->rlo, 0.0, DISPLAYNUM * 2,
                              LOWACC, &nextbin);
      if (norm_const == 0.0) {
         for (ii = 0; ii < DISPLAYNUM; ii++) {
            fv->rs[ii] = fv->lor + ii * fv->dr;
            index = (int) ((fv->rs[ii] - fp->rlo) * split + 0.5);
            fv->powers[ii] = POWER(interp[ii].r, interp[ii].i) * fp->normvals[index];
         }
      } else {
         for (ii = 0; ii < DISPLAYNUM; ii++) {
            fv->rs[ii] = fv->lor + ii * fv->dr;
            fv->powers[ii] = POWER(interp[ii].r, interp[ii].i) * norm_const;
         }
      }
      vect_free(interp);
   } else {                     /* Down-sampled power spectrum */
      int jj, powindex, normindex, binstocombine;
      float *tmprawpwrs, maxpow;

      binstocombine = (1 << abs(zoomlevel));
      fv->numbins = DISPLAYNUM * binstocombine;
      fv->dr = (double) binstocombine;
      fv->lor = (int) floor(centerr - 0.5 * fv->numbins);
      if (fv->lor + fv->numbins > Nfft) {
         fv->lor = Nfft - fv->numbins;
         fv->centerr = fv->lor + fv->numbins / 2;
      }
      if (fv->lor < 0)
         fv->lor = 0;
      tmprawpwrs = gen_fvect(fv->numbins);
      if (norm_const == 0.0) {
         for (ii = 0; ii < fv->numbins; ii++) {
            powindex = (int) (fv->lor - fp->rlo + ii + 0.5);
            normindex = (int) (powindex * split);
            tmprawpwrs[ii] = fp->rawpowers[powindex] * fp->normvals[normindex];
         }
      } else {
         for (ii = 0; ii < fv->numbins; ii++) {
            powindex = (int) (fv->lor - fp->rlo + ii + 0.5);
            tmprawpwrs[ii] = fp->rawpowers[powindex] * norm_const;
         }
      }
      powindex = 0;
      for (ii = 0; ii < DISPLAYNUM; ii++) {
         maxpow = 0.0;
         for (jj = 0; jj < binstocombine; jj++, powindex++)
            if (tmprawpwrs[powindex] > maxpow)
               maxpow = tmprawpwrs[powindex];
         fv->rs[ii] = fv->lor + ii * fv->dr;
         fv->powers[ii] = maxpow;
      }
   }
   fv->maxpow = 0.0;
   for (ii = 0; ii < DISPLAYNUM; ii++)
      if (fv->powers[ii] > fv->maxpow)
         fv->maxpow = fv->powers[ii];
   return fv;
}
Esempio n. 21
0
void *power_copy(power *expr) {
    return POWER(copy(expr->primary), copy(expr->u_expr));
}
Esempio n. 22
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);
}
Esempio n. 23
0
static void process_bird(double basebin, int harm, double *lofreq, double *hifreq)
{
   int ii, plotnumpts = 1000, not_done_yet = 1, plotoffset;
   int lodatabin, firstcorrbin, numgoodpts, replot = 1;
   char inchar;
   float med, xx[2], yy[2], inx, iny;
   float powargr, powargi, pwr, maxpow = 0.0, maxbin = 0.0;
   double truebin, pred_freq, average;
   double firstbin = 0.0, lastbin = 0.0, numbins = 0.0;
   fcomplex *data, *result;

   /* 'bin' means normal resolution FFT amplitude */
   /* 'pt'  means an interpolated FFT amplitude   */
   /* 'pts'=='bins' only if NUMBETWEEN==1         */

   *lofreq = *hifreq = 0.0;
   truebin = basebin * harm;
   pred_freq = truebin / T;
   xx[0] = xx[1] = pred_freq;
   data = get_rawbins(fftfile, truebin, BINSTOGET, &med, &lodatabin);
   if (lodatabin <= 0) {
      data[abs(lodatabin)].r = 1.0;
      data[abs(lodatabin)].i = 1.0;
   }
   firstcorrbin = (int) truebin - MAXBINSTOSHOW / 2;
   average = med / -log(0.5);
   result = gen_cvect(FFTLEN);
   numgoodpts = corr_complex(data, BINSTOGET, RAW,
                             kernel, FFTLEN, FFT,
                             result, MAXPTSTOSHOW,
                             firstcorrbin - lodatabin, NUMBETWEEN, khw, CORR);
   for (ii = 0; ii < numgoodpts; ii++) {
      pwr = POWER(result[ii].r, result[ii].i) / average;
      if (pwr > maxpow) {
         maxpow = pwr;
         maxbin = firstcorrbin + dr * ii;
      }
   }
   printf("\nHarmonic %d of %.15g Hz (%.15g Hz, bin = %.15g)\n",
          harm, basebin / T, pred_freq, truebin);
   printf("  Max power = %.2f at %.15g Hz (bin = %.15g)\n",
          maxpow, maxbin / T, maxbin);
   do {
      cpgsci(1);
      if (replot) {
         plotoffset = MAXPTSTOSHOW / 2 - plotnumpts / 2;
         firstbin = firstcorrbin + dr * plotoffset;
         numbins = dr * plotnumpts;
         lastbin = firstbin + numbins;
         plot_spectrum(result + plotoffset, plotnumpts, firstbin, dr, T, average);
         cpgswin(0.0, 1.0, 0.0, 1.0);
         xx[0] = xx[1] = (truebin - firstbin) / numbins;
         yy[0] = 0.0;
         yy[1] = 1.0;
         cpgsci(2);             /* red */
         cpgline(2, xx, yy);    /* Predicted freq */
         cpgsci(7);             /* yellow */
         if (*lofreq) {
            xx[0] = xx[1] = ((*lofreq * T) - firstbin) / numbins;
            cpgline(2, xx, yy); /* Boundary */
         }
         if (*hifreq) {
            xx[0] = xx[1] = ((*hifreq * T) - firstbin) / numbins;
            cpgline(2, xx, yy); /* Boundary */
         }
      }
      replot = 1;
      cpgsci(7);                /* yellow */
      cpgcurs(&inx, &iny, &inchar);
      switch (inchar) {
      case ' ':
      case 'A':
      case 'a':
         xx[0] = xx[1] = inx;
         cpgline(2, xx, yy);    /* New boundary */
         if (*lofreq == 0.0) {
            *lofreq = (inx * numbins + firstbin) / T;
            printf("  Added 1st boundary at %.12g Hz\n", *lofreq);
         } else {
            *hifreq = (inx * numbins + firstbin) / T;
            printf("  Added 2nd boundary at %.12g Hz\n", *hifreq);
         }
         replot = 0;
         break;
      case 'I':                /* Zoom in */
      case 'i':
         plotnumpts /= 2;
         if (plotnumpts <= 8)
            plotnumpts = 8;
         printf("  Zooming in...\n");
         break;
      case 'O':                /* Zoom out */
      case 'o':
         plotnumpts *= 2;
         if (plotnumpts > MAXPTSTOSHOW)
            plotnumpts = MAXPTSTOSHOW;
         printf("  Zooming out...\n");
         break;
      case 'C':                /* Clear/Delete the points */
      case 'c':
      case 'D':
      case 'd':
      case 'X':
      case 'x':
         *lofreq = *hifreq = 0.0;
         printf("  Clearing boundaries.\n");
         break;
      case 'Q':                /* Quit/Next birdie */
      case 'q':
      case 'N':
      case 'n':
         *lofreq = *hifreq = 0.0;
         free(data);
         vect_free(result);
         printf("  Skipping to next harmonic.\n");
         return;
      default:
         printf("  Unrecognized option '%c'.\n", inchar);
         break;
      }
      if (*lofreq && *hifreq)
         not_done_yet = 0;
   } while (not_done_yet);
   if (*hifreq < *lofreq) {
      double tmpfreq;
      tmpfreq = *lofreq;
      *lofreq = *hifreq;
      *hifreq = tmpfreq;
   }
   free(data);
   vect_free(result);
}
Esempio n. 24
0
ffdotpows *subharm_ffdot_plane(int numharm, int harmnum,
                               double fullrlo, double fullrhi,
                               subharminfo * shi, accelobs * obs)
{
   int ii, lobin, hibin, numdata, nice_numdata, nrs, fftlen, binoffset;
   static int numrs_full = 0, numzs_full = 0;
   float powargr, powargi;
   double drlo, drhi, harm_fract;
   ffdotpows *ffdot;
   fcomplex *data, **result;
   presto_datainf datainf;

   if (numrs_full == 0) {
      if (numharm == 1 && harmnum == 1) {
         numrs_full = ACCEL_USELEN;
         numzs_full = shi->numkern;
      } else {
         printf("You must call subharm_ffdot_plane() with numharm=1 and\n");
         printf("harnum=1 before you use other values!  Exiting.\n\n");
         exit(0);
      }
   }
   ffdot = (ffdotpows *) malloc(sizeof(ffdotpows));

   /* Calculate and get the required amplitudes */

   harm_fract = (double) harmnum / (double) numharm;
   drlo = calc_required_r(harm_fract, fullrlo);
   drhi = calc_required_r(harm_fract, fullrhi);
   ffdot->rlo = (int) floor(drlo);
   ffdot->zlo = calc_required_z(harm_fract, obs->zlo);

   /* Initialize the lookup indices */
   if (numharm > 1) {
      double rr, subr;
      for (ii = 0; ii < numrs_full; ii++) {
         rr = fullrlo + ii * ACCEL_DR;
         subr = calc_required_r(harm_fract, rr);
         shi->rinds[ii] = index_from_r(subr, ffdot->rlo);
      }
   }
   ffdot->rinds = shi->rinds;
   ffdot->numrs = (int) ((ceil(drhi) - floor(drlo))
                         * ACCEL_RDR + DBLCORRECT) + 1;
   if (numharm == 1 && harmnum == 1) {
      ffdot->numrs = ACCEL_USELEN;
   } else {
      if (ffdot->numrs % ACCEL_RDR) {
         ffdot->numrs = (ffdot->numrs / ACCEL_RDR + 1) * ACCEL_RDR;
      }
   }
   ffdot->numzs = shi->numkern;
   binoffset = shi->kern[0].kern_half_width;
   fftlen = shi->kern[0].fftlen;
   lobin = ffdot->rlo - binoffset;
   hibin = (int) ceil(drhi) + binoffset;
   numdata = hibin - lobin + 1;
   nice_numdata = next2_to_n(numdata);  // for FFTs
   data = get_fourier_amplitudes(lobin, nice_numdata, obs);
   if (!obs->mmap_file && !obs->dat_input && 0)
       printf("This is newly malloc'd!\n");

   // Normalize the Fourier amplitudes

   if (obs->nph > 0.0) {
       //  Use freq 0 normalization if requested (i.e. photons)
       double norm = 1.0 / sqrt(obs->nph);
       for (ii = 0; ii < numdata; ii++) {
           data[ii].r *= norm;
           data[ii].i *= norm;
       }
   } else if (obs->norm_type == 0) {
       //  old-style block median normalization
       float *powers;
       double norm;

       powers = gen_fvect(numdata);
       for (ii = 0; ii < numdata; ii++)
           powers[ii] = POWER(data[ii].r, data[ii].i);
       norm = 1.0 / sqrt(median(powers, numdata)/log(2.0));
       free(powers);
       for (ii = 0; ii < numdata; ii++) {
           data[ii].r *= norm;
           data[ii].i *= norm;
       }
   } else {
       //  new-style running double-tophat local-power normalization
       float *powers, *loc_powers;

       powers = gen_fvect(nice_numdata);
       for (ii = 0; ii < nice_numdata; ii++) {
           powers[ii] = POWER(data[ii].r, data[ii].i);
       }
       loc_powers = corr_loc_pow(powers, nice_numdata);
       for (ii = 0; ii < numdata; ii++) {
           float norm = invsqrt(loc_powers[ii]);
           data[ii].r *= norm;
           data[ii].i *= norm;
       }
       free(powers);
       free(loc_powers);
   }

   /* Perform the correlations */

   result = gen_cmatrix(ffdot->numzs, ffdot->numrs);
   datainf = RAW;
   for (ii = 0; ii < ffdot->numzs; ii++) {
      nrs = corr_complex(data, numdata, datainf,
                         shi->kern[ii].data, fftlen, FFT,
                         result[ii], ffdot->numrs, binoffset,
                         ACCEL_NUMBETWEEN, binoffset, CORR);
      datainf = SAME;
   }

   // Always free data
   free(data);

   /* Convert the amplitudes to normalized powers */

   ffdot->powers = gen_fmatrix(ffdot->numzs, ffdot->numrs);
   for (ii = 0; ii < (ffdot->numzs * ffdot->numrs); ii++)
      ffdot->powers[0][ii] = POWER(result[0][ii].r, result[0][ii].i);
   free(result[0]);
   free(result);
   return ffdot;
}
Esempio n. 25
0
void
_acb_poly_powsum_one_series_sieved(acb_ptr z, const acb_t s, slong n, slong len, slong prec)
{
    slong * divisors;
    slong powers_alloc;
    slong i, j, k, ibound, kprev, power_of_two, horner_point;
    int critical_line, integer;

    acb_ptr powers;
    acb_ptr t, u, x;
    acb_ptr p1, p2;
    arb_t logk, v, w;

    critical_line = arb_is_exact(acb_realref(s)) &&
        (arf_cmp_2exp_si(arb_midref(acb_realref(s)), -1) == 0);

    integer = arb_is_zero(acb_imagref(s)) && arb_is_int(acb_realref(s));

    divisors = flint_calloc(n / 2 + 1, sizeof(slong));
    powers_alloc = (n / 6 + 1) * len;
    powers = _acb_vec_init(powers_alloc);

    ibound = n_sqrt(n);
    for (i = 3; i <= ibound; i += 2)
        if (DIVISOR(i) == 0)
            for (j = i * i; j <= n; j += 2 * i)
                DIVISOR(j) = i;

    t = _acb_vec_init(len);
    u = _acb_vec_init(len);
    x = _acb_vec_init(len);
    arb_init(logk);
    arb_init(v);
    arb_init(w);

    power_of_two = 1;
    while (power_of_two * 2 <= n)
        power_of_two *= 2;
    horner_point = n / power_of_two;

    _acb_vec_zero(z, len);

    kprev = 0;
    COMPUTE_POWER(x, 2, kprev);

    for (k = 1; k <= n; k += 2)
    {
        /* t = k^(-s) */
        if (DIVISOR(k) == 0)
        {
            COMPUTE_POWER(t, k, kprev);
        }
        else
        {
            p1 = POWER(DIVISOR(k));
            p2 = POWER(k / DIVISOR(k));

            if (len == 1)
                acb_mul(t, p1, p2, prec);
            else
                _acb_poly_mullow(t, p1, len, p2, len, len, prec);
        }

        if (k * 3 <= n)
            _acb_vec_set(POWER(k), t, len);

        _acb_vec_add(u, u, t, len, prec);

        while (k == horner_point && power_of_two != 1)
        {
            _acb_poly_mullow(t, z, len, x, len, len, prec);
            _acb_vec_add(z, t, u, len, prec);

            power_of_two /= 2;
            horner_point = n / power_of_two;
            horner_point -= (horner_point % 2 == 0);
        }
    }

    _acb_poly_mullow(t, z, len, x, len, len, prec);
    _acb_vec_add(z, t, u, len, prec);

    flint_free(divisors);
    _acb_vec_clear(powers, powers_alloc);
    _acb_vec_clear(t, len);
    _acb_vec_clear(u, len);
    _acb_vec_clear(x, len);
    arb_clear(logk);
    arb_clear(v);
    arb_clear(w);
}
Esempio n. 26
0
int main(int argc, char *argv[])
{
   FILE *fftfile, *candfile;
   float powargr, powargi, *powers = NULL, *minifft;
   float norm, numchunks, *powers_pos;
   int nbins, newncand, nfftsizes, fftlen, halffftlen, binsleft;
   int numtoread, filepos = 0, loopct = 0, powers_offset, ncand2;
   int ii, ct, newper = 0, oldper = 0, numsumpow = 1;
   double T, totnumsearched = 0.0, minsig = 0.0, min_orb_p, max_orb_p;
   char *rootfilenm, *notes;
   fcomplex *data = NULL;
   rawbincand tmplist[MININCANDS], *list;
   infodata idata;
   struct tms runtimes;
   double ttim, utim, stim, tott;
   Cmdline *cmd;
   fftwf_plan fftplan;

   /* Prep the timer */

   tott = times(&runtimes) / (double) CLK_TCK;

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

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

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

   cmd = parseCmdline(argc, argv);

#ifdef DEBUG
   showOptionValues();
#endif

   printf("\n\n");
   printf("     Phase Modulation Pulsar Search Routine\n");
   printf("              by Scott M. Ransom\n\n");

   {
      int hassuffix = 0;
      char *suffix;

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

   /* Read the info file */

   readinf(&idata, rootfilenm);
   T = idata.N * idata.dt;
   if (strlen(remove_whitespace(idata.object)) > 0) {
      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]);
   }
   min_orb_p = MINORBP;
   if (cmd->noaliasP)
      max_orb_p = T / 2.0;
   else
      max_orb_p = T / 1.2;

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

   fftfile = chkfopen(cmd->argv[0], "rb");
   nbins = chkfilelen(fftfile, sizeof(fcomplex));

   /* Check that cmd->maxfft is an acceptable power of 2 */

   ct = 4;
   ii = 1;
   while (ct < MAXREALFFT || ii) {
      if (ct == cmd->maxfft)
         ii = 0;
      ct <<= 1;
   }
   if (ii) {
      printf("\n'maxfft' is out of range or not a power-of-2.\n\n");
      exit(1);
   }

   /* Check that cmd->minfft is an acceptable power of 2 */

   ct = 4;
   ii = 1;
   while (ct < MAXREALFFT || ii) {
      if (ct == cmd->minfft)
         ii = 0;
      ct <<= 1;
   }
   if (ii) {
      printf("\n'minfft' is out of range or not a power-of-2.\n\n");
      exit(1);
   }

   /* Low and high Fourier freqs to check */

   if (cmd->floP) {
      cmd->rlo = floor(cmd->flo * T);
      if (cmd->rlo < cmd->lobin)
         cmd->rlo = cmd->lobin;
      if (cmd->rlo > cmd->lobin + nbins - 1) {
         printf("\nLow frequency to search 'flo' is greater than\n");
         printf("   the highest available frequency.  Exiting.\n\n");
         exit(1);
      }
   } else {
      cmd->rlo = 1.0;
      if (cmd->rlo < cmd->lobin)
         cmd->rlo = cmd->lobin;
      if (cmd->rlo > cmd->lobin + nbins - 1) {
         printf("\nLow frequency to search 'rlo' is greater than\n");
         printf("   the available number of points.  Exiting.\n\n");
         exit(1);
      }
   }
   if (cmd->fhiP) {
      cmd->rhi = ceil(cmd->fhi * T);
      if (cmd->rhi > cmd->lobin + nbins - 1)
         cmd->rhi = cmd->lobin + nbins - 1;
      if (cmd->rhi < cmd->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) {
      if (cmd->rhi > cmd->lobin + nbins - 1)
         cmd->rhi = cmd->lobin + nbins - 1;
      if (cmd->rhi < cmd->rlo) {
         printf("\nHigh frequency to search 'rhi' is less than\n");
         printf("   the lowest frequency to search 'rlo'.  Exiting.\n\n");
         exit(1);
      }
   }

   /* Determine how many different mini-fft sizes we will use */

   nfftsizes = 1;
   ii = cmd->maxfft;
   while (ii > cmd->minfft) {
      ii >>= 1;
      nfftsizes++;
   }

   /* Allocate some memory and prep some variables.             */
   /* For numtoread, the 6 just lets us read extra data at once */

   numtoread = 6 * cmd->maxfft;
   if (cmd->stack == 0)
      powers = gen_fvect(numtoread);
   minifft = (float *) fftwf_malloc(sizeof(float) *
                                    (cmd->maxfft * cmd->numbetween + 2));
   ncand2 = 2 * cmd->ncand;
   list = (rawbincand *) malloc(sizeof(rawbincand) * ncand2);
   for (ii = 0; ii < ncand2; ii++)
      list[ii].mini_sigma = 0.0;
   for (ii = 0; ii < MININCANDS; ii++)
      tmplist[ii].mini_sigma = 0.0;
   filepos = cmd->rlo - cmd->lobin;
   numchunks = (float) (cmd->rhi - cmd->rlo) / numtoread;
   printf("Searching...\n");
   printf("   Amount complete = %3d%%", 0);
   fflush(stdout);

   /* Prep FFTW */
   read_wisdom();

   /* Loop through fftfile */

   while ((filepos + cmd->lobin) < cmd->rhi) {

      /* Calculate percentage complete */

      newper = (int) (loopct / numchunks * 100.0);

      if (newper > oldper) {
         newper = (newper > 99) ? 100 : newper;
         printf("\r   Amount complete = %3d%%", newper);
         oldper = newper;
         fflush(stdout);
      }

      /* Adjust our search parameters if close to end of zone to search */

      binsleft = cmd->rhi - (filepos + cmd->lobin);
      if (binsleft < cmd->minfft)
         break;
      if (binsleft < numtoread) {       /* Change numtoread */
         numtoread = cmd->maxfft;
         while (binsleft < numtoread) {
            cmd->maxfft /= 2;
            numtoread = cmd->maxfft;
         }
      }
      fftlen = cmd->maxfft;

      /* Read from fftfile */

      if (cmd->stack == 0) {
         data = read_fcomplex_file(fftfile, filepos, numtoread);
         for (ii = 0; ii < numtoread; ii++)
            powers[ii] = POWER(data[ii].r, data[ii].i);
         numsumpow = 1;
      } else {
         powers = read_float_file(fftfile, filepos, numtoread);
         numsumpow = cmd->stack;
      }
      if (filepos == 0)
         powers[0] = 1.0;

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

      prune_powers(powers, numtoread, numsumpow);

      /* Loop through the different small FFT sizes */

      while (fftlen >= cmd->minfft) {

         halffftlen = fftlen / 2;
         powers_pos = powers;
         powers_offset = 0;

         /* Create the appropriate FFT plan */

         fftplan = fftwf_plan_dft_r2c_1d(cmd->interbinP ? fftlen : 2 * fftlen,
                                         minifft, (fftwf_complex *) minifft,
                                         FFTW_PATIENT);

         /* Perform miniffts at each section of the powers array */

         while ((numtoread - powers_offset) >
                (int) ((1.0 - cmd->overlap) * cmd->maxfft + DBLCORRECT)) {

            /* Copy the proper amount and portion of powers into minifft */

            memcpy(minifft, powers_pos, fftlen * sizeof(float));
            /* For Fourier interpolation use a zeropadded FFT */
            if (cmd->numbetween > 1 && !cmd->interbinP) {
               for (ii = fftlen; ii < cmd->numbetween * fftlen; ii++)
                  minifft[ii] = 0.0;
            }

            /* Perform the minifft */

            fftwf_execute(fftplan);

            /* Normalize and search the miniFFT */

            norm = sqrt(fftlen * numsumpow) / minifft[0];
            for (ii = 0; ii < (cmd->interbinP ? fftlen + 1 : 2 * fftlen + 1); ii++)
               minifft[ii] *= norm;
            search_minifft((fcomplex *) minifft, halffftlen, min_orb_p,
                           max_orb_p, tmplist, MININCANDS, cmd->harmsum,
                           cmd->numbetween, idata.N, T,
                           (double) (powers_offset + filepos + cmd->lobin),
                           cmd->interbinP ? INTERBIN : INTERPOLATE,
                           cmd->noaliasP ? NO_CHECK_ALIASED : CHECK_ALIASED);

            /* Check if the new cands should go into the master cand list */

            for (ii = 0; ii < MININCANDS; ii++) {
               if (tmplist[ii].mini_sigma > minsig) {

                  /* Check to see if another candidate with these properties */
                  /* is already in the list.                                 */

                  if (not_already_there_rawbin(tmplist[ii], list, ncand2)) {
                     list[ncand2 - 1] = tmplist[ii];
                     minsig = percolate_rawbincands(list, ncand2);
                  }
               } else {
                  break;
               }
               /* Mini-fft search for loop */
            }

            totnumsearched += fftlen;
            powers_pos += (int) (cmd->overlap * fftlen);
            powers_offset = powers_pos - powers;

            /* Position of mini-fft in data set while loop */
         }

         fftwf_destroy_plan(fftplan);
         fftlen >>= 1;

         /* Size of mini-fft while loop */
      }

      if (cmd->stack == 0)
         vect_free(data);
      else
         vect_free(powers);
      filepos += (numtoread - (int) ((1.0 - cmd->overlap) * cmd->maxfft));
      loopct++;

      /* File position while loop */
   }

   /* Print the final percentage update */

   printf("\r   Amount complete = %3d%%\n\n", 100);

   /* Print the number of frequencies searched */

   printf("Searched %.0f pts (including interbins).\n\n", totnumsearched);

   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 time: %.3f sec (User: %.3f sec, System: %.3f sec)\n",
          ttim, utim, stim);
   printf("  Total time: %.3f sec\n\n", tott);

   printf("Writing result files and cleaning up.\n");

   /* Count how many candidates we actually have */

   ii = 0;
   while (ii < ncand2 && list[ii].mini_sigma != 0)
      ii++;
   newncand = (ii > cmd->ncand) ? cmd->ncand : ii;

   /* Set our candidate notes to all spaces */

   notes = malloc(sizeof(char) * newncand * 18 + 1);
   for (ii = 0; ii < newncand; ii++)
      strncpy(notes + ii * 18, "                     ", 18);

   /* Check the database for possible known PSR detections */

   if (idata.ra_h && idata.dec_d) {
      for (ii = 0; ii < newncand; ii++) {
         comp_rawbin_to_cand(&list[ii], &idata, notes + ii * 18, 0);
      }
   }

   /* Compare the candidates with each other */

   compare_rawbin_cands(list, newncand, notes);

   /* Send the candidates to the text file */

   file_rawbin_candidates(list, notes, newncand, cmd->harmsum, rootfilenm);

   /* Write the binary candidate file */
   {
      char *candnm;

      candnm = (char *) calloc(strlen(rootfilenm) + 15, sizeof(char));
      sprintf(candnm, "%s_bin%d.cand", rootfilenm, cmd->harmsum);
      candfile = chkfopen(candnm, "wb");
      chkfwrite(list, sizeof(rawbincand), (unsigned long) newncand, candfile);
      fclose(candfile);
      free(candnm);
   }

   /* Free our arrays and close our files */

   if (cmd->stack == 0)
      vect_free(powers);
   free(list);
   fftwf_free(minifft);
   free(notes);
   free(rootfilenm);
   fclose(fftfile);
   printf("Done.\n\n");
   return (0);
}
Esempio n. 27
0
void deredden(fcomplex * fft, int numamps)
/* Attempt to remove rednoise from a time series by using   */
/* a median-filter of logarithmically increasing width.     */
/* Thanks to Jason Hessels and Maggie Livingstone for the   */
/* initial implementation (in rednoise.c)                   */
{
   int ii, initialbuflen = 6, lastbuflen, newbuflen, maxbuflen = 200;
   int newoffset = 1, fixedoffset = 1;
   float *powers, mean_old, mean_new;
   double slope, lineval, scaleval = 1.0, lineoffset = 0;

   powers = gen_fvect(numamps);

   /* Takes care of the DC term */
   fft[0].r = 1.0;
   fft[0].i = 0.0;

   /* Step through the input FFT and create powers */
   for (ii = 0; ii < numamps; ii++) {
      float powargr, powargi;
      powers[ii] = POWER(fft[ii].r, fft[ii].i);
   }

   /* Calculate initial values */
   mean_old = median(powers + newoffset, initialbuflen) / log(2.0);
   newoffset += initialbuflen;
   lastbuflen = initialbuflen;
   newbuflen = initialbuflen * log(newoffset);
   if (newbuflen > maxbuflen)
      newbuflen = maxbuflen;

   while (newoffset + newbuflen < numamps) {
      /* Calculate the next mean */
      mean_new = median(powers + newoffset, newbuflen) / log(2.0);
      //slope = (mean_new-mean_old)/(0.5*(newbuflen+lastbuflen));
      slope = (mean_new - mean_old) / (newbuflen + lastbuflen);

      /* Correct the previous segment */
      lineoffset = 0.5 * (newbuflen + lastbuflen);
      for (ii = 0; ii < lastbuflen; ii++) {
         lineval = mean_old + slope * (lineoffset - ii);
         scaleval = 1.0 / sqrt(lineval);
         fft[fixedoffset + ii].r *= scaleval;
         fft[fixedoffset + ii].i *= scaleval;
      }

      /* Update our values */
      fixedoffset += lastbuflen;
      lastbuflen = newbuflen;
      mean_old = mean_new;
      newoffset += lastbuflen;
      newbuflen = initialbuflen * log(newoffset);
      if (newbuflen > maxbuflen)
         newbuflen = maxbuflen;
   }

   /* Scale the last (partial) chunk the same way as the last point */

   while (fixedoffset < numamps) {
      fft[fixedoffset].r *= scaleval;
      fft[fixedoffset].i *= scaleval;
      fixedoffset++;
   }

   /* Free the powers */
   free(powers);
}
Esempio n. 28
0
int main(int argc, char *argv[])
{
   FILE *fftfile;
   double flook, dt, nph, t, maxz, pwr, hipow = 0.0;
   double zlo = -30.0, zhi = 30.0, dr, dz = 2.0;
   double hir = 0.0, hiz = 0.0, newhir, newhiz;
   fcomplex **ffdotplane, *data;
   float powargr, powargi;
   int startbin, numdata, nextbin, nr, nz, numkern;
   int i, j, realpsr, kernel_half_width, numbetween = 4;
   int n, corrsize = 1024;
   char filenm[80], compare[200];
   rderivs derivs;
   fourierprops props;
   infodata idata;
   struct tms runtimes;
   double ttim, utim, stim, tott;


   tott = times(&runtimes) / (double) CLK_TCK;
   if (argc != 3) {
      printf("\nUsage:  'quicklook filename fftfreq dt'\n\n");
      printf("   'filename' = a string containing the FFT file's name.\n");
      printf("                (do not include the '.fft' suffix)\n");
      printf("    'fftfreq' = the central fourier frequency to examine.\n");
      printf("  Quicklook will search a region of the f-fdot plane\n");
      printf("  of a file containing a long, single precision FFT\n");
      printf("  using the Correlation method (i.e. Ransom and \n");
      printf("  Eikenberry, 1997, unpublished as of yet).\n");
      printf("  The search uses a spacing of 0.5 frequency bins in\n");
      printf("  the fourier frequency (r) direction, and 2 'bins' in\n");
      printf("  the fdot (z) direction.  The routine will output\n");
      printf("  statistics for the best candidate in the region.\n\n");
      printf("  The routine was written as a quick but useful hack\n");
      printf("  to show the power of the Correlation method, and the\n");
      printf("  forthcoming power of Scott Ransom's Pulsar Finder\n");
      printf("  Software.\n");
      printf("                                        2 March 2001\n\n");
      exit(0);
   }
   printf("\n\n");
   printf("  Quick-Look Pulsation Search\n");
   printf("     With database lookup.\n");
   printf("      by Scott M. Ransom\n");
   printf("         2 March, 2001\n\n");

   /*  Initialize our data: */

   sprintf(filenm, "%s.fft", argv[1]);
   readinf(&idata, argv[1]);
   flook = atof(argv[2]);
   dt = idata.dt;
   dr = 1.0 / (double) numbetween;
   fftfile = chkfopen(filenm, "r");
   nph = get_numphotons(fftfile);
   n = chkfilelen(fftfile, sizeof(float));
   t = n * dt;
   nz = (int) ((zhi - zlo) / dz) + 1;

   /* Determine our starting frequency and get the data */

   maxz = (fabs(zlo) < fabs(zhi)) ? zhi : zlo;
   kernel_half_width = z_resp_halfwidth(maxz, HIGHACC);
   numkern = 2 * numbetween * kernel_half_width;
   while (numkern > 2 * corrsize)
      corrsize *= 2;
   startbin = (int) (flook) - corrsize / (2 * numbetween);
   numdata = corrsize / numbetween;
   data = read_fcomplex_file(fftfile, startbin, numdata);

   /*  Do the f-fdot plane correlations: */

   ffdotplane = corr_rz_plane(data, numdata, numbetween, kernel_half_width,
                              zlo, zhi, nz, corrsize, LOWACC, &nextbin);
   nr = corrsize - 2 * kernel_half_width * numbetween;

   /*  Search the resulting data set: */

   for (i = 0; i < nz; i++) {
      for (j = 0; j < nr; j++) {
         pwr = POWER(ffdotplane[i][j].r, ffdotplane[i][j].i);
         if (pwr > hipow) {
            hir = j * dr + kernel_half_width;
            hiz = i * dz + zlo;
            hipow = pwr;
         }
      }
   }

   /*  Maximize the best candidate: */

   hipow = max_rz_arr(data, numdata, hir, hiz, &newhir, &newhiz, &derivs);
   newhir += startbin;
   calc_props(derivs, newhir, newhiz, 0.0, &props);

   printf("Searched %d pts ", nz * nr);
   printf("(r: %.1f to %.1f, ", (double) startbin + kernel_half_width,
          (double) startbin + kernel_half_width + dr * (nr - 1));
   printf("z: %.1f to %.1f)\n\n", zlo, zhi);

   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 time: %.3f sec (User: %.3f sec, System: %.3f sec)\n",
          ttim, utim, stim);
   printf("  Total time: %.3f sec\n\n", tott);

   printf("The best candidate is:\n");

   print_candidate(&props, dt, n, nph, 2);
   realpsr = comp_psr_to_cand(&props, &idata, compare, 1);
   printf("%s\n", compare);
   fclose(fftfile);

   /* Cleanup and exit */

   free(ffdotplane[0]);
   free(ffdotplane);
   free(data);
   exit(0);
}
/**
 * Routine to apply local filter.
 *
 * @param aInputChannel             [TUint8*] The input image channel.
 * @param aOutputChannel            [TUint8*] The output image channel after filtering.
 * @param aFilterParams             [TAlgoGenericFilterParams*] The generic parameters for filter.
 * @param aMaxPixelVal              [TUint8] The maximum pixel value.
 *
 * @return                          [TAlgoError] EErrorNone if the filtering is successful.
 */
TAlgoError ApplyLocalFilter(TUint8* aInputChannel,
                            TUint8* aOutputChannel,
                            TAlgoGenericFilterParams* aFilterParams,
                            TUint8 aMaxPixelVal)
    {

    TUint8 *inputPtr = aInputChannel + aFilterParams->iStartIndexY * aFilterParams->iImageParams.iImageWidth 
                        + aFilterParams->iStartIndexX;
	TReal64 temp;
	TUint32 satCount = 0;
    TUint32 y=0;
    TUint32 x=0;

	/* Assuming 3*3 matrix, for 5*5 following lines to be changed - TBD */
	TUint8 *outputPtr = aOutputChannel 
                        + (aFilterParams->iStartIndexY) * aFilterParams->iImageParams.iImageWidth  
                        + (aFilterParams->iStartIndexX);

	/* For applying the convolution, basic problem is about the (N/2) pixel
	 * boundary, as convolution assumes N*N-1 neighbor around it.
	 * For the purpose of testing we will not apply any filter on the first
	 * pixels
	 */

	for (y=0; y < aFilterParams->iPixelsToGrabY; y++)
	    {
		for (x=0; x < aFilterParams->iPixelsToGrabX; x++)
		    {
			temp = 0;

			if (aFilterParams->iFilterType == EFilterBrightness)
			    {
				temp = *inputPtr + aFilterParams->iParam;
			    }
			else if (aFilterParams->iFilterType == EFilterGamma)
			    {
				temp = POWER(*inputPtr, aFilterParams->iParam);
			    }
			else if (aFilterParams->iFilterType == EFilterContrast)
			    {
				temp = *inputPtr * aFilterParams->iParam;
			    }
			else if (aFilterParams->iFilterType == EFilterNegative)
			    {
				temp = aMaxPixelVal - *inputPtr;
			    }
			else 
			    {
				//ALGO_Log_0("\n Wrong type of Local filter");
				return EErrorArgument;
			    }

			if (temp > aMaxPixelVal)
			    {
				*outputPtr = aMaxPixelVal;
				satCount++;
			    }
			else if (temp < 0x0)
			    {
				*outputPtr = 0;
			    }
			else
			    {
				*outputPtr = (TUint8)temp;
			    }

			outputPtr++;
			inputPtr++;
		    }
		outputPtr += (aFilterParams->iImageParams.iImageWidth - aFilterParams->iPixelsToGrabX);		
		inputPtr += (aFilterParams->iImageParams.iImageWidth - aFilterParams->iPixelsToGrabX);	
	    }

	//ALGO_Log_1("\n Saturation Count: %d", satCount);

	return EErrorNone;
    }
Esempio n. 30
0
 virtual void compute (CSOUND* csound, MYFLT* output, void *p)
       {
           int     nn = ((OPDATA*)p)->h.insdshead->ksmps;
           uint32_t offset = ((OPDATA *) p)->h.insdshead->ksmps_offset;
           uint32_t early  = ((OPDATA *) p)->h.insdshead->ksmps_no_end;
           MYFLT   fSlow0  = POWER(FL(10.0),(FL(0.08333333333333333) * fslider0));
           MYFLT   fSlow1  = EXP(-(fConst3 * fSlow0));
           MYFLT   fSlow2  = EXP(-(fConst5 * fSlow0));
           MYFLT   fSlow3  = -fSlow2 * -fSlow1;
           MYFLT   fSlow4  = -fSlow2 - fSlow1;
           MYFLT   fSlow5  = EXP(-(fConst9 * fSlow0));
           MYFLT   fSlow6  = EXP(-(fConst11 * fSlow0));
           MYFLT   fSlow7  = -fSlow6 * -fSlow5;
           MYFLT   fSlow8  = -fSlow6 - fSlow5;
           MYFLT   fSlow9  = EXP(-(fConst15 * fSlow0));
           MYFLT   fSlow10 = EXP(-(fConst17 * fSlow0));
           MYFLT   fSlow11 = -fSlow10 * -fSlow9;
           MYFLT   fSlow12 = -fSlow10 - fSlow9;
           MYFLT   fSlow13 = EXP(-(fConst21 * fSlow0));
           MYFLT   fSlow14 = EXP(-(fConst23 * fSlow0));
           MYFLT   fSlow15 = -fSlow14 * -fSlow13;
           MYFLT   fSlow16 = (FL(0.0) - (fSlow14 + fSlow13));
           MYFLT   fSlow17 = EXP(-(fConst27 * fSlow0));
           MYFLT   fSlow18 = EXP(-(fConst29 * fSlow0));
           MYFLT   fSlow19 = -fSlow18 * -fSlow17;
           MYFLT   fSlow20 = -fSlow18 - fSlow17;
           MYFLT   fSlow21 = EXP(-(fConst33 * fSlow0));
           MYFLT   fSlow22 = EXP(-(fConst35 * fSlow0));
           MYFLT   fSlow23 = -fSlow22 * -fSlow21;
           MYFLT   fSlow24 = -fSlow22 - fSlow21;
           MYFLT   fSlow25 = EXP(-(fConst39 * fSlow0));
           MYFLT   fSlow26 = EXP(-(fConst41 * fSlow0));
           MYFLT   fSlow27 = -fSlow26 * -fSlow25;
           MYFLT   fSlow28 = -fSlow26 - fSlow25;
           MYFLT   fSlow29 = (- EXP(-(fConst1 * fSlow0)));
           MYFLT   fSlow30 = fslider1;
           MYFLT*  output0 = output;
           if (UNLIKELY(offset)) memset(output0, '\0', offset*sizeof(MYFLT));
           if (UNLIKELY(early)) {
             nn -= early;
             memset(&output0[nn], '\0', early*sizeof(MYFLT));
           }
           for (int i=offset; i<nn; i++) {
             iRec8[0] = (csound->GetRandSeed(csound, 1) + (1103515245 * iRec8[1]));
             fRec7[0] = -((fConst8 * fRec7[2]) + (fConst7 * fRec7[1])) +
                         (iRec8[0] * dv2_31);
             fRec6[0] = (0 - (((fConst14 * fRec6[2]) + (fConst13 * fRec6[1]))
                              - ((fSlow4 * fRec7[1]) +
                                 (fRec7[0] + (fSlow3 * fRec7[2])))));
             fRec5[0] = (0 - (((fConst20 * fRec5[2]) + (fConst19 * fRec5[1]))
                              - ((fSlow8 * fRec6[1]) + (fRec6[0] +
                                                        (fSlow7 * fRec6[2])))));
             fRec4[0] = (0 - (((fConst26 * fRec4[2]) + (fConst25 * fRec4[1]))
                              - ((fSlow12 * fRec5[1]) +
                                 (fRec5[0] + (fSlow11 * fRec5[2])))));
             fRec3[0] = (0 - (((fConst32 * fRec3[2]) + (fConst31 * fRec3[1]))
                              - ((fSlow16 * fRec4[1]) +
                                 (fRec4[0] + (fSlow15 * fRec4[2])))));
             fRec2[0] = (0 - (((fConst38 * fRec2[2]) + (fConst37 * fRec2[1]))
                              - ((fSlow20 * fRec3[1]) +
                                 (fRec3[0] + (fSlow19 * fRec3[2])))));
             fRec1[0] = (0 - (((fConst44 * fRec1[2]) + (fConst43 * fRec1[1]))
                              - ((fSlow24 * fRec2[1]) +
                                 (fRec2[0] + (fSlow23 * fRec2[2])))));
             fRec0[0] = (((fSlow28 * fRec1[1]) + (fRec1[0] + (fSlow27 * fRec1[2])))
                         - (fConst2 * fRec0[1]));
             output0[i] = (MYFLT)(fSlow30 * (fRec0[0] + (fSlow29 * fRec0[1])));
             // post processing
             fRec0[1] = fRec0[0];
             fRec1[2] = fRec1[1]; fRec1[1] = fRec1[0];
             fRec2[2] = fRec2[1]; fRec2[1] = fRec2[0];
             fRec3[2] = fRec3[1]; fRec3[1] = fRec3[0];
             fRec4[2] = fRec4[1]; fRec4[1] = fRec4[0];
             fRec5[2] = fRec5[1]; fRec5[1] = fRec5[0];
             fRec6[2] = fRec6[1]; fRec6[1] = fRec6[0];
             fRec7[2] = fRec7[1]; fRec7[1] = fRec7[0];
             iRec8[1] = iRec8[0];
           }
       }