int XLALSQTPNAllocateCoherentGW(CoherentGW *wave, UINT4 length) {

	if (!wave) {
		XLAL_ERROR(XLAL_EFAULT);
	}
	if (length <= 0) {
		XLAL_ERROR(XLAL_EBADLEN);
	}
	if (wave->a || wave->f || wave->phi || wave->shift) {
		XLAL_ERROR(XLAL_EFAULT);
	}
	wave->a = (REAL4TimeVectorSeries *)LALMalloc(sizeof(REAL4TimeVectorSeries));
	wave->f = (REAL4TimeSeries *)LALMalloc(sizeof(REAL4TimeSeries));
	wave->phi = (REAL8TimeSeries *)LALMalloc(sizeof(REAL8TimeSeries));
	wave->shift = (REAL4TimeSeries *)LALMalloc(sizeof(REAL4TimeSeries));
	if (!(wave->a && wave->f && wave->phi && wave->shift)) {
		XLALSQTPNDestroyCoherentGW(wave);
		XLAL_ERROR(XLAL_ENOMEM);
	}
	xlalErrno = 0;
	wave->a->data = XLALCreateREAL4VectorSequence(length, 2);
	wave->f->data = XLALCreateREAL4Vector(length);
	wave->phi->data = XLALCreateREAL8Vector(length);
	wave->shift->data = XLALCreateREAL4Vector(length);
	if (!(wave->a->data && wave->f->data && wave->phi->data && wave->shift->data)) {
		XLALSQTPNDestroyCoherentGW(wave);
		XLAL_ERROR(XLAL_ENOMEM);
	}
	return XLAL_SUCCESS;
}
STYPE * XFUNC ( UINT4 length, UINT4 veclen )
{
  STYPE *seq;

  if ( ! length || ! veclen )
    XLAL_ERROR_NULL( XLAL_EBADLEN );

  seq = LALMalloc( sizeof( *seq ) );
  if ( ! seq )
    XLAL_ERROR_NULL( XLAL_ENOMEM );

  seq->length = length;
  seq->vectorLength = veclen;

  if ( ! length || ! veclen )
    seq->data = NULL;
  else
  {
    seq->data = LALMalloc( length * veclen * sizeof( *seq->data ) );
    if ( ! seq )
    {
      LALFree( seq );
      XLAL_ERROR_NULL( XLAL_ENOMEM );
    }
  }

  return seq;
}
Ejemplo n.º 3
0
/* test to make sure padding does what it's supposed to do */
static int testPadding( void )
{
  int keep = lalDebugLevel;

  XLALClobberDebugLevel(lalDebugLevel | LALMEMDBGBIT | LALMEMPADBIT);
  XLALClobberDebugLevel(lalDebugLevel & ~LALMEMTRKBIT);

  /* try to free NULL pointer */
  /* changed behaviour: LALFree is a no-op when passed NULL */
  // trial( LALFree( NULL ), SIGSEGV, "error: tried to free NULL pointer" );

  /* double free */
  /* actually, this cannot be done robustly -- system can change values
   * in unallocated space at will */
  //trial( p = LALMalloc( 2 * sizeof( *p ) ), 0, "" );
  //trial( LALFree( p ), 0, "" );
  //trial( LALFree( p ), SIGSEGV, "error: tried to free a freed pointer" );
  //trial( LALCheckMemoryLeaks(), 0, "" );

  /* wrong magic */
  trial( p = LALMalloc( 2 * sizeof( *p ) ), 0, "" );
  p[-1] = 4;
  trial( LALFree( p ), SIGSEGV, "error: wrong magic" );
  p[-1] = 0xABadCafe;
  trial( LALFree( p ), 0, "" );
  trial( LALCheckMemoryLeaks(), 0, "" );

  /* corrupt size */
  trial( p = LALMalloc( 4 * sizeof( *p ) ), 0, "");
  n = p[-2];
  p[-2] = -2;
  trial( LALFree( p ), SIGSEGV, "error: corrupt size descriptor" );
  p[-2] = n;
  trial( LALFree( p ), 0, "" );
  trial( LALCheckMemoryLeaks(), 0, "" );

  /* overwritten array bounds */
  trial( p = LALMalloc( 8 * sizeof( *p ) ), 0, "" );
  n = p[8];
  p[8] = 0;
  trial( LALFree( p ), SIGSEGV, "error: array bounds overwritten" );
  p[8] = n;
  trial( LALFree( p ), 0, "" );
  trial( LALCheckMemoryLeaks(), 0, "" );

  /* free too much memory */
  q = malloc( 4 * sizeof( *p ) );
  trial( p = LALMalloc( sizeof( *p ) ), 0, "" );
  memcpy( q, p - 2, 4 * sizeof( *p ) );
  trial( LALFree( p ), 0, "" );
  trial( LALFree( q + 2 ), SIGSEGV, "error: lalMallocTotal too small" );
  free( q );
  trial( LALCheckMemoryLeaks(), 0, "" );

  XLALClobberDebugLevel(keep);
  return 0;
}
Ejemplo n.º 4
0
/* sets up a FstatCheckpointFile from parameters */
int fstat_cpt_file_create (FstatCheckpointFile **cptf,
			   CHAR  *filename,
			   UINT4 bufsize,
			   UINT4 maxsize,
			   toplist_t*list) {

  /* input sanity checks */
  if ( (cptf == NULL) ||
       (*cptf != NULL) ||
       (list == NULL) ||
       (filename == NULL) ||
       (strlen (filename) == 0) ) {
    LogPrintf (LOG_CRITICAL, "ERROR: error in input parameters (fstat_cpt_file_create)\n");
    return(-1);
  }

  /* allocation */
  *cptf = LALMalloc(sizeof(FstatCheckpointFile));
  if (!(*cptf)) {
    LogPrintf (LOG_CRITICAL, "ERROR: out of memeory (fstat_cpt_file_create)\n");
    return(-1);
  }

  (*cptf)->filename = LALMalloc(strlen(filename)+1);
  if (!((*cptf)->filename)) {
    LogPrintf (LOG_CRITICAL, "ERROR: out of memeory (fstat_cpt_file_create)\n");
    LALFree(*cptf);
    *cptf = NULL;
    return(-1);
  }

  if (bufsize > 0) {
    (*cptf)->buffer = LALMalloc(bufsize);
    if (!((*cptf)->buffer)) {
      LogPrintf (LOG_CRITICAL, "ERROR: out of memeory (fstat_cpt_file_create)\n");
      LALFree(*cptf);
      LALFree((*cptf)->filename);
      *cptf = NULL;
      return(-1);
    }
  }

  /* initialization */
  strncpy((*cptf)->filename,filename,strlen(filename)+1);

  (*cptf)->bytes = 0;
  (*cptf)->bufsize = bufsize;
  (*cptf)->maxsize = maxsize;
  (*cptf)->checksum = 0;
  (*cptf)->fp = NULL;
  (*cptf)->list = list;
  return(0);
}
Ejemplo n.º 5
0
ATYPE * XFUNC ( UINT4Vector *dimLength )
{
  ATYPE *arr;
  UINT4 size = 1;
  UINT4 ndim;
  UINT4 dim;

  if ( ! dimLength )
    XLAL_ERROR_NULL( XLAL_EFAULT );
  if ( ! dimLength->length )
    XLAL_ERROR_NULL( XLAL_EBADLEN );
  if ( ! dimLength->data )
    XLAL_ERROR_NULL( XLAL_EINVAL );

  ndim = dimLength->length;
  for ( dim = 0; dim < ndim; ++dim )
    size *= dimLength->data[dim];

  if ( ! size )
    XLAL_ERROR_NULL( XLAL_EBADLEN );

  /* create array */
  arr = LALMalloc( sizeof( *arr ) );
  if ( ! arr )
    XLAL_ERROR_NULL( XLAL_ENOMEM );

  /* create array dimensions */
  arr->dimLength = XLALCreateUINT4Vector( ndim );
  if ( ! arr->dimLength )
  {
    LALFree( arr );
    XLAL_ERROR_NULL( XLAL_EFUNC );
  }

  /* copy dimension lengths */
  memcpy( arr->dimLength->data, dimLength->data,
      ndim * sizeof( *arr->dimLength->data ) );

  /* allocate data storage */
  arr->data = LALMalloc( size * sizeof( *arr->data ) );
  if ( ! arr->data )
  {
    XLALDestroyUINT4Vector( arr->dimLength );
    LALFree( arr );
    XLAL_ERROR_NULL( XLAL_ENOMEM );
  }

  return arr;
}
Ejemplo n.º 6
0
int AllocateMem(struct CommandLineArgsTag CLA)
{ 
  int ndeltaf,k;
  INT4  res;                    /*resolution of the argument of the trig functions: 2pi/res.*/

  SFTData=(FFT **)LALMalloc(CLA.number*sizeof(FFT *));

  ndeltaf=ifmax-ifmin+1;

  for (k=0;k<CLA.number;k++)
    {
      SFTData[k]=(FFT *)LALMalloc(sizeof(FFT));
      SFTData[k]->fft=(COMPLEX8FrequencySeries *)LALMalloc(sizeof(COMPLEX8FrequencySeries));
      SFTData[k]->fft->data=(COMPLEX8Vector *)LALMalloc(sizeof(COMPLEX8Vector));
      SFTData[k]->fft->data->data=(COMPLEX8 *)LALMalloc(ndeltaf*sizeof(COMPLEX8));
    }

  /* res=10*(params->mCohSFT); */
  /* This size LUT gives errors ~ 10^-7 with a three-term Taylor series */
   res=64;
   sinVal=(REAL8 *)LALMalloc((res+1)*sizeof(REAL8));
   cosVal=(REAL8 *)LALMalloc((res+1)*sizeof(REAL8)); 
   for (k=0; k<=res; k++){
     sinVal[k]=sin((LAL_TWOPI*k)/res);
     cosVal[k]=cos((LAL_TWOPI*k)/res);
   }

  return 0;

}
Ejemplo n.º 7
0
/**
 * Turn pulsar doppler-params into a single string that can be used for filenames
 * The format is
 * tRefNNNNNN_RAXXXXX_DECXXXXXX_FreqXXXXX[_f1dotXXXXX][_f2dotXXXXx][_f3dotXXXXX]
 */
CHAR*
XLALPulsarDopplerParams2String ( const PulsarDopplerParams *par )
{
#define MAXLEN 1024
  CHAR buf[MAXLEN];
  CHAR *ret = NULL;
  int len;
  UINT4 i;

  if ( !par )
    {
      LogPrintf(LOG_CRITICAL, "%s: NULL params input.\n", __func__ );
      XLAL_ERROR_NULL( XLAL_EDOM);
    }

  len = snprintf ( buf, MAXLEN, "tRef%09d_RA%.9g_DEC%.9g_Freq%.15g",
		      par->refTime.gpsSeconds,
		      par->Alpha,
		      par->Delta,
		      par->fkdot[0] );
  if ( len >= MAXLEN )
    {
      LogPrintf(LOG_CRITICAL, "%s: filename-size (%d) exceeded maximal length (%d): '%s'!\n", __func__, len, MAXLEN, buf );
      XLAL_ERROR_NULL( XLAL_EDOM);
    }

  for ( i = 1; i < PULSAR_MAX_SPINS; i++)
    {
      if ( par->fkdot[i] )
	{
	  CHAR buf1[MAXLEN];
	  len = snprintf ( buf1, MAXLEN, "%s_f%ddot%.7g", buf, i, par->fkdot[i] );
	  if ( len >= MAXLEN )
	    {
	      LogPrintf(LOG_CRITICAL, "%s: filename-size (%d) exceeded maximal length (%d): '%s'!\n", __func__, len, MAXLEN, buf1 );
	      XLAL_ERROR_NULL( XLAL_EDOM);
	    }
	  strcpy ( buf, buf1 );
	}
    }

  if ( par->asini > 0 )
    {
      LogPrintf(LOG_NORMAL, "%s: orbital params not supported in Doppler-filenames yet\n", __func__ );
    }

  len = strlen(buf) + 1;
  if ( (ret = LALMalloc ( len )) == NULL )
    {
      LogPrintf(LOG_CRITICAL, "%s: failed to LALMalloc(%d)!\n", __func__, len );
      XLAL_ERROR_NULL( XLAL_ENOMEM);
    }

  strcpy ( ret, buf );

  return ret;
} /* PulsarDopplerParams2String() */
int FUNC(VECTORTYPE *vector, FILTERTYPE *filter)
{
  INT4 j;            /* Index for filter coeficients. */
  INT4 length;       /* Length of vector. */
  DATATYPE *data;       /* Vector data. */
  DBLDATATYPE w, datum;    /* Current auxiliary and output values. */
  INT4 directOrder;  /* Number of direct filter coefficients. */
  INT4 recursOrder;  /* Number of recursive filter coefficients. */
  INT4 numHist;      /* The number of auxiliary data kept. */
  REAL8 *directCoef; /* Direct filter coefficients. */
  REAL8 *recursCoef; /* Recursive filter coefficients. */
  DBLDATATYPE *temp=NULL;  /* Temporary storage for auxiliary sequence. */

  /* Make sure all the structures have been initialized. */
  if ( ! vector || ! filter )
    XLAL_ERROR( XLAL_EFAULT );
  if ( ! vector->data )
    XLAL_ERROR( XLAL_EINVAL );
  if ( ! filter->directCoef || ! filter->recursCoef || ! filter->history
      || !  filter->directCoef->data || ! filter->recursCoef->data
      || !  filter->history->data )
    XLAL_ERROR( XLAL_EINVAL );

  length=vector->length;
  data=vector->data+length-1;
  directOrder=filter->directCoef->length;
  recursOrder=filter->recursCoef->length;
  directCoef=filter->directCoef->data;
  recursCoef=filter->recursCoef->data;
  numHist=filter->history->length+1;
  temp = LALMalloc( numHist*sizeof(*temp) );
  if ( ! temp )
    XLAL_ERROR( XLAL_ENOMEM );
  memset(temp,0,(numHist-1)*sizeof(*temp));

  /* Run through the vector. */
  while(length--){

    /* Compute the auxiliary variable. */
    for(j=numHist-1;j>=recursOrder;j--)
      temp[j]=temp[j-1];
    w=*data;
    for(;j;j--)
      w+=recursCoef[j]*(temp[j]=temp[j-1]);

    /* Compute filter output. */
    datum=*directCoef*(*temp=w);
    for(j=1;j<directOrder;j++)
      datum+=directCoef[j]*temp[j];
    *(data--)=datum;
  }
  LALFree(temp);

  /* Normal exit */
  return 0;
}
Ejemplo n.º 9
0
/* test to make sure alloc list does what it's supposed to do */
static int testAllocList( void )
{
  int keep = lalDebugLevel;

  s = malloc( sizeof( *s ) );

  XLALClobberDebugLevel(lalDebugLevel | LALMEMDBGBIT | LALMEMTRKBIT);
  XLALClobberDebugLevel(lalDebugLevel & ~LALMEMPADBIT);

  /* empty allocation list */
  trial( LALCheckMemoryLeaks(), 0, "" );
  trial( LALFree( s ), SIGSEGV, "not found" );

  /* can't find allocation in PopAlloc */
  trial( p = LALMalloc( 2 * sizeof( *p ) ), 0, "" );
  trial( q = LALMalloc( 4 * sizeof( *q ) ), 0, "" );
  trial( r = LALMalloc( 8 * sizeof( *r ) ), 0, "" );
  trial( LALFree( s ), SIGSEGV, "not found" );
  trial( LALFree( p ), 0, "" );
  trial( LALFree( r ), 0, "" );
  trial( LALCheckMemoryLeaks(), SIGSEGV, "memory leak" );
  trial( LALFree( q ), 0, "" );
  trial( LALCheckMemoryLeaks(), 0, "" );

  /* can't find allocation in ModAlloc */
  /* For some reason this next test fails on Snow Leopard... */
  /* trial( s = LALRealloc( s, 1024 ), SIGSEGV, "not found" ); */
  trial( p = LALRealloc( NULL, 2 * sizeof( *p ) ), 0, "" );
  /* trial( s = LALRealloc( s, 1024 ), SIGSEGV, "not found" ); */
  trial( LALFree( p ), 0, "" );
  trial( LALCheckMemoryLeaks(), 0, "" );

  free( s );
  XLALClobberDebugLevel(keep);
  return 0;
}
Ejemplo n.º 10
0
int SetupBaryInput()
{
FILE *fpE;
FILE *fpS;

              /*allocate memory for the ephemeris*/
         edat=(EphemerisData *)LALMalloc(sizeof(EphemerisData));

         (*edat).ephiles.earthEphemeris="/home/re/data/LAL_tmp/earth00-04.dat";
         (*edat).ephiles.sunEphemeris="/home/re/data/LAL_tmp/sun00-04.dat";
         	 
	 /*Check that the ephemeris files exist*/
	 fpE=fopen((*edat).ephiles.earthEphemeris,"r");
         fpS=fopen((*edat).ephiles.sunEphemeris,"r");

	 if ((fpE==NULL) || (fpS==NULL))
	   {	 
	      fprintf(stdout,"impossible to find ephemeris files ");
           } else 
	 {
		 fprintf(stdout,"ephemeris file %s %s\n found!\n", (*edat).ephiles.sunEphemeris, (*edat).ephiles.earthEphemeris);
         }

	 fscanf(fpS,"%d \t %le \t %d\n",&x, &y, &z);
	 
	 /*fprintf(stdout,"x y z are %d \t %12.12le \t %d\n", x,y,z);*/

         /*Read in ephemeris files*/
        LALInitBarycenter(&status, edat);

#ifdef DEBUG_STACKSLIDE_FNC
	fprintf(stdout,"first entry %f\n",(*edat).ephemE[0].gps);
#endif
	
	printf("end of function SetupBaryInput\n");

 return 3;
  /* convert the observation start time at the detector into start time at the SSB */

	
}
Ejemplo n.º 11
0
/**
 * Returns input string with line-breaks '\n' removed (replaced by space)
 * The original string is unmodified. The returned string is allocated here.
 */
char *
XLALClearLinebreaks ( const char *str )
{
  char *ret, *tmp;

  if ( !str )
    return NULL;

  if ( (ret = LALMalloc( strlen ( str ) + 1) ) == NULL )
    return NULL;
  strcpy ( ret, str );

  tmp = ret;
  while ( (tmp = strchr ( tmp, '\n' ) ) )
    {
      *tmp = ' ';
      tmp ++;
    }

  return ret;

} /* XLALClearLinebreaks() */
Ejemplo n.º 12
0
/** \brief Returns structure containing TaylorF2 phasing coefficients for given
 *  physical parameters.
 */
int XLALSimInspiralTaylorF2AlignedPhasing(
        PNPhasingSeries **pn,   /**< phasing coefficients (output) */
        const REAL8 m1,         /**< mass of body 1 */
        const REAL8 m2,		/**< mass of body 2 */
        const REAL8 chi1,	/**< aligned spin parameter of body 1 */
        const REAL8 chi2,	/**< aligned spin parameter of body 2 */
        LALDict *p              /**< LAL dictionary containing accessory parameters */
	)
{
    PNPhasingSeries *pfa;

    if (!pn) XLAL_ERROR(XLAL_EFAULT);
    if (*pn) XLAL_ERROR(XLAL_EFAULT);


    pfa = (PNPhasingSeries *) LALMalloc(sizeof(PNPhasingSeries));

    XLALSimInspiralPNPhasing_F2(pfa, m1, m2, chi1, chi2, chi1*chi1, chi2*chi2, chi1*chi2, p);

    *pn = pfa;

    return XLAL_SUCCESS;
}
Ejemplo n.º 13
0
/* vvvvvvvvvvvvvvvvvvvvvvvvvvvvvv------------------------------------ */
int main(int argc, char *argv[]){

  static LALStatus       status;
  static VelocityPar     velPar;
  static REAL8           vel[3];
  static REAL8           pos[3];
  static EphemerisData  *edat = NULL;
  LIGOTimeGPS   tGPS;
  INT4   arg;                         /* Argument counter */
  REAL8  vTol=0.01 ;
  /* INT4   c, errflg=0;*/
  /*  optarg = NULL; */
  /* ------------------------------------------------------- */


  /* default values */
  velPar.detector = lalCachedDetectors[LALDetectorIndexGEO600DIFF];
  velPar.startTime.gpsSeconds = T0SEC;
  velPar.startTime.gpsNanoSeconds = T0NSEC;
  velPar.tBase = TBASE;
  velPar.vTol = ACCURACY;

 /********************************************************/
  /* Parse argument list.  i stores the current position. */
  /********************************************************/
  arg = 1;
  while ( arg < argc ) {
    /* Parse debuglevel option. */
    if ( !strcmp( argv[arg], "-d" ) ) {
      if ( argc > arg + 1 ) {
        arg++;
      } else {
        ERROR( TESTVELOCITYC_EARG, TESTVELOCITYC_MSGEARG, 0 );
        XLALPrintError( USAGE, *argv );
        return TESTVELOCITYC_EARG;
      }
    }
    /* Parse accuracy option. */
    else if ( !strcmp( argv[arg], "-a" ) ) {
      if ( argc > arg + 1 ) {
        arg++;
	vTol= atof( argv[arg++]);
        velPar.vTol= vTol;
      } else {
        ERROR( TESTVELOCITYC_EARG, TESTVELOCITYC_MSGEARG, 0 );
        XLALPrintError( USAGE, *argv );
        return TESTVELOCITYC_EARG;
      }
    }
    /* Unrecognized option. */
    else {
      ERROR( TESTVELOCITYC_EARG, TESTVELOCITYC_MSGEARG, 0 );
      XLALPrintError( USAGE, *argv );
      return TESTVELOCITYC_EARG;
    }
  } /* End of argument parsing loop. */
  /******************************************************************/

  /* read ephemeris data */
  /* ephemeris info */
  edat = (EphemerisData *)LALMalloc(sizeof(EphemerisData));
  (*edat).ephiles.earthEphemeris = EARTHDATA;
  (*edat).ephiles.sunEphemeris = SUNDATA;

  /* read in ephemeris data */
  SUB( LALInitBarycenter( &status, edat), &status);

  /* fill in ephemeris data in velPar */
  velPar.edat = edat;


  tGPS.gpsSeconds = T0SEC;
  tGPS.gpsNanoSeconds = T0NSEC;


  SUB( LALDetectorVel( &status,  vel,  &tGPS, velPar.detector, velPar.edat), &status);

  printf("Detector velocity at %d = %g, %g, %g \n", T0SEC, vel[0],vel[1],vel[2]);

  SUB( LALDetectorPos( &status,  vel,  &tGPS, velPar.detector, velPar.edat), &status);

  printf("Detector position at %d = %g, %g, %g \n", T0SEC, vel[0],vel[1],vel[2]);

  SUB( LALAvgDetectorVel ( &status, vel, &velPar), &status );

  printf("Avg. detector velocity in a interval of %g from %d = %g, %g, %g \n", TBASE, T0SEC, vel[0],vel[1],vel[2]);

  SUB( LALAvgDetectorPos ( &status, pos, &velPar), &status );

  printf("Avg. detector position in a interval of %g from %d = %g, %g, %g \n", TBASE, T0SEC, pos[0],pos[1],pos[2]);

  LALFree(edat->ephemE);
  LALFree(edat->ephemS);
  LALFree(edat);
  LALCheckMemoryLeaks();

  //INFO(TESTVELOCITYC_MSGENORM);
  return TESTVELOCITYC_ENORM;
}
Ejemplo n.º 14
0
int
main(int argc, char *argv[])
{
  FILE *fp = NULL;
  BarycenterInput XLAL_INIT_DECL(baryinput);
  INT4 leap0,leap;
  LIGOTimeGPS epoch;
  LIGOTimeGPS TstartSSB, TendSSB, TendGPS;
  INT4 n;
  LIGOTimeGPS *TSSB = NULL;
  MJDTime TstartUTCMJD;
  LIGOTimeGPS TDET;
  REAL8 temp;
  INT4 i;
  MJDTime tempTOA;
  REAL8 dt;
  LIGOTimeGPS TstartGPS;
  MJDTime *TOA = NULL;
  CHAR tempstr[18];
  CHAR *tempstr2;
  CHAR TstartMJDstr[20],TfinishMJDstr[20],TOAstr[22];
  PulsarSignalParams pulsarparams;
  CHAR parfile[256];
  CHAR timfile[256];
  CHAR detcode[16];
  REAL8 TstartUTCMJDtest;
  REAL8 diff;
  MJDTime MJDdiff, MJDtest;

  MJDTime TrefTDBMJD;
  LIGOTimeGPS TrefSSB_TDB_GPS;

  // ----------------------------------------------------------------------
  UserVariables_t XLAL_INIT_DECL(uvar);
  XLAL_CHECK ( initUserVars (argc, argv, &uvar) == XLAL_SUCCESS, XLAL_EFUNC );

  unsigned int seed = uvar.randSeed;
  if ( uvar.randSeed == 0 ) {
    seed = clock();
  }
  srand ( seed );

  // ----- sky position: random or user-specified ----------
  REAL8 alpha, delta;
  CHAR *RAJ = NULL, *DECJ = NULL;

  BOOLEAN have_RAJ  = XLALUserVarWasSet ( &uvar.RAJ );
  BOOLEAN have_DECJ = XLALUserVarWasSet ( &uvar.DECJ );
  if ( have_RAJ )
    {
      XLAL_CHECK ( XLALTranslateHMStoRAD ( &alpha, uvar.RAJ ) == XLAL_SUCCESS, XLAL_EFUNC );
      RAJ = XLALStringDuplicate ( uvar.RAJ );
    }
  else
    { // pick randomly
      alpha = LAL_TWOPI * (1.0 * rand() / ( RAND_MAX + 1.0 ) );  // alpha uniform in [0, 2pi)
      XLAL_CHECK ( (RAJ = XLALTranslateRADtoHMS ( alpha )) != NULL, XLAL_EFUNC );
    }
  if ( have_DECJ )
    {
      XLAL_CHECK ( XLALTranslateDMStoRAD ( &delta, uvar.DECJ ) == XLAL_SUCCESS, XLAL_EFUNC );
      DECJ = XLALStringDuplicate ( uvar.DECJ );
    }
  else
    { // pick randomly
      delta = LAL_PI_2 - acos ( 1 - 2.0 * rand()/RAND_MAX );	// sin(delta) uniform in [-1,1]
      XLAL_CHECK ( (DECJ = XLALTranslateRADtoDMS ( delta )) != NULL, XLAL_EFUNC );
    }

  /* define start time in an MJD structure */
  REAL8toMJD ( &TstartUTCMJD, uvar.TstartUTCMJD );
  XLALPrintInfo ( "TstartUTCMJD=%f converted to MJD days = %d fracdays = %6.12f\n", uvar.TstartUTCMJD, TstartUTCMJD.days, TstartUTCMJD.fracdays );

  /* convert back to test conversions */
  TstartUTCMJDtest = MJDtoREAL8 (TstartUTCMJD);
  diff = uvar.TstartUTCMJD - TstartUTCMJDtest;
  if ( fabs(diff) > 1e-9) {
    fprintf(stderr,"ERROR : Time conversion gives discrepancy of %e sec. Exiting.\n",diff);
    return(-1);
  }
  XLALPrintInfo ( "MJD conversion gives discrepancies of %e sec\n", diff);

  /* use start time to define an epoch for the leap seconds */
  /* Note that epochs are defined in TDB !!! but here we only need to be rough to get a leap second value */
  TDBMJDtoGPS(&epoch,TstartUTCMJD);
  XLALPrintInfo ( "leap second epoch = %d %d\n",epoch.gpsSeconds,epoch.gpsNanoSeconds);

  /* deal with ephemeris files and compute leap seconds */
  EphemerisData *edat;
  XLAL_CHECK ( (edat = XLALInitBarycenter( uvar.ephemEarth, uvar.ephemSun )) != NULL, XLAL_EFUNC );

  leap0 = XLALGPSLeapSeconds (epoch.gpsSeconds);
  XLALPrintInfo ( "leap seconds = %d\n",leap0);

  /* select detector location */
  if (strcmp(uvar.Observatory,"GBT")==0) {
    baryinput.site.location[0] = GBT_LOCATION_X;
    baryinput.site.location[1] = GBT_LOCATION_Y;
    baryinput.site.location[2] = GBT_LOCATION_Z;
    sprintf(detcode,"gbt");
  }
  else if (strcmp(uvar.Observatory,"NARRABRI")==0) {
    baryinput.site.location[0] = NARRABRI_LOCATION_X;
    baryinput.site.location[1] = NARRABRI_LOCATION_Y;
    baryinput.site.location[2] = NARRABRI_LOCATION_Z;
    sprintf(detcode,"atca");
  }
   else if (strcmp(uvar.Observatory,"ARECIBO")==0) {
    baryinput.site.location[0] = ARECIBO_LOCATION_X;
    baryinput.site.location[1] = ARECIBO_LOCATION_Y;
    baryinput.site.location[2] = ARECIBO_LOCATION_Z;
    sprintf(detcode,"ao");
  }
   else if (strcmp(uvar.Observatory,"NANSHAN")==0) {
    baryinput.site.location[0] = NANSHAN_LOCATION_X;
    baryinput.site.location[1] = NANSHAN_LOCATION_Y;
    baryinput.site.location[2] = NANSHAN_LOCATION_Z;
    sprintf(detcode,"nanshan");
  }
   else if (strcmp(uvar.Observatory,"DSS_43")==0) {
    baryinput.site.location[0] = DSS_43_LOCATION_X;
    baryinput.site.location[1] = DSS_43_LOCATION_Y;
    baryinput.site.location[2] = DSS_43_LOCATION_Z;
    sprintf(detcode,"tid43");
  }
  else if (strcmp(uvar.Observatory,"PARKES")==0) {
    baryinput.site.location[0] = PARKES_LOCATION_X;
    baryinput.site.location[1] = PARKES_LOCATION_Y;
    baryinput.site.location[2] = PARKES_LOCATION_Z;
    sprintf(detcode,"pks");
  }
   else if (strcmp(uvar.Observatory,"JODRELL")==0) {
    baryinput.site.location[0] = JODRELL_LOCATION_X;
    baryinput.site.location[1] = JODRELL_LOCATION_Y;
    baryinput.site.location[2] = JODRELL_LOCATION_Z;
    sprintf(detcode,"jb");
  }
   else if (strcmp(uvar.Observatory,"VLA")==0) {
    baryinput.site.location[0] = VLA_LOCATION_X;
    baryinput.site.location[1] = VLA_LOCATION_Y;
    baryinput.site.location[2] = VLA_LOCATION_Z;
    sprintf(detcode,"vla");
  }
   else if (strcmp(uvar.Observatory,"NANCAY")==0) {
    baryinput.site.location[0] = NANCAY_LOCATION_X;
    baryinput.site.location[1] = NANCAY_LOCATION_Y;
    baryinput.site.location[2] = NANCAY_LOCATION_Z;
    sprintf(detcode,"ncy");
  }
  else if (strcmp(uvar.Observatory,"EFFELSBERG")==0) {
    baryinput.site.location[0] = EFFELSBERG_LOCATION_X;
    baryinput.site.location[1] = EFFELSBERG_LOCATION_Y;
    baryinput.site.location[2] = EFFELSBERG_LOCATION_Z;
    sprintf(detcode,"eff");
  }
  else if (strcmp(uvar.Observatory,"JODRELLM4")==0) {
    baryinput.site.location[0] = JODRELLM4_LOCATION_X;
    baryinput.site.location[1] = JODRELLM4_LOCATION_Y;
    baryinput.site.location[2] = JODRELLM4_LOCATION_Z;
    sprintf(detcode,"jbm4");
  }
  else if (strcmp(uvar.Observatory,"GB300")==0) {
    baryinput.site.location[0] = GB300_LOCATION_X;
    baryinput.site.location[1] = GB300_LOCATION_Y;
    baryinput.site.location[2] = GB300_LOCATION_Z;
    sprintf(detcode,"gb300");
  }
  else if (strcmp(uvar.Observatory,"GB140")==0) {
    baryinput.site.location[0] = GB140_LOCATION_X;
    baryinput.site.location[1] = GB140_LOCATION_Y;
    baryinput.site.location[2] = GB140_LOCATION_Z;
    sprintf(detcode,"gb140");
  }
  else if (strcmp(uvar.Observatory,"GB853")==0) {
    baryinput.site.location[0] = GB853_LOCATION_X;
    baryinput.site.location[1] = GB853_LOCATION_Y;
    baryinput.site.location[2] = GB853_LOCATION_Z;
    sprintf(detcode,"gb853");
  }
  else if (strcmp(uvar.Observatory,"LA_PALMA")==0) {
    baryinput.site.location[0] = LA_PALMA_LOCATION_X;
    baryinput.site.location[1] = LA_PALMA_LOCATION_Y;
    baryinput.site.location[2] = LA_PALMA_LOCATION_Z;
    sprintf(detcode,"lap");
  }
  else if (strcmp(uvar.Observatory,"Hobart")==0) {
    baryinput.site.location[0] = Hobart_LOCATION_X;
    baryinput.site.location[1] = Hobart_LOCATION_Y;
    baryinput.site.location[2] = Hobart_LOCATION_Z;
    sprintf(detcode,"hob");
  }
  else if (strcmp(uvar.Observatory,"Hartebeesthoek")==0) {
    baryinput.site.location[0] = Hartebeesthoek_LOCATION_X;
    baryinput.site.location[1] = Hartebeesthoek_LOCATION_Y;
    baryinput.site.location[2] = Hartebeesthoek_LOCATION_Z;
    sprintf(detcode,"hart");
  }
  else if (strcmp(uvar.Observatory,"WSRT")==0) {
    baryinput.site.location[0] = WSRT_LOCATION_X;
    baryinput.site.location[1] = WSRT_LOCATION_Y;
    baryinput.site.location[2] = WSRT_LOCATION_Z;
    sprintf(detcode,"wsrt");
  }
  else if (strcmp(uvar.Observatory,"COE")==0) {
    baryinput.site.location[0] = COE_LOCATION_X;
    baryinput.site.location[1] = COE_LOCATION_Y;
    baryinput.site.location[2] = COE_LOCATION_Z;
    sprintf(detcode,"coe");
  }
  else if (strcmp(uvar.Observatory,"SSB")!=0) {
    fprintf(stderr,"ERROR. Unknown Observatory %s. Exiting.\n",uvar.Observatory);
    return(-1);
  }
  XLALPrintInfo ( "selected observatory %s - observatoryt code = %s\n",uvar.Observatory,detcode);
  XLALPrintInfo ( "baryinput location = %6.12f %6.12f %6.12f\n",baryinput.site.location[0],baryinput.site.location[1],baryinput.site.location[2]);

  /* convert start time to UTC GPS */
  UTCMJDtoGPS(&TstartGPS, TstartUTCMJD, leap0);
  XLALPrintInfo ( "TstartGPS = %d %d\n",TstartGPS.gpsSeconds,TstartGPS.gpsNanoSeconds);

  /* convert back to test conversion */
  UTCGPStoMJD(&MJDtest,&TstartGPS,leap0);
  deltaMJD ( &MJDdiff, &MJDtest, &TstartUTCMJD );
  diff = (MJDdiff.days+MJDdiff.fracdays)*86400;
  if ( fabs(diff)  > 1e-9) {
    fprintf(stderr,"ERROR : Time conversion gives discrepancy of %e sec. Exiting.\n",diff);
    return(-1);
  }
  XLALPrintInfo ( "MJD conversion gives discrepancies of %e sec\n",diff);

  /* define reference time in an MJD structure */
  REAL8toMJD ( &TrefTDBMJD, uvar.TrefTDBMJD );
  XLALPrintInfo ( "TrefTDBMJD converted to MJD days = %d fracdays = %6.12f\n",TrefTDBMJD.days,TrefTDBMJD.fracdays);

  /* convert reference time to TDB GPS */
  TDBMJDtoGPS(&TrefSSB_TDB_GPS,TrefTDBMJD);
  XLALPrintInfo ( "TrefSSB_TDB_GPS = %d %d\n",TrefSSB_TDB_GPS.gpsSeconds,TrefSSB_TDB_GPS.gpsNanoSeconds);

  /* convert back to test conversion */
  TDBGPStoMJD ( &MJDtest, TrefSSB_TDB_GPS, leap0 );
  deltaMJD ( &MJDdiff, &MJDtest, &TrefTDBMJD );
  diff = (MJDdiff.days+MJDdiff.fracdays)*86400;
  if ( fabs(diff)  > 1e-9) {
    fprintf(stderr,"ERROR : Time conversion gives discrepancy of %e sec. Exiting.\n",diff);
    return(-1);
  }
  XLALPrintInfo ( "MJD conversion gives discrepancies of %e sec\n",diff);

  /* fill in required pulsar params structure for Barycentering */
  LALDetector *site = NULL;
  site = (LALDetector *)LALMalloc(sizeof(LALDetector));
  site->location[0] = baryinput.site.location[0];
  site->location[1] = baryinput.site.location[1];
  site->location[2] = baryinput.site.location[2];
  pulsarparams.site = site;

  pulsarparams.pulsar.position.longitude = alpha;
  pulsarparams.pulsar.position.latitude = delta;
  pulsarparams.pulsar.position.system = COORDINATESYSTEM_EQUATORIAL;
  pulsarparams.ephemerides = edat;

  /* generate SSB initial TOA in GPS */
  XLALConvertGPS2SSB ( &TstartSSB, TstartGPS, &pulsarparams);
  XLALPrintInfo ( "TstartSSB = %d %d\n",TstartSSB.gpsSeconds,TstartSSB.gpsNanoSeconds);

  /* define TOA end time in GPS */
  temp = uvar.DurationMJD*86400.0;
  TendGPS = TstartGPS;
  XLALGPSAdd(&TendGPS, temp);
  XLALPrintInfo ( "GPS end time of TOAs = %d %d\n",TendGPS.gpsSeconds,TendGPS.gpsNanoSeconds);

  /* generate SSB end time in GPS (force integer seconds) */
  XLALConvertGPS2SSB (&TendSSB,TendGPS,&pulsarparams);
  XLALPrintInfo  ( "TendSSB = %d %d\n",TendSSB.gpsSeconds,TendSSB.gpsNanoSeconds);

  /* define TOA seperation in the SSB */
  dt = uvar.DeltaTMJD*86400.0;
  n = (INT4)ceil(uvar.DurationMJD/uvar.DeltaTMJD);
  XLALPrintInfo ( "TOA seperation at SSB = %g sec\n",dt);
  XLALPrintInfo ( "number of TOAs to generate = %d\n",n);

  /* allocate memory for artificial SSB TOAs */
  TSSB = (LIGOTimeGPS *)LALMalloc(n*sizeof(LIGOTimeGPS));
  TOA = (MJDTime *)LALMalloc(n*sizeof(MJDTime));

  /* generate artificial SSB TOAs given the phase model phi = 2*pi*(f0*(t-tref) + 0.5*fdot*(t-tref)^2) */
  for  (i=0;i<n;i++)
    {
      REAL8 dtref,fnow,cyclefrac,dtcor;
      LIGOTimeGPS tnow;

      /* define current interval */
      XLALPrintInfo ( "current (t-tstart) = %g sec\n", i * dt);

      /* define current t */
      tnow = TstartSSB;
      XLALGPSAdd(&tnow, i * dt);
      XLALPrintInfo ( "current t = %d %d\n",tnow.gpsSeconds,tnow.gpsNanoSeconds);

      /* define current t-tref */
      dtref = XLALGPSDiff(&tnow,&TrefSSB_TDB_GPS);
      XLALPrintInfo ( "current (t - tref) = %9.12f\n",dtref);

      dtcor = 1;
      while (dtcor>1e-9)
        {

          /* define actual cycle fraction at requested time */
          cyclefrac = fmod(uvar.f0*dtref + 0.5*uvar.fdot*dtref*dtref,1.0);
          XLALPrintInfo ( "cyclefrac = %9.12f\n",cyclefrac);

          /* define instantaneous frequency */
          fnow = uvar.f0 + uvar.fdot*dtref;
          XLALPrintInfo ( "instananeous frequency = %9.12f\n",fnow);

          /* add correction to time */
          dtcor = cyclefrac/fnow;
          dtref -= dtcor;
          XLALPrintInfo ( "timing correction = %9.12f\n",dtcor);
          XLALPrintInfo ( "corrected dtref to = %9.12f\n",dtref);
        } // while dtcor>1e-9

      /* define time of zero phase */
      TSSB[i] = TrefSSB_TDB_GPS;
      XLALGPSAdd(&TSSB[i], dtref);
      XLALPrintInfo ( "TSSB[%d] = %d %d\n",i,TSSB[i].gpsSeconds,TSSB[i].gpsNanoSeconds);
    } // for i < n

  /* loop over SSB time of arrivals and compute detector time of arrivals */
  for (i=0;i<n;i++)
    {
      LIGOTimeGPS TSSBtest;
      LIGOTimeGPS GPStest;

      /* convert SSB to Detector time */
      int ret = XLALConvertSSB2GPS ( &TDET, TSSB[i], &pulsarparams);
      if ( ret != XLAL_SUCCESS ) {
        XLALPrintError ("XLALConvertSSB2GPS() failed with xlalErrno = %d\n", xlalErrno );
	return(-1);
      }

      XLALPrintInfo ( "converted SSB TOA %d %d -> Detector TOA %d %d\n",TSSB[i].gpsSeconds,TSSB[i].gpsNanoSeconds,TDET.gpsSeconds,TDET.gpsNanoSeconds);

      /* convert back for testing conversion */
      XLALConvertGPS2SSB (&TSSBtest,TDET,&pulsarparams);
      diff = XLALGPSDiff(&TSSBtest,&TSSB[i]);
      if ( fabs(diff)  > 1e-9) {
	fprintf(stderr,"ERROR : Time conversion gives discrepancy of %e sec. Exiting.\n",diff);
	return(-1);
      }
      XLALPrintInfo ( "SSB -> detector conversion gives discrepancies of %e sec\n",diff);

      /* recompute leap seconds incase they've changed */
      leap = XLALGPSLeapSeconds (TDET.gpsSeconds);

      /* must now convert to an MJD time for TEMPO */
      /* Using UTC conversion as used by Matt in his successful comparison */
      UTCGPStoMJD (&tempTOA,&TDET,leap);
      XLALPrintInfo ( "output MJD time = %d %6.12f\n",tempTOA.days,tempTOA.fracdays);

      /* convert back to test conversion */
      UTCMJDtoGPS ( &GPStest, tempTOA, leap );
      diff = XLALGPSDiff(&TDET,&GPStest);
      if ( fabs(diff)  > 1e-9) {
	fprintf(stderr,"ERROR. Time conversion gives discrepancy of %e sec. Exiting.\n",diff);
	return(-1);
      }
      XLALPrintInfo ( "MJD time conversion gives discrepancies of %e sec\n",diff);

      /* fill in results */
      TOA[i].days = tempTOA.days;
      TOA[i].fracdays = tempTOA.fracdays;

    } // for i < n

  snprintf(tempstr,15,"%1.13f",TOA[0].fracdays);
  tempstr2 = tempstr+2;
  snprintf(TstartMJDstr,19,"%d.%s",TOA[0].days,tempstr2);
  XLALPrintInfo ( "Converted initial TOA MJD %d %6.12f to the string %s\n",TOA[0].days,TOA[0].fracdays,TstartMJDstr);

  snprintf(tempstr,15,"%1.13f",TOA[n-1].fracdays);
  tempstr2 = tempstr+2;
  snprintf(TfinishMJDstr,19,"%d.%s",TOA[n-1].days,tempstr2);
  XLALPrintInfo ( "*** Converted MJD to a string %s\n",TfinishMJDstr);
  XLALPrintInfo ( "Converted final TOA MJD %d %6.12f to the string %s\n",TOA[n-1].days,TOA[n-1].fracdays,TfinishMJDstr);

  /* define output file names */
  sprintf(parfile,"%s.par",uvar.PSRJ);
  sprintf(timfile,"%s.tim",uvar.PSRJ);

  /* output to par file in format required by TEMPO 2 */
  if ((fp = fopen(parfile,"w")) == NULL) {
    fprintf(stderr,"ERROR. Could not open file %s. Exiting.\n",parfile);
    return(-1);
  }
  fprintf(fp,"PSRJ\t%s\n",uvar.PSRJ);
  fprintf(fp,"RAJ\t%s\t1\n",RAJ);
  fprintf(fp,"DECJ\t%s\t1\n",DECJ);
  fprintf(fp,"PEPOCH\t%6.12f\n",uvar.TrefTDBMJD);
  fprintf(fp,"POSEPOCH\t%6.12f\n",uvar.TrefTDBMJD);
  fprintf(fp,"DMEPOCH\t%6.12f\n",uvar.TrefTDBMJD);
  fprintf(fp,"DM\t0.0\n");
  fprintf(fp,"F0\t%6.16f\t1\n",uvar.f0);
  fprintf(fp,"F1\t%6.16f\t0\n",uvar.fdot);
  fprintf(fp,"START\t%s\n",TstartMJDstr);
  fprintf(fp,"FINISH\t%s\n",TfinishMJDstr);
  fprintf(fp,"TZRSITE\t%s\n",detcode);
  fprintf(fp,"CLK\tUTC(NIST)\n");
  fprintf(fp,"EPHEM\tDE405\n");
  fprintf(fp,"UNITS\tTDB\n");
  fprintf(fp,"MODE\t0\n");

  /* close par file */
  fclose(fp);

  /* output to tim file in format required by TEMPO 2 */
  if ((fp = fopen(timfile,"w")) == NULL) {
    fprintf(stderr,"ERROR. Could not open file %s. Exiting.\n",timfile);
    return(-1);
  }

  fprintf(fp,"FORMAT 1\n");
  for (i=0;i<n;i++)
    {
      /* convert each TOA to a string for output */
      snprintf(tempstr,18,"%1.16f",TOA[i].fracdays);
      tempstr2 = tempstr+2;
      snprintf(TOAstr,22,"%d.%s",TOA[i].days,tempstr2);
      fprintf(fp,"blank.dat\t1000.0\t%s\t1.0\t%s\n",TOAstr,detcode);
      XLALPrintInfo ( "Converting MJD time %d %6.16f to string %s\n",TOA[i].days,TOA[i].fracdays,TOAstr);
    } // for i < n

  /* close tim file */
  fclose(fp);

  /* free memory */
  XLALFree ( TSSB );
  XLALFree ( TOA );
  XLALFree ( site );
  XLALDestroyEphemerisData ( edat );
  XLALDestroyUserVars ();
  LALCheckMemoryLeaks();

  return XLAL_SUCCESS;

} /* main() */
Ejemplo n.º 15
0
UINT4
XLALMCMCSample(
  LALMCMCInput *inputMCMC,
  LALMCMCParameter **paraPtr,
  REAL4  *oldLogPosterior,
  gsl_matrix *covMat
  )
{

  static LALStatus status;

  LALMCMCParameter *parameter=NULL; /* parameter value    */
  LALMCMCParameter *proposal=NULL;  /* proposal  value    */
  LALMCMCParameter *help=NULL;      /* help parameter set */
  LALMCMCParam* paraHead = NULL;

  REAL4 alpha, my_random, s;
  REAL4 logPrior, logLikelihood, logPosterior;
  UINT4 move, accept, c;
  INT4 UNUSED testPrior;

  /* set the parameter */
  parameter=*paraPtr;
  move=0;

  /* allocate spec for proposal set */
  proposal=(LALMCMCParameter*)LALMalloc( sizeof(LALMCMCParameter) );

  do {
    accept = 1;
    XLALMCMCCopyPara( &proposal, parameter);
    XLALMCMCJump( inputMCMC, proposal, covMat);

    for (paraHead = proposal->param,c=0; paraHead; paraHead=paraHead->next,c++ )
    {
      /* check if parameter lies in valid range */
      if (paraHead->value < paraHead->core->minVal ||
          paraHead->value > paraHead->core->maxVal)
      {
        accept=0;
        /*
        if ( inputMCMC->verbose )
          printf("MCMCSAMPLE Parameter %10s outside range. Value: %8.3f  Range: %8.3f - %8.3f \n",
                 paraHead->core->name, paraHead->value,
                 paraHead->core->minVal,  paraHead->core->maxVal );
        */
      }
    }
  } while ( !accept );

  /* calculate the log Prior */
  testPrior = inputMCMC->funcPrior( inputMCMC, proposal );
  logPrior = proposal->logPrior;

  /*-- determine likelihood if prior gives something reasonable:   --*/
  if ( logPrior>-HUGE_VAL )
  {

    /* calculate the new posterior value for the proposal parameter set */
    logLikelihood = inputMCMC->funcLikelihood( inputMCMC, proposal );
    logPosterior = logLikelihood + logPrior;

    /* calculate the alpha-value and draw a random number */
    s=inputMCMC->scaling;
    alpha=exp( s*(logPosterior - *oldLogPosterior) );
    LALUniformDeviate( &status, &my_random, inputMCMC->randParams );

    /* now check accept/reject criterion */
    if ( my_random<=alpha )
    {
      /* accept the proposal set */
      move = 1;

      /* just swap the two pointers */
      help=proposal;
      proposal=parameter;
      parameter=help;

      /* return the new log posterior value */
      *oldLogPosterior = logPosterior;
    }

    /* output */
    if ( inputMCMC->verbose )
    {
      if (move==1)
        printf("MCMCSAMPLE: ++JumpIsAccepted ");
      else
        printf("MCMCSAMPLE: --JumpNotAccepted ");
      printf("current logPost: %6.3f  proposal logPost: %6.3f alpha: %6.3f  "
             "u: %6.3f\n",
             *oldLogPosterior, logPosterior, alpha, my_random);
    }
  }

  /* test printout */
  if ( inputMCMC->verbose )
  {
    printf("MCMCPARAMETER: ");
    printf("| SNR: %f  ", *oldLogPosterior);
    for (paraHead=parameter->param; paraHead; paraHead=paraHead->next) {
      printf(" | %s: %9.5f", paraHead->core->name, paraHead->value);
    }
    fprintf(stdout, "\n");
  }


  /* recopy the correct parameter structure */
  *paraPtr=parameter;

  /* free proposal parameter set */
  XLALMCMCFreePara( proposal );

  return move;
}
Ejemplo n.º 16
0
/**
 * \brief Provides an interface between code build from \ref lalinspiral_findchirp and
 * various simulation packages for injecting chirps into data.
 * \author Brown, D. A. and Creighton, T. D
 *
 * Injects the signals described
 * in the linked list of \c SimInspiralTable structures \c events
 * into the data \c chan. The response function \c resp should
 * contain the response function to use when injecting the signals into the data.
 */
void
LALFindChirpInjectIMR (
    LALStatus                  *status,
    REAL4TimeSeries            *chan,
    SimInspiralTable           *events,
    SimRingdownTable           *ringdownevents,
    COMPLEX8FrequencySeries    *resp,
    INT4                        injectSignalType
    )

{
  UINT4                 k;
  DetectorResponse      detector;
  SimInspiralTable     *thisEvent = NULL;
  SimRingdownTable     *thisRingdownEvent = NULL;
  PPNParamStruc         ppnParams;
  CoherentGW            waveform, *wfm;
  INT8                  waveformStartTime;
  REAL4TimeSeries       signalvec;
  COMPLEX8Vector       *unity = NULL;
  CHAR                  warnMsg[512];
#if 0
  UINT4 n;
  UINT4 i;
#endif

  INITSTATUS(status);
  ATTATCHSTATUSPTR( status );

  ASSERT( chan, status,
      FINDCHIRPH_ENULL, FINDCHIRPH_MSGENULL );
  ASSERT( chan->data, status,
      FINDCHIRPH_ENULL, FINDCHIRPH_MSGENULL );
  ASSERT( chan->data->data, status,
      FINDCHIRPH_ENULL, FINDCHIRPH_MSGENULL );

  ASSERT( events, status,
      FINDCHIRPH_ENULL, FINDCHIRPH_MSGENULL );

  ASSERT( resp, status,
      FINDCHIRPH_ENULL, FINDCHIRPH_MSGENULL );
  ASSERT( resp->data, status,
      FINDCHIRPH_ENULL, FINDCHIRPH_MSGENULL );
  ASSERT( resp->data->data, status,
      FINDCHIRPH_ENULL, FINDCHIRPH_MSGENULL );


  /*
   *
   * set up structures and parameters needed
   *
   */

  /* fixed waveform injection parameters */
  memset( &ppnParams, 0, sizeof(PPNParamStruc) );
  ppnParams.deltaT   = chan->deltaT;
  ppnParams.lengthIn = 0;
  ppnParams.ppn      = NULL;


  /*
   *
   * compute the transfer function from the given response function
   *
   */


  /* allocate memory and copy the parameters describing the freq series */
  memset( &detector, 0, sizeof( DetectorResponse ) );
  detector.transfer = (COMPLEX8FrequencySeries *)
    LALCalloc( 1, sizeof(COMPLEX8FrequencySeries) );
  if ( ! detector.transfer )
  {
    ABORT( status, FINDCHIRPH_EALOC, FINDCHIRPH_MSGEALOC );
  }
  memcpy( &(detector.transfer->epoch), &(resp->epoch),
      sizeof(LIGOTimeGPS) );
  detector.transfer->f0 = resp->f0;
  detector.transfer->deltaF = resp->deltaF;

  detector.site = (LALDetector *) LALMalloc( sizeof(LALDetector) );
  /* set the detector site */
  switch ( chan->name[0] )
  {
    case 'H':
      *(detector.site) = lalCachedDetectors[LALDetectorIndexLHODIFF];
      LALWarning( status, "computing waveform for Hanford." );
      break;
    case 'L':
      *(detector.site) = lalCachedDetectors[LALDetectorIndexLLODIFF];
      LALWarning( status, "computing waveform for Livingston." );
      break;
    case 'G':
      *(detector.site) = lalCachedDetectors[LALDetectorIndexGEO600DIFF];
      LALWarning( status, "computing waveform for GEO600." );
      break;
    case 'T':
      *(detector.site) = lalCachedDetectors[LALDetectorIndexTAMA300DIFF];
      LALWarning( status, "computing waveform for TAMA300." );
      break;
    case 'V':
      *(detector.site) = lalCachedDetectors[LALDetectorIndexVIRGODIFF];
      LALWarning( status, "computing waveform for Virgo." );
      break;
    default:
      LALFree( detector.site );
      detector.site = NULL;
      LALWarning( status, "Unknown detector site, computing plus mode "
          "waveform with no time delay" );
      break;
  }

  /* set up units for the transfer function */
  if (XLALUnitDivide( &(detector.transfer->sampleUnits),
                      &lalADCCountUnit, &lalStrainUnit ) == NULL) {
    ABORTXLAL(status);
  }

  /* invert the response function to get the transfer function */
  LALCCreateVector( status->statusPtr, &( detector.transfer->data ),
      resp->data->length );
  CHECKSTATUSPTR( status );

  LALCCreateVector( status->statusPtr, &unity, resp->data->length );
  CHECKSTATUSPTR( status );
  for ( k = 0; k < resp->data->length; ++k )
  {
    unity->data[k] = 1.0;
  }

  LALCCVectorDivide( status->statusPtr, detector.transfer->data, unity,
      resp->data );
  CHECKSTATUSPTR( status );

  LALCDestroyVector( status->statusPtr, &unity );
  CHECKSTATUSPTR( status );

  thisRingdownEvent = ringdownevents;

  /*
   *
   * loop over the signals and inject them into the time series
   *
   */


  for ( thisEvent = events; thisEvent; thisEvent = thisEvent->next)
  {
    /*
     *
     * generate waveform and inject it into the data
     *
     */


    /* clear the waveform structure */
    memset( &waveform, 0, sizeof(CoherentGW) );

    LALGenerateInspiral(status->statusPtr, &waveform, thisEvent, &ppnParams);
    CHECKSTATUSPTR( status );

    /* add the ringdown */
    wfm = XLALGenerateInspRing( &waveform, thisEvent, thisRingdownEvent,
       injectSignalType );

    if ( !wfm )
    {
      fprintf( stderr, "Failed to generate the waveform \n" );
      if (xlalErrno == XLAL_EFAILED)
      {
        fprintf( stderr, "Too much merger\n");
        XLALDestroyREAL4TimeSeries( chan );
        xlalErrno = XLAL_SUCCESS;
        return;
      }
      else exit ( 1 );
    }


    waveform = *wfm;

    LALInfo( status, ppnParams.termDescription );

    if ( thisEvent->geocent_end_time.gpsSeconds )
    {
      /* get the gps start time of the signal to inject */
      waveformStartTime = XLALGPSToINT8NS( &(thisEvent->geocent_end_time) );
      waveformStartTime -= (INT8) ( 1000000000.0 * ppnParams.tc );
    }
    else
    {
      LALInfo( status, "Waveform start time is zero: injecting waveform "
          "into center of data segment" );

      /* center the waveform in the data segment */
      waveformStartTime = XLALGPSToINT8NS( &(chan->epoch) );

      waveformStartTime += (INT8) ( 1000000000.0 *
          ((REAL8) (chan->data->length - ppnParams.length) / 2.0) * chan->deltaT
          );
    }

    snprintf( warnMsg, sizeof(warnMsg)/sizeof(*warnMsg),
        "Injected waveform timing:\n"
        "thisEvent->geocent_end_time.gpsSeconds = %d\n"
        "thisEvent->geocent_end_time.gpsNanoSeconds = %d\n"
        "ppnParams.tc = %e\n"
        "waveformStartTime = %" LAL_INT8_FORMAT "\n",
        thisEvent->geocent_end_time.gpsSeconds,
        thisEvent->geocent_end_time.gpsNanoSeconds,
        ppnParams.tc,
        waveformStartTime );
    LALInfo( status, warnMsg );

    /* clear the signal structure */
    memset( &signalvec, 0, sizeof(REAL4TimeSeries) );

    /* set the start times for injection */
    XLALINT8NSToGPS( &(waveform.a->epoch), waveformStartTime );
    memcpy( &(waveform.f->epoch), &(waveform.a->epoch),
        sizeof(LIGOTimeGPS) );
    memcpy( &(waveform.phi->epoch), &(waveform.a->epoch),
        sizeof(LIGOTimeGPS) );

    /* set the start time of the signal vector to the start time of the chan */
    signalvec.epoch = chan->epoch;

    /* set the parameters for the signal time series */
    signalvec.deltaT = chan->deltaT;
    if ( ( signalvec.f0 = chan->f0 ) != 0 )
    {
      ABORT( status, FINDCHIRPH_EHETR, FINDCHIRPH_MSGEHETR );
    }
    signalvec.sampleUnits = lalADCCountUnit;

    /* simulate the detectors response to the inspiral */
    LALSCreateVector( status->statusPtr, &(signalvec.data), chan->data->length );
    CHECKSTATUSPTR( status );

    LALSimulateCoherentGW( status->statusPtr,
        &signalvec, &waveform, &detector );
    CHECKSTATUSPTR( status );

/* *****************************************************************************/
#if 0
    FILE *fp;
    char fname[512];
    UINT4 jj, kplus, kcross;
    snprintf( fname, sizeof(fname) / sizeof(*fname),
        "waveform-%d-%d-%s.txt",
        thisEvent->geocent_end_time.gpsSeconds,
        thisEvent->geocent_end_time.gpsNanoSeconds,
        thisEvent->waveform );
    fp = fopen( fname, "w" );
    for( jj = 0, kplus = 0, kcross = 1; jj < waveform.phi->data->length;
        ++jj, kplus += 2, kcross +=2 )
    {
      fprintf(fp, "%d %e %e %le %e\n", jj,
          waveform.a->data->data[kplus],
          waveform.a->data->data[kcross],
          waveform.phi->data->data[jj],
          waveform.f->data->data[jj]);
    }
    fclose( fp );
#endif

/* ********************************************************************************/
#if 0
    FILE *fp;
    char fname[512];
    UINT4 jj;
    snprintf( fname, sizeof(fname) / sizeof(*fname),
        "waveform-%d-%d-%s.txt",
        thisEvent->geocent_end_time.gpsSeconds,
        thisEvent->geocent_end_time.gpsNanoSeconds,
        thisEvent->waveform );
    fp = fopen( fname, "w" );
    for( jj = 0; jj < signalvec.data->length; ++jj )
    {
      fprintf(fp, "%d %e %e \n", jj, signalvec.data->data[jj]);
    }
    fclose( fp );
#endif

/* ********************************************************************************/


    /* inject the signal into the data channel */
    LALSSInjectTimeSeries( status->statusPtr, chan, &signalvec );
    CHECKSTATUSPTR( status );

    /* allocate and go to next SimRingdownTable */
    if( thisEvent->next )
      thisRingdownEvent = thisRingdownEvent->next = (SimRingdownTable *)
      calloc( 1, sizeof(SimRingdownTable) );
    else
      thisRingdownEvent->next = NULL;

    /* destroy the signal */
    LALSDestroyVector( status->statusPtr, &(signalvec.data) );
    CHECKSTATUSPTR( status );

    LALSDestroyVectorSequence( status->statusPtr, &(waveform.a->data) );
    CHECKSTATUSPTR( status );

    LALSDestroyVector( status->statusPtr, &(waveform.f->data) );
    CHECKSTATUSPTR( status );

    LALDDestroyVector( status->statusPtr, &(waveform.phi->data) );
    CHECKSTATUSPTR( status );

    if ( waveform.shift )
    {
      LALSDestroyVector( status->statusPtr, &(waveform.shift->data) );
      CHECKSTATUSPTR( status );
    }

    LALFree( waveform.a );
    LALFree( waveform.f );
    LALFree( waveform.phi );
    if ( waveform.shift )
    {
      LALFree( waveform.shift );
    }

  }

  LALCDestroyVector( status->statusPtr, &( detector.transfer->data ) );
  CHECKSTATUSPTR( status );

  if ( detector.site ) LALFree( detector.site );
  LALFree( detector.transfer );

  DETATCHSTATUSPTR( status );
  RETURN( status );
}
Ejemplo n.º 17
0
void
LALRingInjectSignals(
    LALStatus               *stat,
    REAL4TimeSeries         *series,
    SimRingdownTable        *injections,
    COMPLEX8FrequencySeries *resp,
    INT4                     calType
    )

{
  UINT4              k;
  INT4               injStartTime;
  INT4               injStopTime;
  DetectorResponse   detector;
  COMPLEX8Vector    *unity = NULL;
  CoherentGW         waveform;
  RingParamStruc     ringParam;
  REAL4TimeSeries    signalvec;
  SimRingdownTable  *simRingdown=NULL;
  LALDetector       *tmpDetector=NULL /*,*nullDetector=NULL*/;
  COMPLEX8FrequencySeries    *transfer = NULL;

  INITSTATUS(stat);
  ATTATCHSTATUSPTR( stat );

  /* set up start and end of injection zone TODO: fix this hardwired 10 */
  injStartTime = series->epoch.gpsSeconds - 10;
  injStopTime = series->epoch.gpsSeconds + 10 + (INT4)(series->data->length
      * series->deltaT);

  /*
   *compute the transfer function
   */

  /* allocate memory and copy the parameters describing the freq series */
  memset( &detector, 0, sizeof( DetectorResponse ) );
  transfer = (COMPLEX8FrequencySeries *)
    LALCalloc( 1, sizeof(COMPLEX8FrequencySeries) );
  if ( ! transfer )
  {
    ABORT( stat, GENERATERINGH_EMEM, GENERATERINGH_MSGEMEM );
  }
  memcpy( &(transfer->epoch), &(resp->epoch),
      sizeof(LIGOTimeGPS) );
  transfer->f0 = resp->f0;
  transfer->deltaF = resp->deltaF;

  tmpDetector = detector.site = (LALDetector *) LALMalloc( sizeof(LALDetector) );
  /* set the detector site */
  switch ( series->name[0] )
  {
    case 'H':
      *(detector.site) = lalCachedDetectors[LALDetectorIndexLHODIFF];
      LALWarning( stat, "computing waveform for Hanford." );
      break;
    case 'L':
      *(detector.site) = lalCachedDetectors[LALDetectorIndexLLODIFF];
      LALWarning( stat, "computing waveform for Livingston." );
      break;
    default:
      LALFree( detector.site );
      detector.site = NULL;
      tmpDetector = NULL;
      LALWarning( stat, "Unknown detector site, computing plus mode "
          "waveform with no time delay" );
      break;
  }

  /* set up units for the transfer function */
  if (XLALUnitDivide( &(detector.transfer->sampleUnits),
                      &lalADCCountUnit, &lalStrainUnit ) == NULL) {
    ABORTXLAL(stat);
  }

  /* invert the response function to get the transfer function */
  LALCCreateVector( stat->statusPtr, &( transfer->data ),
      resp->data->length );
  CHECKSTATUSPTR( stat );

  LALCCreateVector( stat->statusPtr, &unity, resp->data->length );
  CHECKSTATUSPTR( stat );
  for ( k = 0; k < resp->data->length; ++k )
  {
    unity->data[k] = 1.0;
  }

  LALCCVectorDivide( stat->statusPtr, transfer->data, unity,
      resp->data );
  CHECKSTATUSPTR( stat );

  LALCDestroyVector( stat->statusPtr, &unity );
  CHECKSTATUSPTR( stat );

  /* Set up a time series to hold signal in ADC counts */
  signalvec.deltaT = series->deltaT;
  if ( ( signalvec.f0 = series->f0 ) != 0 )
  {
    ABORT( stat, GENERATERINGH_EMEM, GENERATERINGH_MSGEMEM );
  }
  signalvec.sampleUnits = lalADCCountUnit;

  signalvec.data=NULL;
  LALSCreateVector( stat->statusPtr, &(signalvec.data),
      series->data->length );
  CHECKSTATUSPTR( stat );

  /* loop over list of waveforms and inject into data stream */
  simRingdown = injections;
  while ( simRingdown )
  {
    /* only do the work if the ring is in injection zone */
    if( (injStartTime - simRingdown->geocent_start_time.gpsSeconds) *
        (injStopTime - simRingdown->geocent_start_time.gpsSeconds) > 0 )
    {
      simRingdown = simRingdown->next;
      continue;
    }

    /* set the ring params */
    ringParam.deltaT = series->deltaT;
    if( !( strcmp( simRingdown->coordinates, "HORIZON" ) ) )
    {
      ringParam.system = COORDINATESYSTEM_HORIZON;
    }
    else if ( !( strcmp( simRingdown->coordinates, "ZENITH" ) ) )
    {
      /* set coordinate system for completeness */
      ringParam.system = COORDINATESYSTEM_EQUATORIAL;
      detector.site = NULL;
    }
    else if ( !( strcmp( simRingdown->coordinates, "GEOGRAPHIC" ) ) )
    {
     ringParam.system = COORDINATESYSTEM_GEOGRAPHIC;
    }
    else if ( !( strcmp( simRingdown->coordinates, "EQUATORIAL" ) ) )
    {
      ringParam.system = COORDINATESYSTEM_EQUATORIAL;
    }
    else if ( !( strcmp( simRingdown->coordinates, "ECLIPTIC" ) ) )
    {
      ringParam.system = COORDINATESYSTEM_ECLIPTIC;
    }
    else if ( !( strcmp( simRingdown->coordinates, "GALACTIC" ) ) )
    {
      ringParam.system = COORDINATESYSTEM_GALACTIC;
    }
    else
      ringParam.system = COORDINATESYSTEM_EQUATORIAL;

    /* generate the ring */
    memset( &waveform, 0, sizeof(CoherentGW) );
    LALGenerateRing( stat->statusPtr, &waveform, series, simRingdown, &ringParam );
    CHECKSTATUSPTR( stat );

    /* print the waveform to a file */
    if ( 0 )
      {
        FILE *fp;
        char fname[512];
        UINT4 jj, kplus, kcross;
        snprintf( fname, sizeof(fname) / sizeof(*fname),
            "waveform-%d-%d-%s.txt",
            simRingdown->geocent_start_time.gpsSeconds,
            simRingdown->geocent_start_time.gpsNanoSeconds,
            simRingdown->waveform );
        fp = fopen( fname, "w" );

        for( jj = 0, kplus = 0, kcross = 1; jj < waveform.phi->data->length;
            ++jj, kplus += 2, kcross +=2 )
          {
            fprintf(fp, "%d %e %e %le %e\n", jj,
                waveform.a->data->data[kplus],
                waveform.a->data->data[kcross],
                waveform.phi->data->data[jj],
                waveform.f->data->data[jj]);
            }
        fclose( fp );
        }
    /* end */
#if 0
    fprintf( stderr, "a->epoch->gpsSeconds = %d\na->epoch->gpsNanoSeconds = %d\n",
        waveform.a->epoch.gpsSeconds, waveform.a->epoch.gpsNanoSeconds );
    fprintf( stderr, "phi->epoch->gpsSeconds = %d\nphi->epoch->gpsNanoSeconds = %d\n",
        waveform.phi->epoch.gpsSeconds, waveform.phi->epoch.gpsNanoSeconds );
    fprintf( stderr, "f->epoch->gpsSeconds = %d\nf->epoch->gpsNanoSeconds = %d\n",
        waveform.f->epoch.gpsSeconds, waveform.f->epoch.gpsNanoSeconds );
#endif
    /* must set the epoch of signal since it's used by coherent GW */
    signalvec.epoch = series->epoch;
    memset( signalvec.data->data, 0, signalvec.data->length * sizeof(REAL4) );

    /* decide which way to calibrate the data; defaul to old way */
    if( calType )
      detector.transfer=NULL;
    else
      detector.transfer=transfer;

    /* convert this into an ADC signal */
    LALSimulateCoherentGW( stat->statusPtr,
        &signalvec, &waveform, &detector );
    CHECKSTATUSPTR( stat );


/* print the waveform to a file */
    if ( 0 )
      {
        FILE *fp;
        char fname[512];
        UINT4 jj;
        snprintf( fname, sizeof(fname) / sizeof(*fname),
            "signal-%d-%d-%s.txt",
            simRingdown->geocent_start_time.gpsSeconds,
            simRingdown->geocent_start_time.gpsNanoSeconds,
            simRingdown->waveform );
        fp = fopen( fname, "w" );

        for( jj = 0; jj < signalvec.data->length; ++jj )
          {
            fprintf( fp, "%d %le\n", jj, signalvec.data->data[jj] );
          }
        fclose( fp );
        }
    /* end */
#if 0
    fprintf( stderr, "series.epoch->gpsSeconds = %d\nseries.epoch->gpsNanoSeconds = %d\n",
        series->epoch.gpsSeconds, series->epoch.gpsNanoSeconds );
    fprintf( stderr, "signalvec->epoch->gpsSeconds = %d\nsignalvec->epoch->gpsNanoSeconds = %d\n",
        signalvec.epoch.gpsSeconds, signalvec.epoch.gpsNanoSeconds );
#endif
    /* if calibration using RespFilt */
    if( calType == 1 )
      XLALRespFilt(&signalvec, transfer);

    /* inject the signal into the data channel */
    LALSSInjectTimeSeries( stat->statusPtr, series, &signalvec );
    CHECKSTATUSPTR( stat );

/* free memory in coherent GW structure.  TODO:  fix this */
    LALSDestroyVectorSequence( stat->statusPtr, &( waveform.a->data ) );
    CHECKSTATUSPTR( stat );
    LALSDestroyVector( stat->statusPtr, &( waveform.f->data ) );
    CHECKSTATUSPTR( stat );
    LALDDestroyVector( stat->statusPtr, &( waveform.phi->data ) );
    CHECKSTATUSPTR( stat );
    LALFree( waveform.a );   waveform.a = NULL;
    LALFree( waveform.f );   waveform.f = NULL;
    LALFree( waveform.phi );  waveform.phi = NULL;

    /* reset the detector site information in case it changed */
    detector.site = tmpDetector;

    /* move on to next one */
    simRingdown = simRingdown->next;
  }

  /* destroy the signal */
  LALSDestroyVector( stat->statusPtr, &(signalvec.data) );
  CHECKSTATUSPTR( stat );

  LALCDestroyVector( stat->statusPtr, &( transfer->data ) );
  CHECKSTATUSPTR( stat );

  if ( detector.site ) LALFree( detector.site );
  LALFree( transfer );

  DETATCHSTATUSPTR( stat );
  RETURN( stat );
}
Ejemplo n.º 18
0
void
LALappsTSAProcessSingleCache(LALStatus    *status,
                             TSAparams    *params)
{
    TSAcache       *cache=NULL;
    TSAMap        **mapArray=NULL;
    TSAMap         *mergeResultMap=NULL;
    TSAMap         *mergeMapTmp=NULL;
    UINT4           i=0;

    /*
     * Read in the cache file to memory
     */
    if (params->cacheFilename == NULL)
    {
        fprintf(stderr,"No map cache file specified!\n");
        LALappsTSassert((params->cacheFilename != NULL),
                        TRACKSEARCHAVERAGERC_ENULL,
                        TRACKSEARCHAVERAGERC_MSGENULL);
    }
    else
    {
        /*
         * Load up the cache file
         */
        if (params->verbosity > quiet)
            fprintf(stdout,"Loading map cache file\n");

        LALappsTSALoadCacheFile(
            params->cacheFilename,
            &cache);
        /*
         * Sort cache structure chrono
         logically
        */
        if (params->verbosity > quiet)
            fprintf(stdout,"Sorting cache file entries chronologically\n");
        LALappsTSASortCache(status,
                            cache,
                            0);
        if (params->verbosity > quiet)
        {
            /*
             * Write out sorted list of map files to screen
             */
            for (i=0; i<cache->numMapFilenames; i++)
                fprintf(stdout,"Time:%f Map name %s\n",
                        cache->mapStartTime[i],
                        cache->filename[i]->data);
        }
    }
    /*
     * Create and Load array of TSA maps from disk
     */
    mapArray=(TSAMap**)LALMalloc(sizeof(TSAMap*)*cache->numMapFilenames);
    for (i=0; i<cache->numMapFilenames; i++)
    {
        mapArray[i]=NULL;
        LALappsTSAReadMapFile(status,
                              &(mapArray[i]),
                              cache->filename[i]);
        LALappsTSassert((mapArray[i] != NULL),
                        TRACKSEARCHAVERAGERC_EMEM,
                        TRACKSEARCHAVERAGERC_MSGEMEM);
    }
    /*
     * Begin merging the files into one output TSAMap
     */
    if (params->operation == Merge)
    {
        if (params->verbosity > quiet)
            fprintf(stdout,"Merging maps\n");
        LALappsTSassert((cache->numMapFilenames >= 2),
                        TRACKSEARCHAVERAGERC_EVAL,
                        TRACKSEARCHAVERAGERC_MSGEVAL);
        /*
         * Merge first two maps "by hand"
         */
        if (params->verbosity > quiet)
            fprintf(stdout,"Merging first two maps by hand\n");
        LALappsTSAMergeMap(status,
                           &mergeResultMap,
                           *(mapArray[0]),
                           *(mapArray[1]));
        /*
         * Loop through the rest here
         */
        if (cache->numMapFilenames > 2)
        {
            for (i=2; i<cache->numMapFilenames; i++)
            {
                if (params->verbosity > quiet)
                    fprintf(stdout,"Looping maps %i \n",i);
                mergeMapTmp=mergeResultMap;
                mergeResultMap=NULL;
                LALappsTSAMergeMap(status,
                                   &mergeResultMap,
                                   *mergeMapTmp,
                                   *(mapArray[i]));
                if (mergeMapTmp != NULL)
                {
                    if (params->verbosity > quiet)
                        fprintf(stdout,"Deleting Struct Entry %i\n",i);
                    LALappsTSADestroyMap(status,
                                         &mergeMapTmp);
                }
            }
        }
        /*
         * Collapse each map if the user has requested it
         */
        if (
            (params->colParams.newTDim > -1)
            ||
            (params->colParams.newFDim > -1)
        )
        {
            if (params->verbosity > quiet)
                fprintf(stdout,"Collapsing individual maps\n");
            for (i=0; i<cache->numMapFilenames; i++)
                LALappsTSACollapseMap(status,
                                      &(mergeResultMap),
                                      params->colParams);
        }
        /*
         * Output the merged map
         */
        if (params->verbosity > quiet)
            fprintf(stdout,"Writing Merged Map\n");

        LALappsTSAWriteMapFile(
            mergeResultMap,
            NULL);
        /*
         * Free RAM for mergeResultMap
         */
        if (mergeResultMap)
            LALappsTSADestroyMap(status,
                                 &mergeResultMap);
    }
    else
    {
        /*ONLY COLLAPSING*/
        /*
         * Collapse each map if the user has requested it
         */
        if (
            (params->colParams.newTDim > -1)
            ||
            (params->colParams.newFDim > -1)
        )
        {
            if (params->verbosity > quiet)
                fprintf(stdout,"Collapsing individual maps\n");
            for (i=0; i<cache->numMapFilenames; i++)
                LALappsTSACollapseMap(status,
                                      &(mapArray[i]),
                                      params->colParams);
        }
        /*
         * Dump out the array of collapse maps if merge not requested
         */

        if (params->verbosity > quiet)
            fprintf(stdout,"Maps not merged writing maps to disk");

        for (i=0; i<cache->numMapFilenames; i++)
        {
            LALappsTSAWriteMapFile(
                mapArray[i],
                NULL);
        }
    }
    /*
     * Deallocate the array of TSA maps
     */
    if (mapArray)
    {
        for (i=0; i<cache->numMapFilenames; i++)
            LALappsTSADestroyMap(status,
                                 &(mapArray[i]));
        LALFree(mapArray);
    }
    /*
     * Deallocate the cache file structure
     */
    LALappsTSADestroyCache(&cache);
    return;
}
void FUNC ( LALStatus *status, STYPE **aseq, CreateArraySequenceIn *in )
{
  UINT4 i;

  /*
   * Initialize status
   */
  INITSTATUS(status);
  ATTATCHSTATUSPTR( status );

  /* Check input structure: report if NULL */

  ASSERT (in != NULL, status, SEQFACTORIESH_EINPTR, SEQFACTORIESH_MSGEINPTR);
  ASSERT (in->dimLength, status,
          SEQFACTORIESH_EINPTR, SEQFACTORIESH_MSGEINPTR);

  /* Check sequence length: report error if 0
   * Use of unsigned for length means we can't check if negative
   * length was passed
   */

  ASSERT (in->length > 0, status,
          SEQFACTORIESH_ESLENGTH, SEQFACTORIESH_MSGESLENGTH);

  /* Check dimension lengths: report error any are 0
   * Use of unsigned for length means we can't check if negative
   * length was passed
   */
#ifndef NDEBUG
  for ( i = 0; i < in->dimLength->length; i++ )
  {
    ASSERT (in->dimLength->data[i] > 0, status,
	    SEQFACTORIESH_EALENGTH, SEQFACTORIESH_MSGEALENGTH);
  }
#endif

  /*
   * Check return structure: If return pointer does not point to a
   *    valid pointer then report an error
   */

  ASSERT (aseq != NULL, status, SEQFACTORIESH_EVPTR, SEQFACTORIESH_MSGEVPTR);
  ASSERT (*aseq == NULL, status, SEQFACTORIESH_EUPTR, SEQFACTORIESH_MSGEUPTR);

  /*
   * Allocate pointer
   */

  *aseq = ( STYPE * ) LALMalloc( sizeof( STYPE ) );
  if ( NULL == *aseq )
  {
    ABORT( status, SEQFACTORIESH_EMALLOC, SEQFACTORIESH_MSGEMALLOC );
  }

  (*aseq)->length = in->length;
  (*aseq)->arrayDim = 1;
  (*aseq)->dimLength = NULL;	/* NULL dimLength until allocated */
  (*aseq)->data   = NULL;	/* NULL data until allocated */

  /*
   * Allocate dimLength
   */
  {
    LALU4CreateVector( status->statusPtr, &((*aseq)->dimLength),
		       in->dimLength->length );
    BEGINFAIL( status ) {
      LALFree ((void *) *aseq);
      ABORT (status, SEQFACTORIESH_EMALLOC, SEQFACTORIESH_MSGEMALLOC);
    } ENDFAIL( status );
    for ( i = 0; i < in->dimLength->length; i++ )
      (*aseq)->arrayDim *= (*aseq)->dimLength->data[i]
	= in->dimLength->data[i];
  }

  /*
   * Allocate storage
   */
  {
    size_t tlength;
    tlength = (*aseq)->length * (*aseq)->arrayDim * sizeof( TYPE );
    (*aseq)->data = ( TYPE * ) LALMalloc (tlength);
  }

  if (NULL == (*aseq)->data)
  {
    /* Must free storage pointed to by *aseq */
    TRY( LALU4DestroyVector( status->statusPtr, &((*aseq)->dimLength) ),
	 status );
    LALFree ((void *) *aseq);
    ABORT (status, SEQFACTORIESH_EMALLOC, SEQFACTORIESH_MSGEMALLOC);
  }

  /* We be done: Normal exit */

  DETATCHSTATUSPTR( status );
  RETURN (status);
}
Ejemplo n.º 20
0
/* vvvvvvvvvvvvvvvvvvvvvvvvvvvvvv------------------------------------ */
int main(int argc, char *argv[]){

  static LALStatus           status;  /* LALStatus pointer */
  
  static LALDetector         detector;
  static LIGOTimeGPSVector   timeV;
  static REAL8Cart3CoorVector velV;
  
  static HOUGHptfLUTVector   lutV; /* the Look Up Table vector*/
  static HOUGHPeakGramVector pgV;
  static PHMDVectorSequence  phmdVS;  /* the partial Hough map derivatives */
  static UINT8FrequencyIndexVector freqInd;

  static HOUGHResolutionPar parRes;
  static HOUGHPatchGrid  patch;   /* Patch description */
  static HOUGHParamPLUT  parLut;  /* parameters needed to build lut  */
  static HOUGHDemodPar   parDem;  /* demodulation parameters or  */
  static HOUGHSizePar    parSize;
  static VelocityPar     velPar;

  static HOUGHMapTotal   ht;   /* the total Hough map */
  /* ------------------------------------------------------- */

  CHAR  *earthEphemeris = NULL;
  CHAR  *sunEphemeris = NULL;
  INT4   ifo;
  REAL8  vel[3];
  INT4   mObsCoh;
  UINT2  maxNBins, maxNBorders;

  INT8   f0Bin;           /* freq. bin to construct LUT */
  INT8   fBin;

  UINT2  xSide, ySide;

  CHAR  *fname = NULL;               /* The output filename */
  FILE  *fp=NULL;                    /* Output file */
  INT4  arg;                         /* Argument counter */
  UINT4 i,j;                       /* Index counter, etc */
  INT4  k;
  REAL8 f0, alpha, delta;
  REAL8 patchSizeX, patchSizeY;
  REAL8 Xx,Xy,Xz;

  /******************************************************************/
  /*    Set up the default parameters.      */
  /* ****************************************************************/

  detector = lalCachedDetectors[LALDetectorIndexGEO600DIFF]; /* default */
  ifo = IFO;
  
  if (ifo ==1) detector=lalCachedDetectors[LALDetectorIndexGEO600DIFF];
  if (ifo ==2) detector=lalCachedDetectors[LALDetectorIndexLLODIFF];
  if (ifo ==3) detector=lalCachedDetectors[LALDetectorIndexLHODIFF];

  earthEphemeris = EARTHEPHEMERIS;
  sunEphemeris = SUNEPHEMERIS;

  mObsCoh = MOBSCOH;
  
  timeV.length   = mObsCoh;
  velV.length    = mObsCoh;
  lutV.length    = mObsCoh;
  pgV.length     = mObsCoh;
  phmdVS.length  = mObsCoh;
  freqInd.length = mObsCoh;
  phmdVS.nfSize  = NFSIZE;

  freqInd.deltaF = DF;
  phmdVS.deltaF  = DF;

  timeV.time = NULL;
  velV.data = NULL;
  lutV.lut = NULL;
  pgV.pg = NULL;
  phmdVS.phmd = NULL;
  freqInd.data = NULL;
  ht.map = NULL;

  f0 =  F0;
  f0Bin = F0*TCOH;

  parRes.f0Bin =  f0Bin;
  parRes.deltaF = DF;
/*
 *   parRes.patchSkySizeX  = patchSizeX = 1.0/(TCOH*F0*VEPI);
 *   parRes.patchSkySizeY  = patchSizeY = 1.0/(TCOH*F0*VEPI);
 */
  parRes.patchSkySizeX  = patchSizeX = PATCHSIZEX;
  parRes.patchSkySizeY  = patchSizeY = PATCHSIZEY;
  parRes.pixelFactor = PIXELFACTOR;
  parRes.pixErr = PIXERR;
  parRes.linErr = LINERR;
  parRes.vTotC = VTOT;

  /* Case: no spins & Non demodulation */
  parDem.deltaF = DF;
  parDem.skyPatch.alpha = ALPHA;
  parDem.skyPatch.delta = DELTA;
  parDem.timeDiff = 0.0;
  parDem.spin.length = 0;
  parDem.spin.data = NULL;
  parDem.positC.x = 0.0;
  parDem.positC.y = 0.0;
  parDem.positC.z = 0.0;

  velPar.detector = detector;
  velPar.tBase = TCOH;
  velPar.vTol = ACCURACY;
  
  alpha = ALPHA;
  delta = DELTA;
  
  /*****************************************************************/
  /*****************************************************************/
  /*    Parse argument list.  i stores the current position.       */
  /*****************************************************************/
  arg = 1;
  while ( arg < argc ) {
    /* Parse debuglevel option. */
    if ( !strcmp( argv[arg], "-d" ) ) {
      if ( argc > arg + 1 ) {
        arg++;
      } else {
        ERROR( VALIDATION1_EARG, VALIDATION1_MSGEARG, 0 );
        XLALPrintError( USAGE, *argv );
        return VALIDATION1_EARG;
      }
    }
    /* Parse interferometer option. */
    else if ( !strcmp( argv[arg], "-i" ) ) {
      if ( argc > arg + 1 ) {
        arg++;
        ifo = atoi( argv[arg++] );
	if (ifo ==1) detector=lalCachedDetectors[LALDetectorIndexGEO600DIFF];
        if (ifo ==2) detector=lalCachedDetectors[LALDetectorIndexLLODIFF];
        if (ifo ==3) detector=lalCachedDetectors[LALDetectorIndexLHODIFF];
        velPar.detector = detector;
      } else {
        ERROR( VALIDATION1_EARG, VALIDATION1_MSGEARG, 0 );
        XLALPrintError( USAGE, *argv );
        return VALIDATION1_EARG;
      }
    }
      /* Parse filename of earth  ephemeris data option. */
      else if ( !strcmp( argv[arg], "-E" ) ) {
        if ( argc > arg + 1 ) {
          arg++;
          earthEphemeris = argv[arg++];
        } else {
          ERROR( VALIDATION1_EARG, VALIDATION1_MSGEARG, 0 );
          XLALPrintError( USAGE, *argv );
          return VALIDATION1_EARG;
        }
      }
      /* Parse filename of sun ephemeris data option. */
      else if ( !strcmp( argv[arg], "-S" ) ) {
        if ( argc > arg + 1 ) {
          arg++;
          sunEphemeris = argv[arg++];
        } else {
          ERROR( VALIDATION1_EARG, VALIDATION1_MSGEARG, 0 );
          XLALPrintError( USAGE, *argv );
          return VALIDATION1_EARG;
        }
      }
    /* Parse output file option. */
    else if ( !strcmp( argv[arg], "-o" ) ) {
      if ( argc > arg + 1 ) {
        arg++;
        fname = argv[arg++];
      } else {
        ERROR( VALIDATION1_EARG, VALIDATION1_MSGEARG, 0 );
        XLALPrintError( USAGE, *argv );
        return VALIDATION1_EARG;
      }
    }
    /* Parse frequency option. */
    else if ( !strcmp( argv[arg], "-f" ) ) {
      if ( argc > arg + 1 ) {
        arg++;
        f0 = atof(argv[arg++]);
        f0Bin = f0*TCOH;
        parRes.f0Bin =  f0Bin;
      } else {
        ERROR( VALIDATION1_EARG, VALIDATION1_MSGEARG, 0 );
        XLALPrintError( USAGE, *argv );
        return VALIDATION1_EARG;
      }
    }
    /* Parse sky position options. */
    else if ( !strcmp( argv[arg], "-p" ) ) {
      if ( argc > arg + 2 ) {
        arg++;
        alpha = atof(argv[arg++]);
        delta = atof(argv[arg++]);
	parDem.skyPatch.alpha = alpha;
        parDem.skyPatch.delta = delta;
      } else {
        ERROR( VALIDATION1_EARG, VALIDATION1_MSGEARG, 0 );
        XLALPrintError( USAGE, *argv );
        return VALIDATION1_EARG;
      }
    }
    /* Parse patch size option. */
    else if ( !strcmp( argv[arg], "-s" ) ) {
      if ( argc > arg + 2 ) {
        arg++;
        parRes.patchSkySizeX = patchSizeX = atof(argv[arg++]);
        parRes.patchSkySizeY = patchSizeY = atof(argv[arg++]);
      } else {
        ERROR( VALIDATION1_EARG, VALIDATION1_MSGEARG, 0 );
        XLALPrintError( USAGE, *argv );
        return VALIDATION1_EARG;
      }
    }
    /* Unrecognized option. */
    else {
      ERROR( VALIDATION1_EARG, VALIDATION1_MSGEARG, 0 );
      XLALPrintError( USAGE, *argv );
      return VALIDATION1_EARG;
    }
  } /* End of argument parsing loop. */
  /******************************************************************/

  if ( f0 < 0 ) {
    ERROR( VALIDATION1_EBAD, VALIDATION1_MSGEBAD, "freq<0:" );
    XLALPrintError( USAGE, *argv  );
    return VALIDATION1_EBAD;
  }

  /******************************************************************/
  /******************************************************************/
  /* create time stamps (for a test) */
  /******************************************************************/
  timeV.time = (LIGOTimeGPS *)LALMalloc(mObsCoh*sizeof(LIGOTimeGPS));
  timeV.time[0].gpsSeconds = T0SEC;
  timeV.time[0].gpsNanoSeconds = T0NSEC;
  for(j=1; j<timeV.length; ++j){
    timeV.time[j].gpsSeconds = timeV.time[j-1].gpsSeconds + TCOH + JUMPTIME;
    timeV.time[j].gpsNanoSeconds = T0NSEC;
  }

  /******************************************************************/
  /* compute detector velocity for those time stamps (for a test) */
  /******************************************************************/

  velV.data = (REAL8Cart3Coor *)LALMalloc(mObsCoh*sizeof(REAL8Cart3Coor));
  velPar.edat = NULL; 
  {
    EphemerisData    *edat=NULL;
   
    /*  ephemeris info */
    edat = (EphemerisData *)LALMalloc(sizeof(EphemerisData));
   (*edat).ephiles.earthEphemeris = earthEphemeris;
   (*edat).ephiles.sunEphemeris = sunEphemeris;

    /* read in ephemeris data */
    SUB( LALInitBarycenter( &status, edat), &status);
    velPar.edat = edat;
    
    for(j=0; j<velV.length; ++j){
      velPar.startTime.gpsSeconds     = timeV.time[j].gpsSeconds;
      velPar.startTime.gpsNanoSeconds = timeV.time[j].gpsNanoSeconds;
    
      SUB( LALAvgDetectorVel ( &status, vel, &velPar), &status );
      velV.data[j].x= vel[0];
      velV.data[j].y= vel[1];
      velV.data[j].z= vel[2];   
    }
    LALFree(edat->ephemE);
    LALFree(edat->ephemS);
    LALFree(edat);
  }

  /******************************************************************/  
  /******************************************************************/
  /* create patch grid */
  /******************************************************************/

  SUB( LALHOUGHComputeNDSizePar( &status, &parSize, &parRes ),  &status );
  
  xSide = parSize.xSide;
  ySide = parSize.ySide;
  maxNBins = parSize.maxNBins;
  maxNBorders = parSize.maxNBorders;

  /* allocate memory based on xSide and ySide */
  patch.xSide = xSide;
  patch.ySide = ySide;
  
  /* allocate memory based on xSide and ySide */
  patch.xCoor = NULL;
  patch.yCoor = NULL;
  patch.xCoor = (REAL8 *)LALMalloc(xSide*sizeof(REAL8));
  patch.yCoor = (REAL8 *)LALMalloc(ySide*sizeof(REAL8));

  SUB( LALHOUGHFillPatchGrid( &status, &patch, &parSize ), &status );

  /******************************************************************/
  /******************************************************************/
  /* memory allocation and settings */
  /******************************************************************/

  lutV.lut = (HOUGHptfLUT *)LALMalloc(mObsCoh*sizeof(HOUGHptfLUT));
  pgV.pg = (HOUGHPeakGram *)LALMalloc(mObsCoh*sizeof(HOUGHPeakGram));
  phmdVS.phmd =(HOUGHphmd *)LALMalloc(mObsCoh*NFSIZE*sizeof(HOUGHphmd));
  freqInd.data =  ( UINT8 *)LALMalloc(mObsCoh*sizeof(UINT8));

  for(j=0; j<lutV.length; ++j){
    lutV.lut[j].maxNBins = maxNBins;
    lutV.lut[j].maxNBorders = maxNBorders;
    lutV.lut[j].border =
         (HOUGHBorder *)LALMalloc(maxNBorders*sizeof(HOUGHBorder));
    lutV.lut[j].bin =
         (HOUGHBin2Border *)LALMalloc(maxNBins*sizeof(HOUGHBin2Border));
  }

  for(j=0; j<phmdVS.length * phmdVS.nfSize; ++j){
    phmdVS.phmd[j].maxNBorders = maxNBorders;
    phmdVS.phmd[j].leftBorderP =
       (HOUGHBorder **)LALMalloc(maxNBorders*sizeof(HOUGHBorder *));
    phmdVS.phmd[j].rightBorderP =
       (HOUGHBorder **)LALMalloc(maxNBorders*sizeof(HOUGHBorder *));
  }


  ht.xSide = xSide;
  ht.ySide = ySide;
  ht.map   = NULL;
  ht.map   = (HoughTT *)LALMalloc(xSide*ySide*sizeof(HoughTT));

  for(j=0; j<phmdVS.length * phmdVS.nfSize; ++j){
    phmdVS.phmd[j].ySide = ySide;
    phmdVS.phmd[j].firstColumn = NULL;
    phmdVS.phmd[j].firstColumn = (UCHAR *)LALMalloc(ySide*sizeof(UCHAR));
  }

  for (j=0; j<lutV.length ; ++j){
    for (i=0; i<maxNBorders; ++i){
      lutV.lut[j].border[i].ySide = ySide;
      lutV.lut[j].border[i].xPixel =
                            (COORType *)LALMalloc(ySide*sizeof(COORType));
    }
  }
  
  /******************************************************************/
  /******************************************************************/
  /* create Peakgrams for testing                                   */
  /******************************************************************/

  /* let us fix a source at a given position 
     (not at the center of the patch, but a pixel center) */
  { 
    UINT2              xPos, yPos;
    REAL8Cart2Coor     sourceProjected;
    REAL8UnitPolarCoor sourceRotated;
    REAL8UnitPolarCoor skyPatchCenter;
    REAL8UnitPolarCoor sourceLocation;
   
    xPos = xSide/2;
    yPos = ySide/2;

     sourceProjected.x = patch.xCoor[xPos];
    sourceProjected.y = patch.yCoor[yPos];
    skyPatchCenter.alpha = parDem.skyPatch.alpha;
    skyPatchCenter.delta = parDem.skyPatch.delta;
    
    /* invert the stereographic projection for a point on the projected plane */
    SUB( LALStereoInvProjectCart( &status, &sourceRotated, &sourceProjected ), &status );
 
    /* undo roation in case the patch is not centered at the south pole */
    SUB( LALInvRotatePolarU( &status, &sourceLocation, &sourceRotated, &skyPatchCenter ), &status );

    Xx= cos(sourceLocation.delta)* cos(sourceLocation.alpha);
    Xy= cos(sourceLocation.delta)* sin(sourceLocation.alpha);
    Xz= sin(sourceLocation.delta); 
  }
  
  for (j=0;j< mObsCoh; ++j) {  /* create all the peakgrams */
    REAL8 veldotX;
    
    pgV.pg[j].deltaF = DF;
/*
 *     pgV.pg[j].fBinIni = f0Bin/2; 
 *     pgV.pg[j].fBinFin = f0Bin*2;
 */
    pgV.pg[j].fBinIni = f0Bin-maxNBins; 
    pgV.pg[j].fBinFin = f0Bin+3*maxNBins;
    /* pgV.pg[j].length = 2; */
    pgV.pg[j].length = 1; 
    pgV.pg[j].peak = NULL;
    pgV.pg[j].peak = (INT4 *)LALMalloc( ( pgV.pg[j].length) * sizeof(INT4));
    
    veldotX = Xx*velV.data[j].x + Xy*velV.data[j].y + Xz*velV.data[j].z;
    /*  fBin = [ f0Bin * ( 1 + veldotX ) ] */
    pgV.pg[j].peak[0]= floor( f0Bin*(1.0+veldotX) +0.5) - pgV.pg[j].fBinIni;
     /* pgV.pg[j].peak[1]= pgV.pg[j].peak[0]+2; */
   
  }
 

 
  /******************************************************************/
  /******************************************************************/
  /* create            all the LUTs                           */
  /******************************************************************/
         
  for (j=0;j< mObsCoh;++j){  /* create all the LUTs */
    parDem.veloC.x = velV.data[j].x;
    parDem.veloC.y = velV.data[j].y;
    parDem.veloC.z = velV.data[j].z;
    
    /* calculate parameters needed for buiding the LUT */
    SUB( LALNDHOUGHParamPLUT( &status, &parLut, &parSize, &parDem ), &status );

    /* build the LUT */
    SUB( LALHOUGHConstructPLUT( &status, &(lutV.lut[j]), &patch, &parLut ),
         &status );
  }

  /******************************************************************/
  /* starting the search  (A very simple case for only 1 frequency) */
  /******************************************************************/
  /* build the set of  PHMD  starting at f0Bin*/
  /******************************************************************/
  fBin = f0Bin;
  phmdVS.fBinMin = fBin;
  SUB( LALHOUGHConstructSpacePHMD(&status, &phmdVS, &pgV, &lutV), &status );

  /* shift the structure one frequency bin */
  /*  SUB( LALHOUGHupdateSpacePHMDup(&status, &phmdVS, &pgV, &lutV), &status );*/


  /******************************************************************/
  /* initializing the Hough map space */
  /******************************************************************/

  SUB( LALHOUGHInitializeHT( &status, &ht, &patch ), &status );

  /******************************************************************/
  /* construction of a total Hough map  */
  /******************************************************************/

  for (j=0;j< mObsCoh;++j){
    freqInd.data[j]= fBin;
  }

  SUB( LALHOUGHConstructHMT( &status, &ht, &freqInd, &phmdVS ), &status );
  /******************************************************************/
  /* printing the results into a particular file                    */
  /* if the -o option was given, or into  FILEOUT                   */
  /******************************************************************/

  if ( fname ) {
    fp = fopen( fname, "w" );
  } else {
    fp = fopen( FILEOUT , "w" );
  }

  if ( !fp ){
    ERROR( VALIDATION1_EFILE, VALIDATION1_MSGEFILE, 0 );
    return VALIDATION1_EFILE;
  }


  for(k=ySide-1; k>=0; --k){
    for(i=0;i<xSide;++i){
      fprintf( fp ," %d", ht.map[k*xSide +i]);
      fflush( fp );
    }
    fprintf( fp ," \n");
    fflush( fp );
  }

  fclose( fp );


  /******************************************************************/
  /* Free memory and exit */
  /******************************************************************/
  for (j=0;j< mObsCoh;++j){
    LALFree( pgV.pg[j].peak);  /* All of them */
  }


  for (j=0; j<lutV.length ; ++j){
    for (i=0; i<maxNBorders; ++i){
      LALFree( lutV.lut[j].border[i].xPixel);
    }
    LALFree( lutV.lut[j].border);
    LALFree( lutV.lut[j].bin);
  }

  for(j=0; j<phmdVS.length * phmdVS.nfSize; ++j){
    LALFree( phmdVS.phmd[j].leftBorderP);
    LALFree( phmdVS.phmd[j].rightBorderP);
    LALFree( phmdVS.phmd[j].firstColumn);
  }

  LALFree(timeV.time);
  LALFree(velV.data);

  LALFree(lutV.lut);
  LALFree(pgV.pg);
  LALFree(phmdVS.phmd);
  LALFree(freqInd.data);

  LALFree(ht.map);

  LALFree(patch.xCoor);
  LALFree(patch.yCoor);

  LALCheckMemoryLeaks();

  INFO( VALIDATION1_MSGENORM );
  return VALIDATION1_ENORM;
}
Ejemplo n.º 21
0
/**
 * Write a multi-PSD into spectrograms for each IFO.
 * Using gnuplot 'binary' matrix format
 * The filename for each IFO is generated as 'bname-IFO'
 */
void
LALfwriteSpectrograms ( LALStatus *status, const CHAR* bname, const MultiPSDVector *multiPSD )
{
  UINT4 X;
  CHAR *fname;
  float num, *row_data;		/* cast to float for writing (gnuplot binary format) */
  FILE *fp;

  INITSTATUS(status);
  ATTATCHSTATUSPTR (status);

  if ( !bname || !multiPSD || multiPSD->length == 0 ) {
    ABORT ( status, COMPUTEPSDC_ENULL, COMPUTEPSDC_MSGENULL );
  }

  /* loop over IFOs */
  for ( X = 0; X < multiPSD->length ; X ++ )
    {
      UINT4 len = strlen ( bname ) + 4;	/* append '-XN' to get IFO-specific filename */
      UINT4 numSFTs, numBins;
      UINT4 j, k;
      const CHAR *tmp;
      REAL8 f0, df;

      numSFTs = multiPSD->data[X]->length;
      numBins = multiPSD->data[X]->data[0].data->length;

      /* allocate memory for data row-vector */
      if ( ( row_data = LALMalloc ( numBins * sizeof(float) )) == NULL ) {
	ABORT ( status, COMPUTEPSDC_EMEM, COMPUTEPSDC_MSGEMEM );
      }

      if ( ( fname = LALMalloc ( len * sizeof(CHAR) )) == NULL ) {
	LALFree ( row_data );
	ABORT ( status, COMPUTEPSDC_EMEM, COMPUTEPSDC_MSGEMEM );
      }
      tmp = multiPSD->data[X]->data[0].name;
      sprintf ( fname, "%s-%c%c", bname, tmp[0], tmp[1] );

      if ( ( fp = fopen( fname, "wb" ))  == NULL ) {
	LogPrintf (LOG_CRITICAL, "Failed to open spectrogram file '%s' for writing!\n", fname );
	goto failed;

      }

      /* write number of columns: i.e. frequency-bins */
      num = (float)numBins;
      if ((fwrite((char *) &num, sizeof(float), 1, fp)) != 1) {
	LogPrintf (LOG_CRITICAL, "Failed to fwrite() to spectrogram file '%s'\n", fname );
	goto failed;
      }

      /* write frequencies as column-titles */
      f0 = multiPSD->data[X]->data[0].f0;
      df = multiPSD->data[X]->data[0].deltaF;
      for ( k=0; k < numBins; k ++ )
	row_data[k] = (float) ( f0 + 1.0 * k * df );
      if ( fwrite((char *) row_data, sizeof(float), numBins, fp) != numBins ) {
	LogPrintf (LOG_CRITICAL, "Failed to fwrite() to spectrogram file '%s'\n", fname );
	goto failed;
      }

      /* write PSDs of successive SFTs in rows, first column is GPS-time in seconds */
      for ( j = 0; j < numSFTs ; j ++ )
	{
	  num = (float) multiPSD->data[X]->data[j].epoch.gpsSeconds;
	  for ( k = 0; k < numBins; k ++ )
	    row_data[k] = (float) sqrt ( multiPSD->data[X]->data[j].data->data[k] );

	  if ( ( fwrite((char *) &num, sizeof(float), 1, fp) != 1 ) ||
	       ( fwrite((char *) row_data, sizeof(float), numBins, fp) != numBins ) ) {
	    LogPrintf (LOG_CRITICAL, "Failed to fwrite() to spectrogram file '%s'\n", fname );
	    goto failed;
	  }

	} /* for j < numSFTs */

      fclose ( fp );
      LALFree ( fname );
      LALFree ( row_data );

    } /* for X < numIFOs */

  DETATCHSTATUSPTR (status);
  RETURN (status);

  /* cleanup and exit on write-error */
 failed:
  if ( fname ) LALFree ( fname );
  if ( row_data ) LALFree ( row_data );
  if ( fp ) fclose ( fp );
  ABORT ( status, COMPUTEPSDC_EFILE, COMPUTEPSDC_MSGEFILE );

} /* LALfwriteSpectrograms() */
/**
 * \author Creighton, T. D.
 *
 * \brief Computes a continuous waveform with frequency drift and Doppler
 * modulation from a parabolic orbital trajectory.
 *
 * This function computes a quaiperiodic waveform using the spindown and
 * orbital parameters in <tt>*params</tt>, storing the result in
 * <tt>*output</tt>.
 *
 * In the <tt>*params</tt> structure, the routine uses all the "input"
 * fields specified in \ref GenerateSpinOrbitCW_h, and sets all of the
 * "output" fields.  If <tt>params-\>f</tt>=\c NULL, no spindown
 * modulation is performed.  If <tt>params-\>oneMinusEcc</tt>\f$\neq0\f$, or if
 * <tt>params-\>rPeriNorm</tt>\f$\times\f$<tt>params-\>angularSpeed</tt>\f$\geq1\f$
 * (faster-than-light speed at periapsis), an error is returned.
 *
 * In the <tt>*output</tt> structure, the field <tt>output-\>h</tt> is
 * ignored, but all other pointer fields must be set to \c NULL.  The
 * function will create and allocate space for <tt>output-\>a</tt>,
 * <tt>output-\>f</tt>, and <tt>output-\>phi</tt> as necessary.  The
 * <tt>output-\>shift</tt> field will remain set to \c NULL.
 *
 * ### Algorithm ###
 *
 * For parabolic orbits, we combine \eqref{eq_spinorbit-tr},
 * \eqref{eq_spinorbit-t}, and \eqref{eq_spinorbit-upsilon} to get \f$t_r\f$
 * directly as a function of \f$E\f$:
 * \f{equation}{
 * \label{eq_cubic-e}
 * t_r = t_p + \frac{r_p\sin i}{c} \left[ \cos\omega +
 * \left(\frac{1}{v_p} + \cos\omega\right)E -
 * \frac{\sin\omega}{4}E^2 + \frac{1}{12v_p}E^3\right] \;,
 * \f}
 * where \f$v_p=r_p\dot{\upsilon}_p\sin i/c\f$ is a normalized velocity at
 * periapsis.  Following the prescription for the general analytic
 * solution to the real cubic equation, we substitute
 * \f$E=x+3v_p\sin\omega\f$ to obtain:
 * \f{equation}{
 * \label{eq_cubic-x}
 * x^3 + px = q \;,
 * \f}
 * where:
 * \f{eqnarray}{
 * \label{eq_cubic-p}
 * p & = & 12 + 12v_p\cos\omega - 3v_p^2\sin^2\omega \;, \\
 * \label{eq_cubic-q}
 * q & = & 12v_p^2\sin\omega\cos\omega - 24v_p\sin\omega +
 * 2v_p^3\sin^3\omega + 12\dot{\upsilon}_p(t_r-t_p) \;.
 * \f}
 * We note that \f$p>0\f$ is guaranteed as long as \f$v_p<1\f$, so the right-hand
 * side of \eqref{eq_cubic-x} is monotonic in \f$x\f$ and has exactly one
 * root.  However, \f$p\rightarrow0\f$ in the limit \f$v_p\rightarrow1\f$ and
 * \f$\omega=\pi\f$.  This may cause some loss of precision in subsequent
 * calculations.  But \f$v_p\sim1\f$ means that our solution will be
 * inaccurate anyway because we ignore significant relativistic effects.
 *
 * Since \f$p>0\f$, we can substitute \f$x=y\sqrt{3/4p}\f$ to obtain:
 * \f{equation}{
 * 4y^3 + 3y = \frac{q}{2}\left(\frac{3}{p}\right)^{3/2} \equiv C \;.
 * \f}
 * Using the triple-angle hyperbolic identity
 * \f$\sinh(3\theta)=4\sinh^3\theta+3\sinh\theta\f$, we have
 * \f$y=\sinh\left(\frac{1}{3}\sinh^{-1}C\right)\f$.  The solution to the
 * original cubic equation is then:
 * \f{equation}{
 * E = 3v_p\sin\omega + 2\sqrt{\frac{p}{3}}
 * \sinh\left(\frac{1}{3}\sinh^{-1}C\right) \;.
 * \f}
 * To ease the calculation of \f$E\f$, we precompute the constant part
 * \f$E_0=3v_p\sin\omega\f$ and the coefficient \f$\Delta E=2\sqrt{p/3}\f$.
 * Similarly for \f$C\f$, we precompute a constant piece \f$C_0\f$ evaluated at
 * the epoch of the output time series, and a stepsize coefficient
 * \f$\Delta C=6(p/3)^{3/2}\dot{\upsilon}_p\Delta t\f$, where \f$\Delta t\f$ is
 * the step size in the (output) time series in \f$t_r\f$.  Thus at any
 * timestep \f$i\f$, we obtain \f$C\f$ and hence \f$E\f$ via:
 * \f{eqnarray}{
 * C & = & C_0 + i\Delta C \;,\\
 * E & = & E_0 + \Delta E\times\left\{\begin{array}{l@{\qquad}c}
 * \sinh\left[\frac{1}{3}\ln\left(
 * C + \sqrt{C^2+1} \right) \right]\;, & C\geq0 \;,\\ \\
 * \sinh\left[-\frac{1}{3}\ln\left(
 * -C + \sqrt{C^2+1} \right) \right]\;, & C\leq0 \;,\\
 * \end{array}\right.
 * \f}
 * where we have explicitly written \f$\sinh^{-1}\f$ in terms of functions in
 * \c math.h.  Once \f$E\f$ is found, we can compute
 * \f$t=E(12+E^2)/(12\dot{\upsilon}_p)\f$ (where again \f$1/12\dot{\upsilon}_p\f$
 * can be precomputed), and hence \f$f\f$ and \f$\phi\f$ via
 * \eqref{eq_taylorcw-freq} and \eqref{eq_taylorcw-phi}.  The
 * frequency \f$f\f$ must then be divided by the Doppler factor:
 * \f[
 * 1 + \frac{\dot{R}}{c} = 1 + \frac{v_p}{4+E^2}\left(
 * 4\cos\omega - 2E\sin\omega \right)
 * \f]
 * (where once again \f$4\cos\omega\f$ and \f$2\sin\omega\f$ can be precomputed).
 *
 * This routine does not account for relativistic timing variations, and
 * issues warnings or errors based on the criterea of
 * \eqref{eq_relativistic-orbit} in GenerateEllipticSpinOrbitCW().
 * The routine will also warn if
 * it seems likely that \c REAL8 precision may not be sufficient to
 * track the orbit accurately.  We estimate that numerical errors could
 * cause the number of computed wave cycles to vary by
 * \f[
 * \Delta N \lesssim f_0 T\epsilon\left[
 * \sim6+\ln\left(|C|+\sqrt{|C|^2+1}\right)\right] \;,
 * \f]
 * where \f$|C|\f$ is the maximum magnitude of the variable \f$C\f$ over the
 * course of the computation, \f$f_0T\f$ is the approximate total number of
 * wave cycles over the computation, and \f$\epsilon\approx2\times10^{-16}\f$
 * is the fractional precision of \c REAL8 arithmetic.  If this
 * estimate exceeds 0.01 cycles, a warning is issued.
 */
void
LALGenerateParabolicSpinOrbitCW( LALStatus             *stat,
				 PulsarCoherentGW            *output,
				 SpinOrbitCWParamStruc *params )
{
  UINT4 n, i;              /* number of and index over samples */
  UINT4 nSpin = 0, j;      /* number of and index over spindown terms */
  REAL8 t, dt, tPow;       /* time, interval, and t raised to a power */
  REAL8 phi0, f0, twopif0; /* initial phase, frequency, and 2*pi*f0 */
  REAL8 f, fPrev;      /* current and previous values of frequency */
  REAL4 df = 0.0;      /* maximum difference between f and fPrev */
  REAL8 phi;           /* current value of phase */
  REAL8 vp;            /* projected speed at periapsis */
  REAL8 argument;      /* argument of periapsis */
  REAL8 fourCosOmega;  /* four times the cosine of argument */
  REAL8 twoSinOmega;   /* two times the sine of argument */
  REAL8 vpCosOmega;    /* vp times cosine of argument */
  REAL8 vpSinOmega;    /* vp times sine of argument */
  REAL8 vpSinOmega2;   /* vpSinOmega squared */
  REAL8 vDot6;         /* 6 times angular speed at periapsis */
  REAL8 oneBy12vDot;   /* one over (12 times angular speed) */
  REAL8 pBy3;          /* constant sqrt(p/3) in cubic equation */
  REAL8 p32;           /* constant (p/3)^1.5 in cubic equation */
  REAL8 c, c0, dc;     /* C variable, offset, and step increment */
  REAL8 e, e2, e0;     /* E variable, E^2, and constant piece of E */
  REAL8 de;            /* coefficient of sinh() piece of E */
  REAL8 tpOff;         /* orbit epoch - time series epoch (s) */
  REAL8 spinOff;       /* spin epoch - orbit epoch (s) */
  REAL8 *fSpin = NULL; /* pointer to Taylor coefficients */
  REAL4 *fData;        /* pointer to frequency data */
  REAL8 *phiData;      /* pointer to phase data */

  INITSTATUS(stat);
  ATTATCHSTATUSPTR( stat );

  /* Make sure parameter and output structures exist. */
  ASSERT( params, stat, GENERATESPINORBITCWH_ENUL,
	  GENERATESPINORBITCWH_MSGENUL );
  ASSERT( output, stat, GENERATESPINORBITCWH_ENUL,
	  GENERATESPINORBITCWH_MSGENUL );

  /* Make sure output fields don't exist. */
  ASSERT( !( output->a ), stat, GENERATESPINORBITCWH_EOUT,
	  GENERATESPINORBITCWH_MSGEOUT );
  ASSERT( !( output->f ), stat, GENERATESPINORBITCWH_EOUT,
	  GENERATESPINORBITCWH_MSGEOUT );
  ASSERT( !( output->phi ), stat, GENERATESPINORBITCWH_EOUT,
	  GENERATESPINORBITCWH_MSGEOUT );
  ASSERT( !( output->shift ), stat, GENERATESPINORBITCWH_EOUT,
	  GENERATESPINORBITCWH_MSGEOUT );

  /* If Taylor coeficients are specified, make sure they exist. */
  if ( params->f ) {
    ASSERT( params->f->data, stat, GENERATESPINORBITCWH_ENUL,
	    GENERATESPINORBITCWH_MSGENUL );
    nSpin = params->f->length;
    fSpin = params->f->data;
  }

  /* Set up some constants (to avoid repeated calculation or
     dereferencing), and make sure they have acceptable values. */
  vp = params->rPeriNorm*params->angularSpeed;
  vDot6 = 6.0*params->angularSpeed;
  n = params->length;
  dt = params->deltaT;
  f0 = fPrev = params->f0;
  if ( params->oneMinusEcc != 0.0 ) {
    ABORT( stat, GENERATESPINORBITCWH_EECC,
	   GENERATESPINORBITCWH_MSGEECC );
  }
  if ( vp >= 1.0 ) {
    ABORT( stat, GENERATESPINORBITCWH_EFTL,
	   GENERATESPINORBITCWH_MSGEFTL );
  }
  if ( vp <= 0.0 || dt <= 0.0 || f0 <= 0.0 || vDot6 <= 0.0 ||
       n == 0 ) {
    ABORT( stat, GENERATESPINORBITCWH_ESGN,
	   GENERATESPINORBITCWH_MSGESGN );
  }
#ifndef NDEBUG
  if ( lalDebugLevel & LALWARNING ) {
    if ( f0*n*dt*vp*vp > 0.5 )
      LALWarning( stat, "Orbit may have significant relativistic"
		  " effects that are not included" );
  }
#endif

  /* Compute offset between time series epoch and periapsis, and
     betweem periapsis and spindown reference epoch. */
  tpOff = (REAL8)( params->orbitEpoch.gpsSeconds -
		   params->epoch.gpsSeconds );
  tpOff += 1.0e-9 * (REAL8)( params->orbitEpoch.gpsNanoSeconds -
			     params->epoch.gpsNanoSeconds );
  spinOff = (REAL8)( params->orbitEpoch.gpsSeconds -
		     params->spinEpoch.gpsSeconds );
  spinOff += 1.0e-9 * (REAL8)( params->orbitEpoch.gpsNanoSeconds -
			       params->spinEpoch.gpsNanoSeconds );

  /* Set up some other constants. */
  twopif0 = f0*LAL_TWOPI;
  phi0 = params->phi0;
  argument = params->omega;
  oneBy12vDot = 0.5/vDot6;
  fourCosOmega = 4.0*cos( argument );
  twoSinOmega = 2.0*sin( argument );
  vpCosOmega = 0.25*vp*fourCosOmega;
  vpSinOmega = 0.5*vp*twoSinOmega;
  vpSinOmega2 = vpSinOmega*vpSinOmega;
  pBy3 = sqrt( 4.0*( 1.0 + vpCosOmega ) - vpSinOmega2 );
  p32 = 1.0/( pBy3*pBy3*pBy3 );
  c0 = p32*( vpSinOmega*( 6.0*vpCosOmega - 12.0 + vpSinOmega2 ) -
	     tpOff*vDot6 );
  dc = p32*vDot6*dt;
  e0 = 3.0*vpSinOmega;
  de = 2.0*pBy3;

  /* Check whether REAL8 precision is good enough. */
#ifndef NDEBUG
  if ( lalDebugLevel & LALWARNING ) {
    REAL8 x = fabs( c0 + n*dc ); /* a temporary computation variable */
    if ( x < fabs( c0 ) )
      x = fabs( c0 );
    x = 6.0 + log( x + sqrt( x*x + 1.0 ) );
    if ( LAL_REAL8_EPS*f0*dt*n*x > 0.01 )
      LALWarning( stat, "REAL8 arithmetic may not have sufficient"
		  " precision for this orbit" );
  }
#endif

  /* Allocate output structures. */
  if ( ( output->a = (REAL4TimeVectorSeries *)
	 LALMalloc( sizeof(REAL4TimeVectorSeries) ) ) == NULL ) {
    ABORT( stat, GENERATESPINORBITCWH_EMEM,
	   GENERATESPINORBITCWH_MSGEMEM );
  }
  memset( output->a, 0, sizeof(REAL4TimeVectorSeries) );
  if ( ( output->f = (REAL4TimeSeries *)
	 LALMalloc( sizeof(REAL4TimeSeries) ) ) == NULL ) {
    LALFree( output->a ); output->a = NULL;
    ABORT( stat, GENERATESPINORBITCWH_EMEM,
	   GENERATESPINORBITCWH_MSGEMEM );
  }
  memset( output->f, 0, sizeof(REAL4TimeSeries) );
  if ( ( output->phi = (REAL8TimeSeries *)
	 LALMalloc( sizeof(REAL8TimeSeries) ) ) == NULL ) {
    LALFree( output->a ); output->a = NULL;
    LALFree( output->f ); output->f = NULL;
    ABORT( stat, GENERATESPINORBITCWH_EMEM,
	   GENERATESPINORBITCWH_MSGEMEM );
  }
  memset( output->phi, 0, sizeof(REAL8TimeSeries) );

  /* Set output structure metadata fields. */
  output->position = params->position;
  output->psi = params->psi;
  output->a->epoch = output->f->epoch = output->phi->epoch
    = params->epoch;
  output->a->deltaT = n*params->deltaT;
  output->f->deltaT = output->phi->deltaT = params->deltaT;
  output->a->sampleUnits = lalStrainUnit;
  output->f->sampleUnits = lalHertzUnit;
  output->phi->sampleUnits = lalDimensionlessUnit;
  snprintf( output->a->name, LALNameLength, "CW amplitudes" );
  snprintf( output->f->name, LALNameLength, "CW frequency" );
  snprintf( output->phi->name, LALNameLength, "CW phase" );

  /* Allocate phase and frequency arrays. */
  LALSCreateVector( stat->statusPtr, &( output->f->data ), n );
  BEGINFAIL( stat ) {
    LALFree( output->a );   output->a = NULL;
    LALFree( output->f );   output->f = NULL;
    LALFree( output->phi ); output->phi = NULL;
  } ENDFAIL( stat );
  LALDCreateVector( stat->statusPtr, &( output->phi->data ), n );
  BEGINFAIL( stat ) {
    TRY( LALSDestroyVector( stat->statusPtr, &( output->f->data ) ),
	 stat );
    LALFree( output->a );   output->a = NULL;
    LALFree( output->f );   output->f = NULL;
    LALFree( output->phi ); output->phi = NULL;
  } ENDFAIL( stat );

  /* Allocate and fill amplitude array. */
  {
    CreateVectorSequenceIn in; /* input to create output->a */
    in.length = 2;
    in.vectorLength = 2;
    LALSCreateVectorSequence( stat->statusPtr, &(output->a->data), &in );
    BEGINFAIL( stat ) {
      TRY( LALSDestroyVector( stat->statusPtr, &( output->f->data ) ),
	   stat );
      TRY( LALDDestroyVector( stat->statusPtr, &( output->phi->data ) ),
	   stat );
      LALFree( output->a );   output->a = NULL;
      LALFree( output->f );   output->f = NULL;
      LALFree( output->phi ); output->phi = NULL;
    } ENDFAIL( stat );
    output->a->data->data[0] = output->a->data->data[2] = params->aPlus;
    output->a->data->data[1] = output->a->data->data[3] = params->aCross;
  }

  /* Fill frequency and phase arrays. */
  fData = output->f->data->data;
  phiData = output->phi->data->data;
  for ( i = 0; i < n; i++ ) {

    /* Compute emission time. */
    c = c0 + dc*i;
    if ( c > 0 )
      e = e0 + de*sinh( log( c + sqrt( c*c + 1.0 ) )/3.0 );
    else
      e = e0 + de*sinh( -log( -c + sqrt( c*c + 1.0 ) )/3.0 );
    e2 = e*e;
    phi = t = tPow = oneBy12vDot*e*( 12.0 + e2 );

    /* Compute source emission phase and frequency. */
    f = 1.0;
    for ( j = 0; j < nSpin; j++ ) {
      f += fSpin[j]*tPow;
      phi += fSpin[j]*( tPow*=t )/( j + 2.0 );
    }

    /* Appy frequency Doppler shift. */
    f *= f0 / ( 1.0 + vp*( fourCosOmega - e*twoSinOmega )
		/( 4.0 + e2 ) );
    phi *= twopif0;
    if ( fabs( f - fPrev ) > df )
      df = fabs( f - fPrev );
    *(fData++) = fPrev = f;
    *(phiData++) = phi + phi0;
  }

  /* Set output field and return. */
  params->dfdt = df*dt;
  DETATCHSTATUSPTR( stat );
  RETURN( stat );
}
Ejemplo n.º 23
0
void
LALGenerateRing(
    LALStatus          *stat,
    CoherentGW         *output,
    REAL4TimeSeries    UNUSED *series,
    SimRingdownTable   *simRingdown,
    RingParamStruc     *params
    )

{
  UINT4 i;      /* number of and index over samples */
  REAL8 t, dt;         /* time, interval */
  REAL8 gtime ;    /* central time, decay time */
  REAL8 f0, quality;   /* frequency and quality factor */
  REAL8 twopif0;       /* 2*pi*f0 */
  REAL4 h0;            /* peak strain for ringdown */
  REAL4 *fData;        /* pointer to frequency data */
  REAL8 *phiData;      /* pointer to phase data */
  REAL8 init_phase;    /*initial phase of injection */
  REAL4 *aData;        /* pointer to frequency data */
  UINT4 nPointInj; /* number of data points in a block */
#if 0
  UINT4 n;
  REAL8 t0;
  REAL4TimeSeries signalvec; /* start time of block that injection is injected into */
  LALTimeInterval  interval;
  INT8 geoc_tns;       /* geocentric_start_time of the injection in ns */
  INT8 block_tns;      /* start time of block in ns */
  REAL8 deltaTns;
  INT8 inj_diff;       /* time between start of segment and injection */
  LALTimeInterval dummyInterval;
#endif

  INITSTATUS(stat);
  ATTATCHSTATUSPTR( stat );

  /* Make sure parameter and output structures exist. */
  ASSERT( params, stat, GENERATERINGH_ENUL,
	  GENERATERINGH_MSGENUL );
  ASSERT( output, stat, GENERATERINGH_ENUL,
	  GENERATERINGH_MSGENUL );

  /* Make sure output fields don't exist. */
  ASSERT( !( output->a ), stat, GENERATERINGH_EOUT,
	  GENERATERINGH_MSGEOUT );
  ASSERT( !( output->f ), stat, GENERATERINGH_EOUT,
	  GENERATERINGH_MSGEOUT );
  ASSERT( !( output->phi ), stat, GENERATERINGH_EOUT,
	  GENERATERINGH_MSGEOUT );
  ASSERT( !( output->shift ), stat, GENERATERINGH_EOUT,
	  GENERATERINGH_MSGEOUT );


  /* Set up some other constants, to avoid repeated dereferencing. */
  dt = params->deltaT;
/* N_point = 2 * floor(0.5+ 1/ dt); */

  nPointInj = 163840;

  /* Generic ring parameters */
  h0 = simRingdown->amplitude;
  quality = (REAL8)simRingdown->quality;
  f0 = (REAL8)simRingdown->frequency;
  twopif0 = f0*LAL_TWOPI;
  init_phase = simRingdown->phase;


  if ( ( output->a = (REAL4TimeVectorSeries *)
	 LALMalloc( sizeof(REAL4TimeVectorSeries) ) ) == NULL ) {
    ABORT( stat, GENERATERINGH_EMEM, GENERATERINGH_MSGEMEM );
  }
  memset( output->a, 0, sizeof(REAL4TimeVectorSeries) );
  if ( ( output->f = (REAL4TimeSeries *)
	 LALMalloc( sizeof(REAL4TimeSeries) ) ) == NULL ) {
    LALFree( output->a ); output->a = NULL;
    ABORT( stat, GENERATERINGH_EMEM, GENERATERINGH_MSGEMEM );
  }
  memset( output->f, 0, sizeof(REAL4TimeSeries) );
  if ( ( output->phi = (REAL8TimeSeries *)
	 LALMalloc( sizeof(REAL8TimeSeries) ) ) == NULL ) {
    LALFree( output->a ); output->a = NULL;
    LALFree( output->f ); output->f = NULL;
    ABORT( stat, GENERATERINGH_EMEM, GENERATERINGH_MSGEMEM );
  }
  memset( output->phi, 0, sizeof(REAL8TimeSeries) );

  /* Set output structure metadata fields. */
  output->position.longitude = simRingdown->longitude;
  output->position.latitude = simRingdown->latitude;
  output->position.system = params->system;
  output->psi = simRingdown->polarization;
   /* set epoch of output time series to that of the block */
  output->a->epoch = output->f->epoch = output->phi->epoch = simRingdown->geocent_start_time;
  output->a->deltaT = params->deltaT;
  output->f->deltaT = output->phi->deltaT = params->deltaT;
  output->a->sampleUnits = lalStrainUnit;
  output->f->sampleUnits = lalHertzUnit;
  output->phi->sampleUnits = lalDimensionlessUnit;
  snprintf( output->a->name, LALNameLength, "Ring amplitudes" );
  snprintf( output->f->name, LALNameLength, "Ring frequency" );
  snprintf( output->phi->name, LALNameLength, "Ring phase" );


  /* Allocate phase and frequency arrays. */
  LALSCreateVector( stat->statusPtr, &( output->f->data ), nPointInj );
  BEGINFAIL( stat ) {
    LALFree( output->a );   output->a = NULL;
    LALFree( output->f );   output->f = NULL;
    LALFree( output->phi ); output->phi = NULL;
  } ENDFAIL( stat );

  LALDCreateVector( stat->statusPtr, &( output->phi->data ), nPointInj );
  BEGINFAIL( stat ) {
    TRY( LALSDestroyVector( stat->statusPtr, &( output->f->data ) ),
	 stat );
    LALFree( output->a );   output->a = NULL;
    LALFree( output->f );   output->f = NULL;
    LALFree( output->phi ); output->phi = NULL;
  } ENDFAIL( stat );


  /* Allocate amplitude array. */
  {
    CreateVectorSequenceIn in; /* input to create output->a */
    in.length = nPointInj;
    in.vectorLength = 2;
    LALSCreateVectorSequence( stat->statusPtr, &(output->a->data), &in );
    BEGINFAIL( stat ) {
      TRY( LALSDestroyVector( stat->statusPtr, &( output->f->data ) ),
	   stat );
      TRY( LALDDestroyVector( stat->statusPtr, &( output->phi->data ) ),
	   stat );
      LALFree( output->a );   output->a = NULL;
      LALFree( output->f );   output->f = NULL;
      LALFree( output->phi ); output->phi = NULL;
    } ENDFAIL( stat );
  }


  /*  set arrays to zero */
  memset( output->f->data->data, 0, sizeof( REAL4 ) *  output->f->data->length );
  memset( output->phi->data->data, 0, sizeof( REAL8 ) * output->phi->data->length );
  memset( output->a->data->data, 0, sizeof( REAL4 ) *
      output->a->data->length * output->a->data->vectorLength );

/* Fill frequency and phase arrays starting at time of injection NOT start */
  fData = output->f->data->data;
  phiData = output->phi->data->data;
  aData = output->a->data->data;

  if ( !( strcmp( simRingdown->waveform, "Ringdown" ) ) )
  {
    for ( i = 0; i < nPointInj; i++ )
    {
      t = i * dt;
      gtime = twopif0 / 2 / quality * t ;
      *(fData++)   = f0;
      *(phiData++) = twopif0 * t+init_phase;
      *(aData++) = h0 * ( 1.0 + pow( cos( simRingdown->inclination ), 2 ) ) *
        exp( - gtime );
      *(aData++) = h0* 2.0 * cos( simRingdown->inclination ) * exp( - gtime );
    }
  }
  else
  {
    ABORT( stat, GENERATERINGH_ETYP, GENERATERINGH_MSGETYP );
  }


/* Set output field and return. */
  DETATCHSTATUSPTR( stat );
  RETURN( stat );
}
Ejemplo n.º 24
0
/**
 * \author Creighton, T. D.
 * \ingroup TwoDMeshPlot_h
 * \brief Plots a hierarchical mesh of templates on an 2-dimensional parameter space.
 *
 * ### Description ###
 *
 * This routine creates a PostScript plot of the parameter mesh list
 * pointed to by \c mesh, using the plotting parameters given in
 * <tt>*params</tt>.  The PostScript output is printed to the writable
 * output stream <tt>*stream</tt> using <tt>fprintf()</tt>.
 *
 * ### Algorithm ###
 *
 * The algorithm is set up so that it requires only one pass through the
 * list.  After defining PostScript macros to plot mesh points, mesh
 * tiles, and mismatch ellipses, the routine then defines a macro to plot
 * the boundary.  Since some PostScript interpreters will fail if a macro
 * contains too many objects, the boundary-plotting macro may be split
 * into several macros.
 *
 * LALPlotTwoDMesh() then calls a static (but LAL-compliant)
 * subroutine LALMakeMeshMacro() to create one or more macros to
 * plot the mesh points, tiles, or ellipses, as required by
 * <tt>*params</tt>.  This subroutine takes a pointer to the head of a list
 * of mesh points as input, and traverses down the list, calling itself
 * recursively on any submeshes it encounters (if
 * <tt>params->maxLevels</tt> permits).
 *
 * While plotting the boundary and other mesh objects,
 * LALPlotTwoDMesh() and LALMakeMeshMacro() keep track of
 * the bounding box surrounding all plotted objects.  This is used either
 * to set a bounding box for the overall plot, or to adjust the scale of
 * the plot, depending on <tt>params->autoscale</tt>.  If the resulting
 * bounding box is larger than a single \f$8.5''\times11''\f$ page,
 * LALPlotTwoDMesh() will divide the plot area up into pages of
 * this side, calling the plotting macros on each page.
 *
 * ### Uses ###
 *
 * \code
 * LALMalloc()             LALFree()
 * \endcode
 *
 * ### Notes ###
 *
 */
void
LALPlotTwoDMesh( LALStatus         *stat,
		 FILE              *stream,
		 TwoDMeshNode      *mesh,
		 TwoDMeshPlotStruc *params )
{
  UINT4 i;          /* an index */
  UINT4 nObj = 0;   /* counter of number of objects boundary macro */
  UINT4 nMacro = 0; /* counter of number of boundary macros */
  UINT4 nPage = 0;  /* number of pages plotted */
  REAL4 bBox[4];    /* bounding box in plot coordinates */
  REAL4 xOff, yOff; /* horizontal and vertical offsets */
  MeshMacroParamStruc macroParams; /* parameters for
				      LALMakeMeshMacro() */

  INITSTATUS(stat);
  ATTATCHSTATUSPTR( stat );

  /* Check that arguments and their fields exist. */
  ASSERT( stream, stat, TWODMESHPLOTH_ENUL, TWODMESHPLOTH_MSGENUL );
  ASSERT( mesh, stat, TWODMESHPLOTH_ENUL, TWODMESHPLOTH_MSGENUL );
  ASSERT( params, stat, TWODMESHPLOTH_ENUL, TWODMESHPLOTH_MSGENUL );
  if ( params->nLevels ) {
    ASSERT( params->plotPoints, stat, TWODMESHPLOTH_ENUL,
	    TWODMESHPLOTH_MSGENUL );
    ASSERT( params->plotTiles, stat, TWODMESHPLOTH_ENUL,
	    TWODMESHPLOTH_MSGENUL );
    ASSERT( params->plotEllipses, stat, TWODMESHPLOTH_ENUL,
	    TWODMESHPLOTH_MSGENUL );
    ASSERT( params->params, stat, TWODMESHPLOTH_ENUL,
	    TWODMESHPLOTH_MSGENUL );
  }

  /* Perform some setup. */
  if ( params->autoscale )
    memcpy( bBox, params->bBox, 4*sizeof(REAL4) );
  params->bBox[0] = params->bBox[1] = LAL_REAL4_MAX;
  params->bBox[2] = params->bBox[3] = -LAL_REAL4_MAX;
  params->cosTheta = cos( LAL_PI_180*params->theta );
  params->sinTheta = sin( LAL_PI_180*params->theta );
  params->clip = ( ( params->clipBox[2] > params->clipBox[0] ) &&
		   ( params->clipBox[3] > params->clipBox[1] ) );

  /* Write the PostScript header. */
  fprintf( stream,
	   "%%!PS-Adobe-1.0\n"
	   "%%%%Creator: LALPlotTwoDMesh()\n"
	   "%%%%Title: mesh.ps\n"
	   "%%%%BoundingBox: %i %i %i %i\n"
	   "%%%%EndComments\n\n",
	   TWODMESHPLOTH_XMARG, TWODMESHPLOTH_YMARG,
	   TWODMESHPLOTH_XMARG + TWODMESHPLOTH_XSIZE,
	   TWODMESHPLOTH_YMARG + TWODMESHPLOTH_YSIZE );

  /* Write PostScript macros for plotting mesh points.  The macros are
     called simply as "point[N]", where [N] is the recursive submesh
     level. */
  for ( i = 0; i < params->nLevels; i++ )
    if ( params->plotPoints[i] > 0 )
      fprintf( stream,
	       "/point%u { gsave currentpoint translate %f %f scale\n"
	       "  auto auto scale %f rotate\n"
	       "  newpath 0 0 %u 0 360 arc closepath fill grestore }"
	       " def\n",
	       i, 1.0/params->xScale, 1.0/params->yScale,
	       -params->theta, params->plotPoints[i] );
    else if ( params->plotPoints[i] < 0 )
      fprintf( stream,
	       "/point%u { gsave currentpoint translate %f %f scale\n"
	       "  auto auto scale %f rotate\n"
	       "  newpath 0 0 r%u 0 360 arc closepath stroke grestore }"
	       " def\n",
	       i, 1.0/params->xScale, 1.0/params->yScale,
	       -params->theta, i );

  /* Write PostScript macro for plotting ellipses.  The macro is
     called as "[axis1] [axis2] [angle] ellipse", where [axis1] and
     [axis2] are the two principal axis lengths, and [angle] is the
     angle in degrees counterclockwise from the x-axis to the first
     principal axis. */
  fprintf( stream,
	   "/ellipse { gsave currentpoint translate rotate scale\n"
	   "  newpath 0 0 1 0 360 arc closepath stroke grestore } def\n" );

  /* Write PostScript macro for plotting tiles.  The macro is called
     as "[dx] [dy1] [dy2] tile", where [dx] is the half-width of the
     tile, and [dy1], [dy2] are the heights of the corners of the tile
     relative to the centre. */
  fprintf( stream,
	   "/tile { gsave currentpoint translate 3 copy\n"
	   "  dup 4 1 roll exch 4 1 roll moveto sub 0 exch rlineto\n"
	   "  2 copy add neg 4 3 roll -2 mul exch rlineto\n"
	   "  sub neg 0 exch rlineto closepath stroke grestore } def\n" );

  /* Write PostScript macro to clip the x-y area, if necessary. */
  if ( params->clip )
    fprintf( stream,
	     "/xyclip { %f %f moveto %f %f lineto %f %f lineto\n"
	     "  %f %f lineto closepath clip } def\n",
	     params->clipBox[0], params->clipBox[1],
	     params->clipBox[0], params->clipBox[3],
	     params->clipBox[2], params->clipBox[3],
	     params->clipBox[2], params->clipBox[1] );

  /* Write PostScript macros for plotting boundary, if necessary. */
  if ( params->nBoundary >= 2 ) {
    REAL4 x, x0, dx;   /* x coordinate, initial value, and increment */
    REAL4 *yBound;     /* array of y-values of boundary points */
    yBound = (REAL4 *)LALMalloc( 2*params->nBoundary*sizeof(REAL4) );
    if ( yBound == NULL ) {
      ABORT( stat, TWODMESHPLOTH_EMEM, TWODMESHPLOTH_MSGEMEM );
    }

    /* Fill array of boundary points. */
    x0 = params->params->domain[0];
    dx = ( params->params->domain[1] - x0 )/( params->nBoundary - 1 );
    for ( i = 0; i < params->nBoundary - 1; i++ ) {
      x = x0 + i*dx;
      (params->params->getRange)( stat->statusPtr, yBound + 2*i, x,
				  params->params->rangeParams );
      BEGINFAIL( stat )
	LALFree( yBound );
      ENDFAIL( stat );
    }
    x = params->params->domain[1];
    (params->params->getRange)( stat->statusPtr, yBound + 2*i, x,
				params->params->rangeParams );
    BEGINFAIL( stat )
      LALFree( yBound );
    ENDFAIL( stat );

    /* Write macro. */
    fprintf( stream,
	     "/boundary%u {\n"
	     "%f %f moveto\n", nMacro, x0, yBound[1] );
    nObj = 3;
    for ( i = 1; i < params->nBoundary - 1; i++ ) {
      x = x0 + i*dx;
      fprintf( stream, "%f %f lineto\n", x, yBound[2*i+1] );
      AdjustBBox( x, yBound[2*i+1], params );
      nObj += 3;
      if ( nObj > TWODMESHPLOTC_MAXOBJ ) {
	fprintf( stream,
		 "stroke } def\n"
		 "/boundary%u {\n"
		 "%f %f moveto\n", ++nMacro, x, yBound[2*i+1] );
	nObj = 3;
      }
    }
    x = params->params->domain[1];
    fprintf( stream, "%f %f lineto\n", x, yBound[2*i+1] );
    fprintf( stream, "%f %f lineto\n", x, yBound[2*i] );
    AdjustBBox( x, yBound[2*i+1], params );
    AdjustBBox( x, yBound[2*i], params );
    nObj += 6;
    for ( i = params->nBoundary - 2; i < (UINT4)( -1 ); i-- ) {
      x = x0 + i*dx;
      fprintf( stream, "%f %f lineto\n", x, yBound[2*i] );
      AdjustBBox( x, yBound[2*i], params );
      nObj += 3;
      if ( nObj > TWODMESHPLOTC_MAXOBJ ) {
	fprintf( stream,
		 "stroke } def\n"
		 "/boundary%u {\n"
		 "%f %f moveto\n", ++nMacro, x, yBound[2*i] );
	nObj = 3;
      }
    }
    fprintf( stream,
	     "%f %f lineto\n"
	     "stroke } def\n", x0, yBound[1] );
    nMacro++;
    LALFree( yBound );
  }

  /* Set up parameters for LALMakeMeshMacro(). */
  macroParams.nMacro = 0;
  macroParams.nObj = 0;
  macroParams.level = 0;
  macroParams.plotParams = params;

  /* Write PostScript macro for plotting the mesh.  The routine
     MakeMeshMacro() traverses the linked list, adding a line to the
     macro for each node, and calling itself recursively on any
     submeshes. */
  fprintf( stream, "\n/mesh%u {\n", macroParams.nMacro );
  TRY( LALMakeMeshMacro( stat->statusPtr, stream, mesh,
			 &macroParams ), stat );
  fprintf( stream, "} def\n" );

  /* Increment macro counter only if the last macro list is not
     empty. */
  if ( macroParams.nObj > 0 )
    macroParams.nMacro++;

  /* Autoscale the axes, if necessary. */
  if ( params->autoscale ) {
    REAL4 xScaleFac = params->bBox[2] - params->bBox[0];
    REAL4 yScaleFac = params->bBox[3] - params->bBox[1];
    if ( ( xScaleFac == 0.0 ) && ( yScaleFac == 0.0 ) ) {
      ABORT( stat, TWODMESHPLOTH_ENOPLOT, TWODMESHPLOTH_MSGENOPLOT );
    }
    xScaleFac = ( bBox[2] - bBox[0] )/xScaleFac;
    yScaleFac = ( bBox[3] - bBox[1] )/yScaleFac;
    if ( yScaleFac < xScaleFac )
      xScaleFac = yScaleFac;
    params->xScale *= xScaleFac;
    params->yScale *= xScaleFac;
    for ( i = 0; i < 4; i++ )
      params->bBox[i] *= xScaleFac;
    fprintf( stream, "/auto %f def\n", 1.0/xScaleFac );
  } else
    fprintf( stream, "/auto 1 def\n" );

  /* Set up coordinate system. */
  if ( params->bBox[2] > params->bBox[0] ) {
    bBox[0] = params->bBox[0];
    bBox[2] = params->bBox[2];
  } else {
    bBox[0] = params->bBox[2];
    bBox[2] = params->bBox[0];
  }
  if ( params->bBox[3] > params->bBox[1] ) {
    bBox[3] = params->bBox[3];
    bBox[1] = params->bBox[1];
  } else {
    bBox[3] = params->bBox[1];
    bBox[1] = params->bBox[3];
  }
  nPage = 0;

  /* Set the global graphics state. */
  fprintf( stream, "\n0 setlinewidth 0 setgray\n" );

  /* Define an overall clipping region for all pages. */
  fprintf( stream, "%i %i moveto %i %i lineto %i %i lineto\n"
	   "%i %i lineto closepath clip newpath\n",
	   TWODMESHPLOTH_XMARG, TWODMESHPLOTH_YMARG,
	   TWODMESHPLOTH_XMARG,
	   TWODMESHPLOTH_YMARG + TWODMESHPLOTH_YSIZE,
	   TWODMESHPLOTH_XMARG + TWODMESHPLOTH_XSIZE,
	   TWODMESHPLOTH_YMARG + TWODMESHPLOTH_YSIZE,
	   TWODMESHPLOTH_XMARG + TWODMESHPLOTH_XSIZE,
	   TWODMESHPLOTH_YMARG );

  /* Plot macros on each page. */
  for ( yOff = params->bBox[1] - TWODMESHPLOTH_YMARG;
	yOff < params->bBox[3] - TWODMESHPLOTH_YMARG - 1;
	yOff += TWODMESHPLOTH_YSIZE )
    for ( xOff = params->bBox[0] - TWODMESHPLOTH_XMARG;
	  xOff < params->bBox[2] - TWODMESHPLOTH_XMARG - 1;
	  xOff += TWODMESHPLOTH_XSIZE ) {
      fprintf( stream, "\n"
	       "%%%%Page: %u\n"
	       "gsave %f %f translate %f rotate %f %f scale",
	       ++nPage, -xOff, -yOff, params->theta, params->xScale,
	       params->yScale );
      if ( params->clip )
	fprintf( stream, " xyclip\n" );
      else
	fprintf( stream, "\n" );
      for ( i = 0; i < nMacro; i++ )
	fprintf( stream, "boundary%u\n", i );
      for ( i = 0; i < macroParams.nMacro; i++ )
	fprintf( stream, "mesh%u\n", i );
      fprintf( stream, "showpage grestore\n" );
    }

  /* Finished plotting.  Restore params->bBox to its original setting,
     if necessary. */
  fprintf( stream, "\n%%%%EOF\n" );
  if ( params->autoscale )
    memcpy( params->bBox, bBox, 4*sizeof(REAL4) );
  DETATCHSTATUSPTR( stat );
  RETURN( stat );
}
Ejemplo n.º 25
0
int
main ( int argc, char *argv[] )
{
  const int size = 8;
  COMPLEX8Vector *z1 = NULL;
  COMPLEX8Vector *z2 = NULL;
  COMPLEX8Vector *z3 = NULL;
  REAL4Vector    *x1 = NULL;
  REAL4Vector    *x2 = NULL;
  REAL4Vector    *x3 = NULL;
  REAL4Vector    *y_1 = NULL;
  REAL4Vector    *y2 = NULL;
  REAL4Vector    *y3 = NULL;
  static LALStatus   status;
  INT4            i;


  ParseOptions( argc, argv );

  LALCCreateVector(&status, &z1, size);
  TestStatus( &status, CODES(0), 1 );
  LALCCreateVector(&status, &z2, size);
  TestStatus( &status, CODES(0), 1 );
  LALCCreateVector(&status, &z3, size);
  TestStatus( &status, CODES(0), 1 );
  LALSCreateVector(&status, &x1, size);
  TestStatus( &status, CODES(0), 1 );
  LALSCreateVector(&status, &x2, size);
  TestStatus( &status, CODES(0), 1 );
  LALSCreateVector(&status, &x3, size);
  TestStatus( &status, CODES(0), 1 );
  LALSCreateVector(&status, &y_1, size/2);
  TestStatus( &status, CODES(0), 1 );
  y2         = (REAL4Vector *)LALMalloc(sizeof(REAL4Vector));
  y2->data   = NULL;
  y2->length = size;
  y3         = (REAL4Vector *)LALMalloc(sizeof(REAL4Vector));
  y3->data   = (REAL4 *)LALMalloc(size*sizeof(REAL4));
  y3->length = 0;

  for (i = 0; i < size; ++i)
  {
    z1->data[i] = 1 + i;
    z1->data[i] += I * (2 + i*i);
    z2->data[i] = 3 + i + i*i*i;
    z2->data[i] += I * (4 + i*i + i*i*i);
    x1->data[i]    = 5 + i + i*i;
    x2->data[i]    = 6 + i + i*i + i*i*i;
  }

  if (verbose) printf("\n");
  LALCCVectorMultiply(&status, z3, z1, z2);
  TestStatus( &status, CODES(0), 1 );
  for (i = 0; i < size; ++i)
    if (verbose) printf("(% 6.0f,% 6.0f) x (% 6.0f,% 6.0f) = (% 6.0f,% 6.0f)\n",
        crealf(z1->data[i]), cimagf(z1->data[i]),
        crealf(z2->data[i]), cimagf(z2->data[i]),
        crealf(z3->data[i]), cimagf(z3->data[i]));

  if (verbose) printf("\n");
  LALCCVectorMultiplyConjugate(&status, z3, z1, z2);
  TestStatus( &status, CODES(0), 1 );
  for (i = 0; i < size; ++i)
    if (verbose) printf("(% 6.0f,% 6.0f) x (% 6.0f,% 6.0f)* = (% 6.0f,% 6.0f)\n",
        crealf(z1->data[i]), cimagf(z1->data[i]),
        crealf(z2->data[i]), cimagf(z2->data[i]),
        crealf(z3->data[i]), cimagf(z3->data[i]));

  if (verbose) printf("\n");
  LALCCVectorDivide(&status, z3, z1, z2);
  TestStatus( &status, CODES(0), 1 );
  for (i = 0; i < size; ++i)
    if (verbose) printf("(% 6.0f,% 6.0f) / (% 6.0f,% 6.0f) = (% 9.6f,% 9.6f)\n",
        crealf(z1->data[i]), cimagf(z1->data[i]),
        crealf(z2->data[i]), cimagf(z2->data[i]),
        crealf(z3->data[i]), cimagf(z3->data[i]));

  if (verbose) printf("\n");
  LALSCVectorMultiply(&status, z3, x1, z1);
  TestStatus( &status, CODES(0), 1 );
  for (i = 0; i < size; ++i)
    if (verbose) printf("% 6.0f x (% 6.0f,% 6.0f) = (% 6.0f,% 6.0f)\n",
        crealf(x1->data[i]),
        crealf(z1->data[i]), cimagf(z1->data[i]),
        crealf(z3->data[i]), cimagf(z3->data[i]));

  if (verbose) printf("\n");
  LALSSVectorMultiply(&status, x3, x1, x2);
  TestStatus( &status, CODES(0), 1 );
  for (i = 0; i < size; ++i)
    if (verbose) printf("% 6.0f x % 6.0f = % 6.0f\n",
        x1->data[i], x2->data[i], x3->data[i]);

  if (verbose) printf("\n");
#ifndef LAL_NDEBUG
  if ( ! lalNoDebug )
  {
    LALSSVectorMultiply(&status, x3, x1, NULL);
    TestStatus( &status, CODES(VECTOROPSH_ENULL), 1 );
    LALSSVectorMultiply(&status, x3, y2, x2);
    TestStatus( &status, CODES(VECTOROPSH_ENULL), 1 );
    LALSSVectorMultiply(&status, y3, x1, x2);
    TestStatus( &status, CODES(VECTOROPSH_ESIZE), 1 );
    LALSSVectorMultiply(&status, x3, x1, y_1);
    TestStatus( &status, CODES(VECTOROPSH_ESZMM), 1 );
  }
#endif

  LALCDestroyVector(&status, &z1);
  TestStatus( &status, CODES(0), 1 );
  LALCDestroyVector(&status, &z2);
  TestStatus( &status, CODES(0), 1 );
  LALCDestroyVector(&status, &z3);
  TestStatus( &status, CODES(0), 1 );
  LALSDestroyVector(&status, &x1);
  TestStatus( &status, CODES(0), 1 );
  LALSDestroyVector(&status, &x2);
  TestStatus( &status, CODES(0), 1 );
  LALSDestroyVector(&status, &x3);
  TestStatus( &status, CODES(0), 1 );
  LALSDestroyVector(&status, &y_1);
  TestStatus( &status, CODES(0), 1 );
  LALFree(y2);
  LALFree(y3->data);
  LALFree(y3);

  x1 = x2 = x3 = y_1 = y2 = y3 = NULL;
  z1 = z2 = z3 = NULL;


  LALCCreateVector(&status, &z1, size);
  TestStatus( &status, CODES(0), 1 );

  LALSCreateVector(&status, &x1, size);
  TestStatus( &status, CODES(0), 1 );
  LALSCreateVector(&status, &x2, size);
  TestStatus( &status, CODES(0), 1 );
  LALSCreateVector(&status, &x3, size);
  TestStatus( &status, CODES(0), 1 );


  for (i = 0; i < size; ++i)
  {
    z1->data[i] = (12.0 + i) *cos(LAL_PI/3.0*i);
    z1->data[i] += I * (12.0 + i )*sin(LAL_PI/3.0*i);
  }

  if (verbose) printf("\n");
  LALCVectorAbs(&status, x1, z1);
  TestStatus( &status, CODES(0), 1 );
  for (i = 0; i < size; ++i)
    if (verbose) printf(" Abs(% f,%f)  = %f \n",
        crealf(z1->data[i]), cimagf(z1->data[i]),
        x1->data[i]);

  LALCVectorAngle(&status, x2, z1);
  TestStatus( &status, CODES(0), 1 );
  for (i = 0; i < size; ++i)
    if (verbose) printf(" Angle(%f,%f)  = %f \n",
        crealf(z1->data[i]), cimagf(z1->data[i]),
        x2->data[i]);

  LALUnwrapREAL4Angle(&status, x3, x2);
  TestStatus( &status, CODES(0), 1 );
  for (i = 0; i < size; ++i)
    if (verbose) printf(" Unwrap Phase Angle ( %f )  = %f \n",
        x2->data[i],
        x3->data[i]);


  LALSCreateVector(&status, &y_1, size/2);
  TestStatus( &status, CODES(0), 1 );

  y2         = (REAL4Vector *)LALMalloc(sizeof(REAL4Vector));
  y2->data   = NULL;
  y2->length = size;

  y3         = (REAL4Vector *)LALMalloc(sizeof(REAL4Vector));
  y3->data   = (REAL4 *)LALMalloc(size*sizeof(REAL4));
  y3->length = 0;

  if (verbose) printf("\n");

#ifndef LAL_NDEBUG
  if ( ! lalNoDebug )
  {
    LALCVectorAbs(&status, x1, NULL);
    TestStatus( &status, CODES(VECTOROPSH_ENULL), 1 );
    LALCVectorAbs(&status, NULL, z1);
    TestStatus( &status, CODES(VECTOROPSH_ENULL), 1 );
    LALCVectorAbs(&status, y_1, z1);
    TestStatus( &status, CODES(VECTOROPSH_ESZMM), 1 );
    LALCVectorAbs(&status, y2, z1);
    TestStatus( &status, CODES(VECTOROPSH_ENULL), 1 );
    LALCVectorAbs(&status, y3, z1);
    TestStatus( &status, CODES(VECTOROPSH_ESIZE), 1 );


    LALCVectorAngle(&status, x2, NULL);
    TestStatus( &status, CODES(VECTOROPSH_ENULL), 1 );
    LALCVectorAngle(&status, NULL, z1);
    TestStatus( &status, CODES(VECTOROPSH_ENULL), 1 );
    LALCVectorAngle(&status, y_1, z1);
    TestStatus( &status, CODES(VECTOROPSH_ESZMM), 1 );
    LALCVectorAngle(&status, y2, z1);
    TestStatus( &status, CODES(VECTOROPSH_ENULL), 1 );
    LALCVectorAngle(&status, y3, z1);
    TestStatus( &status, CODES(VECTOROPSH_ESIZE), 1 );

    LALUnwrapREAL4Angle(&status, x3, NULL);
    TestStatus( &status, CODES(VECTOROPSH_ENULL), 1 );
    LALUnwrapREAL4Angle(&status, NULL, x2);
    TestStatus( &status, CODES(VECTOROPSH_ENULL), 1 );
    LALUnwrapREAL4Angle(&status, y_1, x2);
    TestStatus( &status, CODES(VECTOROPSH_ESZMM), 1 );
    LALUnwrapREAL4Angle(&status, y2, x2);
    TestStatus( &status, CODES(VECTOROPSH_ENULL), 1 );
    LALUnwrapREAL4Angle(&status, y3, x2);
    TestStatus( &status, CODES(VECTOROPSH_ESIZE), 1 );
    LALUnwrapREAL4Angle(&status, x2, x2);
    TestStatus( &status, CODES(VECTOROPSH_ESAME), 1 );
  }
#endif


  LALCDestroyVector(&status, &z1);
  TestStatus( &status, CODES(0), 1 );

  LALSDestroyVector(&status, &x1);
  TestStatus( &status, CODES(0), 1 );
  LALSDestroyVector(&status, &x2);
  TestStatus( &status, CODES(0), 1 );
  LALSDestroyVector(&status, &x3);
  TestStatus( &status, CODES(0), 1 );

  LALSDestroyVector(&status, &y_1);
  TestStatus( &status, CODES(0), 1 );
  LALFree(y2);
  LALFree(y3->data);
  LALFree(y3);

  LALCheckMemoryLeaks();
  return 0;
}
int
main (int argc, char *argv[])
{
  static LALStatus              status;


  INT4                          i,j,k,l;

  UINT4                         numDetectors=0;
  FILE                         *fpcohSNR;
  REAL4                         theta,phi,vPlus,vMinus;
  REAL4                         x,y;

  UINT2Vector                  *detIDVec;
  DetectorVector               *detectorVec;

  CoherentInspiralInitParams   *cohInspInitParams = NULL;
  CoherentInspiralFilterParams *cohInspFilterParams = NULL;
  CoherentInspiralFilterInput  *cohInspFilterInput = NULL;
  CoherentInspiralBeamVector   *cohInspBeamVec = NULL;
  CoherentInspiralZVector      *cohInspZVec = NULL;
  InspiralTemplate             *tmplt = NULL;
  CoherentInspiralEvent        *cohInspEvent = NULL;

  char namearray[6][256] = {"0","0","0","0","0","0"};
  char namearray2[6][256] = {"0","0","0","0","0","0"};


  /*
   *
   * parse options, allocate memory, init params and set values
   *
   */

  ParseOptions (argc, argv);


  /* override numSegments if outputting coherent SNR */
  if ( cohSNROut )
    {
      numSegments = 1;
      numTmplts = 1;
      fpcohSNR = fopen ("cohSNR.dat", "w");
    }


  /* read in the network detectors */
  for (l=0;l<6;l++)
    {
      if(caseID[l] == 1)
	numDetectors++;
    }

  fprintf(stdout, "You have specified %2d  detector(s).\n",numDetectors);
  fprintf(stdout, "The caseID is: %d %d %d %d %d %d (H1,H2,L1,GEO,VIRGO,TAMA) \n",caseID[0],caseID[1],caseID[2],caseID[3],caseID[4],caseID[5]);

  if (numDetectors > 4)
    {
    fprintf(stdout, "Too many detectors specified - exiting. \n");
    goto cleanexit;
    }
  if (numDetectors == 0)
    {
      fprintf(stdout, "You must specify data filename(s) for 1 to 4 detectors - exiting. \n");
      goto cleanexit;
    }


  /*
   *
   * allocate memory to structures
   *
   */

  /* fill the init params structure */
  cohInspInitParams = (CoherentInspiralInitParams *)
    LALMalloc (sizeof(CoherentInspiralInitParams));

  cohInspInitParams->numDetectors            = numDetectors;
  cohInspInitParams->numSegments             = numSegments;
  cohInspInitParams->numPoints               = numPoints;
  cohInspInitParams->numBeamPoints           = numBeamPoints;
  cohInspInitParams->cohSNROut               = cohSNROut;

  /* Create input structure for coherent filter code */
  LALCoherentInspiralFilterInputInit (&status, &cohInspFilterInput,
					cohInspInitParams);
  TestStatus (&status, "0", 1);
  ClearStatus (&status);



  /*
   * information for calculating chirp time
   */

  /* inspiral template structure */
  tmplt = cohInspFilterInput->tmplt = (InspiralTemplate *)
    LALMalloc (sizeof(InspiralTemplate));
  memset( tmplt, 0, sizeof(InspiralTemplate) );

  /* generate dummy template parameters */
  {
    REAL4 m1 = mass;
    REAL4 m2 = mass;
    tmplt->mass1     = m1;
    tmplt->mass2     = m2;
    tmplt->totalMass = m1 + m2;
    tmplt->mu        = m1 * m2 / tmplt->totalMass;
    tmplt->eta       = tmplt->mu / tmplt->totalMass;
  }

  /* fill the params structure */
  LALCoherentInspiralFilterParamsInit (&status, &cohInspFilterParams,
				       cohInspInitParams);
  TestStatus (&status, "0", 1);
  ClearStatus (&status);

  cohInspFilterParams->numDetectors            = numDetectors;
  cohInspFilterParams->numSegments             = numSegments;
  cohInspFilterParams->numPoints               = numPoints;
  cohInspFilterParams->numBeamPoints           = numBeamPoints;
  cohInspFilterParams->deltaT                  = 1/((REAL4) sampleRate);
  cohInspFilterParams->cohSNROut               = cohSNROut;
  cohInspFilterParams->cohSNRThresh            = cohSNRThresh;
  cohInspFilterParams->numTmplts               = numTmplts;
  cohInspFilterParams->fLow                    = fLow;
  cohInspFilterParams->maximiseOverChirp       = maximiseOverChirp;

  detIDVec = cohInspFilterParams->detIDVec;

  /*assign detIDs to the coincident detectors in the network */
  for ( i=0 ; i < 6 ; i++) {
    detIDVec->data[i] = caseID[i];
  }

 /* create and fill the DetectorVector structure of detector IDs*/

  detectorVec = cohInspFilterParams->detectorVec;

  i=0;
  for ( j=0 ; j < 6 ; j++ ) {
    /*    if (((j != 5) && caseID[j++])) { */
    if ( caseID[j] ) {
      detectorVec->detector[i++] = lalCachedDetectors[j];
    }
  }

  if (caseID[5]) {
    detectorVec->detector[numDetectors-1] = lalCachedDetectors[0];
  }


  /* Now read in all the filenames and store them in arrays */
  /* This will keep the files in the order:
     H1(0), L1(1), VIRGO(2), GEO(3), TAMA(4), H2(5)*/

  if(caseID[0])
    {
    strcpy(namearray[0],H1filename);
    strcpy(namearray2[0],H1Beam);
    }

  if(caseID[1])
    {
    strcpy(namearray[1],L1filename);
    strcpy(namearray2[1],L1Beam);
    }

  if(caseID[2])
    {
    strcpy(namearray[2],VIRGOfilename);
    strcpy(namearray2[2],VIRGOBeam);
    }

  if(caseID[3])
    {
    strcpy(namearray[3],GEOfilename);
    strcpy(namearray2[3],GEOBeam);
    }

  if(caseID[4])
    {
    strcpy(namearray[4],TAMAfilename);
    strcpy(namearray2[4],TAMABeam);
    }

  if (caseID[5])
    {
    strcpy(namearray[5],H2filename);
    strcpy(namearray2[5],H2Beam);
    }



  /* create and fill the CoherentInspiralBeamVector structure of beam-patterns*/
  cohInspBeamVec = cohInspFilterInput->beamVec;

  l=0;
  for ( j=0 ; j < 6 ; j++ ) {
    if ( caseID[j] ) {
      /*      for (l=0;l<numDetectors;l++) { */

      fp2[l] = fopen(namearray2[j], "r");
      if(!fp2[l])
	{
	  fprintf(stdout,"The file %s containing the coefficients could not be found - exiting...\n",namearray2[j]);
	  goto  cleanexit;
	}
      for ( k=0 ; k<numBeamPoints ; k++)
	{
	  fscanf(fp2[l],"%f, %f, %f, %f",&theta,&phi,&vPlus,&vMinus);
	  cohInspBeamVec->detBeamArray[l].thetaPhiVs[k].data->data[0] = theta;
	  cohInspBeamVec->detBeamArray[l].thetaPhiVs[k].data->data[1] = phi;
	  cohInspBeamVec->detBeamArray[l].thetaPhiVs[k].data->data[2] = vPlus;
	  cohInspBeamVec->detBeamArray[l].thetaPhiVs[k].data->data[3] = vMinus;
	}
      fclose(fp2[l++]);
    }
  }


  /*
   * CREATE the multi-z data structure;
   * the z=x+iy data from multiple detectors was read above along with
   * the beam-pattern functions
   */
  cohInspZVec = cohInspFilterInput->multiZData;

  /* First, the files will be tested for length consistency
     and then the z-data for multiple detectors will be read in */
  l=0;
  for ( j=0 ; j < 6 ; j++ ) {
    if ( caseID[j] ) {
      fp[l] = fopen(namearray[j], "r");
      if(!fp[l])
	{
	  fprintf(stdout,"The file %s does not exist - exiting...\n",
		  namearray[j]);
	  goto cleanexit;
	}
      for (k = 0; k < numPoints; k++)
	{
	  fscanf(fp[l],"%f %f", &x, &y);
	  cohInspZVec->zData[l].data->data[k].re = x;
	  cohInspZVec->zData[l].data->data[k].im = y;
	}
      fclose(fp[l++]);
    }
  }

  /*Do the filtering and output events */
  cohInspEvent = NULL;

  LALCoherentInspiralFilterSegment (&status, &cohInspEvent, cohInspFilterInput, cohInspFilterParams);
  TestStatus (&status, "0", 1);

  if ( cohInspEvent )
	{
	  fprintf( stdout, "\nEvents found in segment!\n\n" );
	  while (cohInspEvent  )
	    {
	      CoherentInspiralEvent *thisEvent = cohInspEvent;

	      cohInspEvent = thisEvent->next;

	      fprintf( stdout, "event id                              = %d\n\n", thisEvent->eventId+1 );

	      fprintf( stdout, "coherent SNR                         = %.2f\n", thisEvent->cohSNR );

	      fprintf( stdout, "'network' timeIndex                   = %d\n", thisEvent->timeIndex );

	      fflush( stdout );

	      LALFree( thisEvent );
	    }

	}
      else
	{
	  fprintf( stdout, "\nNo events found in segment for mass = %.4f solar mass template!\n", mass );
	}
  /* outputting coherent SNR */
  if ( cohSNROut )
    {
      for ( i = 0; i < cohInspFilterParams->cohSNRVec->data->length; ++i )
	{
	  fprintf( fpcohSNR, "%d\t%e\n", i, cohInspFilterParams->cohSNRVec->data->data[i] );
	}
    }

 cleanexit:

  fclose( fpcohSNR);

  /* Destroy params structure for coherent filter code */
  LALCoherentInspiralFilterParamsFinalize (&status, &cohInspFilterParams);
  TestStatus (&status, "0", 1);
  ClearStatus (&status);

  /* Destroy input structure for coherent filter code */
  LALCoherentInspiralFilterInputFinalize (&status, &cohInspFilterInput);
  TestStatus (&status, "0", 1);
  ClearStatus (&status);


  LALCheckMemoryLeaks ();

  return 0;

} /* end main */
Ejemplo n.º 27
0
int main(int argc, char *argv[]){

  static LALStatus  status;  

  static LALDetector          *detector;
  static LIGOTimeGPSVector    timeV;
  static REAL8Cart3CoorVector velV;
  static REAL8Vector          timeDiffV;
  static REAL8                foft;
  static HoughPulsarTemplate  pulsarTemplate;

  EphemerisData   *edat = NULL;
  CHAR  *uvar_earthEphemeris = NULL; 
  CHAR  *uvar_sunEphemeris = NULL;
  SFTVector  *inputSFTs  = NULL;  
  REAL8 *alphaVec=NULL;
  REAL8 *deltaVec=NULL;
  REAL8 *freqVec=NULL;
  REAL8 *spndnVec=NULL;

  /* pgV is vector of peakgrams and pg1 is onepeakgram */
  static UCHARPeakGram    *pg1, **pgV; 
  UINT4  msp; /*number of spin-down parameters */
  CHAR   *uvar_ifo = NULL;
  CHAR   *uvar_sftDir = NULL; /* the directory where the SFT  could be */
  CHAR   *uvar_fnameOut = NULL;               /* The output prefix filename */
  CHAR   *uvar_fnameIn = NULL;  
  INT4   numberCount, ind;
  UINT8  nTemplates;   
  UINT4   mObsCoh;
  REAL8  uvar_peakThreshold;
  REAL8  f_min, f_max, fWings, timeBase;
  INT4  uvar_blocksRngMed;
  UINT4  sftlength; 
  INT4   sftFminBin;
  UINT4 loopId, tempLoopId;
  FILE  *fpOut = NULL;
  CHAR *fnameLog=NULL;
  FILE *fpLog = NULL;
  CHAR *logstr=NULL;
  /*REAL8 asq, bsq;*/ /* square of amplitude modulation functions a and b */

  /******************************************************************/
  /*    Set up the default parameters.      */
  /* ****************************************************************/

  /* LAL error-handler */
  lal_errhandler = LAL_ERR_EXIT;
  
  msp = 1; /*only one spin-down */
 
  /* memory allocation for spindown */
  pulsarTemplate.spindown.length = msp;
  pulsarTemplate.spindown.data = NULL;
  pulsarTemplate.spindown.data = (REAL8 *)LALMalloc(msp*sizeof(REAL8));
 
 
  uvar_peakThreshold = THRESHOLD;

  uvar_earthEphemeris = (CHAR *)LALMalloc(1024*sizeof(CHAR));
  strcpy(uvar_earthEphemeris,EARTHEPHEMERIS);

  uvar_sunEphemeris = (CHAR *)LALMalloc(1024*sizeof(CHAR));
  strcpy(uvar_sunEphemeris,SUNEPHEMERIS);

  uvar_sftDir = (CHAR *)LALMalloc(1024*sizeof(CHAR));
  strcpy(uvar_sftDir,SFTDIRECTORY);

  uvar_fnameOut = (CHAR *)LALMalloc(1024*sizeof(CHAR));
  strcpy(uvar_fnameOut,VALIDATEOUT);

  uvar_fnameIn = (CHAR *)LALMalloc(1024*sizeof(CHAR));
  strcpy(uvar_fnameIn,VALIDATEIN);

  uvar_blocksRngMed = BLOCKSRNGMED;

  /* register user input variables */
  XLAL_CHECK_MAIN( XLALRegisterNamedUvar( &uvar_ifo,            "ifo",            STRING, 'i', OPTIONAL, "Detector GEO(1) LLO(2) LHO(3)" ) == XLAL_SUCCESS, XLAL_EFUNC);
  XLAL_CHECK_MAIN( XLALRegisterNamedUvar( &uvar_earthEphemeris, "earthEphemeris", STRING, 'E', OPTIONAL, "Earth Ephemeris file") == XLAL_SUCCESS, XLAL_EFUNC);
  XLAL_CHECK_MAIN( XLALRegisterNamedUvar( &uvar_sunEphemeris,   "sunEphemeris",   STRING, 'S', OPTIONAL, "Sun Ephemeris file") == XLAL_SUCCESS, XLAL_EFUNC);
  XLAL_CHECK_MAIN( XLALRegisterNamedUvar( &uvar_sftDir,         "sftDir",         STRING, 'D', OPTIONAL, "SFT Directory") == XLAL_SUCCESS, XLAL_EFUNC);
  XLAL_CHECK_MAIN( XLALRegisterNamedUvar( &uvar_fnameIn,        "fnameIn",        STRING, 'T', OPTIONAL, "Input template file") == XLAL_SUCCESS, XLAL_EFUNC);
  XLAL_CHECK_MAIN( XLALRegisterNamedUvar( &uvar_fnameOut,       "fnameOut",       STRING, 'o', OPTIONAL, "Output filename") == XLAL_SUCCESS, XLAL_EFUNC);
  XLAL_CHECK_MAIN( XLALRegisterNamedUvar( &uvar_blocksRngMed,   "blocksRngMed",   INT4,   'w', OPTIONAL, "RngMed block size") == XLAL_SUCCESS, XLAL_EFUNC);
  XLAL_CHECK_MAIN( XLALRegisterNamedUvar( &uvar_peakThreshold,  "peakThreshold",  REAL8,  't', OPTIONAL, "Peak selection threshold") == XLAL_SUCCESS, XLAL_EFUNC);

  /* read all command line variables */
  BOOLEAN should_exit = 0;
  XLAL_CHECK_MAIN( XLALUserVarReadAllInput(&should_exit, argc, argv, lalAppsVCSInfoList) == XLAL_SUCCESS, XLAL_EFUNC);
  if (should_exit)
    exit(1);
 
  /* open log file for writing */
  fnameLog = LALCalloc( (strlen(uvar_fnameOut) + strlen(".log") + 10),1);
  strcpy(fnameLog,uvar_fnameOut);
  strcat(fnameLog,".log");
  if ((fpLog = fopen(fnameLog, "w")) == NULL) {
    fprintf(stderr, "Unable to open file %s for writing\n", fnameLog);
    LALFree(fnameLog);
    exit(1);
  }
  
  /* get the log string */
  XLAL_CHECK_MAIN( ( logstr = XLALUserVarGetLog(UVAR_LOGFMT_CFGFILE) ) != NULL, XLAL_EFUNC);  

  fprintf( fpLog, "## Log file for HoughValidate\n\n");
  fprintf( fpLog, "# User Input:\n");
  fprintf( fpLog, "#-------------------------------------------\n");
  fprintf( fpLog, "%s", logstr);
  LALFree(logstr);

  /* append an ident-string defining the exact CVS-version of the code used */
  {
    CHAR command[1024] = "";
    fprintf (fpLog, "\n\n# CVS-versions of executable:\n");
    fprintf (fpLog, "# -----------------------------------------\n");
    fclose (fpLog);
    
    sprintf (command, "ident %s | sort -u >> %s", argv[0], fnameLog);
    /* we don't check this. If it fails, we assume that */
    /* one of the system-commands was not available, and */
    /* therefore the CVS-versions will not be logged */
    if ( system(command) ) fprintf (stderr, "\nsystem('%s') returned non-zero status!\n\n", command );

    LALFree(fnameLog);
  }

  /* open output file for writing */
  fpOut= fopen(uvar_fnameOut, "w");
  /*setlinebuf(fpOut);*/  /* line buffered on */  
  setvbuf(fpOut, (char *)NULL, _IOLBF, 0);

  /*****************************************************************/
  /* read template file */
  /*****************************************************************/
  {
    FILE  *fpIn = NULL;
    INT4   r;
    REAL8  temp1, temp2, temp3, temp4, temp5;
    UINT8  templateCounter; 
    
    fpIn = fopen(uvar_fnameIn, "r");
    if ( !fpIn )
      {
	fprintf(stderr, "Unable to fine file %s\n", uvar_fnameIn);
	return DRIVEHOUGHCOLOR_EFILE;
      }


    nTemplates = 0;
    do 
      {
	r=fscanf(fpIn,"%lf%lf%lf%lf%lf\n", &temp1, &temp2, &temp3, &temp4, &temp5);
	/* make sure the line has the right number of entries or is EOF */
	if (r==5) nTemplates++;
      } while ( r != EOF);
    rewind(fpIn);
    
    alphaVec = (REAL8 *)LALMalloc(nTemplates*sizeof(REAL8));
    deltaVec = (REAL8 *)LALMalloc(nTemplates*sizeof(REAL8));     
    freqVec = (REAL8 *)LALMalloc(nTemplates*sizeof(REAL8));
    spndnVec = (REAL8 *)LALMalloc(nTemplates*sizeof(REAL8));     
    
    
    for (templateCounter = 0; templateCounter < nTemplates; templateCounter++)
      {
	r=fscanf(fpIn,"%lf%lf%lf%lf%lf\n", &temp1, alphaVec + templateCounter, deltaVec + templateCounter, 
		 freqVec + templateCounter,  spndnVec + templateCounter);
      }     
    fclose(fpIn);      
  }


  /**************************************************/
  /* read sfts */     
  /*************************************************/
  f_min = freqVec[0];     /* initial frequency to be analyzed */
  /* assume that the last frequency in the templates file is also the highest frequency */
  f_max = freqVec[nTemplates-1] ; 
  
  /* we need to add wings to fmin and fmax to account for 
     the Doppler shift, the size of the rngmed block size
     and also nfsizecylinder.  The block size and nfsizecylinder are
     specified in terms of frequency bins...this goes as one of the arguments of 
     LALReadSFTfiles */
  /* first correct for Doppler shift */
  fWings =  f_max * VTOT; 
  f_min -= fWings;    
  f_max += fWings; 
  
  /* create pattern to look for in SFT directory */   

  {
    CHAR *tempDir = NULL;
    SFTCatalog *catalog = NULL;
    static SFTConstraints constraints;

    /* set detector constraint */
    constraints.detector = NULL;
    if ( XLALUserVarWasSet( &uvar_ifo ) )    
      constraints.detector = XLALGetChannelPrefix ( uvar_ifo );

    /* get sft catalog */
    tempDir = (CHAR *)LALCalloc(512, sizeof(CHAR));
    strcpy(tempDir, uvar_sftDir);
    strcat(tempDir, "/*SFT*.*");
    XLAL_CHECK_MAIN( ( catalog = XLALSFTdataFind( tempDir, &constraints) ) != NULL, XLAL_EFUNC);
    
    detector = XLALGetSiteInfo( catalog->data[0].header.name);

    mObsCoh = catalog->length;
    timeBase = 1.0 / catalog->data->header.deltaF;

    XLAL_CHECK_MAIN( ( inputSFTs = XLALLoadSFTs ( catalog, f_min, f_max) ) != NULL, XLAL_EFUNC);

    XLAL_CHECK_MAIN( XLALNormalizeSFTVect( inputSFTs, uvar_blocksRngMed, 0.0 ) == XLAL_SUCCESS, XLAL_EFUNC);

    if ( XLALUserVarWasSet( &uvar_ifo ) )    
      LALFree( constraints.detector );
    LALFree( tempDir);
    XLALDestroySFTCatalog(catalog );  	

  }



  sftlength = inputSFTs->data->data->length;
  {
    INT4 tempFbin;
    sftFminBin = floor( (REAL4)(timeBase * inputSFTs->data->f0) + (REAL4)(0.5));
    tempFbin = floor( timeBase * inputSFTs->data->f0 + 0.5);

    if (tempFbin - sftFminBin)
      {
	fprintf(stderr, "Rounding error in calculating fminbin....be careful! \n");
      }
  }

  /* loop over sfts and select peaks */

  /* first the memory allocation for the peakgramvector */
  pgV = NULL;
  pgV = (UCHARPeakGram **)LALMalloc(mObsCoh*sizeof(UCHARPeakGram *));  

  /* memory for  peakgrams */
  for (tempLoopId=0; tempLoopId < mObsCoh; tempLoopId++)
    {
      pgV[tempLoopId] = (UCHARPeakGram *)LALMalloc(sizeof(UCHARPeakGram));
      pgV[tempLoopId]->length = sftlength; 
      pgV[tempLoopId]->data = NULL; 
      pgV[tempLoopId]->data = (UCHAR *)LALMalloc(sftlength* sizeof(UCHAR));
   
      LAL_CALL (SFTtoUCHARPeakGram( &status, pgV[tempLoopId], inputSFTs->data + tempLoopId, uvar_peakThreshold), &status);
    }


  /* having calculated the peakgrams we don't need the sfts anymore */
  XLALDestroySFTVector( inputSFTs);


  
  /* ****************************************************************/
  /* setting timestamps vector */
  /* ****************************************************************/
  timeV.length = mObsCoh;
  timeV.data = NULL;  
  timeV.data = (LIGOTimeGPS *)LALMalloc(mObsCoh*sizeof(LIGOTimeGPS));
  
  { 
    UINT4    j; 
    for (j=0; j < mObsCoh; j++){
      timeV.data[j].gpsSeconds = pgV[j]->epoch.gpsSeconds;
      timeV.data[j].gpsNanoSeconds = pgV[j]->epoch.gpsNanoSeconds;
    }    
  }
  
  /******************************************************************/
  /* compute the time difference relative to startTime for all SFTs */
  /******************************************************************/
  timeDiffV.length = mObsCoh;
  timeDiffV.data = NULL; 
  timeDiffV.data = (REAL8 *)LALMalloc(mObsCoh*sizeof(REAL8));
  
  {   
    REAL8   t0, ts, tn, midTimeBase;
    UINT4   j; 

    midTimeBase=0.5*timeBase;
    ts = timeV.data[0].gpsSeconds;
    tn = timeV.data[0].gpsNanoSeconds * 1.00E-9;
    t0=ts+tn;
    timeDiffV.data[0] = midTimeBase;

    for (j=1; j< mObsCoh; ++j){
      ts = timeV.data[j].gpsSeconds;
      tn = timeV.data[j].gpsNanoSeconds * 1.00E-9;  
      timeDiffV.data[j] = ts + tn -t0 + midTimeBase; 
    }  
  }

  /******************************************************************/
  /* compute detector velocity for those time stamps                */
  /******************************************************************/
  velV.length = mObsCoh;
  velV.data = NULL;
  velV.data = (REAL8Cart3Coor *)LALMalloc(mObsCoh*sizeof(REAL8Cart3Coor));
  
  {  
    VelocityPar   velPar;
    REAL8     vel[3]; 
    UINT4     j; 

    velPar.detector = *detector;
    velPar.tBase = timeBase;
    velPar.vTol = ACCURACY;
    velPar.edat = NULL;

    /* read in ephemeris data */
    XLAL_CHECK_MAIN( ( edat = XLALInitBarycenter( uvar_earthEphemeris, uvar_sunEphemeris ) ) != NULL, XLAL_EFUNC);
    velPar.edat = edat;

    /* now calculate average velocity */    
    for(j=0; j< velV.length; ++j){
      velPar.startTime.gpsSeconds     = timeV.data[j].gpsSeconds;
      velPar.startTime.gpsNanoSeconds = timeV.data[j].gpsNanoSeconds;
      
      LAL_CALL( LALAvgDetectorVel ( &status, vel, &velPar), &status );
      velV.data[j].x= vel[0];
      velV.data[j].y= vel[1];
      velV.data[j].z= vel[2];   
    }  
  }


  
  /* amplitude modulation stuff */
  {
    AMCoeffs XLAL_INIT_DECL(amc);
    AMCoeffsParams *amParams;
    EarthState earth;
    BarycenterInput baryinput;  /* Stores detector location and other barycentering data */

    /* detector location */
    baryinput.site.location[0] = detector->location[0]/LAL_C_SI;
    baryinput.site.location[1] = detector->location[1]/LAL_C_SI;
    baryinput.site.location[2] = detector->location[2]/LAL_C_SI;
    baryinput.dInv = 0.e0;
    /* alpha and delta must come from the skypatch */
    /* for now set it to something arbitrary */
    baryinput.alpha = 0.0;
    baryinput.delta = 0.0;

    /* Allocate space for amParams stucture */
    /* Here, amParams->das is the Detector and Source info */
    amParams = (AMCoeffsParams *)LALMalloc(sizeof(AMCoeffsParams));
    amParams->das = (LALDetAndSource *)LALMalloc(sizeof(LALDetAndSource));
    amParams->das->pSource = (LALSource *)LALMalloc(sizeof(LALSource));
    /* Fill up AMCoeffsParams structure */
    amParams->baryinput = &baryinput;
    amParams->earth = &earth; 
    amParams->edat = edat;
    amParams->das->pDetector = detector; 
    /* make sure alpha and delta are correct */
    amParams->das->pSource->equatorialCoords.latitude = baryinput.delta;
    amParams->das->pSource->equatorialCoords.longitude = baryinput.alpha;
    amParams->das->pSource->orientation = 0.0;
    amParams->das->pSource->equatorialCoords.system = COORDINATESYSTEM_EQUATORIAL;
    amParams->polAngle = amParams->das->pSource->orientation ; /* These two have to be the same!!*/

    /* timeV is start time ---> change to mid time */    
    LAL_CALL (LALComputeAM(&status, &amc, timeV.data, amParams), &status); 

    /* calculate a^2 and b^2 */
    /* for (ii=0, asq=0.0, bsq=0.0; ii<mObsCoh; ii++) */
    /*       { */
    /* 	REAL8 *a, *b; */
    /*        	a = amc.a + ii; */
    /* 	b = amc.b + ii; */
    /* 	asq += (*a) * (*a); */
    /* 	bsq += (*b) * (*b); */
    /*       } */
    
    /* free amParams */
    LALFree(amParams->das->pSource);
    LALFree(amParams->das);
    LALFree(amParams);

  }

  /* loop over templates */    
  for(loopId=0; loopId < nTemplates; ++loopId){
    
    /* set template parameters */    
    pulsarTemplate.f0 = freqVec[loopId];
    pulsarTemplate.longitude = alphaVec[loopId];
    pulsarTemplate.latitude = deltaVec[loopId];
    pulsarTemplate.spindown.data[0] = spndnVec[loopId];
	   
 
    {
      REAL8   f0new, vcProdn, timeDiffN;
      REAL8   sourceDelta, sourceAlpha, cosDelta, factorialN;
      UINT4   j, i, f0newBin; 
      REAL8Cart3Coor       sourceLocation;
      
      sourceDelta = pulsarTemplate.latitude;
      sourceAlpha = pulsarTemplate.longitude;
      cosDelta = cos(sourceDelta);
      
      sourceLocation.x = cosDelta* cos(sourceAlpha);
      sourceLocation.y = cosDelta* sin(sourceAlpha);
      sourceLocation.z = sin(sourceDelta);      

      /* loop for all different time stamps,calculate frequency and produce number count*/ 
      /* first initialize number count */
      numberCount=0;
      for (j=0; j<mObsCoh; ++j)
	{  
	  /* calculate v/c.n */
	  vcProdn = velV.data[j].x * sourceLocation.x
	    + velV.data[j].y * sourceLocation.y
	    + velV.data[j].z * sourceLocation.z;

	  /* loop over spindown values to find f_0 */
	  f0new = pulsarTemplate.f0;
	  factorialN = 1.0;
	  timeDiffN = timeDiffV.data[j];	  
	  for (i=0; i<msp;++i)
	    { 
	      factorialN *=(i+1.0);
	      f0new += pulsarTemplate.spindown.data[i]*timeDiffN / factorialN;
	      timeDiffN *= timeDiffN;
	    }
	  
	  f0newBin = floor(f0new*timeBase + 0.5);
	  foft = f0newBin * (1.0 +vcProdn) / timeBase;    
	  
	  /* get the right peakgram */      
	  pg1 = pgV[j];
	  
	  /* calculate frequency bin for template */
	  ind =  floor( foft * timeBase + 0.5 ) - sftFminBin; 
	  
	  /* update the number count */
	  numberCount+=pg1->data[ind]; 
	}      
      
    } /* end of block calculating frequency path and number count */      
    

    /******************************************************************/
    /* printing result in the output file */
    /******************************************************************/
    
    fprintf(fpOut,"%d %f %f %f %g \n", 
	    numberCount, pulsarTemplate.longitude, pulsarTemplate.latitude, pulsarTemplate.f0,
	    pulsarTemplate.spindown.data[0] );
    
  } /* end of loop over templates */

  /******************************************************************/
  /* Closing files */
  /******************************************************************/  
  fclose(fpOut); 

  
  /******************************************************************/
  /* Free memory and exit */
  /******************************************************************/

  LALFree(alphaVec);
  LALFree(deltaVec);
  LALFree(freqVec);
  LALFree(spndnVec);
  

  for (tempLoopId = 0; tempLoopId < mObsCoh; tempLoopId++){
    pg1 = pgV[tempLoopId];  
    LALFree(pg1->data);
    LALFree(pg1);
  }
  LALFree(pgV);
  
  LALFree(timeV.data);
  LALFree(timeDiffV.data);
  LALFree(velV.data);
  
  LALFree(pulsarTemplate.spindown.data);
   
  XLALDestroyEphemerisData(edat);
  
  XLALDestroyUserVars();

  LALCheckMemoryLeaks();
    
  return DRIVEHOUGHCOLOR_ENORM;
}
Ejemplo n.º 28
0
void LALCreateTimeFreqParam (LALStatus *status,
			TimeFreqParam **param,
			CreateTimeFreqIn *in)
{
  /* Initialize status */
  INITSTATUS(status);

  /* Check input structure: report if NULL */
  ASSERT (in != NULL, status, CREATETFP_ENULL, CREATETFP_MSGENULL);

  /* Check return structure  */
  ASSERT (param != NULL, status, CREATETFP_ENULL, CREATETFP_MSGENULL);
  ASSERT (*param == NULL, status, CREATETFP_ENNUL, CREATETFP_MSGENNUL);

  *param = (TimeFreqParam *) LALMalloc(sizeof(TimeFreqParam));

  /* Check Allocation */
  ASSERT (*param != NULL, status, CREATETFP_EMALL, CREATETFP_MSGEMALL);

  (*param)->type=Undefined; /* Undefined until storage allocated */
  (*param)->windowT = NULL; /* NULL data until allocated */
  (*param)->windowF = NULL; /* NULL data until allocated */

  switch (in->type) {
  case Spectrogram :

    /* Make sure the window length is a odd number */
    ASSERT (in->wlengthT%2 != 0, status, CREATETFP_EWSIZ, CREATETFP_MSGEWSIZ);

    LALSCreateVector(status,&(*param)->windowT,in->wlengthT);
    (*param)->type = Spectrogram;

    break;
  case WignerVille :

    (*param)->type = WignerVille;

    break;
  case PSWignerVille :

    /* Make sure the window length is a odd number */
    ASSERT (in->wlengthT%2 != 0, status, CREATETFP_EWSIZ, CREATETFP_MSGEWSIZ);

    /* Make sure the window length is a odd number */
    ASSERT (in->wlengthF%2 != 0, status, CREATETFP_EWSIZ, CREATETFP_MSGEWSIZ);

    LALSCreateVector(status,&(*param)->windowT,in->wlengthT);
    LALSCreateVector(status,&(*param)->windowF,in->wlengthF);
    (*param)->type = PSWignerVille;

    break;
  case RSpectrogram :

    /* Make sure the window length is a odd number */
    ASSERT (in->wlengthT%2 != 0, status, CREATETFP_EWSIZ, CREATETFP_MSGEWSIZ);

    LALSCreateVector(status,&(*param)->windowT,in->wlengthT);
    (*param)->type = RSpectrogram;

    break;
  default :
    ABORT(status,CREATETFP_ETYPE, CREATETFP_MSGETYPE);

  }

  /* We be done: Normal exit */

  RETURN (status);
}
Ejemplo n.º 29
0
/* vvvvvvvvvvvvvvvvvvvvvvvvvvvvvv------------------------------------ */
int main(int argc, char *argv[]) {

    static LALStatus       status;
    static HOUGHMapTotal   ht;
    static HoughStats      stats;
    static UINT8Vector     hist;

    const CHAR   *fname = NULL;               /* The output filename */
    INT4   arg;                         /* Argument counter */
    INT4   i;
    FILE   *fp=NULL;                    /* Output file */

    fname = FILEOUT;
    /********************************************************/
    /* Parse argument list.  i stores the current position. */
    /********************************************************/
    arg = 1;
    while ( arg < argc ) {
        /* Parse debuglevel option. */
        if ( !strcmp( argv[arg], "-d" ) ) {
            if ( argc > arg + 1 ) {
                arg++;
            } else {
                ERROR( TESTSTATISTICSC_EARG, TESTSTATISTICSC_MSGEARG, 0 );
                XLALPrintError( USAGE, *argv );
                return TESTSTATISTICSC_EARG;
            }
        }
        /* Parse output file option. */
        else if ( !strcmp( argv[arg], "-o" ) ) {
            if ( argc > arg + 1 ) {
                arg++;
                fname = argv[arg++];
            } else {
                ERROR( TESTSTATISTICSC_EARG, TESTSTATISTICSC_MSGEARG, 0 );
                XLALPrintError( USAGE, *argv );
                return TESTSTATISTICSC_EARG;
            }
        }
        /* Unrecognized option. */
        else {
            ERROR( TESTSTATISTICSC_EARG, TESTSTATISTICSC_MSGEARG, 0 );
            XLALPrintError( USAGE, *argv );
            return TESTSTATISTICSC_EARG;
        }
    } /* End of argument parsing loop. */
    /******************************************************************/

    /* ------------------------------------------------------- */

    /* create a hough map */
    ht.mObsCoh = 1000;
    ht.xSide = 100;
    ht.ySide = 100;
    /* allocate memory for hough map */
    ht.map = (HoughTT *)LALMalloc(ht.xSide * ht.ySide * sizeof(HoughTT));
    /* make up a hough map */
    for (i = 0; i < floor(ht.xSide * ht.ySide / 2.0); i++) ht.map[i] = 500;
    for (i = ceil(ht.xSide * ht.ySide / 2.0); i < ht.xSide * ht.ySide; i++) ht.map[i] = 900;
    SUB( LALHoughStatistics ( &status, &stats, &ht), &status );

    printf(" Maximum number count: %d\n", (int)stats.maxCount);
    printf(" Location: %d  %d\n", stats.maxIndex[0], stats.maxIndex[1]);
    printf(" Minimum number count: %d\n", (int)stats.minCount);
    printf(" Location: %d  %d\n", stats.minIndex[0], stats.minIndex[1]);
    printf(" Average number count: %f\n", stats.avgCount);
    printf(" Standard deviation of number count: %f\n", stats.stdDev);

    /* allocate memory for histogram */

    hist.length = ht.mObsCoh +1;
    hist.data= NULL;
    hist.data = (UINT8 *)LALMalloc((hist.length)*sizeof(UINT8));

    SUB( LALHoughHistogram ( &status, &hist, &ht), &status);

    /* write histogram to a file */
    fp = fopen(fname, "w");

    if ( !fp ) {
        ERROR( TESTSTATISTICSC_EFILE, TESTSTATISTICSC_MSGEFILE, 0 );
        return TESTSTATISTICSC_EFILE;
    }

    for (i=0; i < (INT4)hist.length; i++) {
        fprintf(fp,"%d  %" LAL_UINT8_FORMAT "\n", i, hist.data[i]);
    }


    fclose(fp);
    LALFree(ht.map);
    LALFree(hist.data);
    LALCheckMemoryLeaks();

    INFO(TESTSTATISTICSC_MSGENORM);
    return TESTSTATISTICSC_ENORM;
}
Ejemplo n.º 30
0
int
main(int argc, char **argv)
{
  /* Command-line parsing variables. */
  int arg;                   /* command-line argument counter */
  static LALStatus stat;     /* status structure */
  CHAR *sourcefile = NULL;   /* name of sourcefile */
  CHAR *respfile = NULL;     /* name of respfile */
  CHAR *infile = NULL;       /* name of infile */
  CHAR *outfile = NULL;      /* name of outfile */
  INT4 seed = 0;             /* random number seed */
  INT4 sec = SEC;            /* ouput epoch.gpsSeconds */
  INT4 nsec = NSEC;          /* ouput epoch.gpsNanoSeconds */
  INT4 npt = NPT;            /* number of output points */
  REAL8 dt = DT;             /* output sampling interval */
  REAL4 sigma = SIGMA;       /* noise amplitude */

  /* File reading variables. */
  FILE *fp = NULL; /* generic file pointer */
  BOOLEAN ok = 1;  /* whether input format is correct */
  UINT4 i;         /* generic index over file lines */
  INT8 epoch;      /* epoch stored as an INT8 */

  /* Other global variables. */
  RandomParams *params = NULL; /* parameters of pseudorandom sequence */
  DetectorResponse detector;   /* the detector in question */
  INT2TimeSeries output;       /* detector ACD output */


  /*******************************************************************
   * PARSE ARGUMENTS (arg stores the current position)               *
   *******************************************************************/

  /* Exit gracefully if no arguments were given.
  if ( argc <= 1 ) {
    INFO( "No testing done." );
    return 0;
  } */

  arg = 1;
  while ( arg < argc ) {
    /* Parse source file option. */
    if ( !strcmp( argv[arg], "-s" ) ) {
      if ( argc > arg + 1 ) {
	arg++;
	sourcefile = argv[arg++];
      }else{
	ERROR( BASICINJECTTESTC_EARG, BASICINJECTTESTC_MSGEARG, 0 );
        LALPrintError( USAGE, *argv );
        return BASICINJECTTESTC_EARG;
      }
    }
    /* Parse response file option. */
    else if ( !strcmp( argv[arg], "-r" ) ) {
      if ( argc > arg + 1 ) {
	arg++;
	respfile = argv[arg++];
      }else{
	ERROR( BASICINJECTTESTC_EARG, BASICINJECTTESTC_MSGEARG, 0 );
        LALPrintError( USAGE, *argv );
        return BASICINJECTTESTC_EARG;
      }
    }
    /* Parse input file option. */
    else if ( !strcmp( argv[arg], "-i" ) ) {
      if ( argc > arg + 1 ) {
	arg++;
	infile = argv[arg++];
      }else{
	ERROR( BASICINJECTTESTC_EARG, BASICINJECTTESTC_MSGEARG, 0 );
        LALPrintError( USAGE, *argv );
        return BASICINJECTTESTC_EARG;
      }
    }
    /* Parse noise output option. */
    else if ( !strcmp( argv[arg], "-n" ) ) {
      if ( argc > arg + 5 ) {
	arg++;
	sec = atoi( argv[arg++] );
	nsec = atoi( argv[arg++] );
	npt = atoi( argv[arg++] );
	dt = atof( argv[arg++] );
	sigma = atof( argv[arg++] );
      }else{
	ERROR( BASICINJECTTESTC_EARG, BASICINJECTTESTC_MSGEARG, 0 );
        LALPrintError( USAGE, *argv );
        return BASICINJECTTESTC_EARG;
      }
    }
    /* Parse output file option. */
    else if ( !strcmp( argv[arg], "-o" ) ) {
      if ( argc > arg + 1 ) {
	arg++;
	outfile = argv[arg++];
      }else{
	ERROR( BASICINJECTTESTC_EARG, BASICINJECTTESTC_MSGEARG, 0 );
        LALPrintError( USAGE, *argv );
        return BASICINJECTTESTC_EARG;
      }
    }
    /* Parse debug level option. */
    else if ( !strcmp( argv[arg], "-d" ) ) {
      if ( argc > arg + 1 ) {
	arg++;
      }else{
	ERROR( BASICINJECTTESTC_EARG, BASICINJECTTESTC_MSGEARG, 0 );
        LALPrintError( USAGE, *argv );
        return BASICINJECTTESTC_EARG;
      }
    }
    /* Parse random seed option. */
    else if ( !strcmp( argv[arg], "-e" ) ) {
      if ( argc > arg + 1 ) {
	arg++;
	seed = atoi( argv[arg++] );
      }else{
	ERROR( BASICINJECTTESTC_EARG, BASICINJECTTESTC_MSGEARG, 0 );
        LALPrintError( USAGE, *argv );
        return BASICINJECTTESTC_EARG;
      }
    }
    /* Check for unrecognized options. */
    else if ( argv[arg][0] == '-' ) {
      ERROR( BASICINJECTTESTC_EARG, BASICINJECTTESTC_MSGEARG, 0 );
      LALPrintError( USAGE, *argv );
      return BASICINJECTTESTC_EARG;
    }
  } /* End of argument parsing loop. */

  /* Check for redundant or bad argument values. */
  CHECKVAL( npt, 0, 2147483647 );
  CHECKVAL( dt, 0, LAL_REAL4_MAX );


  /*******************************************************************
   * SETUP                                                           *
   *******************************************************************/

  /* Set up output, detector, and random parameter structures. */
  output.data = NULL;
  detector.transfer = (COMPLEX8FrequencySeries *)
    LALMalloc( sizeof(COMPLEX8FrequencySeries) );
  if ( !(detector.transfer) ) {
    ERROR( BASICINJECTTESTC_EMEM, BASICINJECTTESTC_MSGEMEM, 0 );
    return BASICINJECTTESTC_EMEM;
  }
  detector.transfer->data = NULL;
  detector.site = NULL;
  SUB( LALCreateRandomParams( &stat, &params, seed ), &stat );

  /* Set up units. */
  output.sampleUnits = lalADCCountUnit;
  if (XLALUnitDivide( &(detector.transfer->sampleUnits),
                      &lalADCCountUnit, &lalStrainUnit ) == NULL) {
    return LAL_EXLAL;
  }

  /* Read response function. */
  if ( respfile ) {
    REAL4VectorSequence *resp = NULL; /* response as vector sequence */
    COMPLEX8Vector *response = NULL;  /* response as complex vector */
    COMPLEX8Vector *unity = NULL;     /* vector of complex 1's */

    if ( ( fp = fopen( respfile, "r" ) ) == NULL ) {
      ERROR( BASICINJECTTESTC_EFILE, BASICINJECTTESTC_MSGEFILE,
	     respfile );
      return BASICINJECTTESTC_EFILE;
    }

    /* Read header. */
    ok &= ( fscanf( fp, "# epoch = %" LAL_INT8_FORMAT "\n", &epoch ) == 1 );
    I8ToLIGOTimeGPS( &( detector.transfer->epoch ), epoch );
    ok &= ( fscanf( fp, "# f0 = %lf\n", &( detector.transfer->f0 ) )
	    == 1 );
    ok &= ( fscanf( fp, "# deltaF = %lf\n",
		    &( detector.transfer->deltaF ) ) == 1 );
    if ( !ok ) {
      ERROR( BASICINJECTTESTC_EINPUT, BASICINJECTTESTC_MSGEINPUT,
	     respfile );
      return BASICINJECTTESTC_EINPUT;
    }

    /* Read and convert body to a COMPLEX8Vector. */
    SUB( LALSReadVectorSequence( &stat, &resp, fp ), &stat );
    fclose( fp );
    if ( resp->vectorLength != 2 ) {
      ERROR( BASICINJECTTESTC_EINPUT, BASICINJECTTESTC_MSGEINPUT,
	     respfile );
      return BASICINJECTTESTC_EINPUT;
    }
    SUB( LALCCreateVector( &stat, &response, resp->length ), &stat );
    memcpy( response->data, resp->data, 2*resp->length*sizeof(REAL4) );
    SUB( LALSDestroyVectorSequence( &stat, &resp ), &stat );

    /* Convert response function to a transfer function. */
    SUB( LALCCreateVector( &stat, &unity, response->length ), &stat );
    for ( i = 0; i < response->length; i++ ) {
      unity->data[i] = 1.0;
    }
    SUB( LALCCreateVector( &stat, &( detector.transfer->data ),
			   response->length ), &stat );
    SUB( LALCCVectorDivide( &stat, detector.transfer->data, unity,
			    response ), &stat );
    SUB( LALCDestroyVector( &stat, &response ), &stat );
    SUB( LALCDestroyVector( &stat, &unity ), &stat );
  }

  /* No response file, so generate a unit response. */
  else {
    I8ToLIGOTimeGPS( &( detector.transfer->epoch ), EPOCH );
    detector.transfer->f0 = 0.0;
    detector.transfer->deltaF = 1.5*FSTOP;
    SUB( LALCCreateVector( &stat, &( detector.transfer->data ), 2 ),
	 &stat );
    detector.transfer->data->data[0] = 1.0;
    detector.transfer->data->data[1] = 1.0;
  }


  /* Read input data. */
  if ( infile ) {
    REAL4VectorSequence *input = NULL; /* input as vector sequence */
    if ( ( fp = fopen( infile, "r" ) ) == NULL ) {
      ERROR( BASICINJECTTESTC_EFILE, BASICINJECTTESTC_MSGEFILE,
	     infile );
      return BASICINJECTTESTC_EFILE;
    }

    /* Read header. */
    ok &= ( fscanf( fp, "# epoch = %" LAL_INT8_FORMAT "\n", &epoch ) == 1 );
    I8ToLIGOTimeGPS( &( output.epoch ), epoch );
    ok &= ( fscanf( fp, "# deltaT = %lf\n", &( output.deltaT ) )
	    == 1 );
    if ( !ok ) {
      ERROR( BASICINJECTTESTC_EINPUT, BASICINJECTTESTC_MSGEINPUT,
	     infile );
      return BASICINJECTTESTC_EINPUT;
    }

    /* Read and convert body. */
    SUB( LALSReadVectorSequence( &stat, &input, fp ), &stat );
    fclose( fp );
    if ( input->vectorLength != 1 ) {
      ERROR( BASICINJECTTESTC_EINPUT, BASICINJECTTESTC_MSGEINPUT,
	     infile );
      return BASICINJECTTESTC_EINPUT;
    }
    SUB( LALI2CreateVector( &stat, &( output.data ), input->length ),
	 &stat );
    for ( i = 0; i < input->length; i++ )
      output.data->data[i] = (INT2)( input->data[i] );
    SUB( LALSDestroyVectorSequence( &stat, &input ), &stat );
  }

  /* No input file, so generate one randomly. */
  else {
    output.epoch.gpsSeconds = sec;
    output.epoch.gpsNanoSeconds = nsec;
    output.deltaT = dt;
    SUB( LALI2CreateVector( &stat, &( output.data ), npt ), &stat );
    if ( sigma == 0 ) {
      memset( output.data->data, 0, npt*sizeof(INT2) );
    } else {
      REAL4Vector *deviates = NULL; /* unit Gaussian deviates */
      SUB( LALSCreateVector( &stat, &deviates, npt ), &stat );
      SUB( LALNormalDeviates( &stat, deviates, params ), &stat );
      for ( i = 0; i < (UINT4)( npt ); i++ )
	output.data->data[i] = (INT2)
	  floor( sigma*deviates->data[i] + 0.5 );
      SUB( LALSDestroyVector( &stat, &deviates ), &stat );
    }
  }


  /*******************************************************************
   * INJECTION                                                       *
   *******************************************************************/

  /* Open sourcefile. */
  if ( sourcefile ) {
    if ( ( fp = fopen( sourcefile, "r" ) ) == NULL ) {
      ERROR( BASICINJECTTESTC_EFILE, BASICINJECTTESTC_MSGEFILE,
	     sourcefile );
      return BASICINJECTTESTC_EFILE;
    }
  }

  /* For each line in the sourcefile... */
  while ( ok ) {
    PPNParamStruc ppnParams;       /* wave generation parameters */
    REAL4 m1, m2, dist, inc, phic; /* unconverted parameters */
    CoherentGW waveform;           /* amplitude and phase structure */
    REAL4TimeSeries signalvec;     /* GW signal */
    REAL8 time;                    /* length of GW signal */
    CHAR timeCode;                 /* code for signal time alignment */
    CHAR message[MSGLEN];          /* warning/info messages */

    /* Read and convert input line. */
    if ( sourcefile ) {
      ok &= ( fscanf( fp, "%c %" LAL_INT8_FORMAT " %f %f %f %f %f\n", &timeCode,
		      &epoch, &m1, &m2, &dist, &inc, &phic ) == 7 );
      ppnParams.mTot = m1 + m2;
      ppnParams.eta = m1*m2/( ppnParams.mTot*ppnParams.mTot );
      ppnParams.d = dist*LAL_PC_SI*1000.0;
      ppnParams.inc = inc*LAL_PI/180.0;
      ppnParams.phi = phic*LAL_PI/180.0;
    } else {
      timeCode = 'i';
      ppnParams.mTot = M1 + M2;
      ppnParams.eta = M1*M2/( ppnParams.mTot*ppnParams.mTot );
      ppnParams.d = DIST;
      ppnParams.inc = INC;
      ppnParams.phi = PHIC;
      epoch = EPOCH;
    }

    if ( ok ) {
      /* Set up other parameter structures. */
      ppnParams.epoch.gpsSeconds = ppnParams.epoch.gpsNanoSeconds = 0;
      ppnParams.position.latitude = ppnParams.position.longitude = 0.0;
      ppnParams.position.system = COORDINATESYSTEM_EQUATORIAL;
      ppnParams.psi = 0.0;
      ppnParams.fStartIn = FSTART;
      ppnParams.fStopIn = FSTOP;
      ppnParams.lengthIn = 0;
      ppnParams.ppn = NULL;
      ppnParams.deltaT = DELTAT;
      memset( &waveform, 0, sizeof(CoherentGW) );

      /* Generate waveform at zero epoch. */
      SUB( LALGeneratePPNInspiral( &stat, &waveform, &ppnParams ),
	   &stat );
      snprintf( message, MSGLEN, "%d: %s", ppnParams.termCode,
		   ppnParams.termDescription );
      INFO( message );
      if ( ppnParams.dfdt > 2.0 ) {
	snprintf( message, MSGLEN,
		     "Waveform sampling interval is too large:\n"
		     "\tmaximum df*dt = %f", ppnParams.dfdt );
	WARNING( message );
      }

      /* Compute epoch for waveform. */
      time = waveform.a->data->length*DELTAT;
      if ( timeCode == 'f' )
	epoch -= (INT8)( 1000000000.0*time );
      else if ( timeCode == 'c' )
	epoch -= (INT8)( 1000000000.0*ppnParams.tc );
      I8ToLIGOTimeGPS( &( waveform.a->epoch ), epoch );
      waveform.f->epoch = waveform.phi->epoch = waveform.a->epoch;

      /* Generate and inject signal. */
      signalvec.epoch = waveform.a->epoch;
      signalvec.epoch.gpsSeconds -= 1;
      signalvec.deltaT = output.deltaT/4.0;
      signalvec.f0 = 0;
      signalvec.data = NULL;
      time = ( time + 2.0 )/signalvec.deltaT;
      SUB( LALSCreateVector( &stat, &( signalvec.data ), (UINT4)time ),
	   &stat );
      SUB( LALSimulateCoherentGW( &stat, &signalvec, &waveform,
				  &detector ), &stat );
      SUB( LALSI2InjectTimeSeries( &stat, &output, &signalvec, params ),
	   &stat );
      SUB( LALSDestroyVectorSequence( &stat, &( waveform.a->data ) ),
	   &stat );
      SUB( LALSDestroyVector( &stat, &( waveform.f->data ) ), &stat );
      SUB( LALDDestroyVector( &stat, &( waveform.phi->data ) ), &stat );
      LALFree( waveform.a );
      LALFree( waveform.f );
      LALFree( waveform.phi );
      SUB( LALSDestroyVector( &stat, &( signalvec.data ) ), &stat );
    }

    /* If there is no source file, inject only one source. */
    if ( !sourcefile )
      ok = 0;
  }

  /* Input file is exhausted (or has a badly-formatted line ). */
  if ( sourcefile )
    fclose( fp );


  /*******************************************************************
   * CLEANUP                                                         *
   *******************************************************************/

  /* Print output file. */
  if ( outfile ) {
    if ( ( fp = fopen( outfile, "w" ) ) == NULL ) {
      ERROR( BASICINJECTTESTC_EFILE, BASICINJECTTESTC_MSGEFILE,
	     outfile );
      return BASICINJECTTESTC_EFILE;
    }
    epoch = 1000000000LL*(INT8)( output.epoch.gpsSeconds );
    epoch += (INT8)( output.epoch.gpsNanoSeconds );
    fprintf( fp, "# epoch = %" LAL_INT8_FORMAT "\n", epoch );
    fprintf( fp, "# deltaT = %23.16e\n", output.deltaT );
    for ( i = 0; i < output.data->length; i++ )
      fprintf( fp, "%8.1f\n", (REAL4)( output.data->data[i] ) );
    fclose( fp );
  }

  /* Destroy remaining memory. */
  SUB( LALDestroyRandomParams( &stat, &params ), &stat );
  SUB( LALI2DestroyVector( &stat, &( output.data ) ), &stat );
  SUB( LALCDestroyVector( &stat, &( detector.transfer->data ) ),
       &stat );
  LALFree( detector.transfer );

  /* Done! */
  LALCheckMemoryLeaks();
  INFO( BASICINJECTTESTC_MSGENORM );
  return BASICINJECTTESTC_ENORM;
}