LALREAL8SequenceInterp *XLALREAL8SequenceInterpCreate(const REAL8Sequence *s, int kernel_length)
{
	LALREAL8SequenceInterp *interp;
	double *cached_kernel;

	if(kernel_length < 3)
		XLAL_ERROR_NULL(XLAL_EDOM);
	/* interpolator induces phase shifts unless this is odd */
	kernel_length -= (~kernel_length) & 1;

	interp = XLALMalloc(sizeof(*interp));
	cached_kernel = XLALMalloc(kernel_length * sizeof(*cached_kernel));
	if(!interp || !cached_kernel) {
		XLALFree(interp);
		XLALFree(cached_kernel);
		XLAL_ERROR_NULL(XLAL_EFUNC);
	}

	interp->s = s;
	interp->kernel_length = kernel_length;
	interp->welch_factor = 1.0 / ((kernel_length - 1.) / 2. + 1.);
	interp->cached_kernel = cached_kernel;
	/* >= 1 --> impossible.  forces kernel init on first eval */
	interp->residual = 2.;
	/* set no-op threshold.  the kernel is recomputed when the residual
	 * changes by this much */
	interp->noop_threshold = 1. / (4 * interp->kernel_length);

	return interp;
}
Exemple #2
0
/**
 * @brief Read a two-column data file.
 * @details Read a data file containing two whitespace separated columns
 * of data and create two arrays containing the data in each column.
 * If any line begins with the character '#' then it is ignored.
 * @param[out] xdat The x-data stored in the first column.
 * @param[out] ydat The y-data stored in the second column.
 * @param fp Pointer to a LALFILE structure opened for input.
 * @return The number of data points read or <0 if an error occurs.
 */
size_t XLALSimReadDataFile2Col(double **xdat, double **ydat, LALFILE * fp)
{
    char line[LINE_MAX];
    size_t size = PAGESIZE;
    size_t lnum = 0;
    size_t npts;
    *xdat = XLALMalloc(size * sizeof(**xdat));
    *ydat = XLALMalloc(size * sizeof(**ydat));
    npts = 0;
    while (XLALFileGets(line, sizeof(line), fp)) {
        ++lnum;
        if (strchr(line, '\n') == NULL) {   /* line too long */
            XLALFree(*xdat);
            XLALFree(*ydat);
            XLAL_ERROR(XLAL_EIO, "Line %zd too long\n", lnum);
        }
        if (*line == '#')       /* ignore lines beginning with a '#' */
            continue;
        if (sscanf(line, "%lf %lf", *xdat + npts, *ydat + npts) != 2) {
            XLALFree(*xdat);
            XLALFree(*ydat);
            XLAL_ERROR(XLAL_EIO, "Line %zd malformed\n", lnum);
        }
        if (++npts == size) {
            size += PAGESIZE;
            *xdat = XLALRealloc(*xdat, size * sizeof(**xdat));
            *ydat = XLALRealloc(*ydat, size * sizeof(**ydat));
        }
    }
    *xdat = XLALRealloc(*xdat, npts * sizeof(**xdat));
    *ydat = XLALRealloc(*ydat, npts * sizeof(**ydat));
    return npts;
}
Exemple #3
0
/**
 * Restrict the EphemerisData 'edat' to the smallest number of entries
 * required to cover the GPS time range ['startGPS', 'endGPS']
 *
 * \ingroup LALBarycenter_h
 */
int XLALRestrictEphemerisData ( EphemerisData *edat, const LIGOTimeGPS *startGPS, const LIGOTimeGPS *endGPS ) {

  // Check input
  XLAL_CHECK(edat != NULL, XLAL_EFAULT);
  XLAL_CHECK(startGPS != NULL, XLAL_EFAULT);
  XLAL_CHECK(endGPS != NULL, XLAL_EFAULT);
  XLAL_CHECK(XLALGPSCmp(startGPS, endGPS) < 0, XLAL_EINVAL);

  // Convert 'startGPS' and 'endGPS' to REAL8s
  const REAL8 start = XLALGPSGetREAL8(startGPS), end = XLALGPSGetREAL8(endGPS);

  // Increase 'ephemE' and decrease 'nentriesE' to fit the range ['start', 'end']
  PosVelAcc *const old_ephemE = edat->ephemE;
  do {
    if (edat->nentriesE > 1 && edat->ephemE[0].gps < start && edat->ephemE[1].gps <= start) {
      ++edat->ephemE;
      --edat->nentriesE;
    } else if (edat->nentriesE > 1 && edat->ephemE[edat->nentriesE-1].gps > end && edat->ephemE[edat->nentriesE-2].gps >= end) {
      --edat->nentriesE;
    } else {
      break;
    }
  } while(1);

  // Reallocate 'ephemE' to new table size, and free old table
  PosVelAcc *const new_ephemE = XLALMalloc(edat->nentriesE * sizeof(*new_ephemE));
  XLAL_CHECK(new_ephemE != NULL, XLAL_ENOMEM);
  memcpy(new_ephemE, edat->ephemE, edat->nentriesE * sizeof(*new_ephemE));
  edat->ephemE = new_ephemE;
  XLALFree(old_ephemE);

  // Increase 'ephemS' and decrease 'nentriesS' to fit the range ['start', 'end']
  PosVelAcc *const old_ephemS = edat->ephemS;
  do {
    if (edat->nentriesS > 1 && edat->ephemS[0].gps < start && edat->ephemS[1].gps <= start) {
      ++edat->ephemS;
      --edat->nentriesS;
    } else if (edat->nentriesS > 1 && edat->ephemS[edat->nentriesS-1].gps > end && edat->ephemS[edat->nentriesS-2].gps >= end) {
      --edat->nentriesS;
    } else {
      break;
    }
  } while(1);

  // Reallocate 'ephemS' to new table size, and free old table
  PosVelAcc *const new_ephemS = XLALMalloc(edat->nentriesS * sizeof(*new_ephemS));
  XLAL_CHECK(new_ephemS != NULL, XLAL_ENOMEM);
  memcpy(new_ephemS, edat->ephemS, edat->nentriesS * sizeof(*new_ephemS));
  edat->ephemS = new_ephemS;
  XLALFree(old_ephemS);

  return XLAL_SUCCESS;

} /* XLALRestrictEphemerisData() */
Exemple #4
0
/**
 * Allocate a candidateVector
 * \param [in] length Length of the candidateVector
 * \return Pointer to the allocated candidateVector
 */
candidateVector * new_candidateVector(UINT4 length)
{

   candidateVector *vector = NULL;
   XLAL_CHECK_NULL( (vector = XLALMalloc(sizeof(*vector))) != NULL, XLAL_ENOMEM );

   vector->length = length;
   vector->numofcandidates = 0;
   if (length==0) vector->data = NULL;
   else XLAL_CHECK_NULL( (vector->data = XLALMalloc( length*sizeof(*vector->data) )) != NULL, XLAL_ENOMEM );

   return vector;

} /* new_candidateVector() */
/**
 * Function that creates the head node of the test GR parameters linked list.
 * It is initialized with a single parameter with given name and value
 */
LALSimInspiralTestGRParam *XLALSimInspiralCreateTestGRParam(
        const char *name, /**< Name of first parameter in new linked list */
        double value 	 /**< Value of first parameter in new linked list */
        )
{
        LALSimInspiralTestGRParam *parameter = (LALSimInspiralTestGRParam *)XLALMalloc(sizeof(LALSimInspiralTestGRParam));
        if (parameter) 
        {
            parameter->data =  (LALSimInspiralTestGRParamData *)XLALMalloc(sizeof(LALSimInspiralTestGRParamData));
            memcpy(parameter->data->name, name, 32);
            parameter->data->value = value;
        }
        parameter->next=NULL;
        return parameter;
}
/// Parse a string into a BOOLEAN
/// Allowed string-values are (case-insensitive):
/// {"yes", "true", "1"} --> TRUE
/// {"no", "false", "0"} --> FALSE
///
/// NOTE: This throws an error on _any_ extraneous leading or trailing characters or whitespace
int
XLALParseStringValueAsBOOLEAN ( BOOLEAN *valBOOLEAN,     ///< [out] return BOOLEAN value
                                const char *valString    ///< [in]  input string value
                                )
{
  XLAL_CHECK ( (valBOOLEAN != NULL) && (valString != NULL ), XLAL_EINVAL );

  /* get rid of case ambiguities */
  char *valStringLower;
  XLAL_CHECK ( (valStringLower = XLALMalloc ( strlen(valString) + 1 )) != NULL, XLAL_ENOMEM );
  strcpy ( valStringLower, valString );
  XLALStringToLowerCase ( valStringLower );

  /* parse it as a bool */
  if ( !strcmp(valStringLower, "yes") || !strcmp(valStringLower, "true") || !strcmp(valStringLower, "1") )
    {
      (*valBOOLEAN) = 1;
    }
  else if ( !strcmp(valStringLower, "no") || !strcmp(valStringLower, "false") || !strcmp(valStringLower, "0") )
    {
      (*valBOOLEAN) = 0;
    }
  else
    {
      XLALFree ( valStringLower );
      XLAL_ERROR ( XLAL_EINVAL, "Illegal bool-string '%s', needs to be one of {'yes', 'true', '1'} or {'no', 'false', '0'} (case-insensitive)\n", valString );
    }

  XLALFree ( valStringLower );

  return XLAL_SUCCESS;

} // XLALParseStringValueAsBOOLEAN()
/**
 * Change frequency-bin order from 'SFT' to fftw-convention
 * ie. from f[-(N-1)/2], ... f[-1], f[0], f[1], .... f[N/2]
 * to FFTW: f[0], f[1],...f[N/2], f[-(N-1)/2], ... f[-2], f[-1]
 */
int
XLALReorderSFTtoFFTW (COMPLEX8Vector *X)
{
  XLAL_CHECK ( (X != NULL) && (X->length > 0), XLAL_EINVAL );

  UINT4 N = X->length;
  UINT4 Npos_and_DC = NhalfPosDC ( N );
  UINT4 Nneg = NhalfNeg ( N );

  /* allocate temporary storage for swap */
  COMPLEX8 *tmp;
  XLAL_CHECK ( (tmp = XLALMalloc ( N * sizeof(*tmp) )) != NULL, XLAL_ENOMEM );

  memcpy ( tmp, X->data, N * sizeof(*tmp) );

  /* Copy second half of FFTW: 'negative' frequencies */
  memcpy ( X->data + Npos_and_DC, tmp, Nneg * sizeof(*tmp) );

  /* Copy first half of FFTW: 'DC + positive' frequencies */
  memcpy ( X->data, tmp + Nneg, Npos_and_DC * sizeof(*tmp) );

  XLALFree(tmp);

  return XLAL_SUCCESS;

}  // XLALReorderSFTtoFFTW()
Exemple #8
0
/**
 * \ingroup Date_h
 * \brief Return a string containing the ASCII base 10 representation of a
 * LIGOTimeGPS.  If s is not NULL, then the string is written to that
 * location which must be large enough to hold the string plus a 0
 * terminator.  If s is NULL then a new buffer is allocated, and the string
 * written to it;  free the buffer with XLALFree().  The return value is
 * the address of the string or NULL on failure.
 */
char *XLALGPSToStr(char *s, const LIGOTimeGPS *t)
{
	char *end;
	/* so we can play with it */
	LIGOTimeGPS copy = *t;

	/* make sure we've got a buffer */

	if(!s) {
		/* 22 = 9 digits to the right of the decimal point +
		 * decimal point + upto 10 digits to the left of the
		 * decimal point plus an optional sign + a null */
		s = XLALMalloc(22 * sizeof(*s));
		if(!s)
			XLAL_ERROR_NULL(XLAL_EFUNC);
	}

	/* normalize the fractional part */

	while(labs(copy.gpsNanoSeconds) >= XLAL_BILLION_INT4) {
		if(copy.gpsNanoSeconds < 0) {
			copy.gpsSeconds -= 1;
			copy.gpsNanoSeconds += XLAL_BILLION_INT4;
		} else {
			copy.gpsSeconds += 1;
			copy.gpsNanoSeconds -= XLAL_BILLION_INT4;
		}
	}

	/* if both components are non-zero, make sure they have the same
	 * sign */

	if(copy.gpsSeconds > 0 && copy.gpsNanoSeconds < 0) {
		copy.gpsSeconds -= 1;
		copy.gpsNanoSeconds += XLAL_BILLION_INT4;
	} else if(copy.gpsSeconds < 0 && copy.gpsNanoSeconds > 0) {
		copy.gpsSeconds += 1;
		copy.gpsNanoSeconds -= XLAL_BILLION_INT4;
	}

	/* print */

	if(copy.gpsSeconds < 0 || copy.gpsNanoSeconds < 0)
		/* number is negative */
		end = s + sprintf(s, "-%ld.%09ld", labs(copy.gpsSeconds), labs(copy.gpsNanoSeconds));
	else
		/* number is non-negative */
		end = s + sprintf(s, "%ld.%09ld", (long) copy.gpsSeconds, (long) copy.gpsNanoSeconds);

	/* remove trailing 0s and decimal point */

	while(*(--end) == '0')
		*end = 0;
	if(*end == '.')
		*end = 0;

	/* done */

	return s;
}
Exemple #9
0
/**
 * Allocate a new UpperLimitVector
 * \param [in] length Length of the vector
 * \return Pointer to newly allocated UpperLimitVector
 */
UpperLimitVector * new_UpperLimitVector(UINT4 length)
{

    UpperLimitVector *vector = NULL;
    XLAL_CHECK_NULL( (vector = XLALMalloc(sizeof(*vector))) != NULL, XLAL_ENOMEM );

    vector->length = length;
    if (length==0) vector->data = NULL;
    else {
        XLAL_CHECK_NULL( (vector->data = XLALMalloc( length*sizeof(*vector->data) )) != NULL, XLAL_ENOMEM );
        for (UINT4 ii=0; ii<length; ii++) reset_UpperLimitStruct(&(vector->data[ii]));
    }

    return vector;

} /* new_UpperLimitVector() */
Exemple #10
0
/**
 * Allocate memory for farStruct
 * \return Pointer to a farStruct
 */
farStruct * new_farStruct(void)
{
   farStruct *farstruct = NULL;
   XLAL_CHECK_NULL( (farstruct = XLALMalloc(sizeof(*farstruct))) != NULL, XLAL_ENOMEM );
   farstruct->far = 1.0;
   farstruct->topRvalues = NULL;
   return farstruct;
} /* new_farStruct() */
Exemple #11
0
inputParamsStruct * new_inputParams(INT4 numofIFOs)
{
   
   inputParamsStruct *input = XLALMalloc(sizeof(*input));
   if (input==NULL) {
      fprintf(stderr,"%s: XLALMalloc(%zu) failed.", __func__, sizeof(*input));
      XLAL_ERROR_NULL(XLAL_ENOMEM);
   }
   input->det = XLALMalloc(numofIFOs*sizeof(LALDetector));
   if (input->det==NULL) {
      fprintf(stderr,"%s: XLALMalloc(%zu) failed.", __func__, numofIFOs*sizeof(LALDetector));
      XLAL_ERROR_NULL(XLAL_ENOMEM);
   }
   input->rng = gsl_rng_alloc(gsl_rng_mt19937);
   if (input->rng==NULL) {
      fprintf(stderr,"%s: gsl_rng_alloc() failed.", __func__);
      XLAL_ERROR_NULL(XLAL_ENOMEM);
   }
   
   return input;

} /* new_inputParams() */
/**
 * Turn the given multiSFTvector into multiple long COMPLEX8TimeSeries, properly dealing with gaps.
 * Memory allocation for the output MultiCOMPLEX8TimeSeries is done within this function.
 *
 */
MultiCOMPLEX8TimeSeries *
XLALMultiSFTVectorToCOMPLEX8TimeSeries ( const MultiSFTVector *multisfts  /**< [in] multi SFT vector */
                                         )
{
  // check input sanity
  XLAL_CHECK_NULL ( (multisfts != NULL) && (multisfts->length > 0), XLAL_EINVAL );
  UINT4 numDetectors = multisfts->length;

  /* allocate memory for the output structure */
  MultiCOMPLEX8TimeSeries *out;
  XLAL_CHECK_NULL ( (out = XLALMalloc ( sizeof(MultiCOMPLEX8TimeSeries) )) != NULL, XLAL_ENOMEM );
  XLAL_CHECK_NULL ( (out->data = XLALMalloc ( numDetectors * sizeof(COMPLEX8TimeSeries*) )) != NULL, XLAL_ENOMEM );
  out->length = numDetectors;

  /* loop over detectors */
  for ( UINT4 X=0; X < numDetectors; X++ ) {
    XLAL_CHECK_NULL ( (out->data[X] = XLALSFTVectorToCOMPLEX8TimeSeries ( multisfts->data[X] )) != NULL, XLAL_EFUNC );
  }

  return out;

} // XLALMultiSFTVectorToCOMPLEX8TimeSeries()
Exemple #13
0
/**
 * Compute the standard deviation of a REAL4Vector
 * \param [out] sigma  Pointer to the output standard deviation value
 * \param [in]  vector Pointer to a REAL4Vector of values
 * \return Status value
 */
INT4 calcStddev(REAL4 *sigma, REAL4Vector *vector)
{

   double *gslarray = NULL;
   XLAL_CHECK( (gslarray = XLALMalloc(sizeof(double)*vector->length)) != NULL, XLAL_ENOMEM );
   for (INT4 ii=0; ii<(INT4)vector->length; ii++) gslarray[ii] = (double)vector->data[ii];
   *sigma = (REAL4)gsl_stats_sd(gslarray, 1, vector->length);

   XLALFree((double*)gslarray);

   return XLAL_SUCCESS;

} /* calcStddev() */
/**
 * Returns a deepcopy of the pointer of the numeraldata attribute of the
 * waveFlags structure. If this is NULL then NULL will be returned.
 * The returned value is independent of the waveFlags structure and will
 * need to be LALFree-d.
 */
char* XLALSimInspiralGetNumrelData(
    LALSimInspiralWaveformFlags *waveFlags
)
{
    char *ret_string;
    if ( waveFlags )
    {
        ret_string = XLALMalloc(FILENAME_MAX * sizeof(char));
        XLALStringCopy(ret_string, waveFlags->numreldata, sizeof(waveFlags->numreldata));
        return ret_string;
    }
    else
    {
        return NULL;
    }
}
static int read_matrix(const char dir[], const char fname[], gsl_matrix *m) {
  size_t size = strlen(dir) + strlen(fname) + 2;
  char *path = XLALMalloc(size);
  snprintf(path, size, "%s/%s", dir, fname);

  FILE *f = fopen(path, "rb");
  if (!f)
    XLAL_ERROR(XLAL_EIO, "Could not find ROM data file at path `%s'", path);
  int ret = gsl_matrix_fread(f, m);
  if (ret != 0)
     XLAL_ERROR(XLAL_EIO, "Error reading data from `%s'", path);
  fclose(f);

  XLAL_PRINT_INFO("Sucessfully read data file `%s'", path);
  XLALFree(path);
  return(XLAL_SUCCESS);
}
LALREAL8TimeSeriesInterp *XLALREAL8TimeSeriesInterpCreate(const REAL8TimeSeries *series, int kernel_length)
{
	LALREAL8TimeSeriesInterp *interp;
	LALREAL8SequenceInterp *seqinterp;

	interp = XLALMalloc(sizeof(*interp));
	seqinterp = XLALREAL8SequenceInterpCreate(series->data, kernel_length);
	if(!interp || !seqinterp) {
		XLALFree(interp);
		XLALREAL8SequenceInterpDestroy(seqinterp);
		XLAL_ERROR_NULL(XLAL_EFUNC);
	}

	interp->series = series;
	interp->seqinterp = seqinterp;

	return interp;
}
Exemple #17
0
RandomParams * XLALCreateRandomParams( INT4 seed )
{
  RandomParams *params;

  params = XLALMalloc( sizeof( *params) );
  if ( ! params )
    XLAL_ERROR_NULL( XLAL_ENOMEM );

  while ( seed == 0 ) /* use system clock to get seed */
    seed = time( NULL );

  if ( seed < 0 )
    seed = -seed;

  XLALResetRandomParams( params, seed );

  return params;
}
Exemple #18
0
/**
 * Simple creator function for MultiLIGOTimeGPSVector with numDetectors entries
 */
MultiLIGOTimeGPSVector *
XLALCreateMultiLIGOTimeGPSVector ( UINT4 numDetectors )
{
  MultiLIGOTimeGPSVector *ret;

  if ( (ret = XLALMalloc ( sizeof(*ret) )) == NULL ) {
    XLALPrintError ("%s: XLALMalloc(%zu) failed.\n", __func__, sizeof(*ret) );
    XLAL_ERROR_NULL ( XLAL_ENOMEM );
  }

  ret->length = numDetectors;
  if ( (ret->data = XLALCalloc ( numDetectors, sizeof(*ret->data) )) == NULL ) {
    XLALPrintError ("%s: XLALCalloc(%d, %zu) failed.\n", __func__, numDetectors, sizeof(*ret->data) );
    XLALFree ( ret );
    XLAL_ERROR_NULL ( XLAL_ENOMEM );
  }

  return ret;

} /* XLALCreateMultiLIGOTimeGPSVector() */
/**
 * Create a new LALSimInspiralWaveformFlags struct
 * with all flags set to their default values.
 *
 * Remember to destroy the struct when you are done with it.
 */
LALSimInspiralWaveformFlags *XLALSimInspiralCreateWaveformFlags(void)
{
    LALSimInspiralWaveformFlags *waveFlags;
    /* Allocate memory for the waveform flags */
    waveFlags = XLALMalloc( sizeof(*waveFlags) );
    if( !waveFlags )
    {
        XLALFree(waveFlags);
        XLAL_ERROR_NULL(XLAL_ENOMEM);
    }

    /* Set all flags to their default values */
    XLALSimInspiralSetSpinOrder(waveFlags,
                                LAL_SIM_INSPIRAL_SPIN_ORDER_DEFAULT);
    XLALSimInspiralSetTidalOrder(waveFlags,
                                 LAL_SIM_INSPIRAL_TIDAL_ORDER_DEFAULT);
    XLALSimInspiralSetFrameAxis(waveFlags,
                                LAL_SIM_INSPIRAL_FRAME_AXIS_DEFAULT);
    XLALSimInspiralSetModesChoice(waveFlags,
                                  LAL_SIM_INSPIRAL_MODES_CHOICE_DEFAULT);

    return waveFlags;
}
Exemple #20
0
/**
 * Function that assembles a default VCS info/version string from LAL and LALapps
 * Also checks LAL header<>library version consistency and returns NULL on error.
 *
 * The VCS version string is allocated here and must be freed by caller.
 */
char *
XLALGetVersionString( int level )
{
    char lal_info[1024];
#ifdef HAVE_LIBLALFRAME
    char lalframe_info[1024];
#endif
#ifdef HAVE_LIBLALMETAIO
    char lalmetaio_info[1024];
#endif
#ifdef HAVE_LIBLALXML
    char lalxml_info[1024];
#endif
#ifdef HAVE_LIBLALSIMULATION
    char lalsimulation_info[1024];
#endif
#ifdef HAVE_LIBLALBURST
    char lalburst_info[1024];
#endif
#ifdef HAVE_LIBLALINSPIRAL
    char lalinspiral_info[1024];
#endif
#ifdef HAVE_LIBLALPULSAR
    char lalpulsar_info[1024];
#endif
#ifdef HAVE_LIBLALINFERENCE
    char lalinference_info[1024];
#endif
#ifdef HAVE_LIBLALSTOCHASTIC
    char lalstochastic_info[1024];
#endif
    char lalapps_info[2048];
    char *ret;
    const char delim[] = ":";
    char *tree_status, *orig_tree_status;

    if ((LAL_VERSION_DEVEL != 0) || (LALAPPS_VERSION_DEVEL != 0))
    {
        /* check lal version consistency */
        if (version_compare(__func__, &lalVCSInfoHeader, &lalVCSInfo))
            exit(1);
    }

#ifdef HAVE_LIBLALFRAME
    if ((LALFRAME_VERSION_DEVEL != 0) || (LALAPPS_VERSION_DEVEL != 0))
    {
        /* check lalframe version consistency */
        if (version_compare(__func__, &lalFrameVCSInfoHeader, &lalFrameVCSInfo))
            exit(1);
    }
#endif

#ifdef HAVE_LIBLALMETAIO
    if ((LALMETAIO_VERSION_DEVEL != 0) || (LALAPPS_VERSION_DEVEL != 0))
    {
        /* check lalmetaio version consistency */
        if (version_compare(__func__, &lalMetaIOVCSInfoHeader, &lalMetaIOVCSInfo))
            exit(1);
    }
#endif

#ifdef HAVE_LIBLALSIMULATION
    if ((LALSIMULATION_VERSION_DEVEL != 0) || (LALSIMULATION_VERSION_DEVEL != 0))
    {
        /* check lalsimulaton version consistency */
        if (version_compare(__func__, &lalSimulationVCSInfoHeader, &lalSimulationVCSInfo))
            exit(1);
    }
#endif

#ifdef HAVE_LIBLALXML
    if ((LALXML_VERSION_DEVEL != 0) || (LALAPPS_VERSION_DEVEL != 0))
    {
        /* check lalxml version consistency */
        if (version_compare(__func__, &lalXMLVCSInfoHeader, &lalXMLVCSInfo))
            exit(1);
    }
#endif

#ifdef HAVE_LIBLALBURST
    if ((LALBURST_VERSION_DEVEL != 0) || (LALAPPS_VERSION_DEVEL != 0))
    {
        /* check lalburst version consistency */
        if (version_compare(__func__, &lalBurstVCSInfoHeader, &lalBurstVCSInfo))
            exit(1);
    }
#endif

#ifdef HAVE_LIBLALINSPIRAL
    if ((LALINSPIRAL_VERSION_DEVEL != 0) || (LALAPPS_VERSION_DEVEL != 0))
    {
        /* check lalinspiral version consistency */
        if (version_compare(__func__, &lalInspiralVCSInfoHeader, &lalInspiralVCSInfo))
            exit(1);
    }
#endif

#ifdef HAVE_LIBLALPULSAR
    if ((LALPULSAR_VERSION_DEVEL != 0) || (LALAPPS_VERSION_DEVEL != 0))
    {
        /* check lalpulsar version consistency */
        if (version_compare(__func__, &lalPulsarVCSInfoHeader, &lalPulsarVCSInfo))
            exit(1);
    }
#endif

#ifdef HAVE_LIBLALINFERENCE
    if ((LALINFERENCE_VERSION_DEVEL != 0) || (LALAPPS_VERSION_DEVEL != 0))
    {
        /* check lalinference version consistency */
        if (version_compare(__func__, &lalInferenceVCSInfoHeader, &lalInferenceVCSInfo))
            exit(1);
    }
#endif

#ifdef HAVE_LIBLALSTOCHASTIC
    if ((LALSTOCHASTIC_VERSION_DEVEL != 0) || (LALAPPS_VERSION_DEVEL != 0))
    {
        /* check lalstochastic version consistency */
        if (version_compare(__func__, &lalStochasticVCSInfoHeader, &lalStochasticVCSInfo))
            exit(1);
    }
#endif

    switch(level)
    {
    case 0:
        /* get lal info */
        tree_status = orig_tree_status = XLALStringDuplicate(lalVCSInfo.vcsStatus);
        snprintf(lal_info, sizeof(lal_info),
                 "%%%% LAL: %s (%s %s)\n", lalVCSInfo.version, \
                 strtok(tree_status, delim), lalVCSInfo.vcsId);
        XLALFree(orig_tree_status);

#ifdef HAVE_LIBLALFRAME
        /* get lalframe info */
        tree_status = orig_tree_status = XLALStringDuplicate(lalFrameVCSInfo.vcsStatus);
        snprintf(lalframe_info, sizeof(lalframe_info),
                 "%%%% LALFrame: %s (%s %s)\n", lalFrameVCSInfo.version, \
                 strtok(tree_status, delim), lalFrameVCSInfo.vcsId);
        XLALFree(orig_tree_status);
#endif

#ifdef HAVE_LIBLALMETAIO
        /* get lalmetaio info */
        tree_status = orig_tree_status = XLALStringDuplicate(lalMetaIOVCSInfo.vcsStatus);
        snprintf(lalmetaio_info, sizeof(lalmetaio_info),
                 "%%%% LALMetaIO: %s (%s %s)\n", lalMetaIOVCSInfo.version, \
                 strtok(tree_status, delim), lalMetaIOVCSInfo.vcsId);
        XLALFree(orig_tree_status);
#endif

#ifdef HAVE_LIBLALXML
        /* get lalxml info */
        tree_status = orig_tree_status = XLALStringDuplicate(lalXMLVCSInfo.vcsStatus);
        snprintf(lalxml_info, sizeof(lalxml_info),
                 "%%%% LALXML: %s (%s %s)\n", lalXMLVCSInfo.version, \
                 strtok(tree_status, delim), lalXMLVCSInfo.vcsId);
        XLALFree(orig_tree_status);
#endif

#ifdef HAVE_LIBLALSIMULATION
        /* get lalsimulation info */
        tree_status = orig_tree_status = XLALStringDuplicate(lalSimulationVCSInfo.vcsStatus);
        snprintf(lalsimulation_info, sizeof(lalsimulation_info),
                 "%%%% LALSimulation: %s (%s %s)\n", lalSimulationVCSInfo.version, \
                 strtok(tree_status, delim), lalSimulationVCSInfo.vcsId);
        XLALFree(orig_tree_status);
#endif

#ifdef HAVE_LIBLALBURST
        /* get lalburst info */
        tree_status = orig_tree_status = XLALStringDuplicate(lalBurstVCSInfo.vcsStatus);
        snprintf(lalburst_info, sizeof(lalburst_info),
                 "%%%% LALBurst: %s (%s %s)\n", lalBurstVCSInfo.version, \
                 strtok(tree_status, delim), lalBurstVCSInfo.vcsId);
        XLALFree(orig_tree_status);
#endif

#ifdef HAVE_LIBLALINSPIRAL
        /* get lalinspiral info */
        tree_status = orig_tree_status = XLALStringDuplicate(lalInspiralVCSInfo.vcsStatus);
        snprintf(lalinspiral_info, sizeof(lalinspiral_info),
                 "%%%% LALInspiral: %s (%s %s)\n", lalInspiralVCSInfo.version, \
                 strtok(tree_status, delim), lalInspiralVCSInfo.vcsId);
        XLALFree(orig_tree_status);
#endif

#ifdef HAVE_LIBLALPULSAR
        /* get lalpulsar info */
        tree_status = orig_tree_status = XLALStringDuplicate(lalPulsarVCSInfo.vcsStatus);
        snprintf(lalpulsar_info, sizeof(lalpulsar_info),
                 "%%%% LALPulsar: %s (%s %s)\n", lalPulsarVCSInfo.version, \
                 strtok(tree_status, delim), lalPulsarVCSInfo.vcsId);
        XLALFree(orig_tree_status);
#endif

#ifdef HAVE_LIBLALINFERENCE
        /* get lalinference info */
        tree_status = orig_tree_status = XLALStringDuplicate(lalInferenceVCSInfo.vcsStatus);
        snprintf(lalinference_info, sizeof(lalinference_info),
                 "%%%% LALInference: %s (%s %s)\n", lalInferenceVCSInfo.version, \
                 strtok(tree_status, delim), lalInferenceVCSInfo.vcsId);
        XLALFree(orig_tree_status);
#endif

#ifdef HAVE_LIBLALSTOCHASTIC
        /* get lalstochastic info */
        tree_status = orig_tree_status = XLALStringDuplicate(lalStochasticVCSInfo.vcsStatus);
        snprintf(lalstochastic_info, sizeof(lalstochastic_info),
                 "%%%% LALStochastic: %s (%s %s)\n", lalStochasticVCSInfo.version, \
                 strtok(tree_status, delim), lalStochasticVCSInfo.vcsId);
        XLALFree(orig_tree_status);
#endif

        /* get lalapps info */
        tree_status = orig_tree_status = XLALStringDuplicate(lalAppsVCSInfo.vcsStatus);
        snprintf(lalapps_info, sizeof(lalapps_info),
                 "%%%% LALApps: %s (%s %s)\n", lalAppsVCSInfo.version, \
                 strtok(tree_status, delim), lalAppsVCSInfo.vcsId);
        XLALFree(orig_tree_status);

        break;

    default:
        /* get lal info */
        snprintf( lal_info, sizeof(lal_info),
                  "%%%% LAL-Version: %s\n"
                  "%%%% LAL-Id: %s\n"
                  "%%%% LAL-Date: %s\n"
                  "%%%% LAL-Branch: %s\n"
                  "%%%% LAL-Tag: %s\n"
                  "%%%% LAL-Status: %s\n"
                  "%%%% LAL-Configure Date: %s\n"
                  "%%%% LAL-Configure Arguments: %s\n",
                  lalVCSInfo.version,
                  lalVCSInfo.vcsId,
                  lalVCSInfo.vcsDate,
                  lalVCSInfo.vcsBranch,
                  lalVCSInfo.vcsTag,
                  lalVCSInfo.vcsStatus,
                  lalConfigureDate ,
                  lalConfigureArgs );

#ifdef HAVE_LIBLALFRAME
        /* get lalframe info */
        snprintf( lalframe_info, sizeof(lalframe_info),
                  "%%%% LALFrame-Version: %s\n"
                  "%%%% LALFrame-Id: %s\n"
                  "%%%% LALFrame-Date: %s\n"
                  "%%%% LALFrame-Branch: %s\n"
                  "%%%% LALFrame-Tag: %s\n"
                  "%%%% LALFrame-Status: %s\n"
                  "%%%% LALFrame-Configure Date: %s\n"
                  "%%%% LALApps-Configure Arguments: %s\n",
                  lalFrameVCSInfo.version,
                  lalFrameVCSInfo.vcsId,
                  lalFrameVCSInfo.vcsDate,
                  lalFrameVCSInfo.vcsBranch,
                  lalFrameVCSInfo.vcsTag,
                  lalFrameVCSInfo.vcsStatus,
                  lalFrameConfigureDate ,
                  lalFrameConfigureArgs );
#endif

#ifdef HAVE_LIBLALMETAIO
        /* get lalmetaio info */
        snprintf( lalmetaio_info, sizeof(lalmetaio_info),
                  "%%%% LALMetaIO-Version: %s\n"
                  "%%%% LALMetaIO-Id: %s\n"
                  "%%%% LALMetaIO-Date: %s\n"
                  "%%%% LALMetaIO-Branch: %s\n"
                  "%%%% LALMetaIO-Tag: %s\n"
                  "%%%% LALMetaIO-Status: %s\n"
                  "%%%% LALMetaIO-Configure Date: %s\n"
                  "%%%% LALMetaIO-Configure Arguments: %s\n",
                  lalMetaIOVCSInfo.version,
                  lalMetaIOVCSInfo.vcsId,
                  lalMetaIOVCSInfo.vcsDate,
                  lalMetaIOVCSInfo.vcsBranch,
                  lalMetaIOVCSInfo.vcsTag,
                  lalMetaIOVCSInfo.vcsStatus,
                  lalMetaIOConfigureDate ,
                  lalMetaIOConfigureArgs );
#endif

#ifdef HAVE_LIBLALXML
        /* get lalxml info */
        snprintf( lalxml_info, sizeof(lalxml_info),
                  "%%%% LALXML-Version: %s\n"
                  "%%%% LALXML-Id: %s\n"
                  "%%%% LALXML-Date: %s\n"
                  "%%%% LALXML-Branch: %s\n"
                  "%%%% LALXML-Tag: %s\n"
                  "%%%% LALXML-Status: %s\n"
                  "%%%% LALXML-Configure Date: %s\n"
                  "%%%% LALXML-Configure Arguments: %s\n",
                  lalXMLVCSInfo.version,
                  lalXMLVCSInfo.vcsId,
                  lalXMLVCSInfo.vcsDate,
                  lalXMLVCSInfo.vcsBranch,
                  lalXMLVCSInfo.vcsTag,
                  lalXMLVCSInfo.vcsStatus,
                  lalXMLConfigureDate ,
                  lalXMLConfigureArgs );
#endif

#ifdef HAVE_LIBLALSIMULATION
        /* get lalsimulation info */
        snprintf( lalsimulation_info, sizeof(lalsimulation_info),
                  "%%%% LALSimulation-Version: %s\n"
                  "%%%% LALSimulation-Id: %s\n"
                  "%%%% LALSimulation-Date: %s\n"
                  "%%%% LALSimulation-Branch: %s\n"
                  "%%%% LALSimulation-Tag: %s\n"
                  "%%%% LALSimulation-Status: %s\n"
                  "%%%% LALSimulation-Configure Date: %s\n"
                  "%%%% LALSimulation-Configure Arguments: %s\n",
                  lalSimulationVCSInfo.version,
                  lalSimulationVCSInfo.vcsId,
                  lalSimulationVCSInfo.vcsDate,
                  lalSimulationVCSInfo.vcsBranch,
                  lalSimulationVCSInfo.vcsTag,
                  lalSimulationVCSInfo.vcsStatus,
                  lalSimulationConfigureDate ,
                  lalSimulationConfigureArgs );
#endif

#ifdef HAVE_LIBLALBURST
        /* get lalburst info */
        snprintf( lalburst_info, sizeof(lalburst_info),
                  "%%%% LALBurst-Version: %s\n"
                  "%%%% LALBurst-Id: %s\n"
                  "%%%% LALBurst-Date: %s\n"
                  "%%%% LALBurst-Branch: %s\n"
                  "%%%% LALBurst-Tag: %s\n"
                  "%%%% LALBurst-Status: %s\n"
                  "%%%% LALBurst-Configure Date: %s\n"
                  "%%%% LALBurst-Configure Arguments: %s\n",
                  lalBurstVCSInfo.version,
                  lalBurstVCSInfo.vcsId,
                  lalBurstVCSInfo.vcsDate,
                  lalBurstVCSInfo.vcsBranch,
                  lalBurstVCSInfo.vcsTag,
                  lalBurstVCSInfo.vcsStatus,
                  lalBurstConfigureDate ,
                  lalBurstConfigureArgs );
#endif

#ifdef HAVE_LIBLALINSPIRAL
        /* get lalinspiral info */
        snprintf( lalinspiral_info, sizeof(lalinspiral_info),
                  "%%%% LALInspiral-Version: %s\n"
                  "%%%% LALInspiral-Id: %s\n"
                  "%%%% LALInspiral-Date: %s\n"
                  "%%%% LALInspiral-Branch: %s\n"
                  "%%%% LALInspiral-Tag: %s\n"
                  "%%%% LALInspiral-Status: %s\n"
                  "%%%% LALInspiral-Configure Date: %s\n"
                  "%%%% LALInspiral-Configure Arguments: %s\n",
                  lalInspiralVCSInfo.version,
                  lalInspiralVCSInfo.vcsId,
                  lalInspiralVCSInfo.vcsDate,
                  lalInspiralVCSInfo.vcsBranch,
                  lalInspiralVCSInfo.vcsTag,
                  lalInspiralVCSInfo.vcsStatus,
                  lalInspiralConfigureDate ,
                  lalInspiralConfigureArgs );
#endif

#ifdef HAVE_LIBLALPULSAR
        /* get lalpulsar info */
        snprintf( lalpulsar_info, sizeof(lalpulsar_info),
                  "%%%% LALPulsar-Version: %s\n"
                  "%%%% LALPulsar-Id: %s\n"
                  "%%%% LALPulsar-Date: %s\n"
                  "%%%% LALPulsar-Branch: %s\n"
                  "%%%% LALPulsar-Tag: %s\n"
                  "%%%% LALPulsar-Status: %s\n"
                  "%%%% LALPulsar-Configure Date: %s\n"
                  "%%%% LALPulsar-Configure Arguments: %s\n",
                  lalPulsarVCSInfo.version,
                  lalPulsarVCSInfo.vcsId,
                  lalPulsarVCSInfo.vcsDate,
                  lalPulsarVCSInfo.vcsBranch,
                  lalPulsarVCSInfo.vcsTag,
                  lalPulsarVCSInfo.vcsStatus,
                  lalPulsarConfigureDate ,
                  lalPulsarConfigureArgs );
#endif

#ifdef HAVE_LIBLALINFERENCE
        /* get lalinference info */
        snprintf( lalinference_info, sizeof(lalinference_info),
                  "%%%% LALInference-Version: %s\n"
                  "%%%% LALInference-Id: %s\n"
                  "%%%% LALInference-Date: %s\n"
                  "%%%% LALInference-Branch: %s\n"
                  "%%%% LALInference-Tag: %s\n"
                  "%%%% LALInference-Status: %s\n"
                  "%%%% LALInference-Configure Date: %s\n"
                  "%%%% LALInference-Configure Arguments: %s\n",
                  lalInferenceVCSInfo.version,
                  lalInferenceVCSInfo.vcsId,
                  lalInferenceVCSInfo.vcsDate,
                  lalInferenceVCSInfo.vcsBranch,
                  lalInferenceVCSInfo.vcsTag,
                  lalInferenceVCSInfo.vcsStatus,
                  lalInferenceConfigureDate ,
                  lalInferenceConfigureArgs );
#endif

#ifdef HAVE_LIBLALSTOCHASTIC
        /* get lalstochastic info */
        snprintf( lalstochastic_info, sizeof(lalstochastic_info),
                  "%%%% LALStochastic-Version: %s\n"
                  "%%%% LALStochastic-Id: %s\n"
                  "%%%% LALStochastic-Date: %s\n"
                  "%%%% LALStochastic-Branch: %s\n"
                  "%%%% LALStochastic-Tag: %s\n"
                  "%%%% LALStochastic-Status: %s\n"
                  "%%%% LALStochastic-Configure Date: %s\n"
                  "%%%% LALStochastic-Configure Arguments: %s\n",
                  lalStochasticVCSInfo.version,
                  lalStochasticVCSInfo.vcsId,
                  lalStochasticVCSInfo.vcsDate,
                  lalStochasticVCSInfo.vcsBranch,
                  lalStochasticVCSInfo.vcsTag,
                  lalStochasticVCSInfo.vcsStatus,
                  lalStochasticConfigureDate ,
                  lalStochasticConfigureArgs );
#endif

        /* add lalapps info */
        snprintf( lalapps_info, sizeof(lalapps_info),
                  "%%%% LALApps-Version: %s\n"
                  "%%%% LALApps-Id: %s\n"
                  "%%%% LALApps-Date: %s\n"
                  "%%%% LALApps-Branch: %s\n"
                  "%%%% LALApps-Tag: %s\n"
                  "%%%% LALApps-Status: %s\n"
                  "%%%% LALApps-Configure Date: %s\n"
                  "%%%% LALApps-Configure Arguments: %s\n",
                  lalAppsVCSInfo.version,
                  lalAppsVCSInfo.vcsId,
                  lalAppsVCSInfo.vcsDate,
                  lalAppsVCSInfo.vcsBranch,
                  lalAppsVCSInfo.vcsTag,
                  lalAppsVCSInfo.vcsStatus,
                  lalAppsConfigureDate ,
                  lalAppsConfigureArgs );

        break;
    }

    size_t len = strlen(lal_info) + strlen(lalapps_info) + 1;
#ifdef HAVE_LIBLALFRAME
    len += strlen(lalframe_info);
#endif
#ifdef HAVE_LIBLALMETAIO
    len += strlen(lalmetaio_info);
#endif
#ifdef HAVE_LIBLALXML
    len += strlen(lalxml_info);
#endif
#ifdef HAVE_LIBLALSIMULATION
    len += strlen(lalsimulation_info);
#endif
#ifdef HAVE_LIBLALBURST
    len += strlen(lalburst_info);
#endif
#ifdef HAVE_LIBLALINSPIRAL
    len += strlen(lalinspiral_info);
#endif
#ifdef HAVE_LIBLALPULSAR
    len += strlen(lalpulsar_info);
#endif
#ifdef HAVE_LIBLALINFERENCE
    len += strlen(lalinference_info);
#endif
#ifdef HAVE_LIBLALSTOCHASTIC
    len += strlen(lalstochastic_info);
#endif
    if ( (ret = XLALMalloc ( len )) == NULL ) {
        XLALPrintError ("%s: Failed to XLALMalloc(%zu)\n", __func__, len );
        XLAL_ERROR_NULL ( XLAL_ENOMEM );
    }

    strcpy ( ret, lal_info );
#ifdef HAVE_LIBLALFRAME
    strcat ( ret, lalframe_info );
#endif
#ifdef HAVE_LIBLALMETAIO
    strcat ( ret, lalmetaio_info );
#endif
#ifdef HAVE_LIBLALXML
    strcat ( ret, lalxml_info );
#endif
#ifdef HAVE_LIBLALSIMULATION
    strcat ( ret, lalsimulation_info );
#endif
#ifdef HAVE_LIBLALBURST
    strcat ( ret, lalburst_info );
#endif
#ifdef HAVE_LIBLALINSPIRAL
    strcat ( ret, lalinspiral_info );
#endif
#ifdef HAVE_LIBLALPULSAR
    strcat ( ret, lalpulsar_info );
#endif
#ifdef HAVE_LIBLALINFERENCE
    strcat ( ret, lalinference_info );
#endif
#ifdef HAVE_LIBLALSTOCHASTIC
    strcat ( ret, lalstochastic_info );
#endif
    strcat ( ret, lalapps_info );

    return ( ret );

} /* XLALGetVersionString() */
Exemple #21
0
int main(int argc, char **argv)
{
    FILE *fp  = NULL;
    FILE *fp2 = NULL;
    FILE *fp3 = NULL;
    FILE *fp4 = NULL;
    LALStatus status = blank_status;
    
    SFTCatalog *catalog = NULL;
    SFTVector *sft_vect = NULL;
    INT4 i,j,k,l;
    INT4 numBins, nSFT;
    SFTConstraints constraints=empty_SFTConstraints;
    LIGOTimeGPS startTime, endTime; 
    REAL8 avg =0;
    REAL4 *timeavg =NULL;
    REAL4 PWR,SNR;
    REAL8 f =0;
    CHAR outbase[256],outfile[256],outfile2[256],outfile3[256], outfile4[256]; /*, outfile6[256]; */
    REAL8 NumBinsAvg =0;
    REAL8 timebaseline =0;
    
    BOOLEAN help = 0;
    CHAR *SFTpatt = NULL;
    CHAR *IFO = NULL;
    INT4 startGPS = 0;
    INT4 endGPS = 0;
    REAL8 f_min = 0.0;
    REAL8 f_max = 0.0;
    REAL8 freqres =0.0;
    INT4 blocksRngMed = 101;
    CHAR *outputBname = NULL;
    INT4 cur_epoch = 0, next_epoch = 0;
    
    /* these varibales are for converting GPS seconds into UTC time and date*/
    struct tm         date;
    CHARVector        *timestamp = NULL;
    CHARVector	     *year_date = NULL;
    REAL8Vector     *timestamps=NULL;
    
    CHAR *psrInput = NULL;
    CHAR *psrEphemeris = NULL;
    CHAR *earthFile = NULL;
    CHAR *sunFile = NULL;
  /*========================================================================================================================*/
    
    
    LAL_CALL(LALRegisterBOOLUserVar  (&status, "help",         'h', UVAR_HELP,     "Print this help message",     &help        ), &status);
    LAL_CALL(LALRegisterSTRINGUserVar(&status, "SFTs",         'p', UVAR_REQUIRED, "SFT location/pattern",        &SFTpatt     ), &status);
    LAL_CALL(LALRegisterSTRINGUserVar(&status, "IFO",          'I', UVAR_REQUIRED, "Detector",                    &IFO         ), &status);
    LAL_CALL(LALRegisterINTUserVar   (&status, "startGPS",     's', UVAR_REQUIRED, "Starting GPS time",           &startGPS    ), &status);
    LAL_CALL(LALRegisterINTUserVar   (&status, "endGPS",       'e', UVAR_REQUIRED, "Ending GPS time",             &endGPS      ), &status);
    LAL_CALL(LALRegisterREALUserVar  (&status, "fMin",         'f', UVAR_REQUIRED, "Minimum frequency",           &f_min       ), &status);
    LAL_CALL(LALRegisterREALUserVar  (&status, "fMax",         'F', UVAR_REQUIRED, "Maximum frequency",           &f_max       ), &status);
    LAL_CALL(LALRegisterINTUserVar   (&status, "blocksRngMed", 'w', UVAR_OPTIONAL, "Running Median window size",  &blocksRngMed), &status);
    LAL_CALL(LALRegisterSTRINGUserVar(&status, "outputBname",  'o', UVAR_OPTIONAL, "Base name of output files",   &outputBname ), &status);
    LAL_CALL(LALRegisterREALUserVar  (&status, "freqRes",      'r', UVAR_REQUIRED, "Spectrogram freq resolution", &freqres     ), &status);
    LAL_CALL(LALRegisterREALUserVar  (&status, "timeBaseline", 't', UVAR_REQUIRED, "The time baseline of sfts",   &timebaseline), &status);
    LAL_CALL(LALRegisterSTRINGUserVar(&status, "psrInput",     'P', UVAR_OPTIONAL, "name of tempo pulsar file",   &psrInput ), &status);
    LAL_CALL(LALRegisterSTRINGUserVar(&status, "psrEphemeris", 'S', UVAR_OPTIONAL, "pulsar ephemeris file",   &psrEphemeris ), &status);
    LAL_CALL(LALRegisterSTRINGUserVar(&status, "earthFile",  'y', UVAR_OPTIONAL, "earth .dat file",   &earthFile ), &status);
    LAL_CALL(LALRegisterSTRINGUserVar(&status, "sunFile",   'z', UVAR_OPTIONAL, "sun .dat file",   &sunFile ), &status);
    
    LAL_CALL(LALUserVarReadAllInput(&status, argc, argv), &status);
    if (help)
    return(0);
    
    startTime.gpsSeconds = startGPS;/*cg; startTime is a structure, and gpsSeconds is a member of that structure*/
    startTime.gpsNanoSeconds = 0;/*cg; gps NanoSeconds is also a member of the startTime structure */
    constraints.minStartTime = &startTime; /*cg; & operator gets the address of variable, &a is a pointer to a.  This line puts the startTime structure into the structure constraints*/
    
    endTime.gpsSeconds = endGPS;
    endTime.gpsNanoSeconds = 0;
    constraints.maxEndTime = &endTime;/*cg; This line puts the end time into the structure constraints*/
    constraints.detector = IFO;/*cg; this adds the interferometer into the contraints structure*/
    LALSFTdataFind ( &status, &catalog, SFTpatt, &constraints );/*cg; creates SFT catalog, uses the constraints structure*/

    if (catalog == NULL)/*need to check for a NULL pointer, and print info about circumstances if it is null*/
    {
        fprintf(stderr, "SFT catalog pointer is NULL!  There has been an error with LALSFTdataFind\n");
        fprintf(stderr, "LALStatus info.... status code: %d, message: %s, offending function: %s\n", status.statusCode, status.statusDescription, status.function);
        exit(0);
    }
    if (catalog->length == 0)
    {
        fprintf(stderr, "No SFTs found, please exmanine start time, end time, frequency range etc\n");
        exit(0);
    }

    LALLoadSFTs ( &status, &sft_vect, catalog, f_min,f_max);/*cg;reads the SFT data into the structure sft_vect*/

    if (sft_vect == NULL)
    {
        fprintf(stderr, "SFT vector pointer is NULL!  There has been an error with LALLoadSFTs\n");
        fprintf(stderr, "LALStatus info.... status code: %d, message: %s, offending function: %s\n", status.statusCode, status.statusDescription, status.function);
        exit(0);
    }

    LALDestroySFTCatalog( &status, &catalog);/*cg; desctroys the SFT catalogue*/
    numBins = sft_vect->data->data->length;/*the number of bins in the freq_range*/
    nSFT = sft_vect->length;/* the number of sfts.*/
    
    fprintf(stderr, "nSFT = %d\tnumBins = %d\tf0 = %f\n", nSFT, numBins,sft_vect->data->f0);/*print->logs/spectrumAverage_testcg_0.err */
    if (LALUserVarWasSet(&outputBname))
    strcpy(outbase, outputBname);
    else
    sprintf(outbase, "spec_%.2f_%.2f_%s_%d_%d", f_min,f_max,constraints.detector,startTime.gpsSeconds,endTime.gpsSeconds);/*cg; this is the default name for producing the output files, the different suffixes are just added to this*/
    sprintf(outfile,  "%s", outbase);/*cg; name of first file to be output*/
    sprintf(outfile2, "%s_timestamps", outbase);/*cg: name of second file to be output*/
    sprintf(outfile3, "%s.txt", outbase);/*cg; name of third file to be output*/
    sprintf(outfile4, "%s_date", outbase);/*cg;file for outputting the date, which is used in matlab plotting.*/

    fp = fopen(outfile, "w");/*cg;  open all three files for writing, if they don't exist create them, if they do exist overwrite them*/
    fp2 = fopen(outfile2, "w");
    fp3 = fopen(outfile3, "w");
    fp4 = fopen(outfile4, "w");

/*----------------------------------------------------------------------------------------------------------------*/
/*cg; Create the first file called spec_blah_blah.  This file outputs the power in each spectrogram bin.  The number of bins depends on the frequency range, freq resolution, and number of SFTs.*/

/*cg;  Create the second file, called    blah_b;ah_blah_timestamps.  This will simply contain the time in GPS seconds of each SFT.*/

    NumBinsAvg = freqres*numBins/(f_max-f_min);/*this calcs the number of bins over which to average the sft data, this is worked out so it produces the same freq resolution as specified in the arguments passed to fscanDriver.py. numBins is the total number of bins in the raw sft data*/

    l=0;/*l is used as a counter to count how many SFTs and fake zero SFTs (used for gaps) are output for specgram.*/
    timestamps = XLALCreateREAL8Vector(l);/*test for getting rid of second loop*/
    LALCHARCreateVector(&status, &year_date, (UINT4)128); 

  /*create output files and check for missing sfts*/
    for (j=0;j<nSFT;j++)/*cg;nSFT is the numnber of SFT files used for the time specified. So process is repeated for each SFT*/
    {
        cur_epoch = sft_vect->data[j].epoch.gpsSeconds;/*finds the gps time of the current sft in the sequence with index j*/
        fprintf(fp2, "%d.\t%d\n", l, cur_epoch);/*cg; this bit writes the second file, i.e. the timestamps*/
    
        XLALResizeREAL8Vector(timestamps, l+1);/*resizes the vector timestamps, so cur_epoch can be added*/
        timestamps->data[l]= cur_epoch;/*number of gaps is not know in advance, hence need for te resizing*/
        XLALGPSToUTC(&date, cur_epoch);/*cg; gets the UTC date in struct tm format from the GPS seconds.*/
        fprintf(fp4, "%d\t %i\t %i\t %i\t %i\t %i\t %i\n", l, (date.tm_year+1900), date.tm_mon+1, date.tm_mday, date.tm_hour, date.tm_min, date.tm_sec);
    
        for ( i=0; i < (numBins-2); i+=NumBinsAvg)/*cg; this loop works out the powers and writes the first file.*/
        {/*cg; each SFT is split up into a number of bins, the number of bins is read in from the SFT file*/
            avg = 0.0;/*cg; the vairable avg is reset each time.*/
            if (i+NumBinsAvg>numBins) {printf("Error\n");return(2);}/*cg; error is detected, to prevent referencing data past the end of sft_vect.*/
            for (k=0;k<NumBinsAvg;k++)/*cg; for each bin, k goes trhough each entry from 0 to 180.*/
                avg += sqrt(2*(crealf(sft_vect->data[j].data->data[i+k])*crealf(sft_vect->data[j].data->data[i+k]) + 
                cimagf(sft_vect->data[j].data->data[i+k])*cimagf(sft_vect->data[j].data->data[i+k]))/timebaseline);/*cg; re amd im are real and imaginary parts of SFT, duh!*/
            fprintf(fp,"%e\t",avg/NumBinsAvg);
        }
        fprintf(fp,"\n");
        /*------------------------------*/
        /*Bit to check if there is a gap in the sfts*/
        if ( j < (nSFT-1) )/*in all cases except when we are examining the last sft, check that there is no gap to the next sft*/
        {
            next_epoch = sft_vect->data[j+1].epoch.gpsSeconds;
            /*test to see if SFT gap is longer than 3/2*timebaseline, if so create another entry in the matrix*/
            while ((cur_epoch+((3/2)*timebaseline)) < next_epoch)
            {
                for ( i=0; i < (numBins-2); i+=NumBinsAvg)
                {
                    avg = 0.0;
                    if (i+NumBinsAvg>numBins) {printf("Error\n");return(2);}
                    fprintf(fp,"%e\t",avg);
                }
                fprintf(fp,"\n");
                l=l+1;
                cur_epoch=cur_epoch+timebaseline;
                fprintf(fp2, "%d.\t%d\n", l, cur_epoch );
                    
                XLALResizeREAL8Vector(timestamps, l+1);
                timestamps->data[l]= cur_epoch;
                XLALGPSToUTC(&date, cur_epoch);/*cg; gets the UTC date in struct tm format from the GPS seconds.*/
                fprintf(fp4, "%d\t %i\t %i\t %i\t %i\t %i\t %i\n", l, (date.tm_year+1900), date.tm_mon+1, date.tm_mday, date.tm_hour, date.tm_min, date.tm_sec);
            }
            
        }
        l=l+1;
    }
    fprintf(stderr,"finished checking for missing sfts, l=%d\n", l);
/*----------------------------------------------------------------------------------------------------------------*/
/*cg;  Create the third and final file, called   blah_blah_blah.txt.  This file will contain the data used in the matlab plot script to plot the normalised average power vs the frequency.*/

    /* Find time average of normalized SFTs */
    LALNormalizeSFTVect(&status, sft_vect, blocksRngMed);   
    LALNormalizeSFTVect(&status, sft_vect, blocksRngMed);   
    timeavg = XLALMalloc(numBins*sizeof(REAL4));
    if (timeavg == NULL) fprintf(stderr,"Timeavg memory not allocated\n");

    for (j=0;j<nSFT;j++)
    { 
        for ( i=0; i < numBins; i++)
        {
            if (j == 0) 
            {
                timeavg[i] = crealf(sft_vect->data[j].data->data[i])*crealf(sft_vect->data[j].data->data[i]) + 
                            cimagf(sft_vect->data[j].data->data[i])*cimagf(sft_vect->data[j].data->data[i]);
            } 
            else 
            {
                timeavg[i] += crealf(sft_vect->data[j].data->data[i])*crealf(sft_vect->data[j].data->data[i]) + 
                            cimagf(sft_vect->data[j].data->data[i])*cimagf(sft_vect->data[j].data->data[i]);
            }
        }
    }
    /*timeavg records the power of each bin*/
    for ( i=0; i < numBins; i++)
    {
        f = sft_vect->data->f0 + ((REAL4)i)*sft_vect->data->deltaF;
	PWR=timeavg[i]/((REAL4)nSFT);
	SNR=(PWR-1)*(sqrt(((REAL4)nSFT)));
        fprintf(fp3,"%16.8f %g %g\n",f, PWR, SNR);
    } 
/*------------------------------------------------------------------------------------------------------------------------*/ 
/*End of normal spec_avg code, the remaining code is for crab freq calc.*/
/*================================================================================================================*/
/*================================================================================================================*/
    /*This next block of code is for the crab specific changes to fscan*/
    #define CRAB 0
    /*change this to CRAB 0 to prevent this section of code from compiling, change to 1 to compile it.*/
    #if CRAB
    /*--------------------------------------------------------------------------------------------------------------*/
    /*some header files for the crab*/
    /*#include "../TDS_isolated/HeterodyneCrabPulsar.h"*/
    /*#include "../TDS_isolated/heterodyne_pulsar.h"*/
    #include<../TDS_isolated/HeterodyneCrabPulsar.h>

    if (psrInput != NULL){

    fprintf(stderr,"--------------------\n\n");
    fprintf(stderr,"start of crab stuff\n");
    LIGOTimeGPS dataEpoch;
    /*below 4 structures are from HeterodyneCrabPulsar.h*/
    GetCrabEphemerisInput input; /*this is needed to get the crab ephemeris*/
    CrabSpindownParamsInput crabEphemerisData;
    CrabSpindownParamsOutput crabOutput;
    ParamsForHeterodyne hetParams;
    
    /*CG; these lines allocate memory for the crab ephemeris and crab output variables...*/
    crabEphemerisData.f1 = NULL;
    LALDCreateVector( &status, &crabEphemerisData.f1, NUM);
    
    crabEphemerisData.f0 = NULL;
    LALDCreateVector( &status, &crabEphemerisData.f0, NUM);
    
    crabEphemerisData.tArr = NULL;
    LALDCreateVector( &status, &crabEphemerisData.tArr, NUM);
    
    crabOutput.tArr = NULL;
    LALDCreateVector( &status, &crabOutput.tArr, NUM);
        
    crabOutput.f0 = NULL;
    LALDCreateVector( &status, &crabOutput.f0, NUM);
    
    crabOutput.f1 = NULL;
    LALDCreateVector( &status, &crabOutput.f1, NUM);
    
    crabOutput.f2 = NULL;
    LALDCreateVector( &status, &crabOutput.f2, NUM);
    
    crabOutput.f3 = NULL;
    LALDCreateVector( &status, &crabOutput.f3, NUM);
    
    crabOutput.f4 = NULL;
    LALDCreateVector( &status, &crabOutput.f4, NUM);
        
        
    /*This next set of variables are to do with the doppler shifts that are then applied to to the crab feq.*/
    REAL8 t2=0., tdt=0.;
    EphemerisData *edat=NULL;
    BarycenterInput baryinput, baryinput2;
    EarthState earth, earth2;
    EmissionTime  emit, emit2;
    REAL8 df=0., freq, finalFreq, max_df, minf, maxf;
    REAL8 dtpos=0.; /* time between position epoch and data timestamp */
    BinaryPulsarParams pulsarParams; /*general pulsar params strcut, despite binary name*/
    /*CHAR *psrInput = NULL;*/ /* pulsar input file containing params f0, f1 etc. */
    LALDetector det;
    CHAR detName[256];
    REAL8 ecliptic_lat, e_tilt=0.409092627;/*the ecliptic latitude of the source, and hte earth's tilt in radians (23.439281 degrees)*/

    char outfile5[256];
    FILE *fp5 = NULL;
    sprintf(outfile5, "%s_crab", outbase);
    fp5 = fopen(outfile5, "w");

    /*----------------------------------------------------------------------------------------------------------------*/
    /*cg; calculating the crab freq, done in three steps. This is done for each sft*/
    /*----------------------------------------------------------------------------------------------------------------*/
    /*    ---1---   */
    /*Find rough guess of crabs freq from ephemeris*/
    /*----------------------------------------------------------------------------------------------------------------*/
    
    /*Get detector position, this is needed for barycentre calcs*/
    det = *XLALGetSiteInfo( IFO );

    /* read in tempo par file for pulsar, This is one of the optional command line arguments*/
    /*fprintf(stderr,"%s\n",psrInput);*/
    fprintf(stderr,"%s\n",psrInput);
    XLALReadTEMPOParFile(&pulsarParams, psrInput);

    /*Make sure that posepoch and pepoch are set*/
    if(pulsarParams.pepoch == 0. && pulsarParams.posepoch != 0.)
	pulsarParams.pepoch = pulsarParams.posepoch;
    else if(pulsarParams.posepoch == 0. && pulsarParams.pepoch != 0.)
	pulsarParams.posepoch = pulsarParams.pepoch;
    fprintf(stderr,"Check on read tempo file, pepoch: %f\n", pulsarParams.pepoch);

    /*input.filename=psrEphemeris;*/ /*/archive/home/colingill/lalsuite/lalapps/src/pulsar/fscan/ /archive/home/colingill/public_html/crab_ephemeris.txt*/
    input.filename = XLALMalloc(sizeof(CHAR)*256);
    if(input.filename == NULL) fprintf(stderr,"input.filename pointer memory not allocated\t");

    strcpy(input.filename,psrEphemeris);
    /*fprintf(stderr,"psrEphemeris:%s\n", input.filename);*/

    /*The first stage is to read in f and fdot from the ephemeris, the crab_ephemeris.txt file is part of lalapps and is maintained by matt*/
    LALGetCrabEphemeris( &status, &crabEphemerisData, &input );
    /*check on the outputs, crabEphemerisData is a struct of type CrabSpindownParamsInput, and has members tArr, f0, f1*/
    fprintf(stderr,"input crab ephemeris present, number of entries: %i\n", crabEphemerisData.numOfData);
    fprintf(stderr,"crabEphemerisData: \ttarr= %f\tf0= %f\tf_dot= %e\n", crabEphemerisData.tArr->data[0], crabEphemerisData.f0->data[0], crabEphemerisData.f1->data[0]);
    
    /*Now I have f and fdot, use function below to compute the higher order derrivatives of the crabs frequency*/
    LALComputeFreqDerivatives( &status, &crabOutput, &crabEphemerisData );
    /*check on this function, crabOutput is datatype CrabSpindownParamsOutput*/
    fprintf(stderr,"crabOutput:\tf0= %f\tf1= %e\tf2= %e\n", crabOutput.f0->data[0], crabOutput.f1->data[0], crabOutput.f2->data[0]);/*need to change the type of printf for F1 and f2 to exponentials.*/
    fprintf(stderr,"--------------------\n");

    /*Allocate memory for edat, no need to do in the loop*/
    edat = XLALMalloc(sizeof(*edat));
    (*edat).ephiles.earthEphemeris = earthFile; /*"/archive/home/colingill/lalsuite/lal/packages/pulsar/test/earth05-09.dat";*/
    (*edat).ephiles.sunEphemeris = sunFile;/*"/archive/home/colingill/lalsuite/lal/packages/pulsar/test/sun05-09.dat";*/

    /*work out the eclitptic lattitude of the source, used in max freq calc.*/
    ecliptic_lat=asin(cos(e_tilt)*sin(pulsarParams.dec)-sin(pulsarParams.ra)*cos(pulsarParams.dec)*sin(e_tilt));
    fprintf(stderr,"eqcliptic_lat: %e\t", ecliptic_lat);

    for (i=0;i<l;i++)
    {
        if (i == (l-1))/*catches the last iteration where there is no i+1 entry in timestamps*/
        {
            cur_epoch = timestamps->data[i]+(timebaseline/2);
        }
        else
        {
            cur_epoch = timestamps->data[i]+((timestamps->data[i+1] - timestamps->data[i])/2);
        }

        fprintf(stderr,"cur_epoch: %d\t", cur_epoch);
        /*The time has to be set so that the nearest entry to that time in the ephemeris can be used*/
        dataEpoch.gpsSeconds = cur_epoch; /*INT8)floor(time->data[j]);*/
        dataEpoch.gpsNanoSeconds = 0;
    
        /*prepare hetParams, which is then used to get the freq derrivatives out and also in the next sub-section for Bary functions*/
        LALSetSpindownParams( &status, &hetParams, &crabOutput, dataEpoch );
        fprintf(stderr,"hetparams epoch: %f\t f0= %f\tf1= %e\n", hetParams.epoch, hetParams.f0, hetParams.f1);
    
        /*----------------------------------------------------------------------------------------------------------------*/
        /*    ---2---   */
        /*Add corrections for timing noise to get a better guess at the freq*/
        /*----------------------------------------------------------------------------------------------------------------*/
    
        /*now I want to use these params to calc the freq at any point in time.  Using the higher order derrivatives is how we adjust for timing noise.*/
    
        /*Get the time difference between the current epoch and the epoch of the ephemeris entry*/
        tdt= cur_epoch - hetParams.epoch;
        fprintf(stderr,"dt: %f,\tf1= %e,\tf2= %e,\tf3= %e,\tf4=%e\n", tdt, hetParams.f1, hetParams.f2, hetParams.f3, hetParams.f4);
    
        freq = 2.0*( hetParams.f0 + ((hetParams.f1)*tdt) + (((hetParams.f2)*tdt*tdt)/2) + (((hetParams.f3)*tdt*tdt*tdt)/6) + (((hetParams.f4)*tdt*tdt*tdt*tdt)/24) );
        fprintf(stderr,"crab fcoarse: %f\t", freq);
    
        /*freq = 2.0*(params->f0 + params->f1*t1 + (params->f2)*t1*t1+ (params->f3)*t1*t1*t1 + (params->f4)*t1*t1*t1*t1);*/  /*cg;line 486 from hetcrabpulsar, works out freq, this is with one order of t removed for each of the derrivatives of f, and also each term is divided by a factorial, 1!, 2!, 3!, but this starts one term along from the oroginal code as we have integrated the orginal code to get freq not phase*/
    
        /*----------------------------------------------------------------------------------------------------------------*/
        /*    ---3---   */
        /*Add doppler shifts for earth's motion back onto the freq to get actual observed freq at detectors.*/
        /*----------------------------------------------------------------------------------------------------------------*/
        
        /*now I have the freq, I need to add the doppler shift for the earths motion around the sun */
        baryinput.dInv = 0.;/*I can always set this to zero, as Matt said so, I must ask him why*/

        LAL_CALL( LALInitBarycenter(&status, edat), &status );/*  */
    
        /*this lines take position of detector which are in xyz coords in meters from earths centre and converts them into seconds (time)*/
        baryinput.site.location[0] = det.location[0]/LAL_C_SI;
        baryinput.site.location[1] = det.location[1]/LAL_C_SI;
        baryinput.site.location[2] = det.location[2]/LAL_C_SI;
    
        /*dtpos should be the time between the entry in the ephemeris and the point in time for which doppler shifts are being calc.ed*/
        dtpos = cur_epoch - pulsarParams.posepoch;
    
        /* set up RA, DEC, and distance variables for LALBarycenter*/
        baryinput.delta = pulsarParams.dec + dtpos*pulsarParams.pmdec;
        baryinput.alpha = pulsarParams.ra + dtpos*pulsarParams.pmra/cos(baryinput.delta);
        
        t2=cur_epoch+1;
    
        baryinput2 = baryinput;
        
        baryinput.tgps.gpsSeconds = (INT4)floor(cur_epoch);
        baryinput.tgps.gpsNanoSeconds = (INT4)floor((fmod(cur_epoch,1.0)*1.e9));
    
        baryinput2.tgps.gpsSeconds = (INT4)floor(t2);
        baryinput2.tgps.gpsNanoSeconds = (INT4)floor((fmod(t2,1.0)*1.e9));
    
        /*the barycentre functions are needed to calc the inputs for the correction to fcoarse, namely emit, earth and baryinput*/
        LAL_CALL( LALBarycenterEarth(&status, &earth, &baryinput.tgps, edat), &status );
        LAL_CALL( LALBarycenter(&status, &emit, &baryinput, &earth), &status );
        
        LAL_CALL( LALBarycenterEarth(&status, &earth2, &baryinput2.tgps, edat), &status );
        LAL_CALL( LALBarycenter(&status, &emit2, &baryinput2, &earth2), &status );
    
        /* I need to calc the correction to the freq for the doppler shifts, the correction is df, from line 1074 heterdyne_pulsar.  deltaT is T_emission in TDB - T_arrrival in GPS + light travel time to SSB.  we are working out delta(delatT) over 1 second, so do not bother with the divide by one bit.*/
        df = freq*(emit2.deltaT - emit.deltaT);
        fprintf(stderr,"df: %f,\t", df);

        /*Calc maximum possible df and then subtract applied df from it, use the remaining df to plot range over which f will wander.*/
        max_df=freq*(( (29.783e3*cos(ecliptic_lat))+(465*cos(pulsarParams.dec)) )/3.0e8);/*max doppler shift, from speed of earth in plane of direction to source over c.*/
        fprintf(stderr,"max df: %f\tbeta: %e\n", max_df, ecliptic_lat);
        maxf=freq+max_df;
        minf=freq-max_df;

        finalFreq=freq+df;
        /*df = fcoarse*(emit2.deltaT - emit.deltaT + binOutput2.deltaT - binOutput.deltaT);*//*use when have binary calcs in here also.*/
        fprintf(fp5,"%f\t%f\t%f\t%f\t%f\n", freq, df, minf, finalFreq, maxf);
        fprintf(stderr,"crab freq calc, i:%d,  minf:%f,  f:%f,  maxf:%f\n", i, minf, finalFreq, maxf);

        /*----------------------------------------------------------------------------------------------------------------*/
    }
    fclose(fp5);
    fprintf(stderr,"end of crab stuff\n");
    
    /*Free up any memory allocated in crab section*/
    XLALFree(edat);
    
    }
    #endif

    /*fprintf(stderr,"end of spec_avg 1\n");*/

    /*=======================================================================================================================*/
    /*=======================================================================================================================*/


    /*release a;; the allocaeted memory*/
    LALCHARDestroyVector(&status, &timestamp);
    LALCHARDestroyVector(&status, &year_date);
    LALDestroySFTVector (&status, &sft_vect );

    /*fprintf(stderr,"end of spec_avg 2\n");*/

    if (timeavg != NULL) XLALFree(timeavg);

    /*fprintf(stderr,"end of spec_avg 3\n");*/

    LAL_CALL(LALDestroyUserVars(&status), &status);

    /*fprintf(stderr,"end of spec_avg 4\n");*/
    /*close all the files, spec_avg.c is done, all info written to the files.*/
    fclose(fp);
    fclose(fp2);
    fclose(fp3);
    fclose(fp4);

    fprintf(stderr,"end of spec_avg\n");

    return(0);


}
Exemple #22
0
void
LALREAL4AverageSpectrum (
    LALStatus                   *status,
    REAL4FrequencySeries        *fSeries,
    REAL4TimeSeries             *tSeries,
    AverageSpectrumParams       *params
    )

{
  UINT4                 i, j, k;          /* seg, ts and freq counters       */
  UINT4                 numSeg;           /* number of segments in average   */
  UINT4                 fLength;          /* length of requested power spec  */
  UINT4                 tLength;          /* length of time series segments  */
  REAL4Vector          *tSegment = NULL;  /* dummy time series segment       */
  COMPLEX8Vector       *fSegment = NULL;  /* dummy freq series segment       */
  REAL4                *tSeriesPtr;       /* pointer to the segment data     */
  REAL4                 psdNorm = 0;      /* factor to multiply windows data */
  REAL4                 fftRe, fftIm;     /* real and imag parts of fft      */
  REAL4                *s;                /* work space for computing mean   */
  REAL4                *psdSeg = NULL;    /* storage for individual specta   */
  LALUnit               unit;
  /* RAT4                  negRootTwo = { -1, 1 }; */

  INITSTATUS(status);
  XLAL_PRINT_DEPRECATION_WARNING("XLALREAL4AverageSpectrumWelch");
  ATTATCHSTATUSPTR (status);

  /* check the input and output data pointers are non-null */
  ASSERT( fSeries, status,
      TIMEFREQFFTH_ENULL, TIMEFREQFFTH_MSGENULL );
  ASSERT( fSeries->data, status,
      TIMEFREQFFTH_ENULL, TIMEFREQFFTH_MSGENULL );
  ASSERT( fSeries->data->data, status,
      TIMEFREQFFTH_ENULL, TIMEFREQFFTH_MSGENULL );
  ASSERT( tSeries, status,
      TIMEFREQFFTH_ENULL, TIMEFREQFFTH_MSGENULL );
  ASSERT( tSeries->data, status,
      TIMEFREQFFTH_ENULL, TIMEFREQFFTH_MSGENULL );
  ASSERT( tSeries->data->data, status,
      TIMEFREQFFTH_ENULL, TIMEFREQFFTH_MSGENULL );

  /* check the contents of the parameter structure */
  ASSERT( params, status,
      TIMEFREQFFTH_ENULL, TIMEFREQFFTH_MSGENULL );
  ASSERT( params->window, status,
      TIMEFREQFFTH_ENULL, TIMEFREQFFTH_MSGENULL );
  ASSERT( params->window->data, status,
      TIMEFREQFFTH_ENULL, TIMEFREQFFTH_MSGENULL );
  ASSERT( params->window->data->length > 0, status,
      TIMEFREQFFTH_EZSEG, TIMEFREQFFTH_MSGEZSEG );
  ASSERT( params->plan, status,
      TIMEFREQFFTH_ENULL, TIMEFREQFFTH_MSGENULL );
  if ( !  ( params->method == useUnity || params->method == useMean ||
        params->method == useMedian ) )
  {
    ABORT( status, TIMEFREQFFTH_EUAVG, TIMEFREQFFTH_MSGEUAVG );
  }

  /* check that the window length and fft storage lengths agree */
  fLength = fSeries->data->length;
  tLength = params->window->data->length;
  if ( fLength != tLength / 2 + 1 )
  {
    ABORT( status, TIMEFREQFFTH_EMISM, TIMEFREQFFTH_MSGEMISM );
  }

  /* compute the number of segs, check that the length and overlap are valid */
  numSeg = (tSeries->data->length - params->overlap) / (tLength - params->overlap);
  if ( (tSeries->data->length - params->overlap) % (tLength - params->overlap) )
  {
    ABORT( status, TIMEFREQFFTH_EMISM, TIMEFREQFFTH_MSGEMISM );
  }

  /* clear the output spectrum and the workspace frequency series */
  memset( fSeries->data->data, 0, fLength * sizeof(REAL4) );

  /* compute the parameters of the output frequency series data */
  fSeries->epoch = tSeries->epoch;
  fSeries->f0 = tSeries->f0;
  fSeries->deltaF = 1.0 / ( (REAL8) tLength * tSeries->deltaT );
  if ( XLALUnitMultiply( &unit, &(tSeries->sampleUnits), &(tSeries->sampleUnits) ) == NULL ) {
    ABORTXLAL(status);
  }
  if ( XLALUnitMultiply( &(fSeries->sampleUnits), &unit, &lalSecondUnit ) == NULL ) {
    ABORTXLAL(status);
  }

  /* if this is a unit spectrum, just set the conents to unity and return */
  if ( params->method == useUnity )
  {
    for ( k = 0; k < fLength; ++k )
    {
      fSeries->data->data[k] = 1.0;
    }
    DETATCHSTATUSPTR( status );
    RETURN( status );
  }

  /* create temporary storage for the dummy time domain segment */
  LALCreateVector( status->statusPtr, &tSegment, tLength );
  CHECKSTATUSPTR( status );

  /* create temporary storage for the individual ffts */
  LALCCreateVector( status->statusPtr, &fSegment, fLength );
  CHECKSTATUSPTR( status );

  if ( params->method == useMedian )
  {
    /* create enough storage for the indivdiual power spectra */
    psdSeg = XLALCalloc( numSeg, fLength * sizeof(REAL4) );
  }

  /* compute each of the power spectra used in the average */
  for ( i = 0, tSeriesPtr = tSeries->data->data; i < (UINT4) numSeg; ++i )
  {
    /* copy the time series data to the dummy segment */
    memcpy( tSegment->data, tSeriesPtr, tLength * sizeof(REAL4) );

    /* window the time series segment */
    for ( j = 0; j < tLength; ++j )
    {
      tSegment->data[j] *= params->window->data->data[j];
    }

    /* compute the fft of the data segment */
    LALForwardRealFFT( status->statusPtr, fSegment, tSegment, params->plan );
    CHECKSTATUSPTR (status);

    /* advance the segment data pointer to the start of the next segment */
    tSeriesPtr += tLength - params->overlap;

    /* compute the psd components */
    if ( params->method == useMean )
    {
      /* we can get away with less storage */
      for ( k = 0; k < fLength; ++k )
      {
        fftRe = crealf(fSegment->data[k]);
        fftIm = cimagf(fSegment->data[k]);
        fSeries->data->data[k] += fftRe * fftRe + fftIm * fftIm;
      }

      /* halve the DC and Nyquist components to be consistent with T010095 */
      fSeries->data->data[0] /= 2;
      fSeries->data->data[fLength - 1] /= 2;
    }
    else if ( params->method == useMedian )
    {
      /* we must store all the spectra */
      for ( k = 0; k < fLength; ++k )
      {
        fftRe = crealf(fSegment->data[k]);
        fftIm = cimagf(fSegment->data[k]);
        psdSeg[i * fLength + k] = fftRe * fftRe + fftIm * fftIm;
      }

      /* halve the DC and Nyquist components to be consistent with T010095 */
      psdSeg[i * fLength] /= 2;
      psdSeg[i * fLength + fLength - 1] /= 2;
    }
  }

  /* destroy the dummy time series segment and the fft scratch space */
  LALDestroyVector( status->statusPtr, &tSegment );
  CHECKSTATUSPTR( status );
  LALCDestroyVector( status->statusPtr, &fSegment );
  CHECKSTATUSPTR( status );

  /* compute the desired average of the spectra */
  if ( params->method == useMean )
  {
    /* normalization constant for the arithmentic mean */
    psdNorm = ( 2.0 * tSeries->deltaT ) /
      ( (REAL4) numSeg * params->window->sumofsquares );

    /* normalize the psd to it matches the conventions document */
    for ( k = 0; k < fLength; ++k )
    {
      fSeries->data->data[k] *= psdNorm;
    }
  }
  else if ( params->method == useMedian )
  {
    REAL8 bias;

    /* determine the running median bias */
    /* note: this is not the correct bias if the segments are overlapped */
    if ( params->overlap )
    {
      LALWarning( status, "Overlapping segments with median method causes a biased spectrum." );
    }
    TRY( LALRngMedBias( status->statusPtr, &bias, numSeg ), status );

    /* normalization constant for the median */
    psdNorm = ( 2.0 * tSeries->deltaT ) /
      ( bias * params->window->sumofsquares );

    /* allocate memory array for insert sort */
    s = XLALMalloc( numSeg * sizeof(REAL4) );
    if ( ! s )
    {
      ABORT( status, TIMEFREQFFTH_EMALLOC, TIMEFREQFFTH_MSGEMALLOC );
    }

    /* compute the median spectra and normalize to the conventions doc */
    for ( k = 0; k < fLength; ++k )
    {
      fSeries->data->data[k] = psdNorm *
        MedianSpec( psdSeg, s, k, fLength, numSeg );
    }

    /* free memory used for sort array */
    XLALFree( s );

    /* destroy the storage for the individual spectra */
    XLALFree( psdSeg );
  }

  DETATCHSTATUSPTR( status );
  RETURN( status );
}
/**
 * Register all our "user-variables" that can be specified from cmd-line and/or config-file.
 * Here we set defaults for some user-variables and register them with the UserInput module.
 */
int
XLALInitUserVars ( UserInput_t *uvar )
{
  /* set a few defaults */
  uvar->help = 0;
  uvar->outputStats = NULL;

  uvar->Alpha = -1;	/* Alpha < 0 indicates "allsky" */
  uvar->Delta = 0;

  uvar->phi0 = 0;
  uvar->psi = 0;

  uvar->dataStartGPS = 814838413;	/* 1 Nov 2005, ~ start of S5 */
  uvar->dataDuration = (INT4) round ( LAL_YRSID_SI );	/* 1 year of data */

  uvar->ephemEarth = XLALStringDuplicate("earth00-19-DE405.dat.gz");
  uvar->ephemSun = XLALStringDuplicate("sun00-19-DE405.dat.gz");

  uvar->numDraws = 1;
  uvar->TAtom = 1800;

  uvar->computeFtotal = 0;
  uvar->useFReg = 0;

  uvar->fixedh0Nat = -1;
  uvar->fixedSNR = -1;
  uvar->fixedh0NatMax = -1;
  uvar->fixedRhohMax = -1;

#define DEFAULT_IFO "H1"
  uvar->IFO = XLALMalloc ( strlen(DEFAULT_IFO)+1 );
  strcpy ( uvar->IFO, DEFAULT_IFO );

  /* ---------- transient window defaults ---------- */
#define DEFAULT_TRANSIENT "rect"
  uvar->injectWindow_type = XLALMalloc(strlen(DEFAULT_TRANSIENT)+1);
  strcpy ( uvar->injectWindow_type, DEFAULT_TRANSIENT );
  uvar->searchWindow_type = XLALMalloc(strlen(DEFAULT_TRANSIENT)+1);
  strcpy ( uvar->searchWindow_type, DEFAULT_TRANSIENT );

  uvar->injectWindow_tauDays     = 1.0;
  uvar->injectWindow_tauDaysBand = 13.0;

  REAL8 tauMaxDays = ( uvar->injectWindow_tauDays +  uvar->injectWindow_tauDaysBand );
  /* default window-ranges are t0 in [dataStartTime, dataStartTime - 3 * tauMax] */
  uvar->injectWindow_t0Days     = 0; // offset in days from uvar->dataStartGPS
  uvar->injectWindow_t0DaysBand = fmax ( 0.0, 1.0*uvar->dataDuration/DAY24 - TRANSIENT_EXP_EFOLDING * tauMaxDays );	/* make sure it's >= 0 */

  /* search-windows by default identical to inject-windows */
  uvar->searchWindow_t0Days = uvar->injectWindow_t0Days;
  uvar->searchWindow_t0DaysBand = uvar->injectWindow_t0DaysBand;
  uvar->searchWindow_tauDays = uvar->injectWindow_tauDays;
  uvar->searchWindow_tauDaysBand = uvar->injectWindow_tauDaysBand;

  uvar->searchWindow_dt0  = uvar->TAtom;
  uvar->searchWindow_dtau = uvar->TAtom;

  /* register all our user-variables */
  XLALregBOOLUserStruct ( help, 		'h',     UVAR_HELP, "Print this message");

  /* signal Doppler parameters */
  XLALregREALUserStruct ( Alpha, 		'a', UVAR_OPTIONAL, "Sky position alpha (equatorial coordinates) in radians [Default:allsky]");
  XLALregREALUserStruct ( Delta, 		'd', UVAR_OPTIONAL, "Sky position delta (equatorial coordinates) in radians [Default:allsky]");

  /* signal amplitude parameters */
  XLALregREALUserStruct ( fixedh0Nat,		 0, UVAR_OPTIONAL, "Alternative 1: if >=0 fix the GW amplitude: h0/sqrt(Sn)");
  XLALregREALUserStruct ( fixedSNR, 		 0, UVAR_OPTIONAL, "Alternative 2: if >=0 fix the optimal SNR of the injected signals");
  XLALregREALUserStruct ( fixedh0NatMax,	 0, UVAR_OPTIONAL, "Alternative 3: if >=0 draw GW amplitude h0 in [0, h0NatMax ] (FReg prior)");
  XLALregREALUserStruct ( fixedRhohMax, 	 0, UVAR_OPTIONAL, "Alternative 4: if >=0 draw rhoh=h0*(detM)^(1/8) in [0, rhohMax] (canonical F-stat prior)");

  XLALregREALUserStruct ( cosi,			'i', UVAR_OPTIONAL, "cos(inclination angle). If not set: randomize within [-1,1].");
  XLALregREALUserStruct ( psi,			 0,  UVAR_OPTIONAL, "polarization angle psi. If not set: randomize within [-pi/4,pi/4].");
  XLALregREALUserStruct ( phi0,		 	 0,  UVAR_OPTIONAL, "initial GW phase phi_0. If not set: randomize within [0, 2pi]");

  XLALregINTUserStruct  ( AmpPriorType,	 	 0,  UVAR_OPTIONAL, "Enumeration of types of amplitude-priors: 0=physical, 1=canonical");

  XLALregSTRINGUserStruct ( IFO,	        'I', UVAR_OPTIONAL, "Detector: 'G1','L1','H1,'H2', 'V1', ... ");
  XLALregINTUserStruct ( dataStartGPS,	 	 0,  UVAR_OPTIONAL, "data start-time in GPS seconds");
  XLALregINTUserStruct ( dataDuration,	 	 0,  UVAR_OPTIONAL, "data-span to generate (in seconds)");

  /* transient window ranges: for injection ... */
  XLALregSTRINGUserStruct( injectWindow_type,    0, UVAR_OPTIONAL, "Type of transient window to inject ('none', 'rect', 'exp')");
  XLALregREALUserStruct  ( injectWindow_tauDays, 0, UVAR_OPTIONAL, "Shortest transient-window timescale to inject, in days");
  XLALregREALUserStruct  ( injectWindow_tauDaysBand,0,UVAR_OPTIONAL,"Range of transient-window timescale to inject, in days");
  XLALregREALUserStruct  ( injectWindow_t0Days,  0, UVAR_OPTIONAL, "Earliest start-time of transient window to inject, as offset in days from dataStartGPS");
  XLALregREALUserStruct  ( injectWindow_t0DaysBand,0,UVAR_OPTIONAL,"Range of GPS start-time of transient window to inject, in days [Default:dataDuration-3*tauMax]");
  /* ... and for search */
  XLALregSTRINGUserStruct( searchWindow_type,    0, UVAR_OPTIONAL, "Type of transient window to search with ('none', 'rect', 'exp') [Default:injectWindow]");
  XLALregREALUserStruct  ( searchWindow_tauDays, 0, UVAR_OPTIONAL, "Shortest transient-window timescale to search, in days [Default:injectWindow]");
  XLALregREALUserStruct  ( searchWindow_tauDaysBand,0,UVAR_OPTIONAL, "Range of transient-window timescale to search, in days [Default:injectWindow]");
  XLALregREALUserStruct  ( searchWindow_t0Days,  0, UVAR_OPTIONAL, "Earliest start-time of transient window to search, as offset in days from dataStartGPS [Default:injectWindow]");
  XLALregREALUserStruct  ( searchWindow_t0DaysBand,0,UVAR_OPTIONAL, "Range of GPS start-time of transient window to search, in days [Default:injectWindow]");

  XLALregINTUserStruct   ( searchWindow_dtau, 	 0, UVAR_OPTIONAL, "Step-size for search/marginalization over transient-window timescale, in seconds [Default:TAtom]");
  XLALregINTUserStruct   ( searchWindow_dt0, 	 0, UVAR_OPTIONAL, "Step-size for search/marginalization over transient-window start-time, in seconds [Default:TAtom]");

  /* misc params */
  XLALregBOOLUserStruct ( computeFtotal,	 0, UVAR_OPTIONAL, "Also compute 'total' F-statistic over the full data-span" );

  XLALregINTUserStruct  ( numDraws,		'N', UVAR_OPTIONAL,"Number of random 'draws' to simulate");
  XLALregINTUserStruct  ( randSeed,		 0, UVAR_OPTIONAL, "GSL random-number generator seed value to use");

  XLALregSTRINGUserStruct ( outputStats,	'o', UVAR_OPTIONAL, "Output file containing 'numDraws' random draws of stats");
  XLALregSTRINGUserStruct ( outputAtoms,	 0,  UVAR_OPTIONAL, "Output F-statistic atoms into a file with this basename");
  XLALregSTRINGUserStruct ( outputFstatMap,	 0,  UVAR_OPTIONAL, "Output F-statistic over 2D parameter space {t0, tau} into file with this basename");

  XLALregSTRINGUserStruct ( outputInjParams,	 0,  UVAR_OPTIONAL,  "Output injection parameters into this file");
  XLALregSTRINGUserStruct ( outputPosteriors,	 0,  UVAR_OPTIONAL,  "output posterior pdfs on t0 and tau (in octave format) into this file ");

  XLALregBOOLUserStruct ( SignalOnly,        	'S', UVAR_OPTIONAL, "Signal only: generate pure signal without noise");
  XLALregBOOLUserStruct ( useFReg,        	 0,  UVAR_OPTIONAL, "use 'regularized' Fstat (1/D)*e^F (if TRUE) for marginalization, or 'standard' e^F (if FALSE)");

  XLALregSTRINGUserStruct ( ephemEarth, 	 0,  UVAR_OPTIONAL, "Earth ephemeris file to use");
  XLALregSTRINGUserStruct ( ephemSun, 	 	 0,  UVAR_OPTIONAL, "Sun ephemeris file to use");

  XLALregBOOLUserStruct ( version,        	'V', UVAR_SPECIAL,  "Output code version");

  /* 'hidden' stuff */
  XLALregINTUserStruct ( TAtom,		  	  0, UVAR_DEVELOPER, "Time baseline for Fstat-atoms (typically Tsft) in seconds." );


  if ( xlalErrno ) {
    XLALPrintError ("%s: something failed in initializing user variabels .. errno = %d.\n", __func__, xlalErrno );
    XLAL_ERROR ( XLAL_EFUNC );
  }

  return XLAL_SUCCESS;

} /* XLALInitUserVars() */
Exemple #24
0
/**
 * Dump complete multi-PSDVector over IFOs, timestamps and frequency-bins into
 * per-IFO ASCII output-files 'outbname-IFO'
 *
 */
int
XLALDumpMultiPSDVector ( const CHAR *outbname,			/**< output basename 'outbname' */
                         const MultiPSDVector *multiPSDVect	/**< multi-psd vector to output */
                  )
{
  /* check input consistency */
  if ( outbname == NULL ) {
    XLALPrintError ("%s: NULL input 'outbname'\n", __func__ );
    XLAL_ERROR ( XLAL_EINVAL );
  }
  if ( multiPSDVect == NULL ) {
    XLALPrintError ("%s: NULL input 'multiPSDVect'\n", __func__ );
    XLAL_ERROR ( XLAL_EINVAL );
  }
  if ( multiPSDVect->length == 0 || multiPSDVect->data==0 ) {
    XLALPrintError ("%s: invalid multiPSDVect input (length=0 or data=NULL)\n", __func__ );
    XLAL_ERROR ( XLAL_EINVAL );
  }

  CHAR *fname;
  FILE *fp;

  UINT4 len = strlen ( outbname ) + 4;
  if ( ( fname = XLALMalloc ( len * sizeof(CHAR) )) == NULL ) {
    XLALPrintError ("%s: XLALMalloc(%d) failed.\n", __func__, len );
    XLAL_ERROR ( XLAL_ENOMEM);
  }

  UINT4 numIFOs = multiPSDVect->length;
  UINT4 X;
  for ( X = 0; X < numIFOs; X ++ )
    {
      PSDVector *thisPSDVect = multiPSDVect->data[X];
      char buf[100];

      sprintf ( fname, "%s-%c%c", outbname, thisPSDVect->data[0].name[0], thisPSDVect->data[0].name[1] );

      if ( ( fp = fopen( fname, "wb" ))  == NULL ) {
        XLALPrintError ("%s: Failed to open PSDperSFT file '%s' for writing!\n", __func__, fname );
        XLALFree ( fname );
        XLAL_ERROR ( XLAL_ESYS );
      }

      REAL8 f0       = thisPSDVect->data[0].f0;
      REAL8 dFreq    = thisPSDVect->data[0].deltaF;
      UINT4 numFreqs = thisPSDVect->data[0].data->length;
      UINT4 iFreq;

      /* write comment header line into this output file */
      /* FIXME: output code-version/cmdline/history info */
      fprintf(fp,"%%%% first line holds frequencies [Hz] of PSD-Columns\n");
      /* loop over frequency and output comnment-header markers */
      fprintf(fp,"%%%%%-17s", "dummy");
      for ( iFreq = 0; iFreq < numFreqs; iFreq ++ )
        {
          sprintf (buf, "f%d [Hz]", iFreq + 1 );
          fprintf (fp, " %-21s", buf );
        }
      fprintf (fp, "\n");

      /* write parseable header-line giving bin frequencies for PSDs */
      fprintf (fp, "%-19d", -1 );
      for (iFreq = 0; iFreq < numFreqs; iFreq++ )
        fprintf (fp, " %-21.16g", f0 + iFreq * dFreq );
      fprintf (fp, "\n\n\n");

      /* output another header line describing the following format "ti[GPS] PSD(f1) ... " */
      fprintf(fp,"%%%%%-17s", "ti[GPS]");
      for ( iFreq = 0; iFreq < numFreqs; iFreq ++ )
        {
          sprintf (buf, "PSD(f%d)", iFreq + 1 );
          fprintf (fp, " %-21s", buf );
        }
      fprintf (fp, "\n");

      /* loop over timestamps: dump all PSDs over frequencies into one line */
      UINT4 numTS = thisPSDVect->length;
      UINT4 iTS;
      for ( iTS = 0; iTS < numTS; iTS++ )
        {
          REAL8FrequencySeries *thisPSD = &thisPSDVect->data[iTS];

          /* first output timestamp GPS time for this line */
          REAL8 tGPS = XLALGPSGetREAL8( &thisPSD->epoch );
          fprintf (fp, "%-19.18g", tGPS );

          /* some internal consistency/paranoia checks */
          if ( ( f0 != thisPSD->f0) || ( dFreq != thisPSD->deltaF ) || (numFreqs != thisPSD->data->length ) ) {
            XLALPrintError ("%s: %d-th timestamp %f: inconsistent PSDVector: f0 = %g : %g,  dFreq = %g : %g, numFreqs = %d : %d \n",
                            __func__, iTS, tGPS, f0, thisPSD->f0, dFreq, thisPSD->deltaF, numFreqs, thisPSD->data->length );
            XLALFree ( fname );
            fclose ( fp );
            XLAL_ERROR ( XLAL_EDOM );
          }

          /* loop over all frequencies and dump PSD-value */
          for ( iFreq = 0; iFreq < numFreqs; iFreq ++ )
            fprintf (fp, " %-21.16g", thisPSD->data->data[iFreq] );

          fprintf (fp, "\n");

        } /* for iTS < numTS */

      fclose ( fp );

    } /* for X < numIFOs */

  XLALFree ( fname );

  return XLAL_SUCCESS;

} /* XLALDumpMultiPSDVector() */
/** Initialize Fstat-code: handle user-input and set everything up. */
int
XLALInitCode ( ConfigVariables *cfg, const UserInput_t *uvar )
{
  /* generate log-string for file-output, containing cmdline-options + code VCS version info */
  char *vcs;
  if ( (vcs = XLALGetVersionString(0)) == NULL ) {	  /* short VCS version string */
    XLALPrintError ( "%s: XLALGetVersionString(0) failed with errno=%d.\n", __func__, xlalErrno );
    XLAL_ERROR ( XLAL_EFUNC );
  }
  char *cmdline;
  if ( (cmdline = XLALUserVarGetLog ( UVAR_LOGFMT_CMDLINE )) == NULL ) {
    XLALPrintError ( "%s: XLALUserVarGetLog ( UVAR_LOGFMT_CMDLINE ) failed with errno=%d.\n", __func__, xlalErrno );
    XLAL_ERROR ( XLAL_EFUNC );
  }
  const char fmt[] = "%%%% cmdline: %s\n%%%%\n%s%%%%\n";
  UINT4 len = strlen(vcs) + strlen(cmdline) + strlen(fmt) + 1;
  if ( ( cfg->logString = XLALMalloc ( len  )) == NULL ) {
    XLALPrintError ("%s: XLALMalloc ( %d ) failed.\n", __func__, len );
    XLAL_ERROR ( XLAL_ENOMEM );
  }
  sprintf ( cfg->logString, fmt, cmdline, vcs );
  XLALFree ( cmdline );
  XLALFree ( vcs );

  /* trivial settings from user-input */
  cfg->SignalOnly = uvar->SignalOnly;

  /* ----- parse user-input on signal amplitude-paramters + ranges ----- */
  /* skypos */
  cfg->skypos.longitude = uvar->Alpha;	/* Alpha < 0 indicates 'allsky' */
  cfg->skypos.latitude  = uvar->Delta;
  cfg->skypos.system = COORDINATESYSTEM_EQUATORIAL;

  /* ----- amplitude-params: create prior pdfs reflecting the user-input */
  if ( XLALInitAmplitudePrior ( &cfg->AmpPrior, uvar ) != XLAL_SUCCESS )
    XLAL_ERROR ( XLAL_EFUNC );

  /* ----- initialize random-number generator ----- */
  /* read out environment variables GSL_RNG_xxx
   * GSL_RNG_SEED: use to set random seed: default = 0, override by using --randSeed on cmdline
   * GSL_RNG_TYPE: type of random-number generator to use: default = 'mt19937'
   */
  gsl_rng_env_setup ();
  /* allow overriding the random-seed per command-line */
  if ( XLALUserVarWasSet ( &uvar->randSeed ) )
    gsl_rng_default_seed = uvar->randSeed;
  cfg->rng = gsl_rng_alloc (gsl_rng_default);

  LogPrintf ( LOG_DEBUG, "random-number generator type: %s\n", gsl_rng_name (cfg->rng));
  LogPrintf ( LOG_DEBUG, "seed = %lu\n", gsl_rng_default_seed );

  /* init ephemeris-data */
  EphemerisData *edat = XLALInitBarycenter( uvar->ephemEarth, uvar->ephemSun );
  if ( !edat ) {
    LogPrintf ( LOG_CRITICAL, "%s: XLALInitBarycenter failed: could not load Earth ephemeris '%s' and Sun ephemeris '%s'\n", __func__, uvar->ephemEarth, uvar->ephemSun);
    XLAL_ERROR ( XLAL_EFUNC );
  }

  /* init detector info */
  LALDetector *site;
  if ( (site = XLALGetSiteInfo ( uvar->IFO )) == NULL ) {
    XLALPrintError ("%s: Failed to get site-info for detector '%s'\n", __func__, uvar->IFO );
    XLAL_ERROR ( XLAL_EFUNC );
  }
  MultiLALDetector multiDet;
  multiDet.length = 1;
  multiDet.sites[0] = (*site); 	/* copy! */
  XLALFree ( site );

  /* init timestamps vector covering observation time */
  UINT4 numSteps = (UINT4) ceil ( uvar->dataDuration / uvar->TAtom );
  MultiLIGOTimeGPSVector * multiTS;
  if ( (multiTS = XLALCalloc ( 1, sizeof(*multiTS))) == NULL ) {
    XLAL_ERROR ( XLAL_ENOMEM );
  }
  multiTS->length = 1;
  if ( (multiTS->data = XLALCalloc (1, sizeof(*multiTS->data))) == NULL ) {
    XLAL_ERROR ( XLAL_ENOMEM );
  }
  if ( (multiTS->data[0] = XLALCreateTimestampVector (numSteps)) == NULL ) {
    XLALPrintError ("%s: XLALCreateTimestampVector(%d) failed.\n", __func__, numSteps );
  }
  multiTS->data[0]->deltaT = uvar->TAtom;
  UINT4 i;
  for ( i=0; i < numSteps; i ++ )
    {
      UINT4 ti = uvar->dataStartGPS + i * uvar->TAtom;
      multiTS->data[0]->data[i].gpsSeconds = ti;
      multiTS->data[0]->data[i].gpsNanoSeconds = 0;
    }

  /* get detector states */
  if ( (cfg->multiDetStates = XLALGetMultiDetectorStates ( multiTS, &multiDet, edat, 0.5 * uvar->TAtom )) == NULL ) {
    XLALPrintError ( "%s: XLALGetMultiDetectorStates() failed.\n", __func__ );
    XLAL_ERROR ( XLAL_EFUNC );
  }

  /* get rid of all temporary memory allocated for this step */
  XLALDestroyEphemerisData ( edat );
  XLALDestroyMultiTimestamps ( multiTS );
  multiTS = NULL;


  /* ---------- initialize transient window ranges, for injection ... ---------- */
  transientWindowRange_t XLAL_INIT_DECL(InjectRange);
  int twtype;
  XLAL_CHECK ( (twtype = XLALParseTransientWindowName ( uvar->injectWindow_type )) >= 0, XLAL_EFUNC );
  InjectRange.type = twtype;

  /* make sure user doesn't set window=none but sets window-parameters => indicates she didn't mean 'none' */
  if ( InjectRange.type == TRANSIENT_NONE ) {
    if ( XLALUserVarWasSet ( &uvar->injectWindow_t0Days ) || XLALUserVarWasSet ( &uvar->injectWindow_t0DaysBand ) ||
         XLALUserVarWasSet ( &uvar->injectWindow_tauDays ) || XLALUserVarWasSet ( &uvar->injectWindow_tauDaysBand ) ) {
      XLALPrintError ("%s: ERROR: injectWindow_type == NONE, but window-parameters were set! Use a different window-type!\n", __func__ );
      XLAL_ERROR ( XLAL_EINVAL );
    }
  }

  if ( uvar->injectWindow_t0DaysBand < 0 || uvar->injectWindow_tauDaysBand < 0 ) {
    XLALPrintError ("%s: only positive t0/tau window injection bands allowed (%f, %f)\n", __func__, uvar->injectWindow_t0DaysBand, uvar->injectWindow_tauDaysBand );
    XLAL_ERROR ( XLAL_EINVAL );
  }

  /* apply correct defaults if unset: t0=dataStart, t0Band=dataDuration-3*tauMax */
  InjectRange.t0 = uvar->dataStartGPS + uvar->injectWindow_t0Days * DAY24;

  REAL8 tauMax = ( uvar->injectWindow_tauDays +  uvar->injectWindow_tauDaysBand ) * DAY24;
  if ( XLALUserVarWasSet (&uvar->injectWindow_t0DaysBand ) )
    InjectRange.t0Band  = uvar->injectWindow_t0DaysBand * DAY24;
  else
    InjectRange.t0Band  = fmax ( 0.0, uvar->dataDuration - TRANSIENT_EXP_EFOLDING * tauMax - InjectRange.t0 ); 	/* make sure it's >= 0 */

  InjectRange.tau     = (UINT4) ( uvar->injectWindow_tauDays * DAY24 );
  InjectRange.tauBand = (UINT4) ( uvar->injectWindow_tauDaysBand * DAY24 );

  cfg->transientInjectRange = InjectRange;

  /* ---------- ... and for search -------------------- */
  transientWindowRange_t XLAL_INIT_DECL(SearchRange);
  XLAL_CHECK ( (twtype = XLALParseTransientWindowName ( uvar->searchWindow_type )) >= 0, XLAL_EFUNC );
  SearchRange.type = twtype;

  /* apply correct defaults if unset: use inect window */
  if ( !XLALUserVarWasSet ( &uvar->searchWindow_type ) )
    SearchRange.type    = InjectRange.type;
  if ( !XLALUserVarWasSet ( &uvar->searchWindow_t0Days ) )
    SearchRange.t0      = InjectRange.t0;
  else
    SearchRange.t0      = uvar->dataStartGPS + uvar->searchWindow_t0Days * DAY24;
  if ( !XLALUserVarWasSet ( &uvar->searchWindow_t0DaysBand ) )
    SearchRange.t0Band = InjectRange.t0Band;
  else
    SearchRange.t0Band  = (UINT4) (uvar->searchWindow_t0DaysBand * DAY24);
  if ( !XLALUserVarWasSet ( &uvar->searchWindow_tauDays ) )
    SearchRange.tau = InjectRange.tau;
  else
    SearchRange.tau     = (UINT4) ( uvar->searchWindow_tauDays * DAY24 );
  if ( !XLALUserVarWasSet ( &uvar->searchWindow_tauDaysBand ) )
    SearchRange.tauBand = InjectRange.tauBand;
  else
    SearchRange.tauBand = (UINT4) ( uvar->searchWindow_tauDaysBand * DAY24 );

  if ( XLALUserVarWasSet ( &uvar->searchWindow_dt0 ) )
    SearchRange.dt0 = uvar->searchWindow_dt0;
  else
    SearchRange.dt0 = uvar->TAtom;

  if ( XLALUserVarWasSet ( &uvar->searchWindow_dtau ) )
    SearchRange.dtau = uvar->searchWindow_dtau;
  else
    SearchRange.dtau = uvar->TAtom;

  /* make sure user doesn't set window=none but sets window-parameters => indicates she didn't mean 'none' */
  if ( SearchRange.type == TRANSIENT_NONE )
    if ( XLALUserVarWasSet ( &uvar->searchWindow_t0Days ) || XLALUserVarWasSet ( &uvar->searchWindow_t0DaysBand ) ||
         XLALUserVarWasSet ( &uvar->searchWindow_tauDays ) || XLALUserVarWasSet ( &uvar->searchWindow_tauDaysBand ) ) {
      XLALPrintError ("%s: ERROR: searchWindow_type == NONE, but window-parameters were set! Use a different window-type!\n", __func__ );
      XLAL_ERROR ( XLAL_EINVAL );
    }

  if (   uvar->searchWindow_t0DaysBand < 0 || uvar->searchWindow_tauDaysBand < 0 ) {
    XLALPrintError ("%s: only positive t0/tau window injection bands allowed (%f, %f)\n", __func__, uvar->searchWindow_t0DaysBand, uvar->searchWindow_tauDaysBand );
    XLAL_ERROR ( XLAL_EINVAL );
  }

  cfg->transientSearchRange = SearchRange;

  return XLAL_SUCCESS;

} /* XLALInitCode() */
Exemple #26
0
static int IMRPhenomCGenerateFD(
    COMPLEX16FrequencySeries **htilde, /**< FD waveform */
    const REAL8 phi0,                  /**< phase at peak */
    const REAL8 deltaF,                /**< frequency resolution */
    const REAL8 m1,                    /**< mass of companion 1 [solar masses] */
    const REAL8 m2,                    /**< mass of companion 2 [solar masses] */
    //const REAL8 chi,                   /**< mass-weighted aligned-spin parameter */
    const REAL8 f_min,                 /**< start frequency */
    const REAL8 f_max,                 /**< end frequency */
    const REAL8 distance,              /**< distance to source (m) */
    const BBHPhenomCParams *params      /**< from ComputeIMRPhenomCParams */
) {
  LIGOTimeGPS ligotimegps_zero = LIGOTIMEGPSZERO; // = {0, 0}

  int errcode = XLAL_SUCCESS;
  /*
   We can't call XLAL_ERROR() directly with OpenMP on.
   Keep track of return codes for each thread and in addition use flush to get out of
   the parallel for loop as soon as possible if something went wrong in any thread.
  */

  const REAL8 M = m1 + m2;
  const REAL8 eta = m1 * m2 / (M * M);

  /* Memory to temporarily store components of amplitude and phase */
  /*
  REAL8 phSPA, phPM, phRD, aPM, aRD;
  REAL8 wPlusf1, wPlusf2, wMinusf1, wMinusf2, wPlusf0, wMinusf0;
  */

  /* compute the amplitude pre-factor */
  REAL8 amp0 = 2. * sqrt(5. / (64.*LAL_PI)) * M * LAL_MRSUN_SI * M * LAL_MTSUN_SI / distance;

  /* allocate htilde */
  size_t n = NextPow2(f_max / deltaF) + 1;
  /* coalesce at t=0 */
  XLALGPSAdd(&ligotimegps_zero, -1. / deltaF); // shift by overall length in time
  *htilde = XLALCreateCOMPLEX16FrequencySeries("htilde: FD waveform", &ligotimegps_zero, 0.0,
      deltaF, &lalStrainUnit, n);
  memset((*htilde)->data->data, 0, n * sizeof(COMPLEX16));
  XLALUnitMultiply(&((*htilde)->sampleUnits), &((*htilde)->sampleUnits), &lalSecondUnit);
  if (!(*htilde)) XLAL_ERROR(XLAL_EFUNC);

  size_t ind_min = (size_t) (f_min / deltaF);
  size_t ind_max = (size_t) (f_max / deltaF);

  /* Set up spline for phase */
  gsl_interp_accel *acc = gsl_interp_accel_alloc();
  size_t L =  ind_max - ind_min;
  gsl_spline *phiI = gsl_spline_alloc(gsl_interp_cspline, L);
  REAL8 *freqs = XLALMalloc(L*sizeof(REAL8));
  REAL8 *phis = XLALMalloc(L*sizeof(REAL8));

  /* now generate the waveform */
  #pragma omp parallel for
  for (size_t i = ind_min; i < ind_max; i++)
  {

    REAL8 phPhenomC = 0.0;
    REAL8 aPhenomC = 0.0;
    REAL8 f = i * deltaF;

    int per_thread_errcode;
    #pragma omp flush(errcode)
    if (errcode != XLAL_SUCCESS)
      goto skip;

    per_thread_errcode = IMRPhenomCGenerateAmpPhase( &aPhenomC, &phPhenomC, f, eta, params );
    if (per_thread_errcode != XLAL_SUCCESS) {
      errcode = per_thread_errcode;
      #pragma omp flush(errcode)
    }

    phPhenomC -= 2.*phi0; // factor of 2 b/c phi0 is orbital phase

    freqs[i-ind_min] = f;
    phis[i-ind_min] = -phPhenomC; // PhenomP uses cexp(-I*phPhenomC); want to use same phase adjustment code, so we will flip the sign of the phase

    /* generate the waveform */
    ((*htilde)->data->data)[i] = amp0 * aPhenomC * cos(phPhenomC);
    ((*htilde)->data->data)[i] += -I * amp0 * aPhenomC * sin(phPhenomC);

  skip: /* this statement intentionally left blank */;

  }

  if( errcode != XLAL_SUCCESS )
    XLAL_ERROR(errcode);

  /* Correct phasing so we coalesce at t=0 (with the definition of the epoch=-1/deltaF above) */
  gsl_spline_init(phiI, freqs, phis, L);

  REAL8 f_final = params->fRingDown;
  XLAL_PRINT_INFO("f_ringdown = %g\n", f_final);

  // Prevent gsl interpolation errors
  if (f_final > freqs[L-1])
    f_final = freqs[L-1];
  if (f_final < freqs[0])
    XLAL_ERROR(XLAL_EDOM, "f_ringdown <= f_min\n");

  /* Time correction is t(f_final) = 1/(2pi) dphi/df (f_final) */
  REAL8 t_corr = gsl_spline_eval_deriv(phiI, f_final, acc) / (2*LAL_PI);
  XLAL_PRINT_INFO("t_corr = %g\n", t_corr);
  /* Now correct phase */
  for (size_t i = ind_min; i < ind_max; i++) {
    REAL8 f = i * deltaF;
    ((*htilde)->data->data)[i] *= cexp(-2*LAL_PI * I * f * t_corr);
  }

  gsl_spline_free(phiI);
  gsl_interp_accel_free(acc);
  XLALFree(freqs);
  XLALFree(phis);

  return XLAL_SUCCESS;
}
Exemple #27
0
/** Initialize Fstat-code: handle user-input and set everything up. */
int
XLALInitCode ( ConfigVariables *cfg, const UserInput_t *uvar )
{
  /* generate log-string for file-output, containing cmdline-options + code VCS version info */
  char *vcs;
  if ( (vcs = XLALGetVersionString(0)) == NULL ) {	  /* short VCS version string */
    XLALPrintError ( "%s: XLALGetVersionString(0) failed with errno=%d.\n", __func__, xlalErrno );
    XLAL_ERROR ( XLAL_EFUNC );
  }
  char *cmdline;
  if ( (cmdline = XLALUserVarGetLog ( UVAR_LOGFMT_CMDLINE )) == NULL ) {
    XLALPrintError ( "%s: XLALUserVarGetLog ( UVAR_LOGFMT_CMDLINE ) failed with errno=%d.\n", __func__, xlalErrno );
    XLAL_ERROR ( XLAL_EFUNC );
  }
  const char fmt[] = "%%%% cmdline: %s\n%%%%\n%s%%%%\n";
  UINT4 len = strlen(vcs) + strlen(cmdline) + strlen(fmt) + 1;
  if ( ( cfg->logString = XLALMalloc ( len  )) == NULL ) {
    XLALPrintError ("%s: XLALMalloc ( %d ) failed.\n", __func__, len );
    XLAL_ERROR ( XLAL_ENOMEM );
  }
  sprintf ( cfg->logString, fmt, cmdline, vcs );
  XLALFree ( cmdline );
  XLALFree ( vcs );

  /* trivial settings from user-input */
  cfg->SignalOnly = uvar->SignalOnly;

  /* ----- parse user-input on signal amplitude-paramters + ranges ----- */
  /* skypos */
  cfg->skypos.longitude = uvar->Alpha;	/* Alpha < 0 indicates 'allsky' */
  cfg->skypos.latitude  = uvar->Delta;
  cfg->skypos.system = COORDINATESYSTEM_EQUATORIAL;

  /* ----- amplitude-params: create prior pdfs reflecting the user-input */
  if ( XLALInitAmplitudePrior ( &cfg->AmpPrior, uvar ) != XLAL_SUCCESS )
    XLAL_ERROR ( XLAL_EFUNC );

  /* ----- initialize random-number generator ----- */
  /* read out environment variables GSL_RNG_xxx
   * GSL_RNG_SEED: use to set random seed: default = 0, override by using --randSeed on cmdline
   * GSL_RNG_TYPE: type of random-number generator to use: default = 'mt19937'
   */
  gsl_rng_env_setup ();
  /* allow overriding the random-seed per command-line */
  if ( XLALUserVarWasSet ( &uvar->randSeed ) )
    gsl_rng_default_seed = uvar->randSeed;
  cfg->rng = gsl_rng_alloc (gsl_rng_default);

  LogPrintf ( LOG_DEBUG, "random-number generator type: %s\n", gsl_rng_name (cfg->rng));
  LogPrintf ( LOG_DEBUG, "seed = %lu\n", gsl_rng_default_seed );

  /* init ephemeris-data */
  EphemerisData *edat = XLALInitBarycenter( uvar->ephemEarth, uvar->ephemSun );
  if ( !edat ) {
    LogPrintf ( LOG_CRITICAL, "%s: XLALInitBarycenter failed: could not load Earth ephemeris '%s' and Sun ephemeris '%s'\n", __func__, uvar->ephemEarth, uvar->ephemSun);
    XLAL_ERROR ( XLAL_EFUNC );
  }

  UINT4 numDetectors = uvar->IFOs->length;
  MultiLALDetector multiDet;
  XLAL_CHECK ( XLALParseMultiLALDetector ( &multiDet, uvar->IFOs ) == XLAL_SUCCESS, XLAL_EFUNC );

  /* init timestamps vector covering observation time */
  UINT4 numSteps = (UINT4) ceil ( uvar->dataDuration / uvar->TAtom );
  MultiLIGOTimeGPSVector * multiTS;
  if ( (multiTS = XLALCreateMultiLIGOTimeGPSVector (numDetectors)) == NULL ) {
     XLALPrintError ("%s: XLALCreateMultiLIGOTimeGPSVector(%d) failed.\n", __func__, numDetectors );
  }

  for ( UINT4 X=0; X < numDetectors; X++ )    {
    if ( (multiTS->data[X] = XLALCreateTimestampVector (numSteps)) == NULL ) {
      XLALPrintError ("%s: XLALCreateTimestampVector(%d) failed.\n", __func__, numSteps );
    }
    multiTS->data[X]->deltaT = uvar->TAtom;
    UINT4 i;
    for ( i=0; i < numSteps; i ++ )
      {
	UINT4 ti = uvar->dataStartGPS + i * uvar->TAtom;
	multiTS->data[X]->data[i].gpsSeconds = ti;
	multiTS->data[X]->data[i].gpsNanoSeconds = 0;
      }
  }

  /* get detector states */
  if ( (cfg->multiDetStates = XLALGetMultiDetectorStates ( multiTS, &multiDet, edat, 0.5 * uvar->TAtom )) == NULL ) {
    XLALPrintError ( "%s: XLALGetMultiDetectorStates() failed.\n", __func__ );
    XLAL_ERROR ( XLAL_EFUNC );
  }

  if ( uvar->sqrtSX ) { /* translate user-input PSD sqrt(SX) to noise-weights (this actually does not care whether they were normalized or not) */

    /* parse input comma-separated list */
    MultiNoiseFloor multiNoiseFloor;
    XLAL_CHECK ( XLALParseMultiNoiseFloor ( &multiNoiseFloor, uvar->sqrtSX, numDetectors ) == XLAL_SUCCESS, XLAL_EFUNC );

    /* translate to noise weights */
    XLAL_CHECK ( ( cfg->multiNoiseWeights = XLALComputeConstantMultiNoiseWeightsFromNoiseFloor ( &multiNoiseFloor, multiTS, uvar->TAtom ) ) != NULL, XLAL_EFUNC );

  } /* if ( uvar->sqrtSX ) */

  /* get rid of all temporary memory allocated for this step */
  XLALDestroyEphemerisData ( edat );
  XLALDestroyMultiTimestamps ( multiTS );
  multiTS = NULL;

  /* ---------- initialize transient window ranges, for injection ... ---------- */
  cfg->transientInjectRange.type = TRANSIENT_NONE;			/* default: no transient signal window */
  /* apply correct defaults if unset: t0=dataStart, t0Band=dataDuration-3*tauMax */
//   cfg->transientInjectRange.t0 = uvar->dataStartGPS + uvar->injectWindow_t0Days * DAY24;

  cfg->transientSearchRange = cfg->transientInjectRange;
  return XLAL_SUCCESS;

} /* XLALInitCode() */
Exemple #28
0
/* Parse command line, sanity check arguments, and return a newly
 * allocated GSParams object */
static GSParams *parse_args(ssize_t argc, char **argv) {
    ssize_t i;
    GSParams *params;
    params = (GSParams *) XLALMalloc(sizeof(GSParams));
    memset(params, 0, sizeof(GSParams));

    /* Set default values to the arguments */
    params->waveFlags = XLALSimInspiralCreateWaveformFlags();
    params->nonGRparams = NULL;
    params->approximant = TaylorT1;
    params->domain = LAL_SIM_DOMAIN_TIME;
    params->phaseO = 7;
    params->ampO = 0;
    params->phiRef = 0.;
    params->deltaT = 1./4096.;
    params->deltaF = 0.125;
    params->m1 = 10. * LAL_MSUN_SI;
    params->m2 = 1.4 * LAL_MSUN_SI;
    params->f_min = 40.;
    params->fRef = 0.;
    params->f_max = 0.; /* Generate as much as possible */
    params->distance = 100. * 1e6 * LAL_PC_SI;
    params->inclination = 0.;
    params->s1x = 0.;
    params->s1y = 0.;
    params->s1z = 0.;
    params->s2x = 0.;
    params->s2y = 0.;
    params->s2z = 0.;
    params->lambda1 = 0.;
    params->lambda2 = 0.;
    strncpy(params->outname, "simulation.dat", 256); /* output to this file */
    params->ampPhase = 0; /* output h+ and hx */
    params->verbose = 0; /* No verbosity */

    /* consume command line */
    for (i = 1; i < argc; ++i) {
        if ((strcmp(argv[i], "-h") == 0) || (strcmp(argv[i], "--help") == 0)) {
            printf("%s", usage);
            XLALFree(params);
            exit(0);
        } else if (strcmp(argv[i], "--verbose") == 0) {
            params->verbose = 1;
        } else if (strcmp(argv[i], "--amp-phase") == 0) {
            params->ampPhase = 1;
        } else if ( ( i == argc ) || ( !argv[i+1] ) ) {
            XLALPrintError("Error: value required for option %s\n", argv[i]);
        } else if (strcmp(argv[i], "--approximant") == 0) {
            params->approximant = XLALSimInspiralGetApproximantFromString(argv[++i]);
            if ( (int) params->approximant == XLAL_FAILURE) {
                XLALPrintError("Error: invalid value %s for --interaction-flag\n", argv[i]);
                goto fail;
            }
        } else if (strcmp(argv[i], "--domain") == 0) {
            i++;
            if (strcmp(argv[i], "TD") == 0)
                params->domain = LAL_SIM_DOMAIN_TIME;
            else if (strcmp(argv[i], "FD") == 0)
                params->domain = LAL_SIM_DOMAIN_FREQUENCY;
            else {
                XLALPrintError("Error: Unknown domain\n");
                goto fail;
            }
        } else if (strcmp(argv[i], "--phase-order") == 0) {
            params->phaseO = atoi(argv[++i]);
        } else if (strcmp(argv[i], "--amp-order") == 0) {
            params->ampO = atoi(argv[++i]);
        } else if (strcmp(argv[i], "--phiRef") == 0) {
            params->phiRef = atof(argv[++i]);
        } else if (strcmp(argv[i], "--fRef") == 0) {
            params->fRef = atof(argv[++i]);
        } else if (strcmp(argv[i], "--sample-rate") == 0) {
            params->deltaT = 1./atof(argv[++i]);
        } else if (strcmp(argv[i], "--deltaF") == 0) {
            params->deltaF = atof(argv[++i]);
        } else if (strcmp(argv[i], "--m1") == 0) {
            params->m1 = atof(argv[++i]) * LAL_MSUN_SI;
        } else if (strcmp(argv[i], "--m2") == 0) {
            params->m2 = atof(argv[++i]) * LAL_MSUN_SI;
        } else if (strcmp(argv[i], "--spin1x") == 0) {
            params->s1x = atof(argv[++i]);
        } else if (strcmp(argv[i], "--spin1y") == 0) {
            params->s1y = atof(argv[++i]);
        } else if (strcmp(argv[i], "--spin1z") == 0) {
            params->s1z = atof(argv[++i]);
        } else if (strcmp(argv[i], "--spin2x") == 0) {
            params->s2x = atof(argv[++i]);
        } else if (strcmp(argv[i], "--spin2y") == 0) {
            params->s2y = atof(argv[++i]);
        } else if (strcmp(argv[i], "--spin2z") == 0) {
            params->s2z = atof(argv[++i]);
        } else if (strcmp(argv[i], "--tidal-lambda1") == 0) {
            params->lambda1 = atof(argv[++i]);
        } else if (strcmp(argv[i], "--tidal-lambda2") == 0) {
            params->lambda2 = atof(argv[++i]);
        } else if (strcmp(argv[i], "--spin-order") == 0) {
            XLALSimInspiralSetSpinOrder( params->waveFlags, atoi(argv[++i]) );
        } else if (strcmp(argv[i], "--tidal-order") == 0) {
            XLALSimInspiralSetTidalOrder( params->waveFlags, atoi(argv[++i]) );
        } else if (strcmp(argv[i], "--f-min") == 0) {
            params->f_min = atof(argv[++i]);
        } else if (strcmp(argv[i], "--f-max") == 0) {
            params->f_max = atof(argv[++i]);
        } else if (strcmp(argv[i], "--distance") == 0) {
            params->distance = atof(argv[++i]) * 1e6 * LAL_PC_SI;
        } else if (strcmp(argv[i], "--inclination") == 0) {
            params->inclination = atof(argv[++i]);
        } else if (strcmp(argv[i], "--axis") == 0) {
            XLALSimInspiralSetFrameAxis( params->waveFlags,
                                         XLALGetFrameAxisFromString(argv[++i]) );
            if ( (int) XLALSimInspiralGetFrameAxis(params->waveFlags)
                    == (int) XLAL_FAILURE) {
                XLALPrintError("Error: invalid value %s for --axis\n", argv[i]);
                goto fail;
            }
        } else if (strcmp(argv[i], "--modes") == 0) {
            XLALSimInspiralSetModesChoice( params->waveFlags,
                                           XLALGetHigherModesFromString(argv[++i]) );
            if ( (int) XLALSimInspiralGetModesChoice(params->waveFlags)
                    == (int) XLAL_FAILURE) {
                XLALPrintError("Error: invalid value %s for --modes\n", argv[i]);
                goto fail;
            }
        } else if (strcmp(argv[i], "--nonGRpar") == 0) {
            char name[100];
            strcpy(name,argv[++i]);
            if ( ( i == argc ) || ( !argv[i+1] ) ) {
                XLALPrintError("Error: 'name value' pair required for option %s\n", argv[i-1]);
            } else if (params->nonGRparams==NULL) {
                params->nonGRparams=XLALSimInspiralCreateTestGRParam(name,atof(argv[++i]));
            } else {
                XLALSimInspiralAddTestGRParam(&params->nonGRparams,name,atof(argv[++i]));
            }
        } else if (strcmp(argv[i], "--outname") == 0) {
            strncpy(params->outname, argv[++i], 256);
        } else {
            XLALPrintError("Error: invalid option: %s\n", argv[i]);
            goto fail;
        }
    }

    return params;

fail:
    printf("%s", usage);
    XLALFree(params);
    exit(1);
}
// ----- local function definitions ----------
static int
XLALComputeFstatDemod ( FstatResults* Fstats,
                        const FstatCommon *common,
                        void *method_data
                      )
{
  // Check input
  XLAL_CHECK(Fstats != NULL, XLAL_EFAULT);
  XLAL_CHECK(common != NULL, XLAL_EFAULT);
  XLAL_CHECK(method_data != NULL, XLAL_EFAULT);

  DemodMethodData *demod = (DemodMethodData*) method_data;
  // get internal timing info
  DemodTimingInfo *ti = &(demod->timingInfo);
  REAL8 tic = 0, toc = 0;

  // Get which F-statistic quantities to compute
  const FstatQuantities whatToCompute = Fstats->whatWasComputed;

  // handy shortcuts
  BOOLEAN returnAtoms = (whatToCompute & FSTATQ_ATOMS_PER_DET);
  PulsarDopplerParams thisPoint = Fstats->doppler;
  const REAL8 fStart = thisPoint.fkdot[0];
  const MultiSFTVector *multiSFTs = demod->multiSFTs;
  const MultiNoiseWeights *multiWeights = common->multiNoiseWeights;
  const MultiDetectorStateSeries *multiDetStates = common->multiDetectorStates;

  UINT4 numDetectors = multiSFTs->length;
  XLAL_CHECK ( multiDetStates->length == numDetectors, XLAL_EINVAL );
  XLAL_CHECK ( multiWeights==NULL || (multiWeights->length == numDetectors), XLAL_EINVAL );
  UINT4 numSFTs = 0;
  for ( UINT4 X = 0; X < numDetectors; X ++ ) {
    numSFTs += multiDetStates->data[X]->length;
  }

  // initialize timing info struct
  if ( ti->collectTiming )
    {
      XLAL_INIT_MEM ( (*ti) );
      ti->collectTiming = 1;

      ti->numDetectors = numDetectors;
      ti->numFreqBins = Fstats->numFreqBins;
      ti->numSFTs = numSFTs;

      tic = XLALGetCPUTime();
    }

  MultiSSBtimes *multiSSB = NULL;
  MultiAMCoeffs *multiAMcoef = NULL;
  // ----- check if we have buffered SSB+AMcoef for current sky-position
  if ( (demod->prevAlpha == thisPoint.Alpha) && (demod->prevDelta == thisPoint.Delta ) &&
       (demod->prevMultiSSBtimes != NULL) && ( XLALGPSDiff(&demod->prevRefTime, &thisPoint.refTime) == 0 ) &&	// have SSB times for same reftime?
       (demod->prevMultiAMcoef != NULL)
       )
    { // if yes ==> reuse
      multiSSB    = demod->prevMultiSSBtimes;
      multiAMcoef = demod->prevMultiAMcoef;
    }
  else
    { // if not, compute SSB + AMcoef for this skyposition
      SkyPosition skypos;
      skypos.system = COORDINATESYSTEM_EQUATORIAL;
      skypos.longitude = thisPoint.Alpha;
      skypos.latitude  = thisPoint.Delta;
      XLAL_CHECK ( (multiSSB = XLALGetMultiSSBtimes ( multiDetStates, skypos, thisPoint.refTime, common->SSBprec )) != NULL, XLAL_EFUNC );
      XLAL_CHECK ( (multiAMcoef = XLALComputeMultiAMCoeffs ( multiDetStates, multiWeights, skypos )) != NULL, XLAL_EFUNC );

      // store these for possible later re-use in buffer
      XLALDestroyMultiSSBtimes ( demod->prevMultiSSBtimes );
      demod->prevMultiSSBtimes = multiSSB;
      demod->prevRefTime = thisPoint.refTime;
      XLALDestroyMultiAMCoeffs ( demod->prevMultiAMcoef );
      demod->prevMultiAMcoef = multiAMcoef;
      demod->prevAlpha = thisPoint.Alpha;
      demod->prevDelta = thisPoint.Delta;
    } // if could not reuse previously buffered quantites

  MultiSSBtimes *multiBinary = NULL;
  MultiSSBtimes *multiSSBTotal = NULL;
  // handle binary-orbital timing corrections, if applicable
  if ( thisPoint.asini > 0 )
    {
      // compute binary time corrections to the SSB time delays and SSB time derivitive
      XLAL_CHECK ( XLALAddMultiBinaryTimes ( &multiBinary, multiSSB, &thisPoint ) == XLAL_SUCCESS, XLAL_EFUNC );
      multiSSBTotal = multiBinary;
    }
  else
    {
      multiSSBTotal = multiSSB;
    }

  if ( ti->collectTiming ) {
    toc = XLALGetCPUTime();
    ti->tauBary = (toc - tic);
  }

  // ----- compute final Fstatistic-value -----
  REAL4 Ad = multiAMcoef->Mmunu.Ad;
  REAL4 Bd = multiAMcoef->Mmunu.Bd;
  REAL4 Cd = multiAMcoef->Mmunu.Cd;
  REAL4 Ed = multiAMcoef->Mmunu.Ed;;
  REAL4 Dd_inv = 1.0 / multiAMcoef->Mmunu.Dd;

  // ---------- Compute F-stat for each frequency bin ----------
  for ( UINT4 k = 0; k < Fstats->numFreqBins; k++ )
    {
      // Set frequency to search at
      thisPoint.fkdot[0] = fStart + k * Fstats->dFreq;

      COMPLEX8 Fa = 0;       		// complex amplitude Fa
      COMPLEX8 Fb = 0;                 // complex amplitude Fb
      MultiFstatAtomVector *multiFstatAtoms = NULL;	// per-IFO, per-SFT arrays of F-stat 'atoms', ie quantities required to compute F-stat

      // prepare return of 'FstatAtoms' if requested
      if ( returnAtoms )
        {
          XLAL_CHECK ( (multiFstatAtoms = XLALMalloc ( sizeof(*multiFstatAtoms) )) != NULL, XLAL_ENOMEM );
          multiFstatAtoms->length = numDetectors;
          XLAL_CHECK ( (multiFstatAtoms->data = XLALMalloc ( numDetectors * sizeof(*multiFstatAtoms->data) )) != NULL, XLAL_ENOMEM );
        } // if returnAtoms

      // loop over detectors and compute all detector-specific quantities
      for ( UINT4 X=0; X < numDetectors; X ++)
        {
          COMPLEX8 FaX, FbX;
          FstatAtomVector *FstatAtoms = NULL;
          FstatAtomVector **FstatAtoms_p = returnAtoms ? (&FstatAtoms) : NULL;

          // call XLALComputeFaFb_...() function for the user-requested hotloop variant
          XLAL_CHECK ( (demod->computefafb_func) ( &FaX, &FbX, FstatAtoms_p, multiSFTs->data[X], thisPoint.fkdot,
                                                   multiSSBTotal->data[X], multiAMcoef->data[X], demod->Dterms ) == XLAL_SUCCESS, XLAL_EFUNC );

          if ( returnAtoms ) {
            multiFstatAtoms->data[X] = FstatAtoms;     // copy pointer to IFO-specific Fstat-atoms 'contents'
          }

          XLAL_CHECK ( isfinite(creal(FaX)) && isfinite(cimag(FaX)) && isfinite(creal(FbX)) && isfinite(cimag(FbX)), XLAL_EFPOVRFLW );

          if ( whatToCompute & FSTATQ_FAFB_PER_DET )
            {
              Fstats->FaPerDet[X][k] = FaX;
              Fstats->FbPerDet[X][k] = FbX;
            }

          // compute single-IFO F-stats, if requested
          if ( whatToCompute & FSTATQ_2F_PER_DET )
            {
              REAL4 AdX = multiAMcoef->data[X]->A;
              REAL4 BdX = multiAMcoef->data[X]->B;
              REAL4 CdX = multiAMcoef->data[X]->C;
              REAL4 EdX = 0;
              REAL4 DdX_inv = 1.0 / multiAMcoef->data[X]->D;

              // compute final single-IFO F-stat
              Fstats->twoFPerDet[X][k] = XLALComputeFstatFromFaFb ( FaX, FbX, AdX, BdX, CdX, EdX, DdX_inv );

            } // if FSTATQ_2F_PER_DET

          /* Fa = sum_X Fa_X */
          Fa += FaX;

          /* Fb = sum_X Fb_X */
          Fb += FbX;

        } // for  X < numDetectors

      if ( whatToCompute & FSTATQ_2F )
        {
          Fstats->twoF[k] = XLALComputeFstatFromFaFb ( Fa, Fb, Ad, Bd, Cd, Ed, Dd_inv );
        }

      // Return multi-detector Fa & Fb
      if ( whatToCompute & FSTATQ_FAFB )
        {
          Fstats->Fa[k] = Fa;
          Fstats->Fb[k] = Fb;
        }

      // Return F-atoms per detector
      if ( whatToCompute & FSTATQ_ATOMS_PER_DET )
        {
          XLALDestroyMultiFstatAtomVector ( Fstats->multiFatoms[k] );
          Fstats->multiFatoms[k] = multiFstatAtoms;
        }

    } // for k < Fstats->numFreqBins

  // this needs to be free'ed, as it's currently not buffered
  XLALDestroyMultiSSBtimes ( multiBinary );

  // Return amplitude modulation coefficients
  Fstats->Mmunu = demod->prevMultiAMcoef->Mmunu;

  // return per-detector antenna-pattern matrices
  for ( UINT4 X=0; X < numDetectors; X ++ )
    {
      Fstats->MmunuX[X].Ad = multiAMcoef->data[X]->A;
      Fstats->MmunuX[X].Bd = multiAMcoef->data[X]->B;
      Fstats->MmunuX[X].Cd = multiAMcoef->data[X]->C;
      Fstats->MmunuX[X].Dd = multiAMcoef->data[X]->D;
      Fstats->MmunuX[X].Ed = 0;
    }

  if ( ti->collectTiming ) {
    toc = XLALGetCPUTime();
    ti->tauTotal = (toc - tic);
    ti->tauF1NoBuf = ti->tauTotal / ( Fstats->numFreqBins * numDetectors );
    ti->tauF1Buf   = (ti->tauTotal - ti->tauBary) / ( Fstats->numFreqBins * numDetectors );
  }

  return XLAL_SUCCESS;

} // XLALComputeFstatDemod()
Exemple #30
0
/**
 * basic initializations: set-up 'ConfigVariables'
 */
int
XLALInitCode ( ConfigVariables *cfg, const UserVariables_t *uvar, const char *app_name)
{
  if ( !cfg || !uvar || !app_name ) {
    LogPrintf (LOG_CRITICAL, "%s: illegal NULL pointer input.\n\n", __func__ );
    XLAL_ERROR (XLAL_EINVAL );
  }

  /* Init ephemerides */
  XLAL_CHECK ( (cfg->edat = XLALInitBarycenter ( uvar->ephemEarth, uvar->ephemSun )) != NULL, XLAL_EFUNC );

  // ----- figure out which segments to use
  BOOLEAN manualSegments = XLALUserVarWasSet(&uvar->duration) || XLALUserVarWasSet(&uvar->startTime) || XLALUserVarWasSet(&uvar->Nseg);
  if ( manualSegments && uvar->segmentList ) {
    XLAL_ERROR ( XLAL_EDOM, "Can specify EITHER {--startTime, --duration, --Nseg} OR --segmentList\n");
  }
  LIGOTimeGPS startTimeGPS;
  REAL8 duration;
  if ( uvar->segmentList == NULL )
    {
      XLAL_CHECK ( uvar->Nseg >= 1, XLAL_EDOM, "Invalid input --Nseg=%d: number of segments must be >= 1\n", uvar->Nseg );
      XLAL_CHECK ( uvar->duration >= 1, XLAL_EDOM, "Invalid input --duration=%f: duration must be >= 1 s\n", uvar->duration );
      startTimeGPS = uvar->startTime;
      int ret = XLALSegListInitSimpleSegments ( &cfg->segmentList, startTimeGPS, uvar->Nseg, uvar->duration / uvar->Nseg );
      XLAL_CHECK ( ret == XLAL_SUCCESS, XLAL_EFUNC, "XLALSegListInitSimpleSegments() failed with xlalErrno = %d\n", xlalErrno );
      duration = uvar->duration;
    }
  else
    {
      LALSegList *segList = XLALReadSegmentsFromFile ( uvar->segmentList );
      XLAL_CHECK ( segList != NULL, XLAL_EIO, "XLALReadSegmentsFromFile() failed to load segment list from file '%s', xlalErrno = %d\n", uvar->segmentList, xlalErrno );
      cfg->segmentList = (*segList);	// copy *contents*
      XLALFree ( segList );
      startTimeGPS = cfg->segmentList.segs[0].start;
      UINT4 Nseg = cfg->segmentList.length;
      LIGOTimeGPS endTimeGPS = cfg->segmentList.segs[Nseg-1].end;
      duration = XLALGPSDiff( &endTimeGPS, &startTimeGPS );
    }

  /* ----- figure out reference time */
  LIGOTimeGPS refTimeGPS;

  /* treat special values first */
  if ( uvar->refTime.gpsSeconds == 0 )		/* 0 = use startTime */
    {
      refTimeGPS = uvar->startTime;
    }
  else if ( !XLALUserVarWasSet ( &uvar->refTime ) )	/* default = use mid-time of observation */
    {
      refTimeGPS = startTimeGPS;
      XLALGPSAdd( &refTimeGPS, duration / 2.0 );
    }
  else
    {
      refTimeGPS = uvar->refTime;
    }

  /* ----- get parameter-space point from user-input) */
  cfg->signalParams.Amp.h0 = uvar->h0;
  cfg->signalParams.Amp.cosi = uvar->cosi;
  cfg->signalParams.Amp.psi = uvar->psi;
  cfg->signalParams.Amp.phi0 = uvar->phi0;

  {
    PulsarDopplerParams *dop = &(cfg->signalParams.Doppler);
    XLAL_INIT_MEM((*dop));
    dop->refTime = refTimeGPS;
    dop->Alpha    = uvar->Alpha;
    dop->Delta    = uvar->Delta;
    dop->fkdot[0] = uvar->Freq;
    dop->fkdot[1] = uvar->f1dot;
    dop->fkdot[2] = uvar->f2dot;
    dop->fkdot[3] = uvar->f3dot;
    dop->asini    = uvar->orbitasini;
    dop->period   = uvar->orbitPeriod;
    dop->tp       = uvar->orbitTp;
    dop->ecc      = uvar->orbitEcc;
    dop->argp     = uvar->orbitArgp;
  }

  /* ----- initialize IFOs and (Multi-)DetectorStateSeries  ----- */
  XLAL_CHECK ( XLALParseMultiLALDetector ( &cfg->multiIFO, uvar->IFOs ) == XLAL_SUCCESS, XLAL_EFUNC );
  UINT4 numDet = cfg->multiIFO.length;
  XLAL_CHECK ( numDet >= 1, XLAL_EINVAL );

  if ( uvar->sqrtSX ) {
    XLAL_CHECK ( XLALParseMultiNoiseFloor ( &cfg->multiNoiseFloor, uvar->sqrtSX, numDet ) == XLAL_SUCCESS, XLAL_EFUNC );
  }

  /* ---------- translate coordinate system into internal representation ---------- */
  if ( XLALDopplerCoordinateNames2System ( &cfg->coordSys, uvar->coords ) ) {
    LogPrintf (LOG_CRITICAL, "%s: Call to XLALDopplerCoordinateNames2System() failed. errno = %d\n\n", __func__, xlalErrno );
    XLAL_ERROR ( XLAL_EFUNC );
  }

  /* ---------- record full 'history' up to and including this application ---------- */
  {
    CHAR *cmdline = NULL;
    CHAR *tmp;
    size_t len = strlen ( app_name ) + 1;

    if ( (cfg->history = XLALCalloc ( 1, sizeof(*cfg->history))) == NULL ) {
      LogPrintf (LOG_CRITICAL, "%s: XLALCalloc(1,%zu) failed.\n\n", __func__, sizeof(*cfg->history));
      XLAL_ERROR ( XLAL_ENOMEM );
    }

    if ( (tmp = XLALMalloc ( len )) == NULL ) {
      LogPrintf (LOG_CRITICAL, "%s: XLALMalloc (%zu) failed.\n\n", __func__, len );
      XLAL_ERROR ( XLAL_ENOMEM );
    }
    strcpy ( tmp, app_name );
    cfg->history->app_name = tmp;

    /* get commandline describing search*/
    if ( (cmdline = XLALUserVarGetLog ( UVAR_LOGFMT_CMDLINE )) == NULL ) {
      LogPrintf (LOG_CRITICAL, "%s: XLALUserVarGetLog() failed with xlalErrno = %d.\n\n", __func__, xlalErrno );
      XLAL_ERROR ( XLAL_EFUNC );
    }
    cfg->history->cmdline = cmdline;
  } /* record history */


  return XLAL_SUCCESS;

} /* XLALInitCode() */