Esempio n. 1
0
void xml_put_gps(LIGOTimeGPS *epoch, FILE *fp)
{
    char tstr[32];
    XLALGPSToStr(tstr, epoch);
    fprintf(fp, "\t\t<Time Type=\"GPS\" Name=\"epoch\">%s</Time>\n", tstr);
    return;
}
Esempio n. 2
0
int main(int argc, char *argv[])
{
	char tstr[32]; // string to hold GPS time -- 31 characters is enough
	const double H0 = 0.72 * LAL_H0FAC_SI; // Hubble's constant in seconds
	const size_t length = 65536; // number of points in a segment
	const size_t stride = length / 2; // number of points in a stride
	size_t i, n;
	REAL8FrequencySeries *OmegaGW = NULL;
	REAL8TimeSeries **seg = NULL;
	LIGOTimeGPS epoch;
	gsl_rng *rng;

	XLALSetErrorHandler(XLALAbortErrorHandler);

	parseargs(argc, argv);

	XLALGPSSetREAL8(&epoch, tstart);
	gsl_rng_env_setup();
	rng = gsl_rng_alloc(gsl_rng_default);
	OmegaGW = XLALSimSGWBOmegaGWFlatSpectrum(Omega0, flow, srate/length, length/2 + 1);

	n = duration * srate;
	seg = LALCalloc(numDetectors, sizeof(*seg));
	printf("# time (s)");
	for (i = 0; i < numDetectors; ++i) {
		char name[LALNameLength];
		snprintf(name, sizeof(name), "%s:STRAIN", detectors[i].frDetector.prefix);
		seg[i] = XLALCreateREAL8TimeSeries(name, &epoch, 0.0, 1.0/srate, &lalStrainUnit, length);
		printf("\t%s (strain)", name);
	}
	printf("\n");

	XLALSimSGWB(seg, detectors, numDetectors, 0, OmegaGW, H0, rng); // first time to initilize

	while (1) { // infinite loop
		size_t j;
		for (j = 0; j < stride; ++j, --n) { // output first stride points
			LIGOTimeGPS t = seg[0]->epoch;
			if (n == 0) // check if we're done
				goto end;
			printf("%s", XLALGPSToStr(tstr, XLALGPSAdd(&t, j * seg[0]->deltaT)));
			for (i = 0; i < numDetectors; ++i)
				printf("\t%e", seg[i]->data->data[j]);
			printf("\n");
		}
		XLALSimSGWB(seg, detectors, numDetectors, stride, OmegaGW, H0, rng); // make more data
	}

end:
	for (i = 0; i < numDetectors; ++i)
		XLALDestroyREAL8TimeSeries(seg[i]);
	XLALFree(seg);
	XLALDestroyREAL8FrequencySeries(OmegaGW);
	LALCheckMemoryLeaks();

	return 0;
}
Esempio n. 3
0
static int output(REAL8TimeSeries *hplus, REAL8TimeSeries *hcross)
{
	char tstr[32]; // GPS time string - 31 characters is enough
	size_t j;
	fprintf(stdout, "# time (s)\tH_PLUS (strain)\tH_CROSS (strain)\n");
	for (j = 0; j < hplus->data->length; ++j) {
		LIGOTimeGPS t = hplus->epoch;
		fprintf(stdout, "%s\t%e\t%e\n", XLALGPSToStr(tstr, XLALGPSAdd(&t, j * hplus->deltaT)), hplus->data->data[j], hcross->data->data[j]);
	}
	return 0;
}
Esempio n. 4
0
void output_ts(const char *fname, REAL8TimeSeries *series)
{
    const char *ext;
    FILE *fp;
    /* determine output type from extension */
    ext = strrchr(fname ? fname : "", '.');
    ext = ext ? ext + 1 : "";
    if (strcasecmp(ext, "wav") == 0) {
        fp = fopen(fname, "w");
        XLALAudioWAVRecordREAL8TimeSeries(fp, series);
        fclose(fp);
    }
    else if (strcasecmp(ext, "au") == 0) {
        fp = fopen(fname, "w");
        XLALAudioAURecordREAL8TimeSeries(fp, series);
        fclose(fp);
    }
    else if (
        strcasecmp(ext, "eps") == 0
        || strcasecmp(ext, "jpeg") == 0
        || strcasecmp(ext, "jpg") == 0
        || strcasecmp(ext, "gif") == 0
        || strcasecmp(ext, "png") == 0
        || strcasecmp(ext, "ps") == 0
        || strcasecmp(ext, "pdf") == 0
        || strcasecmp(ext, "svg") == 0
        )
        gnuplot_output_ts(fname, ext, series);
    else if (strcasecmp(ext, "xml") == 0)
        xml_output_ts(fname, series);
    else { /* default is an ascii file */
        size_t i;
        fp = fname ? fopen(fname, "w") : stdout;
        for (i = 0; i < series->data->length; ++i) {
            char tstr[32];
            LIGOTimeGPS t = series->epoch;
            XLALGPSToStr(tstr, XLALGPSAdd(&t, i * series->deltaT));
            fprintf(fp, "%s\t%.15g\n", tstr, series->data->data[i]);
        }
        if (fname)
            fclose(fp);
    }
    return;
}
Esempio n. 5
0
static int WriteLIGOLwXMLArrayMeta(
	FILE *stream,
	const char *indent,
	const LIGOTimeGPS *epoch,
	REAL8 f0
)
{
	int error = 0;
	char *s = XLALGPSToStr(NULL, epoch);

	if(!s)
		return -1;

	error |= fprintf(stream, "%s<Time Name=\"epoch\" Type=\"GPS\">%s</Time>\n", indent, s) < 0;
	error |= fprintf(stream, "%s<Param Name=\"f0\" Unit=\"s^-1\" Type=\"real_8\">%.16g</Param>\n", indent, f0) < 0;

	XLALFree(s);

	return error ? -1 : 0;
}
Esempio n. 6
0
/** dump given COMPLEX8 time-series into a text-file */
int
XLALdumpCOMPLEX8TimeSeries ( const char *fname, const COMPLEX8TimeSeries *series )
{
  XLAL_CHECK ( fname != NULL, XLAL_EINVAL );
  XLAL_CHECK ( series != NULL, XLAL_EINVAL );

  FILE *fp;
  XLAL_CHECK ( (fp = fopen (fname, "wb")) != NULL, XLAL_ESYS );

  REAL8 dt = series->deltaT;
  UINT4 numSamples = series->data->length;
  char buf[256];
  for ( UINT4 i = 0; i < numSamples; i++ )
  {
    LIGOTimeGPS ti = series->epoch;
    XLALGPSAdd ( &ti, i * dt );
    XLALGPSToStr ( buf, &ti );
    fprintf( fp, "%20s %20.16g %20.16g\n", buf, crealf(series->data->data[i]), cimagf(series->data->data[i]) );
  }
  fclose ( fp );

  return XLAL_SUCCESS;

} // XLALdumpCOMPLEX8TimeSeries()
/**
 * some basic consistency checks of the (XLAL) UserInput module, far from exhaustive,
 * but should be enough to catch big obvious malfunctions
 */
int
main(void)
{
  int i, my_argc = 8;
  char **my_argv;
  const char *argv_in[] = { "progname", "--argNum=1", "--argStr=xyz", "--argBool=true", "-a", "1", "-b", "@" TEST_DATA_DIR "ConfigFileSample.cfg" };
  UserInput_t XLAL_INIT_DECL(my_uvars);

  my_argv = XLALCalloc ( my_argc, sizeof(char*) );
  for (i=0; i < my_argc; i ++ )
    {
      my_argv[i] = XLALCalloc ( 1, strlen(argv_in[i])+1);
      strcpy ( my_argv[i], argv_in[i] );
    }

  /* ---------- Register all test user-variables ---------- */
  UserInput_t *uvar = &my_uvars;
  uvar->string2 = XLALStringDuplicate ( "this is the default value");

  XLAL_CHECK ( XLALRegisterUvarMember( argNum, REAL8, 0, REQUIRED, "Testing float argument") == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALRegisterUvarMember( argStr, STRING, 0, REQUIRED, "Testing string argument") == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALRegisterUvarMember( argBool, BOOLEAN, 0, REQUIRED, "Testing bool argument") == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALRegisterUvarMember( argInt, INT4, 'a', REQUIRED, "Testing INT4 argument") == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALRegisterUvarMember( dummy,  INT4, 'c', OPTIONAL, "Testing INT4 argument") == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALRegisterUvarMember( argB2, BOOLEAN, 'b', REQUIRED, "Testing short-option bool argument") == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALRegisterUvarMember( string2, STRING, 0, REQUIRED, "Testing another string argument") == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALRegisterUvarMember( epochGPS, EPOCH, 0, REQUIRED, "Testing epoch given as GPS time") == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALRegisterUvarMember( epochMJDTT, EPOCH, 0, REQUIRED, "Testing epoch given as MJD(TT) time") == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALRegisterUvarMember( longHMS, RAJ, 0, REQUIRED, "Testing RAJ(HMS) argument") == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALRegisterUvarMember( longRad, RAJ, 0, REQUIRED, "Testing RAJ(rad) argument") == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALRegisterUvarMember( latDMS, DECJ, 0, REQUIRED, "Testing DECJ(DMS) argument") == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALRegisterUvarMember( latRad, DECJ, 0, REQUIRED, "Testing DECJ(rad) argument") == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALRegisterUvarMember( longInt, INT8, 0, REQUIRED, "Testing INT8 argument") == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALRegisterUvarMember( long_help, BOOLEAN, 0, NODEFAULT,
                                       "This option is here to test the help page wrapping of long strings. "
                                       "This option is here to test the help page wrapping of long strings. "
                                       "This option is here to test the help page wrapping of long strings. "
                                       "This option is here to test the help page wrapping of long strings. "
                                       "This option is here to test the help page wrapping of long strings. "
                                       "\n"
                                       "This~option~is~here~to~test~the~help~page~wrapping~of~long~strings~without~spaces.~"
                                       "This~option~is~here~to~test~the~help~page~wrapping~of~long~strings~without~spaces.~"
                                       "This~option~is~here~to~test~the~help~page~wrapping~of~long~strings~without~spaces."
                 ) == XLAL_SUCCESS, XLAL_EFUNC );

  /* ---------- now read all input from commandline and config-file ---------- */
  BOOLEAN should_exit = 0;
  XLAL_CHECK ( XLALUserVarReadAllInput ( &should_exit, my_argc, my_argv ) == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( should_exit == 0, XLAL_EFUNC );

  /* ---------- test print usage and help page */
  printf( "=== Begin usage string ===\n" );
  fflush( stdout );
  XLALUserVarPrintUsage( stdout );
  printf( "--- End usage string ---\n" );
  printf( "=== Begin help page ===\n" );
  fflush( stdout );
  XLALUserVarPrintHelp( stdout );
  printf( "--- End help page ---\n" );
  fflush( stdout );

  /* ---------- test log-generation */
  CHAR *logstr;
  XLAL_CHECK ( ( logstr = XLALUserVarGetLog (   UVAR_LOGFMT_CFGFILE )) != NULL, XLAL_EFUNC );
  XLALFree ( logstr );

  /* ---------- test values were read in correctly ---------- */
  XLAL_CHECK ( uvar->argNum == 1, XLAL_EFAILED, "Failed to read in argNum\n" );
  XLAL_CHECK ( strcmp ( uvar->argStr, "xyz" ) == 0, XLAL_EFAILED, "Failed to read in argStr\n" );
  XLAL_CHECK ( uvar->argBool, XLAL_EFAILED, "Failed to read in argBool\n" );
  XLAL_CHECK ( uvar->argInt == 1, XLAL_EFAILED, "Failed to read in argInt\n" );
  XLAL_CHECK ( uvar->argB2, XLAL_EFAILED, "Failed to read in argB2\n" );
  XLAL_CHECK ( strcmp ( uvar->string2, "this is also possible, and # here does nothing; and neither does semi-colon " ) == 0, XLAL_EFAILED, "Failed to read in string2\n" );

  char buf1[256], buf2[256];
  XLAL_CHECK ( XLALGPSCmp ( &uvar->epochGPS, &uvar->epochMJDTT ) == 0, XLAL_EFAILED, "GPS epoch %s differs from MJD(TT) epoch %s\n",
               XLALGPSToStr ( buf1, &uvar->epochGPS), XLALGPSToStr ( buf2, &uvar->epochMJDTT ) );

  REAL8 diff, tol = 3e-15;
  XLAL_CHECK ( (diff = fabs(uvar->longHMS - uvar->longRad)) < tol, XLAL_EFAILED, "longitude(HMS) = %.16g differs from longitude(rad) = %.16g by %g > %g\n", uvar->longHMS, uvar->longRad, diff, tol );
  XLAL_CHECK ( (diff = fabs(uvar->latDMS - uvar->latRad)) < tol, XLAL_EFAILED, "latitude(HMS) = %.16g differs from latitude(rad) = %.16g by %g > %g\n", uvar->latDMS, uvar->latRad, diff, tol );

  XLAL_CHECK ( uvar->longInt == 4294967294, XLAL_EFAILED, "Failed to read an INT8: longInt = %" LAL_INT8_FORMAT " != 4294967294", uvar->longInt );

  /* ----- cleanup ---------- */
  XLALDestroyUserVars();
  for (i=0; i < my_argc; i ++ ) {
    XLALFree ( my_argv[i] );
  }
  XLALFree ( my_argv );

  LALCheckMemoryLeaks();

  return XLAL_SUCCESS;

} // main()
Esempio n. 8
0
/**
 * Handle user-input and set up shop accordingly, and do all
 * consistency-checks on user-input.
 */
int
XLALInitMakefakedata ( ConfigVars_t *cfg, UserVariables_t *uvar )
{
  XLAL_CHECK ( cfg != NULL, XLAL_EINVAL, "Invalid NULL input 'cfg'\n" );
  XLAL_CHECK ( uvar != NULL, XLAL_EINVAL, "Invalid NULL input 'uvar'\n");

  cfg->VCSInfoString = XLALGetVersionString(0);
  XLAL_CHECK ( cfg->VCSInfoString != NULL, XLAL_EFUNC, "XLALGetVersionString(0) failed.\n" );

  // version info was requested: output then exit
  if ( uvar->version )
    {
      printf ("%s\n", cfg->VCSInfoString );
      exit (0);
    }

  /* if requested, log all user-input and code-versions */
  if ( uvar->logfile ) {
    XLAL_CHECK ( XLALWriteMFDlog ( uvar->logfile, cfg ) == XLAL_SUCCESS, XLAL_EFUNC, "XLALWriteMFDlog() failed with xlalErrno = %d\n", xlalErrno );
  }

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

  /* check for negative fMin and Band, which would break the fMin_eff, fBand_eff calculation below */
  XLAL_CHECK ( uvar->fmin >= 0, XLAL_EDOM, "Invalid negative frequency fMin=%f!\n\n", uvar->fmin );
  XLAL_CHECK ( uvar->Band > 0, XLAL_EDOM, "Invalid non-positive frequency band Band=%f!\n\n", uvar->Band );

  // ---------- check user-input consistency ----------

  // ----- check if frames + frame channels given
  BOOLEAN have_frames  = (uvar->inFrames != NULL);
  BOOLEAN have_channels= (uvar->inFrChannels != NULL);
  XLAL_CHECK ( !(have_frames || have_channels) || (have_frames && have_channels), XLAL_EINVAL, "Need both --inFrames and --inFrChannels, or NONE\n");

  // ----- IFOs : only from one of {--IFOs, --noiseSFTs, --inFrChannels}: mutually exclusive
  BOOLEAN have_IFOs      = (uvar->IFOs != NULL);
  BOOLEAN have_noiseSFTs = (uvar->noiseSFTs != NULL);
  XLAL_CHECK ( have_frames || have_IFOs || have_noiseSFTs, XLAL_EINVAL, "Need one of --IFOs, --noiseSFTs or --inFrChannels to determine detectors\n");

  if ( have_frames ) {
    XLAL_CHECK ( !have_IFOs && !have_noiseSFTs, XLAL_EINVAL, "If --inFrames given, cannot handle --IFOs or --noiseSFTs input\n");
    XLAL_CHECK ( XLALParseMultiLALDetector ( &(cfg->multiIFO), uvar->inFrChannels ) == XLAL_SUCCESS, XLAL_EFUNC );
  } else { // !have_frames
    XLAL_CHECK ( !(have_IFOs && have_noiseSFTs), XLAL_EINVAL, "Cannot handle both --IFOs and --noiseSFTs input\n");
  }
  if ( have_IFOs ) {
    XLAL_CHECK ( XLALParseMultiLALDetector ( &(cfg->multiIFO), uvar->IFOs ) == XLAL_SUCCESS, XLAL_EFUNC );
  }

  // ----- TIMESTAMPS: either from --timestampsFiles, --startTime+duration, or --noiseSFTs
  BOOLEAN have_startTime = XLALUserVarWasSet ( &uvar->startTime );
  BOOLEAN have_duration = XLALUserVarWasSet ( &uvar->duration );
  BOOLEAN have_timestampsFiles = ( uvar->timestampsFiles != NULL );
  // need BOTH startTime+duration or none
  XLAL_CHECK ( ( have_duration && have_startTime) || !( have_duration || have_startTime ), XLAL_EINVAL, "Need BOTH {--startTime,--duration} or NONE\n");
  // at least one of {startTime,timestamps,noiseSFTs,inFrames} required
  XLAL_CHECK ( have_timestampsFiles || have_startTime || have_noiseSFTs || have_frames, XLAL_EINVAL, "Need at least one of {--timestampsFiles, --startTime+duration, --noiseSFTs, --inFrames}\n" );
  // don't allow timestamps + {startTime+duration OR noiseSFTs}
  XLAL_CHECK ( !have_timestampsFiles || !(have_startTime||have_noiseSFTs), XLAL_EINVAL, "--timestampsFiles incompatible with {--noiseSFTs or --startTime+duration}\n");
  // note, however, that we DO allow --noiseSFTs and --startTime+duration, which will act as a constraint
  // on the noise-SFTs to load in

  // don't allow --SFToverlap with either --noiseSFTs OR --timestampsFiles
  XLAL_CHECK ( uvar->SFToverlap >= 0, XLAL_EDOM );
  BOOLEAN haveOverlap = ( uvar->SFToverlap > 0 );
  XLAL_CHECK ( !haveOverlap || !( have_noiseSFTs || have_timestampsFiles ), XLAL_EINVAL, "--SFToverlap incompatible with {--noiseSFTs or --timestampsFiles}\n" );

  // now handle the 3 mutually-exclusive cases: have_noiseSFTs || have_timestampsFiles || have_startTime (only)
  if ( have_noiseSFTs )
    {
      SFTConstraints XLAL_INIT_DECL(constraints);
      if ( have_startTime && have_duration )	 // use optional (startTime+duration) as constraints,
        {
          LIGOTimeGPS minStartTime, maxStartTime;
          minStartTime = uvar->startTime;
          maxStartTime = uvar->startTime;
          XLALGPSAdd ( &maxStartTime, uvar->duration );
          constraints.minStartTime = &minStartTime;
          constraints.maxStartTime = &maxStartTime;
          char bufGPS1[32], bufGPS2[32];
          XLALPrintWarning ( "Only noise-SFTs between GPS [%s, %s] will be used!\n", XLALGPSToStr(bufGPS1, &minStartTime), XLALGPSToStr(bufGPS2, &maxStartTime) );
        } /* if start+duration given */
      XLAL_CHECK ( (cfg->noiseCatalog = XLALSFTdataFind ( uvar->noiseSFTs, &constraints )) != NULL, XLAL_EFUNC );
      XLAL_CHECK (  cfg->noiseCatalog->length > 0, XLAL_EINVAL, "No noise-SFTs matching (start+duration, timestamps) were found!\n" );
      XLAL_CHECK ( (cfg->multiNoiseCatalogView = XLALGetMultiSFTCatalogView ( cfg->noiseCatalog )) != NULL, XLAL_EFUNC );

      // extract multi-timestamps from the multi-SFT-catalog view
      XLAL_CHECK ( (cfg->multiTimestamps = XLALTimestampsFromMultiSFTCatalogView ( cfg->multiNoiseCatalogView )) != NULL, XLAL_EFUNC );
      // extract IFOs from multi-SFT catalog
      XLAL_CHECK ( XLALMultiLALDetectorFromMultiSFTCatalogView ( &(cfg->multiIFO), cfg->multiNoiseCatalogView ) == XLAL_SUCCESS, XLAL_EFUNC );

    } // endif have_noiseSFTs
  else if ( have_timestampsFiles )
    {
      XLAL_CHECK ( (cfg->multiTimestamps = XLALReadMultiTimestampsFiles ( uvar->timestampsFiles )) != NULL, XLAL_EFUNC );

      XLAL_CHECK ( (cfg->multiTimestamps->length > 0) && (cfg->multiTimestamps->data != NULL), XLAL_EINVAL, "Got empty timestamps-list from XLALReadMultiTimestampsFiles()\n" );

      for ( UINT4 X=0; X < cfg->multiTimestamps->length; X ++ ) {
        cfg->multiTimestamps->data[X]->deltaT = uvar->Tsft;	// Tsft information not given by timestamps-file
      }
    } // endif have_timestampsFiles
  else if ( have_startTime && have_duration )
    {
      XLAL_CHECK ( ( cfg->multiTimestamps = XLALMakeMultiTimestamps ( uvar->startTime, uvar->duration, uvar->Tsft, uvar->SFToverlap, cfg->multiIFO.length )) != NULL, XLAL_EFUNC );
    } // endif have_startTime

  // check if the user asked for Gaussian white noise to be produced (sqrtSn[X]!=0), otherwise leave noise-floors at 0
  if ( uvar->sqrtSX != NULL ) {
    XLAL_CHECK ( XLALParseMultiNoiseFloor ( &(cfg->multiNoiseFloor), uvar->sqrtSX, cfg->multiIFO.length ) == XLAL_SUCCESS, XLAL_EFUNC );
  } else {
    cfg->multiNoiseFloor.length = cfg->multiIFO.length;
    // values remain at their default sqrtSn[X] = 0;
  }

#ifdef HAVE_LIBLALFRAME
  // if user requested time-series data from frames to be added: try to read the frames now
  if ( have_frames )
    {
      UINT4 numDetectors = uvar->inFrChannels->length;
      XLAL_CHECK ( uvar->inFrames->length == numDetectors, XLAL_EINVAL, "Need equal number of channel names (%d) as frame specifications (%d)\n", uvar->inFrChannels->length, numDetectors );

      XLAL_CHECK ( (cfg->inputMultiTS = XLALCalloc ( 1, sizeof(*cfg->inputMultiTS))) != NULL, XLAL_ENOMEM );
      cfg->inputMultiTS->length = numDetectors;
      XLAL_CHECK ( (cfg->inputMultiTS->data = XLALCalloc ( numDetectors, sizeof(cfg->inputMultiTS->data[0]) )) != NULL, XLAL_ENOMEM );
      if ( cfg->multiTimestamps == NULL )
        {
          XLAL_CHECK ( (cfg->multiTimestamps = XLALCalloc ( 1, sizeof(*cfg->multiTimestamps) )) != NULL, XLAL_ENOMEM );
          XLAL_CHECK ( (cfg->multiTimestamps->data = XLALCalloc ( numDetectors, sizeof(cfg->multiTimestamps->data[0]))) != NULL, XLAL_ENOMEM );
          cfg->multiTimestamps->length = numDetectors;
        }
      for ( UINT4 X = 0; X < numDetectors; X ++ )
        {
          LALCache *cache;
          XLAL_CHECK ( (cache = XLALCacheImport ( uvar->inFrames->data[X] )) != NULL, XLAL_EFUNC, "Failed to import cache file '%s'\n", uvar->inFrames->data[X] );
          // this is a sorted cache, so extract its time-range:
          REAL8 cache_tStart = cache->list[0].t0;
          REAL8 cache_tEnd   = cache->list[cache->length-1].t0 + cache->list[cache->length-1].dt;
          REAL8 cache_duration = (cache_tEnd - cache_tStart);
          LIGOTimeGPS ts_start;
          REAL8 ts_duration;
          // check that it's consistent with timestamps, if given, otherwise create timestamps from this
          if ( cfg->multiTimestamps->data[X] != NULL )	// FIXME: implicitly assumes timestamps are sorted, which is not guaranteed by timestamps-reading from file
            {
              const LIGOTimeGPSVector *timestampsX = cfg->multiTimestamps->data[X];
              REAL8 tStart = XLALGPSGetREAL8( &timestampsX->data[0] );
              REAL8 tEnd   = XLALGPSGetREAL8( &timestampsX->data[timestampsX->length-1]) + timestampsX->deltaT;
              XLAL_CHECK ( tStart >= cache_tStart && tEnd <= cache_tEnd, XLAL_EINVAL, "Detector X=%d: Requested timestamps-range [%.0f, %.0f]s outside of cache range [%.0f,%.0f]s\n",
                           X, tStart, tEnd, cache_tStart, cache_tEnd );
              XLALGPSSetREAL8 ( &ts_start, tStart );
              ts_duration = (tEnd - tStart);
            }
          else
            {
              XLALGPSSetREAL8 ( &ts_start, (REAL8)cache_tStart + 1); // cache times can apparently be by rounded up or down by 1s, so shift by 1s to be safe
              ts_duration = cache_duration - 1;
              XLAL_CHECK ( (cfg->multiTimestamps->data[X] = XLALMakeTimestamps ( ts_start, ts_duration, uvar->Tsft, uvar->SFToverlap ) ) != NULL, XLAL_EFUNC );
            }
          // ----- now open frame stream and read *all* the data within this time-range [FIXME] ----------
          LALFrStream *stream;
          XLAL_CHECK ( (stream = XLALFrStreamCacheOpen ( cache )) != NULL, XLAL_EFUNC, "Failed to open stream from cache file '%s'\n", uvar->inFrames->data[X] );
          XLALDestroyCache ( cache );

          const char *channel = uvar->inFrChannels->data[X];
          size_t limit = 0;	// unlimited read
          REAL8TimeSeries *ts;
          XLAL_CHECK ( (ts = XLALFrStreamInputREAL8TimeSeries ( stream, channel, &ts_start, ts_duration, limit )) != NULL,
                       XLAL_EFUNC, "Frame reading failed for stream created for '%s': ts_start = {%d,%d}, duration=%.0f\n", uvar->inFrames->data[X], ts_start.gpsSeconds, ts_start.gpsNanoSeconds, ts_duration );
          cfg->inputMultiTS->data[X] = ts;

          XLAL_CHECK ( XLALFrStreamClose ( stream ) == XLAL_SUCCESS, XLAL_EFUNC, "Stream closing failed for cache file '%s'\n", uvar->inFrames->data[X] );
        } // for X < numDetectors
    } // if inFrames

  // if user requested timeseries *output* to frame files, handle deprecated options
  XLAL_CHECK ( !(uvar->TDDframedir && uvar->outFrameDir), XLAL_EINVAL, "Specify only ONE of {--TDDframedir or --outFrameDir} or NONE\n");
  if ( uvar->TDDframedir ) {
    cfg->outFrameDir = uvar->TDDframedir;
  } else if ( uvar->outFrameDir ) {
    cfg->outFrameDir = uvar->outFrameDir;
  }
#endif

  return XLAL_SUCCESS;

} /* XLALInitMakefakedata() */
Esempio n. 9
0
int main(int argc, char **argv)
{
	REAL8TimeSeries *hplus = NULL;
	REAL8TimeSeries *hcross = NULL;
	struct params p;
	int status = 0;
	gsl_rng *rng = NULL;

	XLALSetErrorHandler(XLALAbortErrorHandler);

	p = parseargs(argc, argv);

	if ((int)(p.waveform) < 0 || (int)(p.waveform) >= NumWaveforms) {
		fprintf(stderr, "error: must specify valid waveform\n");
		exit(1);
	}

	if (p.waveform == BLTWNB) { /* set up gsl random number generator */
		gsl_rng_env_setup();
		rng = gsl_rng_alloc(gsl_rng_default);
	}

	if (IS_INVALID_DOUBLE(p.srate) || p.srate <= 0.0) {
		fprintf(stderr, "error: must specify valid sample rate\n");
		status = 1;
	}

	verbose_output("Input parameters:\n");
	verbose_output("%-31s `%s' - %s\n", "waveform:", waveform_names[p.waveform], waveform_long_names[p.waveform]);
	verbose_output("%-31s %g (Hz)\n", "sample rate:", p.srate);

	switch (p.waveform) {

	case BLTWNB:

		/* sanity check relevant parameters */
		if (IS_INVALID_DOUBLE(p.duration) || p.duration < 0.0) {
			fprintf(stderr, "error: must specify valid duration for waveform `%s'\n", waveform_names[p.waveform]);
			status = 1;
		}
		if (IS_INVALID_DOUBLE(p.frequency) || p.frequency < 0.0) {
			fprintf(stderr, "error: must specify valid frequency for waveform `%s'\n", waveform_names[p.waveform]);
			status = 1;
		}
		if (IS_INVALID_DOUBLE(p.bandwidth) || p.bandwidth < 0.0) {
			fprintf(stderr, "error: must specify valid bandwidth for waveform `%s'\n", waveform_names[p.waveform]);
			status = 1;
		}
		if (IS_INVALID_DOUBLE(p.eccentricity) || p.eccentricity < 0.0 || p.eccentricity > 1.0) {
			fprintf(stderr, "error: must specify valid eccentricity in domain [0,1] for waveform `%s'\n", waveform_names[p.waveform]);
			status = 1;
		}
		if (IS_INVALID_DOUBLE(p.fluence) || p.fluence < 0.0) {
			fprintf(stderr, "error: must specify valid fluence for waveform `%s'\n", waveform_names[p.waveform]);
			status = 1;
		}

		/* detect set but ignored parameters */
		if (!IS_INVALID_DOUBLE(p.q))
			fprintf(stderr, "warning: quality-factor parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (p.phase != DEFAULT_PHASE)
			fprintf(stderr, "warning: phase parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.amplitude))
			fprintf(stderr, "warning: amplitude parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.hrss))
			fprintf(stderr, "warning: hrss parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);

		if (!status) {
			double int_hdot_squared_dt;
			int_hdot_squared_dt = p.fluence * LAL_GMSUN_SI * 4 / LAL_C_SI / LAL_PC_SI / LAL_PC_SI;

			verbose_output("%-31s %g (s)\n", "duration:", p.duration);
			verbose_output("%-31s %g (Hz)\n", "frequency:", p.frequency);
			verbose_output("%-31s %g (Hz)\n", "bandwidth:", p.bandwidth);
			verbose_output("%-31s %g\n", "eccentricity:", p.eccentricity);
			verbose_output("%-31s %g (Msun c^2 pc^-2)\n", "fluence:", p.fluence);
			verbose_output("%-31s %g (s^-1)\n", "integral (dh/dt)^2 dt:", int_hdot_squared_dt);
			verbose_output("%-31s GSL_RNG_TYPE=%s\n", "GSL random number generator:", gsl_rng_name(rng));
			verbose_output("%-31s GSL_RNG_SEED=%lu\n", "GSL random number seed:", gsl_rng_default_seed);
			status = XLALGenerateBandAndTimeLimitedWhiteNoiseBurst(&hplus, &hcross, p.duration, p.frequency, p.bandwidth, p.eccentricity, int_hdot_squared_dt, 1.0/p.srate, rng);
		}
		break;

	case StringCusp:

		/* sanity check relevant parameters */
		if (IS_INVALID_DOUBLE(p.amplitude) || p.amplitude < 0.0) {
			fprintf(stderr, "error: must specify valid amplitude for waveform `%s'\n", waveform_names[p.waveform]);
			status = 1;
		}
		if (IS_INVALID_DOUBLE(p.frequency) || p.frequency < 0.0) {
			fprintf(stderr, "error: must specify valid frequency for waveform `%s'\n", waveform_names[p.waveform]);
			status = 1;
		}

		/* detect set but ignored parameters */
		if (!IS_INVALID_DOUBLE(p.duration))
			fprintf(stderr, "warning: duration parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.bandwidth))
			fprintf(stderr, "warning: bandwidth parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.q))
			fprintf(stderr, "warning: quality-factor parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (p.eccentricity != DEFAULT_ECCENTRICITY)
			fprintf(stderr, "warning: eccentricity parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (p.phase != DEFAULT_PHASE)
			fprintf(stderr, "warning: phase parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.hrss))
			fprintf(stderr, "warning: hrss parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.fluence))
			fprintf(stderr, "warning: fluence parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);

		if (!status) {
			verbose_output("%-31s %g (s^-1/3)\n", "amplitude:", p.amplitude);
			verbose_output("%-31s %g (Hz)\n", "frequency:", p.frequency);
			status = XLALGenerateStringCusp(&hplus, &hcross, p.amplitude, p.frequency, 1.0/p.srate);
		}
		break;

	case SineGaussian:

		/* sanity check relevant parameters */
		if (IS_INVALID_DOUBLE(p.q) || p.q < 0.0) {
			fprintf(stderr, "error: must specify valid quality factor for waveform `%s'\n", waveform_names[p.waveform]);
			status = 1;
		}
		if (IS_INVALID_DOUBLE(p.frequency) || p.frequency < 0.0) {
			fprintf(stderr, "error: must specify valid frequency for waveform `%s'\n", waveform_names[p.waveform]);
			status = 1;
		}
		if (IS_INVALID_DOUBLE(p.hrss) || p.hrss < 0.0) {
			fprintf(stderr, "error: must specify valid hrss for waveform `%s\n", waveform_names[p.waveform]);
			status = 1;
		}
		if (IS_INVALID_DOUBLE(p.eccentricity) || p.eccentricity < 0.0 || p.eccentricity > 1.0) {
			fprintf(stderr, "error: must specify valid eccentricity in domain [0,1] for waveform `%s'\n", waveform_names[p.waveform]);
			status = 1;
		}
		if (IS_INVALID_DOUBLE(p.phase)) {
			fprintf(stderr, "error: must specify valid phase for waveform `%s'\n", waveform_names[p.waveform]);
			status = 1;
		}

		/* detect set but ignored parameters */
		if (!IS_INVALID_DOUBLE(p.duration))
			fprintf(stderr, "warning: duration parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.bandwidth))
			fprintf(stderr, "warning: bandwidth parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.amplitude))
			fprintf(stderr, "warning: amplitude parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.fluence))
			fprintf(stderr, "warning: fluence parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);

		if (!status) {
			verbose_output("%-31s %g\n", "quality-factor:", p.q);
			verbose_output("%-31s %g (Hz)\n", "frequency:", p.frequency);
			verbose_output("%-31s %g (Hz^-1/2)\n", "root-sum-squared strain:", p.hrss);
			verbose_output("%-31s %g\n", "eccentricity:", p.eccentricity);
			verbose_output("%-31s %g (degrees)\n", "phase:", p.phase / LAL_PI_180);
			status = XLALSimBurstSineGaussian(&hplus, &hcross, p.q, p.frequency, p.hrss, p.eccentricity, p.phase, 1.0/p.srate);
		}
		break;

	case Gaussian:

		/* sanity check relevant parameters */
		if (IS_INVALID_DOUBLE(p.duration) || p.duration < 0.0) {
			fprintf(stderr, "error: must specify valid duration for waveform `%s'\n", waveform_names[p.waveform]);
			status = 1;
		}
		if (IS_INVALID_DOUBLE(p.hrss) || p.hrss < 0.0) {
			fprintf(stderr, "error: must specify valid hrss for waveform `%s'\n", waveform_names[p.waveform]);
			status = 1;
		}
		/* detect set but ignored parameters */
		if (!IS_INVALID_DOUBLE(p.frequency))
			fprintf(stderr, "warning: frequency parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.bandwidth))
			fprintf(stderr, "warning: bandwidth parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.q))
			fprintf(stderr, "warning: quality-factor parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (p.eccentricity != DEFAULT_ECCENTRICITY)
			fprintf(stderr, "warning: eccentricity parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (p.phase != DEFAULT_PHASE)
			fprintf(stderr, "warning: phase parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.amplitude))
			fprintf(stderr, "warning: amplitude parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.fluence))
			fprintf(stderr, "warning: fluence parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!status) {
			verbose_output("%-31s %g (s)\n", "duration:", p.duration);
			verbose_output("%-31s %g (Hz^-1/2)\n", "root-sum-squared strain:", p.hrss);
			status = XLALSimBurstGaussian(&hplus, &hcross, p.duration, p.hrss, 1.0/p.srate);
		}

		break;

	case Impulse:

		/* sanity check relevant parameters */
		if (IS_INVALID_DOUBLE(p.amplitude) || p.amplitude < 0.0) {
			fprintf(stderr, "error: must specify valid amplitude for waveform `%s'\n", waveform_names[p.waveform]);
			status = 1;
		}

		/* detect set but ignored parameters */
		if (!IS_INVALID_DOUBLE(p.duration))
			fprintf(stderr, "warning: duration parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.frequency))
			fprintf(stderr, "warning: frequency parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.bandwidth))
			fprintf(stderr, "warning: bandwidth parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.q))
			fprintf(stderr, "warning: quality-factor parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (p.eccentricity != DEFAULT_ECCENTRICITY)
			fprintf(stderr, "warning: eccentricity parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (p.phase != DEFAULT_PHASE)
			fprintf(stderr, "warning: phase parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.hrss))
			fprintf(stderr, "warning: hrss parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.fluence))
			fprintf(stderr, "warning: fluence parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);

		if (!status) {
			verbose_output("%-31s %g (dimensionless)\n", "amplitude:", p.amplitude);
			status = XLALGenerateImpulseBurst(&hplus, &hcross, p.amplitude, 1.0/p.srate);
		}
		break;

	default:
		fprintf(stderr, "error: unrecognized waveform\n");
		exit(1);
	};

	if (status)
		exit(1);

	if (verbose) {
		char peak_time[32]; // GPS time string - 31 characters is enough
		LIGOTimeGPS tpeak;
		COMPLEX16 hpeak;
		double hrss;
		double fluence;
		unsigned ipeak;
		hpeak = XLALMeasureHPeak(hplus, hcross, &ipeak);
		tpeak = hplus->epoch;
		XLALGPSAdd(&tpeak, ipeak * hplus->deltaT);
		XLALGPSToStr(peak_time, &tpeak);
		hrss = XLALMeasureHrss(hplus, hcross);
		fluence = XLALMeasureEoverRsquared(hplus, hcross);
		verbose_output("Measured parameters:\n");
		verbose_output("%-31s %s (s)\n", "peak time:", peak_time);
		verbose_output("%-31s (h+, hx) = (%g, %g)\n", "peak strain amplitude:", creal(hpeak), cimag(hpeak));
		verbose_output("%-31s abs(h+, hx) = %g\n", "peak strain amplitude:", cabs(hpeak));
		verbose_output("%-31s arg(h+, hx) = %g (rad)\n", "peak strain amplitude:", carg(hpeak));
		verbose_output("%-31s %g (Hz^-1/2)\n", "root-sum-squared strain:", hrss);
		verbose_output("%-31s %g (J m^-2)\n", "isotropic energy fluence:", fluence);
		verbose_output("%-31s %g (Msun c^2 pc^-2)\n", "isotropic energy fluence:", fluence * LAL_PC_SI * LAL_PC_SI / LAL_MSUN_SI / LAL_C_SI / LAL_C_SI);
	}

	output(hplus, hcross);

	XLALDestroyREAL8TimeSeries(hcross);
	XLALDestroyREAL8TimeSeries(hplus);
	LALCheckMemoryLeaks();
	return 0;
}
Esempio n. 10
0
/*----------------------------------------------------------------------
 * main function
 *----------------------------------------------------------------------*/
int
main(int argc, char *argv[])
{
  SFTConstraints XLAL_INIT_DECL(constraints);
  CHAR detector[2] = "??";	/* allow reading v1-SFTs without detector-info */
  SFTVector *diffs = NULL;
  REAL8 maxd = 0;

  /* register all user-variables */
  UserInput_t XLAL_INIT_DECL(uvar);
  XLAL_CHECK_MAIN ( initUserVars ( &uvar ) == XLAL_SUCCESS, XLAL_EFUNC );

  /* read cmdline & cfgfile  */
  XLAL_CHECK_MAIN ( XLALUserVarReadAllInput ( argc, argv ) == XLAL_SUCCESS, XLAL_EFUNC );

  if (uvar.help) { 	/* help requested: we're done */
    exit (0);
  }

  /* now read in the two complete sft-vectors */
  constraints.detector = detector;

  SFTCatalog *catalog;
  XLAL_CHECK_MAIN ( (catalog = XLALSFTdataFind ( uvar.sftBname1, &constraints )) != NULL, XLAL_EFUNC );
  SFTVector *SFTs1;
  XLAL_CHECK_MAIN ( (SFTs1 = XLALLoadSFTs( catalog, -1, -1 )) != NULL, XLAL_EFUNC );
  XLALDestroySFTCatalog ( catalog );

  XLAL_CHECK_MAIN ( (catalog = XLALSFTdataFind ( uvar.sftBname2, &constraints )) != NULL, XLAL_EFUNC );
  SFTVector *SFTs2;
  XLAL_CHECK_MAIN ( (SFTs2 = XLALLoadSFTs( catalog, -1, -1 )) != NULL, XLAL_EFUNC );
  XLALDestroySFTCatalog ( catalog );

  /* ---------- do some sanity checks of consistency of SFTs ----------*/
  XLAL_CHECK_MAIN ( SFTs1->length == SFTs2->length, XLAL_EINVAL, "Number of SFTs differ for SFTbname1 and SFTbname2!\n");

  for ( UINT4 i=0; i < SFTs1->length; i++ )
    {
      SFTtype *sft1 = &(SFTs1->data[i]);
      SFTtype *sft2 = &(SFTs2->data[i]);

      if( strcmp( sft1->name, sft2->name ) )
	{
	  if ( lalDebugLevel ) { XLALPrintError("WARNING SFT %d: detector-prefix differ! '%s' != '%s'\n", i, sft1->name, sft2->name ); }
	  /* exit (1); */  /* can't be too strict here, as we also allow v1-SFTs, which don't have detector-name */
	}

      XLAL_CHECK_MAIN ( sft1->data->length == sft2->data->length, XLAL_EINVAL, "\nERROR SFT %d: lengths differ! %d != %d\n", i, sft1->data->length, sft2->data->length );

      REAL8 Tdiff = XLALGPSDiff(&(sft1->epoch), &(sft2->epoch));
      CHAR buf1[32], buf2[32];;
      XLAL_CHECK_MAIN ( Tdiff == 0.0, XLAL_EINVAL, "SFT %d: epochs differ: %s vs %s\n", i, XLALGPSToStr(buf1,&sft1->epoch), XLALGPSToStr(buf2,&sft2->epoch) );
      XLAL_CHECK_MAIN ( sft1->f0 == sft2->f0, XLAL_EINVAL, "ERROR SFT %d: fmin differ: %fHz vs %fHz\n", i, sft1->f0, sft2->f0 );
      XLAL_CHECK_MAIN ( sft1->deltaF == sft2->deltaF, XLAL_EINVAL, "ERROR SFT %d: deltaF differs: %fHz vs %fHz\n", i, sft1->deltaF, sft2->deltaF );
    } /* for i < numSFTs */

  /*---------- now do some actual comparisons ----------*/
  XLAL_CHECK_MAIN ( (diffs = subtractSFTVectors ( SFTs1, SFTs2)) != NULL, XLAL_EFUNC );

  if ( uvar.verbose)
    {
      for ( UINT4 i=0; i < SFTs1->length; i++)
	{
	  SFTtype *sft1 = &(SFTs1->data[i]);
	  SFTtype *sft2 = &(SFTs2->data[i]);

	  XLALPrintInfo ("i=%02d: ", i);
	  REAL4 norm1 = scalarProductSFT ( sft1, sft1 );
	  norm1 = sqrt(norm1);
	  REAL4 norm2 = scalarProductSFT ( sft2, sft2 );
	  norm2 = sqrt(norm2);
	  REAL4 scalar = scalarProductSFT ( sft1, sft2 );

	  REAL4 normdiff = scalarProductSFT ( &(diffs->data[i]), &(diffs->data[i]) );

	  REAL4 d1 = (norm1 - norm2)/norm1;
	  REAL4 d2 = 1.0 - scalar / (norm1*norm2);
	  REAL4 d3 = normdiff / (norm1*norm1 + norm2*norm2 );
	  REAL4 d4 = getMaxErrSFT (sft1, sft2);
	  XLALPrintInfo ("(|x|-|y|)/|x|=%10.3e, 1-x.y/(|x||y|)=%10.3e, |x-y|^2/(|x|^2+|y|^2))=%10.3e, maxErr=%10.3e\n", d1, d2, d3, d4);
	} /* for i < SFTs->length */
    } /* if verbose */

  /* ---------- COMBINED measures ---------- */
  {
    REAL4 ret;
    ret = scalarProductSFTVector ( SFTs1, SFTs1 );
    REAL8 norm1 = sqrt( (REAL8)ret );

    ret = scalarProductSFTVector ( SFTs2, SFTs2 );
    REAL8 norm2 = sqrt( (REAL8)ret );

    ret = scalarProductSFTVector ( SFTs1, SFTs2 );
    REAL8 scalar = (REAL8) ret;

    ret = scalarProductSFTVector ( diffs, diffs );
    REAL8 normdiff = (REAL8) ret;

    REAL8 d1 = (norm1 - norm2)/norm1;
    maxd = fmax ( maxd, d1 );
    REAL8 d2 = 1.0 - scalar / (norm1*norm2);
    maxd = fmax ( maxd, d2 );
    REAL8 d3 = normdiff / ( norm1*norm1 + norm2*norm2);
    maxd = fmax ( maxd, d3 );
    REAL8 d4 = getMaxErrSFTVector (SFTs1, SFTs2);
    maxd = fmax ( maxd, d4 );

    if ( uvar.verbose ) {
      printf ("\nTOTAL:(|x|-|y|)/|x|=%10.3e, 1-x.y/(|x||y|)=%10.3e, |x-y|^2/(|x|^2+|y|^2)=%10.3e, maxErr=%10.3e\n", d1, d2, d3, d4);
    }
    else
      {
        printf ("%10.3e  %10.3e\n", d3, d4);
      }

  } /* combined total measures */


  /* free memory */
  XLALDestroySFTVector ( SFTs1 );
  XLALDestroySFTVector ( SFTs2 );
  XLALDestroySFTVector ( diffs );
  XLALDestroyUserVars();

  LALCheckMemoryLeaks();

  if ( maxd <= uvar.relErrorMax ) {
    return 0;
  }
  else {
    return 1;
  }

} /* main */
Esempio n. 11
0
/**
 * some basic consistency checks of the (XLAL) UserInput module, far from exhaustive,
 * but should be enough to catch big obvious malfunctions
 */
int
main(int argc, char *argv[])
{
  int i, my_argc = 8;
  char **my_argv;
  const char *argv_in[] = { "progname", "--argNum=1", "--argStr=xyz", "--argBool=true", "-a", "1", "-b", "@" TEST_DATA_DIR "ConfigFileSample.cfg" };
  UserInput_t XLAL_INIT_DECL(my_uvars);

  XLAL_CHECK ( argc == 1, XLAL_EINVAL, "No input arguments allowed.\n");

  my_argv = XLALCalloc ( my_argc, sizeof(char*) );
  for (i=0; i < my_argc; i ++ )
    {
      my_argv[i] = XLALCalloc ( 1, strlen(argv_in[i])+1);
      strcpy ( my_argv[i], argv_in[i] );
    }

  /* ---------- Register all test user-variables ---------- */
  UserInput_t *uvar = &my_uvars;
  XLAL_CHECK ( XLALregREALUserStruct( argNum, 0, UVAR_REQUIRED, "Testing float argument") == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALregSTRINGUserStruct( argStr, 0, UVAR_REQUIRED, "Testing string argument") == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALregBOOLUserStruct( argBool, 0, UVAR_REQUIRED, "Testing bool argument") == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALregINTUserStruct( argInt, 'a', UVAR_REQUIRED, "Testing INT argument") == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALregINTUserStruct( dummy,  'c', UVAR_OPTIONAL, "Testing INT argument") == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALregBOOLUserStruct( argB2, 'b', UVAR_REQUIRED, "Testing short-option bool argument") == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALregSTRINGUserStruct( string2, 0, UVAR_REQUIRED, "Testing another string argument") == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALregEPOCHUserStruct( epochGPS, 0, UVAR_REQUIRED, "Testing epoch given as GPS time") == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALregEPOCHUserStruct( epochMJDTT, 0, UVAR_REQUIRED, "Testing epoch given as MJD(TT) time") == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALregRAJUserStruct( longHMS, 0, UVAR_REQUIRED, "Testing RAJ(HMS) argument") == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALregRAJUserStruct( longRad, 0, UVAR_REQUIRED, "Testing RAJ(rad) argument") == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALregDECJUserStruct( latDMS, 0, UVAR_REQUIRED, "Testing DECJ(DMS) argument") == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALregDECJUserStruct( latRad, 0, UVAR_REQUIRED, "Testing DECJ(rad) argument") == XLAL_SUCCESS, XLAL_EFUNC );

  /* ---------- now read all input from commandline and config-file ---------- */
  XLAL_CHECK ( XLALUserVarReadAllInput ( my_argc, my_argv ) == XLAL_SUCCESS, XLAL_EFUNC );

  /* ---------- test help-string generation */
  CHAR *helpstr;
  XLAL_CHECK ( (helpstr = XLALUserVarHelpString ( argv[0])) != NULL, XLAL_EFUNC );
  XLALFree ( helpstr );

  /* ---------- test log-generation */
  CHAR *logstr;
  XLAL_CHECK ( ( logstr = XLALUserVarGetLog (   UVAR_LOGFMT_CFGFILE )) != NULL, XLAL_EFUNC );
  XLALFree ( logstr );

  /* ---------- test values were read in correctly ---------- */
  XLAL_CHECK ( uvar->argNum == 1, XLAL_EFAILED, "Failed to read in argNum\n" );
  XLAL_CHECK ( strcmp ( uvar->argStr, "xyz" ) == 0, XLAL_EFAILED, "Failed to read in argStr\n" );
  XLAL_CHECK ( uvar->argBool, XLAL_EFAILED, "Failed to read in argBool\n" );
  XLAL_CHECK ( uvar->argInt == 1, XLAL_EFAILED, "Failed to read in argInt\n" );
  XLAL_CHECK ( uvar->argB2, XLAL_EFAILED, "Failed to read in argB2\n" );
  XLAL_CHECK ( strcmp ( uvar->string2, "this is also possible, and # here does nothing; and neither does semi-colon " ) == 0, XLAL_EFAILED, "Failed to read in string2\n" );

  char buf1[256], buf2[256];
  XLAL_CHECK ( XLALGPSCmp ( &uvar->epochGPS, &uvar->epochMJDTT ) == 0, XLAL_EFAILED, "GPS epoch %s differs from MJD(TT) epoch %s\n",
               XLALGPSToStr ( buf1, &uvar->epochGPS), XLALGPSToStr ( buf2, &uvar->epochMJDTT ) );

  REAL8 diff, tol = 3e-15;
  XLAL_CHECK ( (diff = fabs(uvar->longHMS - uvar->longRad)) < tol, XLAL_EFAILED, "longitude(HMS) = %.16g differs from longitude(rad) = %.16g by %g > tolerance\n", uvar->longHMS, uvar->longRad, diff, tol );
  XLAL_CHECK ( (diff = fabs(uvar->latDMS - uvar->latRad)) < tol, XLAL_EFAILED, "latitude(HMS) = %.16g differs from latitude(rad) = %.16g by %g > tolerance\n", uvar->latDMS, uvar->latRad, diff, tol );

  /* ----- cleanup ---------- */
  XLALDestroyUserVars();
  for (i=0; i < my_argc; i ++ ) {
    XLALFree ( my_argv[i] );
  }
  XLALFree ( my_argv );

  LALCheckMemoryLeaks();

  return XLAL_SUCCESS;

} // main()
Esempio n. 12
0
///
/// Make SFTs from given REAL8TimeSeries at given timestamps, potentially applying a time-domain window on each timestretch first
///
SFTVector *
XLALMakeSFTsFromREAL8TimeSeries ( const REAL8TimeSeries *timeseries,	//!< input time-series
                                  const LIGOTimeGPSVector *timestamps, 	//!< timestamps to produce SFTs for (can be NULL), if given must all lies within timeseries' time-span
                                  const char *windowType,		//!< optional time-domain window function to apply before FFTing
                                  REAL8 windowBeta			//!< window parameter, if any
                                  )
{
  XLAL_CHECK_NULL ( timeseries != NULL, XLAL_EINVAL, "Invalid NULL input 'timeseries'\n");
  XLAL_CHECK_NULL ( timestamps != NULL, XLAL_EINVAL, "Invalid NULL input 'timestamps'\n");

  REAL8 dt = timeseries->deltaT;	// timeseries timestep */
  REAL8 Tsft = timestamps->deltaT;
  REAL8 df = 1.0 / Tsft;		// SFT frequency spacing

  // make sure that number of timesamples/SFT is an integer (up to possible rounding error 'eps')
  REAL8 timestepsSFT0 = Tsft / dt;
  UINT4 timestepsSFT  = lround ( timestepsSFT0 );
  XLAL_CHECK_NULL ( fabs ( timestepsSFT0 - timestepsSFT ) / timestepsSFT0 < eps, XLAL_ETOL,
                    "Inconsistent sampling-step (dt=%g) and Tsft=%g: must be integer multiple Tsft/dt = %g >= %g\n",
                    dt, Tsft, timestepsSFT0, eps );

  // prepare window function if requested
  REAL8Window *window = NULL;
  if ( windowType != NULL ) {
    XLAL_CHECK_NULL ( (window = XLALCreateNamedREAL8Window ( windowType, windowBeta, timestepsSFT )) != NULL, XLAL_EFUNC );
  }

  // ---------- Prepare FFT ----------
  REAL8Vector *timeStretchCopy;	// input array of length N
  XLAL_CHECK_NULL ( (timeStretchCopy = XLALCreateREAL8Vector ( timestepsSFT )) != NULL, XLAL_EFUNC, "XLALCreateREAL4Vector(%d) failed.\n", timestepsSFT );
  UINT4 numSFTBins = timestepsSFT / 2 + 1;	// number of positive frequency-bins + 'DC' to be stored in SFT
  fftw_complex *fftOut;	// output array of length N/2 + 1
  XLAL_CHECK_NULL ( (fftOut = fftw_malloc ( numSFTBins * sizeof(fftOut[0]) )) != NULL, XLAL_ENOMEM, "fftw_malloc(%d*sizeof(complex)) failed\n", numSFTBins );
  fftw_plan fftplan;	// FFTW plan
  LAL_FFTW_WISDOM_LOCK;
  XLAL_CHECK_NULL ( (fftplan = fftw_plan_dft_r2c_1d ( timestepsSFT, timeStretchCopy->data, fftOut, FFTW_ESTIMATE)) != NULL, XLAL_EFUNC );	// FIXME: or try FFTW_MEASURE
  LAL_FFTW_WISDOM_UNLOCK;

  LIGOTimeGPS tStart = timeseries->epoch;

  // get last possible start-time for an SFT
  REAL8 duration =  round ( timeseries->data->length * dt ); // rounded to seconds
  LIGOTimeGPS tLast = tStart;
  XLALGPSAdd( &tLast, duration - Tsft );

  // check that all timestamps lie within [tStart, tLast]
  for ( UINT4 i = 0; i < timestamps->length; i ++ )
    {
      char buf1[256], buf2[256];
      XLAL_CHECK_NULL ( XLALGPSDiff ( &tStart, &(timestamps->data[i]) ) <= 0, XLAL_EDOM, "Timestamp i=%d: %s before start-time %s\n",
                        i, XLALGPSToStr ( buf1, &(timestamps->data[i]) ), XLALGPSToStr ( buf2, &tStart ) );
      XLAL_CHECK_NULL ( XLALGPSDiff ( &tLast,   &(timestamps->data[i]) ) >=0, XLAL_EDOM, "Timestamp i=%d: %s after last start-time %s\n",
                        i, XLALGPSToStr ( buf1, &(timestamps->data[i]) ), XLALGPSToStr ( buf2, &tLast ) );
    }

  UINT4 numSFTs = timestamps->length;

  // prepare output SFT-vector
  SFTVector *sftvect;
  XLAL_CHECK_NULL ( (sftvect = XLALCreateSFTVector ( numSFTs, numSFTBins )) != NULL, XLAL_EFUNC,
                    "XLALCreateSFTVector(numSFTs=%d, numBins=%d) failed.\n", numSFTs, numSFTBins );

  // main loop: apply FFT to the requested time-stretches and store in output SFTs
  for ( UINT4 iSFT = 0; iSFT < numSFTs; iSFT++ )
    {
      SFTtype *thisSFT = &(sftvect->data[iSFT]);	// point to current SFT-slot to store output in

      // find the start-bin for this SFT in the time-series
      REAL8 offset = XLALGPSDiff ( &(timestamps->data[iSFT]), &tStart );
      INT4 offsetBins = lround ( offset / dt );

      // copy timeseries-data for that SFT into local buffer
      memcpy ( timeStretchCopy->data, timeseries->data->data + offsetBins, timeStretchCopy->length * sizeof(timeStretchCopy->data[0]) );

      // window the current time series stretch if required
      REAL8 sigma_window = 1;
      if ( window != NULL )
        {
	  sigma_window = sqrt ( window->sumofsquares / window->data->length );
	  for( UINT4 iBin = 0; iBin < timeStretchCopy->length; iBin++ ) {
            timeStretchCopy->data[iBin] *= window->data->data[iBin];
          }
        } // if window

      // FFT this time-stretch
      fftw_execute ( fftplan );

      // fill the header of the i'th output SFT */
      strcpy ( thisSFT->name, timeseries->name );
      thisSFT->epoch = timestamps->data[iSFT];
      thisSFT->f0 = timeseries->f0;			// SFT starts at heterodyning frequency
      thisSFT->deltaF = df;

      // normalize DFT-data to conform to v2 specification ==> multiply DFT by (dt/sigma{window})
      // the SFT normalization in case of windowing follows the conventions detailed in the SFTv2 specification,
      // namely LIGO-T040164, and in particular Eqs.(3),(4) and (6) in T010095-00.pdf
      // https://dcc.ligo.org/cgi-bin/private/DocDB/ShowDocument?.submit=Number&docid=T010095
      // https://dcc.ligo.org/DocDB/0026/T010095/000/T010095-00.pdf
      REAL8 norm = dt / sigma_window;
      for ( UINT4 k = 0; k < numSFTBins ; k ++ ) {
        thisSFT->data->data[k] = (COMPLEX8) ( norm * fftOut[k] );
      }

      // correct heterodyning-phase, IF NECESSARY: ie if (fHet * tStart) is not an integer, such that phase-corr = multiple of 2pi
      if ( ( (INT4)timeseries->f0 != timeseries->f0  ) || (timeseries->epoch.gpsNanoSeconds != 0) || (thisSFT->epoch.gpsNanoSeconds != 0) ) {
        XLAL_CHECK_NULL ( XLALcorrect_phase ( thisSFT, timeseries->epoch) == XLAL_SUCCESS, XLAL_EFUNC );
      }

    } // for iSFT < numSFTs

  // free memory
  fftw_free ( fftOut );
  LAL_FFTW_WISDOM_LOCK;
  fftw_destroy_plan ( fftplan );
  LAL_FFTW_WISDOM_UNLOCK;
  XLALDestroyREAL8Vector ( timeStretchCopy );
  XLALDestroyREAL8Window ( window );

  return sftvect;

} // XLALMakeSFTsFromREAL8TimeSeries()
Esempio n. 13
0
int main(int argc, char *argv[])
{
	char tstr[32]; // string to hold GPS time -- 31 characters is enough
	size_t length;
	size_t stride;
	size_t n;
	REAL8FrequencySeries *psd = NULL;
	REAL8TimeSeries *seg = NULL;
	gsl_rng *rng;

	XLALSetErrorHandler(XLALAbortErrorHandler);

	parseargs(argc, argv);
	if (overrideflow > 0.0)
		flow = overrideflow;
	length = segdur * srate;
	stride = length / 2;

	/* handle 0noise case first */
	if (strcmp(detector, "0noise") == 0) {
		/* just print out a bunch of zeros */
		if (psdonly) {
			double deltaF = srate / length;
			size_t klow = flow / deltaF;
			size_t k;
			fprintf(stdout, "# freq (s^-1)\tPSD (strain^2 s)\n");
			for (k = klow; k < length/2 - 1; ++k)
				fprintf(stdout, "%e\t%e\n", k * deltaF, 0.0);
		} else {
			size_t j;
			fprintf(stdout, "# time (s)\tNOISE (strain)\n");
			n = duration * srate;
			for (j = 0; j < n; ++j) { 
				LIGOTimeGPS t = tstart;
				fprintf(stdout, "%s\t%e\n", XLALGPSToStr(tstr, XLALGPSAdd(&t, j/srate)), 0.0);
			}
		}
		return 0;
	}

	gsl_rng_env_setup();
	rng = gsl_rng_alloc(gsl_rng_default);
	psd = XLALCreateREAL8FrequencySeries(detector, &tstart, 0.0, srate/length, &strainSquaredPerHertzUnit, length/2 + 1);
	if (asdfile)
		XLALSimNoisePSDFromFile(psd, flow, asdfile);
	else if (official && opsdfunc)
		opsdfunc(psd, flow);
	else
		XLALSimNoisePSD(psd, flow, psdfunc);
	if (verbose) {
		double Mpc = 1e6 * LAL_PC_SI;
		double horizon_distance;
		fprintf(stderr, "%-39s %s\n", "detector: ", detector);
		fprintf(stderr, "%-39s %g Hz\n", "low-frequency cutoff: ", flow);
		horizon_distance = XLALMeasureStandardSirenHorizonDistance(psd, flow, -1.0);
		fprintf(stderr, "%-39s %g Mpc\n", "standard siren horizon distance: ", horizon_distance / Mpc);
		fprintf(stderr, "%-39s %g Mpc\n", "sense-monitor range: ", horizon_distance / Mpc / LAL_HORIZON_DISTANCE_OVER_SENSEMON_RANGE);
		fprintf(stderr, "%-39s GSL_RNG_TYPE=%s\n", "GSL random number generator:", gsl_rng_name(rng));
		fprintf(stderr, "%-39s GSL_RNG_SEED=%lu\n", "GSL random number seed:", gsl_rng_default_seed);
	}
	if (psdonly) { // output PSD and exit
		size_t klow = flow / psd->deltaF;
		size_t k;
		fprintf(stdout, "# freq (s^-1)\tPSD (strain^2 s)\n");
		for (k = klow; k < length/2 - 1; ++k)
			fprintf(stdout, "%e\t%e\n", k * psd->deltaF, sqrt(psd->data->data[k]));
		goto end;
	}

	n = duration * srate;
	seg = XLALCreateREAL8TimeSeries("STRAIN", &tstart, 0.0, 1.0/srate, &lalStrainUnit, length);
	XLALSimNoise(seg, 0, psd, rng); // first time to initialize
	fprintf(stdout, "# time (s)\tNOISE (strain)\n");
	while (1) { // infinite loop
		size_t j;
		for (j = 0; j < stride; ++j, --n) { // output first stride points
			LIGOTimeGPS t = seg->epoch;
			if (n == 0) // check if we're done
				goto end;
			fprintf(stdout, "%s\t%e\n", XLALGPSToStr(tstr, XLALGPSAdd(&t, j * seg->deltaT)), seg->data->data[j]);
		}
		XLALSimNoise(seg, stride, psd, rng); // make more data
	}

end:
	XLALDestroyREAL8TimeSeries(seg);
	XLALDestroyREAL8FrequencySeries(psd);
	LALCheckMemoryLeaks();

	return 0;
}