/** register all "user-variables" */
int
XLALInitUserVars ( UserVariables_t *uvar )
{
  XLAL_CHECK ( uvar != NULL, XLAL_EINVAL );

  /* set a few defaults */
  uvar->ephemEarth = XLALStringDuplicate("earth00-19-DE405.dat.gz");
  uvar->ephemSun = XLALStringDuplicate("sun00-19-DE405.dat.gz");

  uvar->timeGPS = 714180733;


  /* register all user-variables */
  XLALRegisterUvarMember( 	detector,	STRING, 'I', REQUIRED, 	"Detector name (eg. H1,H2,L1,G1,etc).");

  XLALRegisterUvarMember(	Alpha,		REAL8, 'a', OPTIONAL,	"skyposition Alpha in radians, equatorial coords.");
  XLALRegisterUvarMember(	Delta, 		REAL8, 'd', OPTIONAL,	"skyposition Delta in radians, equatorial coords.");

  XLALRegisterUvarMember( 	timeGPS,        REAL8, 't', OPTIONAL, 	"GPS time at which to compute detector state");

  XLALRegisterUvarMember(	ephemEarth,   	 STRING, 0,  OPTIONAL,     "Earth ephemeris file to use");
  XLALRegisterUvarMember(	ephemSun,     	 STRING, 0,  OPTIONAL,     "Sun ephemeris file to use");

  XLALRegisterUvarMember(	version,        BOOLEAN, 'V', SPECIAL,      "Output code version");

  return XLAL_SUCCESS;

} /* XLALInitUserVars() */
Esempio n. 2
0
/**
 * Function to determine the PulsarParamsVector input from a user-input defining CW sources.
 *
 * This option supports a dual-type feature: if any string in the list is of the form '{...}', then
 * it determines the *contents* of a config-file, otherwise the name-pattern of config-files to be parsed by XLALFindFiles(),
 * NOTE: when specifying file-contents, options can be separated by ';' and/or newlines)
 */
PulsarParamsVector *
XLALPulsarParamsFromUserInput ( const LALStringVector *UserInput		///< [in] user-input CSV list defining 'CW sources'
                                )
{
  XLAL_CHECK_NULL ( UserInput, XLAL_EINVAL );
  XLAL_CHECK_NULL ( UserInput->length > 0, XLAL_EINVAL );

  PulsarParamsVector *allSources = NULL;

  for ( UINT4 l = 0; l < UserInput->length; l ++ )
    {
      const char *thisInput = UserInput->data[l];

      if ( thisInput[0] != '{' )	// if it's an actual file-specification
        {
          LALStringVector *file_list;
          XLAL_CHECK_NULL ( ( file_list = XLALFindFiles ( &thisInput[0] )) != NULL, XLAL_EFUNC );
          UINT4 numFiles = file_list->length;
          for ( UINT4 i = 0; i < numFiles; i ++ )
            {
              PulsarParamsVector *sources_i;
              XLAL_CHECK_NULL ( (sources_i = XLALPulsarParamsFromFile ( file_list->data[i] )) != NULL, XLAL_EFUNC );

              XLAL_CHECK_NULL ( (allSources = XLALPulsarParamsVectorAppend ( allSources, sources_i )) != NULL, XLAL_EFUNC );
              XLALDestroyPulsarParamsVector ( sources_i );
            } // for i < numFiles

          XLALDestroyStringVector ( file_list );

        } // if file-pattern given
      else
        {
          UINT4 len = strlen(thisInput);
          XLAL_CHECK_NULL ( (thisInput[0] == '{') && (thisInput[len-1] == '}'), XLAL_EINVAL, "Invalid file-content input:\n%s\n", thisInput );
          char *buf;
          XLAL_CHECK_NULL ( (buf = XLALStringDuplicate ( &thisInput[1] )) != NULL, XLAL_EFUNC );
          len = strlen(buf);
          buf[len-1] = 0;	// remove trailing '}'

          LALParsedDataFile *cfgdata = NULL;
          XLAL_CHECK_NULL ( XLALParseDataFileContent ( &cfgdata, buf ) == XLAL_SUCCESS, XLAL_EFUNC );
          XLALFree ( buf );

          PulsarParamsVector *addSource;
          XLAL_CHECK_NULL ( (addSource = XLALCreatePulsarParamsVector ( 1 )) != NULL, XLAL_EFUNC );

          XLAL_CHECK_NULL ( XLALReadPulsarParams ( &addSource->data[0], cfgdata, NULL ) == XLAL_SUCCESS, XLAL_EFUNC );
          XLAL_CHECK_NULL ( (addSource->data[0].name = XLALStringDuplicate ( "direct-string-input" )) != NULL, XLAL_EFUNC );
          XLALDestroyParsedDataFile ( cfgdata );

          XLAL_CHECK_NULL ( (allSources = XLALPulsarParamsVectorAppend ( allSources, addSource )) != NULL, XLAL_EFUNC );
          XLALDestroyPulsarParamsVector ( addSource );

        } // if direct config-string given

    } // for l < len(UserInput)

  return allSources;

} // XLALPulsarParamsFromUserInput()
Esempio n. 3
0
/**
 * register all our "user-variables"
 */
void
InitUserVars (LALStatus *status, struct CommandLineArgsTag *CLA)
{

  INITSTATUS(status);
  ATTATCHSTATUSPTR (status);

  /* Initialize default values */
  CLA->Tsft=1800;
  CLA->nTsft=0;            
  CLA->timestamps=NULL;
  CLA->gpsStart=-1;
  CLA->sqrtSh=1.0;
  
  /** Default year-span of ephemeris-files to be used */
  CLA->ephemEarth = XLALStringDuplicate("earth00-19-DE405.dat.gz");
  CLA->ephemSun = XLALStringDuplicate("sun00-19-DE405.dat.gz");
  
  /* ---------- register all our user-variable ---------- */
  XLAL_CHECK_LAL( status, XLALRegisterNamedUvar(&(CLA->Alpha),      "Alpha",          REAL8,  'a', OPTIONAL,  "Sky position Alpha (equatorial coordinates) in radians") == XLAL_SUCCESS, XLAL_EFUNC);
  XLAL_CHECK_LAL( status, XLALRegisterNamedUvar(&(CLA->Alpha),      "longitude",      REAL8,  0,   DEVELOPER, "[DEPRECATED] Use --Alpha instead!") == XLAL_SUCCESS, XLAL_EFUNC);

  XLAL_CHECK_LAL( status, XLALRegisterNamedUvar(&(CLA->Delta),      "Delta",          REAL8,  'd', OPTIONAL,  "Sky position Delta (equatorial coordinates) in radians") == XLAL_SUCCESS, XLAL_EFUNC);
  XLAL_CHECK_LAL( status, XLALRegisterNamedUvar(&(CLA->Delta),      "latitude",       REAL8,  0,   DEVELOPER, "[DEPRECATED] Use --Delta instead!") == XLAL_SUCCESS, XLAL_EFUNC);
 
  XLAL_CHECK_LAL( status, XLALRegisterNamedUvar(&(CLA->phi0),       "phi0",           REAL8,  'Q', OPTIONAL,  "Phi_0: Initial phase in radians") == XLAL_SUCCESS, XLAL_EFUNC);

  XLAL_CHECK_LAL( status, XLALRegisterNamedUvar(&(CLA->psi),        "psi",            REAL8,  'Y', OPTIONAL,  "Polarisation in radians") == XLAL_SUCCESS, XLAL_EFUNC);

  XLAL_CHECK_LAL( status, XLALRegisterNamedUvar(&(CLA->cosi),       "cosi",           REAL8,  'i', OPTIONAL,  "Cos(iota)") == XLAL_SUCCESS, XLAL_EFUNC);
  XLAL_CHECK_LAL( status, XLALRegisterNamedUvar(&(CLA->cosiota),    "cosiota",        REAL8,  0,   DEVELOPER, "[DEPRECATED] Use --cosi instead") == XLAL_SUCCESS, XLAL_EFUNC);

  XLAL_CHECK_LAL( status, XLALRegisterNamedUvar(&(CLA->h0),         "h0",             REAL8,  's', OPTIONAL,  "Strain amplitude h_0") == XLAL_SUCCESS, XLAL_EFUNC);
  XLAL_CHECK_LAL( status, XLALRegisterNamedUvar(&(CLA->sqrtSh),     "sqrtSh",         REAL8,  'N', OPTIONAL,  "Noise floor: one-sided sqrt(Sh) in 1/sqrt(Hz)") == XLAL_SUCCESS, XLAL_EFUNC);
  
  XLAL_CHECK_LAL( status, XLALRegisterNamedUvar(&(CLA->timestamps), "timestampsFile", STRING, 'T', OPTIONAL,  "Name of timestamps file") == XLAL_SUCCESS, XLAL_EFUNC);
  
  XLAL_CHECK_LAL( status, XLALRegisterNamedUvar(&(CLA->gpsStart),   "startTime",      INT4,   'S', OPTIONAL,  "GPS start time of continuous observation") == XLAL_SUCCESS, XLAL_EFUNC);
  
  XLAL_CHECK_LAL( status, XLALRegisterNamedUvar(&(CLA->Tsft),       "Tsft",           REAL8,  't', OPTIONAL,  "Length of an SFT in seconds") == XLAL_SUCCESS, XLAL_EFUNC);
  
  XLAL_CHECK_LAL( status, XLALRegisterNamedUvar(&(CLA->nTsft),      "nTsft",          INT4,   'n', OPTIONAL,  "Number of SFTs") == XLAL_SUCCESS, XLAL_EFUNC);
  
  XLAL_CHECK_LAL( status, XLALRegisterNamedUvar(&(CLA->IFO),        "IFO",            STRING, 'D', OPTIONAL,  "Detector: H1, H2, L1, G1, ... ") == XLAL_SUCCESS, XLAL_EFUNC);
  XLAL_CHECK_LAL( status, XLALRegisterNamedUvar(&(CLA->detector),   "detector",       STRING, 0,   DEVELOPER, "[DEPRECATED] Use --IFO instead!") == XLAL_SUCCESS, XLAL_EFUNC);
  
  XLAL_CHECK_LAL( status, XLALRegisterNamedUvar(&(CLA->ephemEarth), "ephemEarth",     STRING, 0,   OPTIONAL,  "Earth ephemeris file to use") == XLAL_SUCCESS, XLAL_EFUNC);

  XLAL_CHECK_LAL( status, XLALRegisterNamedUvar(&(CLA->ephemSun),   "ephemSun",       STRING, 0,   OPTIONAL,  "Sun ephemeris file to use") == XLAL_SUCCESS, XLAL_EFUNC);

  /* ----- added for mfd_v4 compatibility ---------- */
  XLAL_CHECK_LAL ( status, XLALRegisterNamedUvar(&(CLA->duration),  "duration",       REAL8, 0,    OPTIONAL,  "Duration of requested signal in seconds") == XLAL_SUCCESS, XLAL_EFUNC);
  
  XLAL_CHECK_LAL ( status, XLALRegisterNamedUvar(&(CLA->aPlus),     "aPlus",          REAL8, 0,    OPTIONAL,  "Plus polarization amplitude aPlus") == XLAL_SUCCESS, XLAL_EFUNC);
  XLAL_CHECK_LAL ( status, XLALRegisterNamedUvar(&(CLA->aCross),    "aCross",         REAL8, 0,    OPTIONAL,  "Cross polarization amplitude aCross") == XLAL_SUCCESS, XLAL_EFUNC);


  DETATCHSTATUSPTR (status);
  RETURN(status);
} /* InitUserVars() */
Esempio n. 4
0
INT4 InitUserVars(UserVariables_t *uvar, int argc, char *argv[])
{
   XLAL_CHECK ( uvar != NULL, XLAL_EINVAL, "Invalid NULL input 'uvar'\n");
   XLAL_CHECK ( argv != NULL, XLAL_EINVAL, "Invalid NULL input 'argv'\n");

   uvar->ephemEarth = XLALStringDuplicate("earth00-19-DE405.dat.gz");
   uvar->ephemSun = XLALStringDuplicate("sun00-19-DE405.dat.gz");
   uvar->outfilename = XLALStringDuplicate("output.dat");
   uvar->Tsft = 1800;
   uvar->SFToverlap = 900;
   uvar->skylocations = 1;

   XLALregBOOLUserStruct(  help,        'h', UVAR_HELP     , "Print this help/usage message");
   XLALregREALUserStruct(  Tsft,         0 , UVAR_OPTIONAL , "SFT coherence time");
   XLALregREALUserStruct(  SFToverlap,   0 , UVAR_OPTIONAL , "SFT overlap in seconds, usually Tsft/2");
   XLALregREALUserStruct(  t0,           0 , UVAR_OPTIONAL , "GPS start time of the search");
   XLALregREALUserStruct(  Tobs,         0 , UVAR_OPTIONAL , "Duration of the search (in seconds)");
   XLALregREALUserStruct(  cosi,         0 , UVAR_OPTIONAL , "Cosine of NS inclinaiont angle");
   XLALregREALUserStruct(  psi,          0 , UVAR_OPTIONAL , "Polarization angle of GW");
   XLALregREALUserStruct(  alpha,        0 , UVAR_OPTIONAL , "Right ascension of source (in radians)");
   XLALregREALUserStruct(  delta,        0 , UVAR_OPTIONAL , "Declination of source (in radians)");
   XLALregINTUserStruct(   skylocations, 0 , UVAR_OPTIONAL , "Number of sky locations");
   XLALregLISTUserStruct(  IFO,          0 , UVAR_REQUIRED , "CSV list of detectors, eg. \"H1,H2,L1,G1, ...\" ");
   XLALregSTRINGUserStruct(outfilename,  0 , UVAR_OPTIONAL , "Output filename");
   XLALregSTRINGUserStruct(ephemEarth,   0 , UVAR_OPTIONAL , "Earth ephemeris file");
   XLALregSTRINGUserStruct(ephemSun,     0 , UVAR_OPTIONAL , "Sun ephemeris file");

   XLAL_CHECK( XLALUserVarReadAllInput(argc, argv) == XLAL_SUCCESS, XLAL_EFUNC );

   if ( uvar->help ) exit (0);

   return XLAL_SUCCESS;
}
Esempio n. 5
0
/**
 * \brief Automatically set the solar system ephemeris file based on environment variables and data time span
 *
 * This function will attempt to construct the file name for Sun, Earth and time correction ephemeris files
 * based on the ephemeris used for the equivalent TEMPO(2) pulsar timing information. It assumes that the
 * ephemeris files are those constructed between 2000 and 2020. The path to the file is not required as this
 * will be found in \c XLALInitBarycenter.
 *
 * \param efile [in] a string that will return the Earth ephemeris file
 * \param sfile [in] a string that will return the Sun ephemeris file
 * \param tfile [in] a string that will return the time correction file
 * \param pulsar [in] the pulsar parameters read from a .par file
 * \param gpsstart [in] the GPS time of the start of the data
 * \param gpsend [in] the GPS time of the end of the data
 *
 * \return The TimeCorrectionType e.g. TDB or TCB
 */
TimeCorrectionType XLALAutoSetEphemerisFiles( CHAR **efile, CHAR **sfile, CHAR **tfile, PulsarParameters *pulsar,
                                              INT4 gpsstart, INT4 gpsend ){
  /* set the times that the ephemeris files span */
  INT4 ephemstart = 630720013; /* GPS time of Jan 1, 2000, 00:00:00 UTC */
  INT4 ephemend = 1261872015; /* GPS time of Jan 1, 2020, 00:00:00 UTC */
  TimeCorrectionType ttype = TIMECORRECTION_NONE;

  if( gpsstart < ephemstart || gpsend < ephemstart || gpsstart > ephemend || gpsend > ephemend ){
    XLAL_ERROR(XLAL_EFUNC, "Start and end times are outside the ephemeris file ranges!" );
  }

  *efile = XLALStringDuplicate("earth00-19-");
  *sfile = XLALStringDuplicate("sun00-19-");

  if( !PulsarCheckParam(pulsar, "EPHEM") ){
    /* default to use DE405 */
    *efile = XLALStringAppend(*efile, "DE405");
    *sfile = XLALStringAppend(*sfile, "DE405");
  }
  else{
    if( !strcmp(PulsarGetStringParam(pulsar, "EPHEM"), "DE405") || !strcmp(PulsarGetStringParam(pulsar, "EPHEM"), "DE200") ||
        !strcmp(PulsarGetStringParam(pulsar, "EPHEM"), "DE414") || !strcmp(PulsarGetStringParam(pulsar, "EPHEM"), "DE421") ){
      *efile = XLALStringAppend(*efile, PulsarGetStringParam(pulsar, "EPHEM"));
      *sfile = XLALStringAppend(*sfile, PulsarGetStringParam(pulsar, "EPHEM"));
    }
    else{
      XLAL_ERROR(XLAL_EFUNC, "Unknown ephemeris %s in par file.", PulsarGetStringParam(pulsar, "EPHEM") );
    }
  }

  /* add .dat.gz extension */
  *efile = XLALStringAppend(*efile, ".dat.gz");
  *sfile = XLALStringAppend(*sfile, ".dat.gz");

  if( !PulsarCheckParam( pulsar, "UNITS" ) ){
    /* default to using TCB units */
    *tfile = XLALStringDuplicate("te405_2000-2019.dat.gz");
    ttype = TIMECORRECTION_TCB;
  }
  else{
    if ( !strcmp( PulsarGetStringParam(pulsar, "UNITS"), "TDB" ) ){
      *tfile = XLALStringDuplicate("tdb_2000-2019.dat.gz");
      ttype = TIMECORRECTION_TDB;
    }
    else if ( !strcmp( PulsarGetStringParam(pulsar, "UNITS"), "TCB" ) ) {
      *tfile = XLALStringDuplicate("te405_2000-2019.dat.gz");
      ttype = TIMECORRECTION_TCB;
    }
    else{
      XLAL_ERROR(XLAL_EFUNC, "Error... unknown units %s in par file!", PulsarGetStringParam(pulsar, "UNITS"));
    }
  }

  return ttype;
}
/** register all "user-variables" */
int
XLALInitUserVars ( UserVariables_t *uvar )
{
  XLAL_CHECK ( uvar != NULL, XLAL_EINVAL );

  /* set a few defaults */
  uvar->help = 0;

  XLAL_CHECK ( (uvar->IFOs = XLALCreateStringVector ( "H1", NULL )) != NULL, XLAL_ENOMEM, "Call to XLALCreateStringVector() failed." );

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

  uvar->Alpha     = 0.0;
  uvar->Delta     = 0.0;
  uvar->skyGridFile = NULL;

  uvar->timeGPS = NULL;
  uvar->timeStampsFile = NULL;
  uvar->outab = 0;
  uvar->outABCD = 0;
  uvar->Tsft = 1800;

  uvar->noiseSqrtShX = NULL;

  /* register all user-variables */
  XLALregBOOLUserStruct(	help,		'h', UVAR_HELP,		"Print this help/usage message");
  XLALregLISTUserStruct( IFOs,                  'I', UVAR_OPTIONAL, "Comma-separated list of detectors, eg. \"H1,H2,L1,G1, ...\" [only 1 detector supported at the moment] ");

  XLALregREALUserStruct(	Alpha,		'a', UVAR_OPTIONAL,	"single skyposition Alpha in radians, equatorial coords.");
  XLALregREALUserStruct(	Delta, 		'd', UVAR_OPTIONAL,	"single skyposition Delta in radians, equatorial coords.");

  XLALregSTRINGUserStruct( skyGridFile,		's', UVAR_OPTIONAL,	"Alternatively: sky-grid file");

  XLALregLISTUserStruct( 	timeGPS,        't', UVAR_OPTIONAL, 	"GPS time at which to compute detector states (separate multiple timestamps by commata)");
  XLALregLISTUserStruct(	timeStampsFiles, 'T', UVAR_OPTIONAL,	"Alternative: time-stamps file(s) (comma-separated list per IFO, or one for all)");
  XLALregINTUserStruct(		Tsft,		 0, UVAR_OPTIONAL,	"Assumed length of one SFT in seconds; needed for timestamps offset consistency with F-stat based codes");

  XLALregLISTUserStruct ( noiseSqrtShX,		 0, UVAR_OPTIONAL, "Per-detector noise PSD sqrt(SX). Only ratios relevant to compute noise weights. Defaults to 1,1,...");

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

  XLALregSTRINGUserStruct(	outab,		'o', UVAR_OPTIONAL,	"output file for antenna pattern functions a(t), b(t) at each timestamp");
  XLALregSTRINGUserStruct(	outABCD,	'O', UVAR_OPTIONAL,	"output file for antenna pattern matrix elements A, B, C, D averaged over timestamps");

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

  /* developer user variables */
  XLALregSTRINGUserStruct(	timeStampsFile,	  0, UVAR_OPTIONAL,	"Alternative: single time-stamps file (deprecated, use --timeStampsFiles instead");

  return XLAL_SUCCESS;

} /* XLALInitUserVars() */
Esempio n. 7
0
/** register all "user-variables" */
int
initUserVars ( int argc, char *argv[], UserVariables_t *uvar )
{
  XLAL_CHECK ( argc > 0 && (argv != NULL) && (uvar != NULL), XLAL_EINVAL );

  /* set a few defaults */
  uvar->RAJ  = NULL;
  uvar->DECJ = NULL;

  uvar->TstartUTCMJD = 53400;
  uvar->TrefTDBMJD = 53400;
  uvar->DeltaTMJD = 1;
  uvar->DurationMJD = 1800;

  uvar->f0 = 1.0;
  uvar->fdot = 0.0;

  uvar->PSRJ = XLALStringDuplicate ( "TEMPOcomparison" );

  uvar->Observatory = XLALStringDuplicate ( "JODRELL" );

  uvar->randSeed = 1;

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

  /* register user input variables */
  XLALRegisterUvarMember( RAJ, 	        STRING, 'r', OPTIONAL, 	"Right ascension hh:mm.ss.ssss [Default=random]");
  XLALRegisterUvarMember( DECJ, 	        STRING, 'j', OPTIONAL, 	"Declination deg:mm.ss.ssss [Default=random]");
  XLALRegisterUvarMember( ephemEarth, 	 STRING, 0,  OPTIONAL, 	"Earth ephemeris file to use");
  XLALRegisterUvarMember( ephemSun, 	 	 STRING, 0,  OPTIONAL, 	"Sun ephemeris file to use");
  XLALRegisterUvarMember( f0,     		REAL8, 'f', OPTIONAL, 	"The signal frequency in Hz at SSB at the reference time");
  XLALRegisterUvarMember( fdot,     		REAL8, 'p', OPTIONAL, 	"The signal frequency derivitive in Hz at SSB at the reference time");
  XLALRegisterUvarMember( TrefTDBMJD, 	REAL8, 'R', OPTIONAL, 	"Reference time at the SSB in TDB in MJD");
  XLALRegisterUvarMember( TstartUTCMJD, 	REAL8, 'T', OPTIONAL, 	"Start time of output TOAs in UTC");
  XLALRegisterUvarMember( DeltaTMJD, 		REAL8, 't', OPTIONAL, 	"Time inbetween TOAs (in days)");
  XLALRegisterUvarMember( DurationMJD, 	REAL8, 'D', OPTIONAL, 	"Full duration of TOAs (in days)");
  XLALRegisterUvarMember( PSRJ,           	STRING, 'n', OPTIONAL, 	"Name of pulsar");
  XLALRegisterUvarMember( Observatory,    	STRING, 'O', OPTIONAL, 	"TEMPO observatory name (GBT,ARECIBO,NARRABRI,NANSHAN,DSS_43,PARKES,JODRELL,VLA,NANCAY,COE,SSB)");
  XLALRegisterUvarMember( randSeed,  		 INT4, 0,  OPTIONAL, 	"The random seed [0 = clock]");

  /* read all command line variables */
  BOOLEAN should_exit = 0;
  XLAL_CHECK( XLALUserVarReadAllInput( &should_exit, argc, argv, lalPulsarVCSInfoList ) == XLAL_SUCCESS, XLAL_EFUNC );
  if ( should_exit ) {
    exit(1);
  }

  return XLAL_SUCCESS;
} /* initUserVars() */
Esempio n. 8
0
/** register all "user-variables" */
int
initUserVars ( int argc, char *argv[], UserVariables_t *uvar )
{
  XLAL_CHECK ( argc > 0 && (argv != NULL) && (uvar != NULL), XLAL_EINVAL );

  /* set a few defaults */
  uvar->help = FALSE;

  uvar->RAJ  = NULL;
  uvar->DECJ = NULL;

  uvar->TstartUTCMJD = 53400;
  uvar->TrefTDBMJD = 53400;
  uvar->DeltaTMJD = 1;
  uvar->DurationMJD = 1800;

  uvar->f0 = 1.0;
  uvar->fdot = 0.0;

  uvar->PSRJ = XLALStringDuplicate ( "TEMPOcomparison" );

  uvar->Observatory = XLALStringDuplicate ( "JODRELL" );

  uvar->randSeed = 1;

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

  /* register user input variables */
  XLALregBOOLUserStruct   ( help, 		'h', UVAR_HELP,    	"Print this message" );
  XLALregSTRINGUserStruct ( RAJ, 	        'r', UVAR_OPTIONAL, 	"Right ascension hh:mm.ss.ssss [Default=random]");
  XLALregSTRINGUserStruct ( DECJ, 	        'j', UVAR_OPTIONAL, 	"Declination deg:mm.ss.ssss [Default=random]");
  XLALregSTRINGUserStruct ( ephemEarth, 	 0,  UVAR_OPTIONAL, 	"Earth ephemeris file to use");
  XLALregSTRINGUserStruct ( ephemSun, 	 	 0,  UVAR_OPTIONAL, 	"Sun ephemeris file to use");
  XLALregREALUserStruct   ( f0,     		'f', UVAR_OPTIONAL, 	"The signal frequency in Hz at SSB at the reference time");
  XLALregREALUserStruct   ( fdot,     		'p', UVAR_OPTIONAL, 	"The signal frequency derivitive in Hz at SSB at the reference time");
  XLALregREALUserStruct   ( TrefTDBMJD, 	'R', UVAR_OPTIONAL, 	"Reference time at the SSB in TDB in MJD");
  XLALregREALUserStruct   ( TstartUTCMJD, 	'T', UVAR_OPTIONAL, 	"Start time of output TOAs in UTC");
  XLALregREALUserStruct   ( DeltaTMJD, 		't', UVAR_OPTIONAL, 	"Time inbetween TOAs (in days)");
  XLALregREALUserStruct   ( DurationMJD, 	'D', UVAR_OPTIONAL, 	"Full duration of TOAs (in days)");
  XLALregSTRINGUserStruct ( PSRJ,           	'n', UVAR_OPTIONAL, 	"Name of pulsar");
  XLALregSTRINGUserStruct ( Observatory,    	'O', UVAR_OPTIONAL, 	"TEMPO observatory name (GBT,ARECIBO,NARRABRI,NANSHAN,DSS_43,PARKES,JODRELL,VLA,NANCAY,COE,SSB)");
  XLALregINTUserStruct    ( randSeed,  		 0,  UVAR_OPTIONAL, 	"The random seed [0 = clock]");

  /* read all command line variables */
  XLAL_CHECK ( XLALUserVarReadAllInput( argc, argv ) == XLAL_SUCCESS, XLAL_EFUNC );

  return XLAL_SUCCESS;
} /* initUserVars() */
Esempio n. 9
0
/**
 * Append the given PulsarParamsVector 'add' to the vector 'list' ( which can be NULL), return resulting list
 * with new elements 'add' appended at the end of 'list'.
 */
PulsarParamsVector *
XLALPulsarParamsVectorAppend ( PulsarParamsVector *list, const PulsarParamsVector *add )
{
  XLAL_CHECK_NULL ( add != NULL, XLAL_EINVAL );

  PulsarParamsVector *ret;
  if ( list == NULL )
    {
      XLAL_CHECK_NULL ( (ret = XLALCalloc ( 1, sizeof(*ret))) != NULL, XLAL_ENOMEM );
    }
  else
    {
      ret = list;
    }

  UINT4 oldlen = ret->length;
  UINT4 addlen = add->length;
  UINT4 newlen = oldlen + addlen;
  ret->length = newlen;
  XLAL_CHECK_NULL ( (ret->data = XLALRealloc ( ret->data, newlen * sizeof(ret->data[0]) )) != NULL, XLAL_ENOMEM );
  memcpy ( ret->data + oldlen, add->data, addlen * sizeof(ret->data[0]) );
  // we have to properly copy the 'name' string fields
  for ( UINT4 i = 0; i < addlen; i ++ )
    {
      XLAL_CHECK_NULL ( (ret->data[oldlen + i].name = XLALStringDuplicate ( add->data[i].name )) != NULL, XLAL_EFUNC );
    }

  return ret;

} // XLALPulsarParamsVectorAppend()
Esempio n. 10
0
/**
 * @brief Opens a specified data file, searching default path if necessary.
 * @details Opens a data file for input with a specified path name.
 * If the path name is an absolute path then this specific file is opened;
 * otherwise, search for the file in paths given in the environment variable
 * LALSIM_DATA_PATH, and finally search in the installed PKG_DATA_DIR path.
 * @param[in] fname The path of the file to open.
 * @return A pointer to a LALFILE structure or NULL on failure.
 */
LALFILE *XLALSimReadDataFileOpen(const char *fname)
{
    const char *pkgdatadir = PKG_DATA_DIR;
    char path[PATH_MAX] = "";
    LALFILE *fp;

    if (strchr(fname, '/')) {   /* a specific path is given */
        if (realpath(fname, path) == NULL)
            XLAL_ERROR_NULL(XLAL_EIO, "Unresolvable path %s\n", path);
    } else {
        /* unspecific path given: use LALSIM_DATA_PATH environment */
        char *env = getenv("LALSIM_DATA_PATH");
        char *str;
        char *dir;
        env = str = XLALStringDuplicate(env ? env : ":");
        while ((dir = strsep(&str, ":"))) {
            if (strlen(dir))
                snprintf(path, sizeof(path), "%s/%s", dir, fname);
            else        /* use default path */
                snprintf(path, sizeof(path), "%s/%s", pkgdatadir, fname);
            if (access(path, R_OK) == 0)        /* found it! */
                break;
            *path = 0;
        }
        XLALFree(env);
    }
    if (!*path) /* could not find file */
        XLAL_ERROR_NULL(XLAL_EIO, "Could not find data file %s\n", fname);
    fp = XLALFileOpenRead(path);
    if (!fp)    /* open failure */
        XLAL_ERROR_NULL(XLAL_EIO, "Could not open data file %s\n", path);
    return fp;
}
Esempio n. 11
0
/**
 * \brief Chops and remerges data into stationary segments
 *
 * This function finds segments of data that appear to be stationary (have the same standard deviation).
 *
 * The function first attempts to chop up the data into as many stationary segments as possible. The splitting may not
 * be optimal, so it then tries remerging consecutive segments to see if the merged segments show more evidence of
 * stationarity. <b>[NOTE: Remerging is currently turned off and will make very little difference to the algorithm]</b>.
 * It then, if necessary, chops the segments again to make sure there are none greater than the required \c chunkMax.
 * The default \c chunkMax is 0, so this rechopping will not normally happen.
 *
 * This is all performed on data that has had a running median subtracted, to try and removed any underlying trends in
 * the data (e.g. those caused by a strong signal), which might affect the calculations (which assume the data is
 * Gaussian with zero mean).
 *
 * If the \c verbose flag is set then a list of the segments will be output to a file called \c data_segment_list.txt,
 * with a prefix of the detector name.
 *
 * \param data [in] A data structure
 * \param chunkMin [in] The minimum length of a segment
 * \param chunkMax [in] The maximum length of a segment
 *
 * \return A vector of segment/chunk lengths
 *
 * \sa subtract_running_median
 * \sa chop_data
 * \sa merge_data
 * \sa rechop_data
 */
UINT4Vector *chop_n_merge( LALInferenceIFOData *data, INT4 chunkMin, INT4 chunkMax ){
  UINT4 j = 0;

  UINT4Vector *chunkLengths = NULL;
  UINT4Vector *chunkIndex = NULL;

  COMPLEX16Vector *meddata = NULL;

  /* subtract a running median value from the data to remove any underlying trends (e.g. caused by a string signal) that
   * might affect the chunk calculations (which can assume the data is Gaussian with zero mean). */
  meddata = subtract_running_median( data->compTimeData->data );

  /* pass chop data a gsl_vector_view, so that internally it can use vector views rather than having to create new vectors */
  gsl_vector_complex_view meddatagsl = gsl_vector_complex_view_array((double*)meddata->data, meddata->length);
  chunkIndex = chop_data( &meddatagsl.vector, chunkMin );

  /* DON'T BOTHER WITH THE MERGING AS IT WILL MAKE VERY LITTLE DIFFERENCE */
  /* merge_data( meddata, chunkIndex ); */

  /* if a maximum chunk length is defined then rechop up the data, to segment any chunks longer than this value */
  if ( chunkMax > chunkMin ) { rechop_data( chunkIndex, chunkMax, chunkMin ); }

  chunkLengths = XLALCreateUINT4Vector( chunkIndex->length );

  /* go through segments and turn into vector of chunk lengths */
  for ( j = 0; j < chunkIndex->length; j++ ){
    if ( j == 0 ) { chunkLengths->data[j] = chunkIndex->data[j]; }
    else { chunkLengths->data[j] = chunkIndex->data[j] - chunkIndex->data[j-1]; }
  }

  /* if verbose print out the segment end indices to a file */
  if ( verbose_output ){
    FILE *fpsegs = NULL;

    CHAR *outfile = NULL;

    /* set detector name as prefix */
    outfile = XLALStringDuplicate( data->detector->frDetector.prefix );

    outfile = XLALStringAppend( outfile, "data_segment_list.txt" );

    if ( (fpsegs = fopen(outfile, "w")) == NULL ){
      fprintf(stderr, "Non-fatal error open file to output segment list.\n");
      return chunkLengths;
    }

    for ( j = 0; j < chunkIndex->length; j++ ) { fprintf(fpsegs, "%u\n", chunkIndex->data[j]); }

    /* add space at the end so that you can separate lists from different detector data streams */
    fprintf(fpsegs, "\n");

    fclose( fpsegs );
  }

  return chunkLengths;
}
Esempio n. 12
0
INT4 InitUserVars(UserVariables_t *uvar, int argc, char *argv[])
{
   XLAL_CHECK ( uvar != NULL, XLAL_EINVAL, "Invalid NULL input 'uvar'\n");
   XLAL_CHECK ( argv != NULL, XLAL_EINVAL, "Invalid NULL input 'argv'\n");

   uvar->ephemEarth = XLALStringDuplicate("earth00-19-DE405.dat.gz");
   uvar->ephemSun = XLALStringDuplicate("sun00-19-DE405.dat.gz");
   uvar->outfilename = XLALStringDuplicate("skygrid.dat");
   uvar->skyRegion = XLALStringDuplicate("allsky");
   uvar->Tsft = 1800;
   uvar->SFToverlap = 900;
   uvar->fspan = 0.25;

   XLALRegisterUvarMember(  help,       BOOLEAN, 'h', HELP     , "Print this help/usage message");
   XLALRegisterUvarMember(  Tsft,        REAL8, 0 , OPTIONAL , "SFT coherence time");
   XLALRegisterUvarMember(  SFToverlap,  REAL8, 0 , OPTIONAL , "SFT overlap in seconds, usually Tsft/2");
   XLALRegisterUvarMember(  t0,          REAL8, 0 , OPTIONAL , "GPS start time of the search; not needed if --v1 is specified");
   XLALRegisterUvarMember(  Tobs,        REAL8, 0 , OPTIONAL , "Duration of the search (in seconds); not needed if --v1 is specified");
   XLALRegisterUvarMember(  fmin,        REAL8, 0 , OPTIONAL , "Minimum frequency of band");
   XLALRegisterUvarMember(  fspan,       REAL8, 0 , OPTIONAL , "Frequency span of band");
   XLALRegisterUvarMember(IFO,         STRING, 0 , REQUIRED , "Interferometer whose data is being analyzed");
   XLALRegisterUvarMember(outfilename, STRING, 0 , OPTIONAL , "Output filename");
   XLALRegisterUvarMember(ephemEarth,  STRING, 0 , OPTIONAL , "Earth ephemeris file");
   XLALRegisterUvarMember(ephemSun,    STRING, 0 , OPTIONAL , "Sun ephemeris file");
   XLALRegisterUvarMember(skyRegion,   STRING, 0 , OPTIONAL , "Region of the sky to search (e.g. (ra1,dec1),(ra2,dec2),(ra3,dec3)...) or allsky");
   XLALRegisterUvarMember(  v1,          BOOLEAN, 0 , DEVELOPER, "Flag to use older style of CompDetectorVmax (for S6/VSR2-3 analysis)");

   XLAL_CHECK( XLALUserVarReadAllInput(argc, argv) == XLAL_SUCCESS, XLAL_EFUNC );

   if ( uvar->help ) exit (0);

   if (!uvar->v1 && !XLALUserVarWasSet(&uvar->t0)) XLAL_ERROR( XLAL_EINVAL, "Must set t0" );
   if (!uvar->v1 && !XLALUserVarWasSet(&uvar->Tobs)) XLAL_ERROR( XLAL_EINVAL, "Must set Tobs" );

   return XLAL_SUCCESS;
}
Esempio n. 13
0
INT4 InitUserVars(UserVariables_t *uvar, int argc, char *argv[])
{
   XLAL_CHECK ( uvar != NULL, XLAL_EINVAL, "Invalid NULL input 'uvar'\n");
   XLAL_CHECK ( argv != NULL, XLAL_EINVAL, "Invalid NULL input 'argv'\n");

   uvar->ephemEarth = XLALStringDuplicate("earth00-40-DE405.dat.gz");
   uvar->ephemSun = XLALStringDuplicate("sun00-40-DE405.dat.gz");
   uvar->outfilename = XLALStringDuplicate("output.dat");
   uvar->Tsft = 1800;
   uvar->SFToverlap = 900;
   uvar->skylocations = 1;
   uvar->unrestrictedCosi = 0;
   uvar->rectWindow = 0;

   XLALRegisterUvarMember(  Tsft,             REAL8, 0 , OPTIONAL , "SFT coherence time");
   XLALRegisterUvarMember(  SFToverlap,       REAL8, 0 , OPTIONAL , "SFT overlap in seconds, usually Tsft/2");
   XLALRegisterUvarMember(  t0,               REAL8, 0 , OPTIONAL , "GPS start time of the search");
   XLALRegisterUvarMember(  Tobs,             REAL8, 0 , OPTIONAL , "Duration of the search (in seconds)");
   XLALRegisterUvarMember(  cosi,             REAL8, 0 , OPTIONAL , "Cosine of NS inclinaiont angle");
   XLALRegisterUvarMember(  psi,              REAL8, 0 , OPTIONAL , "Polarization angle of GW");
   XLALRegisterUvarMember(  alpha,            REAL8, 0 , OPTIONAL , "Right ascension of source (in radians)");
   XLALRegisterUvarMember(  delta,            REAL8, 0 , OPTIONAL , "Declination of source (in radians)");
   XLALRegisterUvarMember(   skylocations,     INT4, 0 , OPTIONAL , "Number of sky locations");
   XLALRegisterUvarMember(  IFO,              STRINGVector, 0 , REQUIRED , "CSV list of detectors, eg. \"H1,H2,L1,G1, ...\" ");
   XLALRegisterUvarMember(outfilename,      STRING, 0 , OPTIONAL , "Output filename");
   XLALRegisterUvarMember(ephemEarth,       STRING, 0 , OPTIONAL , "Earth ephemeris file");
   XLALRegisterUvarMember(ephemSun,         STRING, 0 , OPTIONAL , "Sun ephemeris file");
   XLALRegisterUvarMember(  unrestrictedCosi, BOOLEAN, 0 , OPTIONAL , "Marginalize over cos(iota) from -1 to 1");
   XLALRegisterUvarMember(  rectWindow,       BOOLEAN, 0 , OPTIONAL , "Use rectangular window function instead of Hann windowing");

   BOOLEAN should_exit = 0;
   XLAL_CHECK( XLALUserVarReadAllInput( &should_exit, argc, argv, lalAppsVCSInfoList ) == XLAL_SUCCESS, XLAL_EFUNC );
   if ( should_exit ) exit (1);

   return XLAL_SUCCESS;
}
Esempio n. 14
0
void gnuplot_output_fs(const char *fname, const char *fmt, REAL8FrequencySeries *series)
{
    LALUnit asdunit;
    char *units;
    size_t i;
    FILE *gp = popen("gnuplot -persistent", "w");

    if (!gp) {
        fprintf(stderr, "require program gnuplot to output .%s files", fmt);
        exit(1);
    }

    /* get the sample units as a string */
    XLALUnitSqrt(&asdunit, &series->sampleUnits);
    units = XLALUnitToString(&asdunit);
    if (units == NULL || *units == '\0') {
        LALFree(units);
        units = XLALStringDuplicate("unknown units");
    }

    /* modify fmt as required by gnuplot */
    if (strcmp(fmt, "jpg") == 0)
        fmt = "jpeg";
    else if (strcmp(fmt, "ps") == 0)
        fmt = "postscript landscape";
    else if (strcmp(fmt, "eps") == 0)
        fmt = "postscript eps";

    /* issue gnuplot commands */
    fprintf(gp, "set terminal %s\n", fmt);
    fprintf(gp, "set output '%s'\n", fname);
    fprintf(gp, "set key off\n");
    fprintf(gp, "set grid xtics mxtics ytics\n");
    fprintf(gp, "set xlabel 'frequency (Hz)'\n");
    fprintf(gp, "set ylabel 'amplitude spectral density (%s)'\n", units);
    fprintf(gp, "set title '%s @ %d.%09d\n", series->name, series->epoch.gpsSeconds, series->epoch.gpsNanoSeconds);
    fprintf(gp, "set logscale\n");
    fprintf(gp, "plot '-' with lines\n");
    for (i = 0; i < series->data->length; ++i)
        fprintf(gp, "%.9f\t%e\n", series->f0 + i * series->deltaF, sqrt(series->data->data[i]));
    fprintf(gp, "e");

    pclose(gp);
    LALFree(units);
    return;
}
Esempio n. 15
0
/**
 * \brief Counts the number of comma separated values in a string
 *
 * This function counts the number of comma separated values in a given input string.
 *
 * \param csvline [in] Any string
 *
 * \return The number of comma separated value in the input string
 */
INT4 count_csv( CHAR *csvline ){
  CHAR *inputstr = NULL;
  INT4 count = 0;

  inputstr = XLALStringDuplicate( csvline );

  /* count number of commas */
  while(1){
    if( XLALStringToken(&inputstr, ",", 0) == NULL ){ XLAL_ERROR( XLAL_EFUNC, "Error... problem counting number of commas!" ); }

    if ( inputstr == NULL ) { break; }

    count++;
  }

  return count+1;
}
Esempio n. 16
0
/**
 * \brief Remove a variable from the current parameters and remove it's scaling and prior values
 *
 * This function will clear out a variable from the \c currentParams and also remove it's scale
 * factors and prior ranges.
 *
 * \param runState [in] The analysis information structure
 * \param ifo [in] The IFO data structure
 * \param var [in] The variable to remove
 *
 */
void remove_variable_and_prior( LALInferenceRunState *runState, LALInferenceIFOModel *ifo, const CHAR *var ){
  /* remove variable from currentParams */
  if( LALInferenceCheckVariable( runState->currentParams, var ) ){
    LALInferenceRemoveVariable( runState->currentParams, var );
  }
  else{
    fprintf(stderr, "Error... variable %s cannot be removed as it does not exist!\n", var);
    exit(3);
  }

  /* remove variable scale parameters from data */
  LALInferenceIFOModel *ifotemp = ifo;
  while ( ifotemp ){
    CHAR *varscale = XLALStringDuplicate( var );
    varscale = XLALStringAppend( varscale, "_scale" );

    if( LALInferenceCheckVariable( ifotemp->params, varscale ) ){
      LALInferenceRemoveVariable( ifotemp->params, varscale );
    }
    else{
      fprintf(stderr, "Error... variable %s cannot be removed as it does not exist!\n", varscale);
      exit(3);
    }

    varscale = XLALStringAppend( varscale, "_min" );
    if( LALInferenceCheckVariable( ifotemp->params, varscale ) ){
      LALInferenceRemoveVariable( ifotemp->params, varscale );
    }
    else{
      fprintf(stderr, "Error... variable %s cannot be removed as it does not exist!\n", varscale);
      exit(3);
    }

    ifotemp = ifotemp->next;
  }

  /* remove prior */
  if ( LALInferenceCheckGaussianPrior( runState->priorArgs, var ) ){
    LALInferenceRemoveGaussianPrior( runState->priorArgs, var );
  }
  else { LALInferenceRemoveMinMaxPrior( runState->priorArgs, var ); }
}
Esempio n. 17
0
int main( void ){
  INT4 i = 0;
  PulsarParameters *pars = NULL;

  /* output par file */
  FILE *fp = NULL;
  if ( (fp = fopen(PARFILE, "w")) == NULL ){
    XLAL_ERROR( XLAL_EIO, "Error... problem writing parfile!\n" );
  }

  for( i=0; i<NUMPARS; i++ ){
    if ( p[i].sigma != NULL ){ /* write out value and error */
      fprintf(fp, "%s\t%s\t%s\t%s\n", p[i].name, p[i].val, p[i].fitFlag, p[i].sigma);
    }
    else{ /* just write out value */
      fprintf(fp, "%s\t%s\n", p[i].name, p[i].val);
    }
  }

  fclose(fp);

  /* read in par file */
  pars = XLALReadTEMPOParFileNew( PARFILE );

  /* check read-in parameters against originals */
  for ( i=0; i<NUMPARS; i++ ){
    CHAR outval[256];
    CHAR outsigma[256];
    CHAR outfitflag[256];

    /* see if the parameter can be split into an alphabet and numerical value (as is the case
     * for e.g. FB, which is held as a vector */
    CHAR *namecopy = NULL, *token = NULL;
    namecopy = XLALStringDuplicate( p[i].name );
    token = strtok(namecopy, delimiters); /* get part of the name before the numerical delimiter */

    if ( !PulsarCheckParam( pars, p[i].name ) && !PulsarCheckParam( pars, token ) ){
      XLAL_ERROR( XLAL_EFAILED, "Error... parameter %s does not exist in the read-in data!\n", p[i].name );
    }

    /* value is a vector */
    if ( PulsarCheckParam( pars, token ) && PulsarGetParamType( pars, token ) == PULSARTYPE_REAL8Vector_t ){
     /* get value and convert to string */
      if ( !strchr( p[i].valcheck, 'e' ) ){ /* number doesn't contain an exponent */
        sprintf(outval, "%.5lf", PulsarGetREAL8VectorParamIndividual(pars, p[i].name));
      }
      else{ /* number does contain an exponent */
        sprintf(outval, "%.5le", PulsarGetREAL8VectorParamIndividual(pars, p[i].name));
      }

      if ( p[i].sigmacheck != NULL ){
        /* get error and convert to string */
        if ( !strchr( p[i].sigmacheck, 'e' ) ){ /* number doesn't contain an exponent */
          sprintf(outsigma, "%.5lf", PulsarGetREAL8VectorParamErrIndividual(pars, p[i].name));
        }
        else{
          sprintf(outsigma, "%.5le", PulsarGetREAL8VectorParamErrIndividual(pars, p[i].name));
        }

        UINT4 *fitFlag = PulsarGetParamFitFlag(pars, token);

        if ( fitFlag[atoi(p[i].name+strlen(token))] == 1 ){ sprintf(outfitflag, "1"); }
        else if ( fitFlag[atoi(p[i].name+strlen(token))] == 0 ){ sprintf(outfitflag, " "); }
        else {
          XLAL_ERROR( XLAL_EFAILED, "Error... fit flag incorrect for %s.\n", p[i].name );
        }
      }
    }
    /* value is a double */
    else if( PulsarGetParamType( pars, p[i].name ) == PULSARTYPE_REAL8_t ){
      /* get value and convert to string */
      if ( !strchr( p[i].valcheck, 'e' ) ){ /* number doesn't contain an exponent */
        sprintf(outval, "%.5lf", PulsarGetREAL8Param(pars, p[i].name));
      }
      else{ /* number does contain an exponent */
        sprintf(outval, "%.5le", PulsarGetREAL8Param(pars, p[i].name));
      }

      if ( p[i].sigmacheck != NULL ){
        /* get error and convert to string */
        if ( !strchr( p[i].sigmacheck, 'e' ) ){ /* number doesn't contain an exponent */
          sprintf(outsigma, "%.5lf", PulsarGetREAL8ParamErr(pars, p[i].name));
        }
        else{
          sprintf(outsigma, "%.5le", PulsarGetREAL8ParamErr(pars, p[i].name));
        }

        UINT4 *fitFlag = PulsarGetParamFitFlag(pars, p[i].name);

        if ( fitFlag[0] == 1 ){ sprintf(outfitflag, "1"); }
        else if ( fitFlag[0] == 0 ){ sprintf(outfitflag, " "); }
        else {
          XLAL_ERROR( XLAL_EFAILED, "Error... fit flag incorrect for %s.\n", p[i].name );
        }
      }
    }
    /* value is a string */
    else if ( PulsarGetParamType( pars, p[i].name ) == PULSARTYPE_string_t ) {
      CHAR *out = XLALStringDuplicate(PulsarGetStringParam(pars, p[i].name));
      sprintf(outval, "%s", out);
      XLALFree(out);
    }

    /* compare returned value with input value */
    if ( strcmp(outval, p[i].valcheck) != 0 ){
      XLAL_ERROR( XLAL_EFAILED, "Error... parameter %s does not match input (%s cf. %s)!\n", p[i].name, outval,
                  p[i].valcheck );
    }

    if( p[i].sigma != NULL ){
      /* compare returned value with input value */
      if ( strcmp(outsigma, p[i].sigmacheck) != 0 ){
        XLAL_ERROR( XLAL_EFAILED, "Error... parameter sigma %s does not match input (%s cf. %s)!\n", p[i].name,
                    outsigma, p[i].sigmacheck );
      }

      if ( strcmp(outfitflag, p[i].fitFlag) != 0 ){
        XLAL_ERROR( XLAL_EFAILED, "Error... parameter %s fit flag does not match input!\n", p[i].fitFlag );
      }
    }

    XLALFree( namecopy );
  }

  /* remove par file */
  if ( remove(PARFILE) != 0 ){
    XLAL_ERROR( XLAL_EIO, "Error... problem removing parfile!\n" );
  }

  fprintf(stderr, "Successfully read in .par file values!\n");

  PulsarFreeParams( pars );

  LALCheckMemoryLeaks();

  return XLAL_SUCCESS;
}
int main(int argc, char *argv[]){

  UserInput_t XLAL_INIT_DECL(uvar);
  static ConfigVariables config;

  /* sft related variables */
  MultiSFTVector *inputSFTs = NULL;
  MultiPSDVector *multiPSDs = NULL;
  MultiNoiseWeights *multiWeights = NULL;
  MultiLIGOTimeGPSVector *multiTimes = NULL;
  MultiLALDetector multiDetectors;
  MultiDetectorStateSeries *multiStates = NULL;
  MultiAMCoeffs *multiCoeffs = NULL;
  SFTIndexList *sftIndices = NULL;
  SFTPairIndexList *sftPairs = NULL;
  REAL8Vector *shiftedFreqs = NULL;
  UINT4Vector *lowestBins = NULL;
  COMPLEX8Vector *expSignalPhases = NULL;
  REAL8VectorSequence *sincList = NULL;
  PulsarDopplerParams XLAL_INIT_DECL(dopplerpos);
  PulsarDopplerParams thisBinaryTemplate, binaryTemplateSpacings;
  PulsarDopplerParams minBinaryTemplate, maxBinaryTemplate;
  SkyPosition XLAL_INIT_DECL(skyPos);
  MultiSSBtimes *multiBinaryTimes = NULL;

  INT4  k;
  UINT4 j;
  REAL8 fMin, fMax; /* min and max frequencies read from SFTs */
  REAL8 deltaF; /* frequency resolution associated with time baseline of SFTs */

  REAL8 diagff = 0; /*diagonal metric components*/
  REAL8 diagaa = 0;
  REAL8 diagTT = 0;
  REAL8 diagpp = 1;
  REAL8 ccStat = 0;
  REAL8 evSquared=0;
  REAL8 estSens=0; /*estimated sensitivity(4.13)*/
  BOOLEAN dopplerShiftFlag = TRUE;
  toplist_t *ccToplist=NULL;
  CrossCorrBinaryOutputEntry thisCandidate;
  UINT4 checksum;

  LogPrintf (LOG_CRITICAL, "Starting time\n"); /*for debug convenience to record calculating time*/
  /* initialize and register user variables */
  LIGOTimeGPS computingStartGPSTime, computingEndGPSTime;
  XLALGPSTimeNow (&computingStartGPSTime); /* record the rough starting GPS time*/

  if ( XLALInitUserVars( &uvar ) != XLAL_SUCCESS ) {
    LogPrintf ( LOG_CRITICAL, "%s: XLALInitUserVars() failed with errno=%d\n", __func__, xlalErrno );
    XLAL_ERROR( XLAL_EFUNC );
  }

  /* read user input from the command line or config file */
  if ( XLALUserVarReadAllInput ( argc, argv ) != XLAL_SUCCESS ) {
    LogPrintf ( LOG_CRITICAL, "%s: XLALUserVarReadAllInput() failed with errno=%d\n", __func__, xlalErrno );
    XLAL_ERROR( XLAL_EFUNC );
  }

  if (uvar.help)	/* if help was requested, then exit */
    return 0;

  CHAR *VCSInfoString = XLALGetVersionString(0);     /**<LAL + LALapps Vsersion string*/
  /*If the version information was requested, output it and exit*/
  if ( uvar.version ){
    XLAL_CHECK ( VCSInfoString != NULL, XLAL_EFUNC, "XLALGetVersionString(0) failed.\n" );
    printf ("%s\n", VCSInfoString );
    exit (0);
  }

  /* configure useful variables based on user input */
  if ( XLALInitializeConfigVars ( &config, &uvar) != XLAL_SUCCESS ) {
    LogPrintf ( LOG_CRITICAL, "%s: XLALInitUserVars() failed with errno=%d\n", __func__, xlalErrno );
    XLAL_ERROR( XLAL_EFUNC );
  }

  deltaF = config.catalog->data[0].header.deltaF;
  REAL8 Tsft = 1.0 / deltaF;

  if (XLALUserVarWasSet(&uvar.spacingF) && XLALUserVarWasSet(&uvar.mismatchF))
    LogPrintf (LOG_CRITICAL, "spacingF and mismatchF are both set, use spacingF %.9g by default\n\n", uvar.spacingF);
  if (XLALUserVarWasSet(&uvar.spacingA) && XLALUserVarWasSet(&uvar.mismatchA))
    LogPrintf (LOG_CRITICAL, "spacingA and mismatchA are both set, use spacingA %.9g by default\n\n", uvar.spacingA);
  if (XLALUserVarWasSet(&uvar.spacingT) && XLALUserVarWasSet(&uvar.mismatchT))
    LogPrintf (LOG_CRITICAL, "spacingT and mismatchT are both set, use spacingT %.9g by default\n\n", uvar.spacingT);
  if (XLALUserVarWasSet(&uvar.spacingP) && XLALUserVarWasSet(&uvar.mismatchP))
    LogPrintf (LOG_CRITICAL, "spacingP and mismatchP are both set, use spacingP %.9g by default\n\n", uvar.spacingP);

  /* create the toplist */
  create_crossCorrBinary_toplist( &ccToplist, uvar.numCand);
  /* now read the data */

  /* /\* get SFT parameters so that we can initialise search frequency resolutions *\/ */
  /* /\* calculate deltaF_SFT *\/ */
  /* deltaF_SFT = catalog->data[0].header.deltaF;  /\* frequency resolution *\/ */
  /* timeBase= 1.0/deltaF_SFT; /\* sft baseline *\/ */

  /* /\* catalog is ordered in time so we can get start, end time and tObs *\/ */
  /* firstTimeStamp = catalog->data[0].header.epoch; */
  /* lastTimeStamp = catalog->data[catalog->length - 1].header.epoch; */
  /* tObs = XLALGPSDiff( &lastTimeStamp, &firstTimeStamp ) + timeBase; */

  /* /\*set pulsar reference time *\/ */
  /* if (LALUserVarWasSet ( &uvar_refTime )) { */
  /*   XLALGPSSetREAL8(&refTime, uvar_refTime); */
  /* }  */
  /* else {	/\*if refTime is not set, set it to midpoint of sfts*\/ */
  /*   XLALGPSSetREAL8(&refTime, (0.5*tObs) + XLALGPSGetREAL8(&firstTimeStamp));  */
  /* } */

  /* /\* set frequency resolution defaults if not set by user *\/ */
  /* if (!(LALUserVarWasSet (&uvar_fResolution))) { */
  /*   uvar_fResolution = 1/tObs; */
  /* } */

  /* { */
  /*   /\* block for calculating frequency range to read from SFTs *\/ */
  /*   /\* user specifies freq and fdot range at reftime */
  /*      we translate this range of fdots to start and endtime and find */
  /*      the largest frequency band required to cover the  */
  /*      frequency evolution  *\/ */
  /*   PulsarSpinRange spinRange_startTime; /\**< freq and fdot range at start-time of observation *\/ */
  /*   PulsarSpinRange spinRange_endTime;   /\**< freq and fdot range at end-time of observation *\/ */
  /*   PulsarSpinRange spinRange_refTime;   /\**< freq and fdot range at the reference time *\/ */

  /*   REAL8 startTime_freqLo, startTime_freqHi, endTime_freqLo, endTime_freqHi, freqLo, freqHi; */

  /*   REAL8Vector *fdotsMin=NULL; */
  /*   REAL8Vector *fdotsMax=NULL; */

  /*   UINT4 k; */

  /*   fdotsMin = (REAL8Vector *)LALCalloc(1, sizeof(REAL8Vector)); */
  /*   fdotsMin->length = N_SPINDOWN_DERIVS; */
  /*   fdotsMin->data = (REAL8 *)LALCalloc(fdotsMin->length, sizeof(REAL8)); */

  /*   fdotsMax = (REAL8Vector *)LALCalloc(1, sizeof(REAL8Vector)); */
  /*   fdotsMax->length = N_SPINDOWN_DERIVS; */
  /*   fdotsMax->data = (REAL8 *)LALCalloc(fdotsMax->length, sizeof(REAL8)); */

  /*   XLAL_INIT_MEM(spinRange_startTime); */
  /*   XLAL_INIT_MEM(spinRange_endTime); */
  /*   XLAL_INIT_MEM(spinRange_refTime); */

  /*   spinRange_refTime.refTime = refTime; */
  /*   spinRange_refTime.fkdot[0] = uvar_f0; */
  /*   spinRange_refTime.fkdotBand[0] = uvar_fBand; */
  /* } */

  /* FIXME: need to correct fMin and fMax for Doppler shift, rngmedian bins and spindown range */
  /* this is essentially just a place holder for now */
  /* FIXME: this running median buffer is overkill, since the running median block need not be centered on the search frequency */
  REAL8 vMax = LAL_TWOPI * (uvar.orbitAsiniSec + uvar.orbitAsiniSecBand) / uvar.orbitPSec + LAL_TWOPI * LAL_REARTH_SI / (LAL_DAYSID_SI * LAL_C_SI) + LAL_TWOPI * LAL_AU_SI/(LAL_YRSID_SI * LAL_C_SI); /*calculate the maximum relative velocity in speed of light*/
  fMin = uvar.fStart * (1 - vMax) - 0.5 * uvar.rngMedBlock * deltaF;
  fMax = (uvar.fStart + uvar.fBand) * (1 + vMax) + 0.5 * uvar.rngMedBlock * deltaF;

  /* read the SFTs*/
  if ((inputSFTs = XLALLoadMultiSFTs ( config.catalog, fMin, fMax)) == NULL){
    LogPrintf ( LOG_CRITICAL, "%s: XLALLoadMultiSFTs() failed with errno=%d\n", __func__, xlalErrno );
    XLAL_ERROR( XLAL_EFUNC );
  }

  /* calculate the psd and normalize the SFTs */
  if (( multiPSDs =  XLALNormalizeMultiSFTVect ( inputSFTs, uvar.rngMedBlock, NULL )) == NULL){
    LogPrintf ( LOG_CRITICAL, "%s: XLALNormalizeMultiSFTVect() failed with errno=%d\n", __func__, xlalErrno );
    XLAL_ERROR( XLAL_EFUNC );
  }

  /* compute the noise weights for the AM coefficients */
  if (( multiWeights = XLALComputeMultiNoiseWeights ( multiPSDs, uvar.rngMedBlock, 0 )) == NULL){
    LogPrintf ( LOG_CRITICAL, "%s: XLALComputeMultiNoiseWeights() failed with errno=%d\n", __func__, xlalErrno );
    XLAL_ERROR( XLAL_EFUNC );
  }

  /* read the timestamps from the SFTs */
  if ((multiTimes = XLALExtractMultiTimestampsFromSFTs ( inputSFTs )) == NULL){
    LogPrintf ( LOG_CRITICAL, "%s: XLALExtractMultiTimestampsFromSFTs() failed with errno=%d\n", __func__, xlalErrno );
    XLAL_ERROR( XLAL_EFUNC );
  }

  /* read the detector information from the SFTs */
  if ( XLALMultiLALDetectorFromMultiSFTs ( &multiDetectors, inputSFTs ) != XLAL_SUCCESS){
    LogPrintf ( LOG_CRITICAL, "%s: XLALMultiLALDetectorFromMultiSFTs() failed with errno=%d\n", __func__, xlalErrno );
    XLAL_ERROR( XLAL_EFUNC );
  }

  /* Find the detector state for each SFT */
  /* Offset by Tsft/2 to get midpoint as timestamp */
  if ((multiStates = XLALGetMultiDetectorStates ( multiTimes, &multiDetectors, config.edat, 0.5 * Tsft )) == NULL){
    LogPrintf ( LOG_CRITICAL, "%s: XLALGetMultiDetectorStates() failed with errno=%d\n", __func__, xlalErrno );
    XLAL_ERROR( XLAL_EFUNC );
  }

  /* Note this is specialized to a single sky position */
  /* This might need to be moved into the config variables */
  skyPos.system = COORDINATESYSTEM_EQUATORIAL;
  skyPos.longitude = uvar.alphaRad;
  skyPos.latitude  = uvar.deltaRad;

  /* Calculate the AM coefficients (a,b) for each SFT */
  if ((multiCoeffs = XLALComputeMultiAMCoeffs ( multiStates, multiWeights, skyPos )) == NULL){
    LogPrintf ( LOG_CRITICAL, "%s: XLALComputeMultiAMCoeffs() failed with errno=%d\n", __func__, xlalErrno );
    XLAL_ERROR( XLAL_EFUNC );
  }

  /* Construct the flat list of SFTs (this sort of replicates the
     catalog, but there's not an obvious way to get the information
     back) */

  if ( ( XLALCreateSFTIndexListFromMultiSFTVect( &sftIndices, inputSFTs ) != XLAL_SUCCESS ) ) {
    LogPrintf ( LOG_CRITICAL, "%s: XLALCreateSFTIndexListFromMultiSFTVect() failed with errno=%d\n", __func__, xlalErrno );
    XLAL_ERROR( XLAL_EFUNC );
  }

  /* Construct the list of SFT pairs */
#define PCC_SFTPAIR_HEADER "# The length of SFT-pair list is %u #\n"
#define PCC_SFTPAIR_BODY "%u %u\n"
#define PCC_SFT_HEADER "# The length of SFT list is %u #\n"
#define PCC_SFT_BODY "%s %d %d\n"
  FILE *fp = NULL;

  if (XLALUserVarWasSet(&uvar.pairListInputFilename)) { /* If the user provided a list for reading, use it */
    if((sftPairs = XLALCalloc(1, sizeof(sftPairs))) == NULL){
      XLAL_ERROR(XLAL_ENOMEM);
    }
    if((fp = fopen(uvar.pairListInputFilename, "r")) == NULL){
      LogPrintf ( LOG_CRITICAL, "didn't find SFT-pair list file with given input name\n");
      XLAL_ERROR( XLAL_EFUNC );
    }
    if(fscanf(fp,PCC_SFTPAIR_HEADER,&sftPairs->length)==EOF){
      LogPrintf ( LOG_CRITICAL, "can't read the length of SFT-pair list from the header\n");
      XLAL_ERROR( XLAL_EFUNC );
    }

    if((sftPairs->data = XLALCalloc(sftPairs->length, sizeof(*sftPairs->data)))==NULL){
      XLALFree(sftPairs);
      XLAL_ERROR(XLAL_ENOMEM);
    }

    for(j = 0; j < sftPairs->length; j++){ /*read in  the SFT-pair list */
      if(fscanf(fp,PCC_SFTPAIR_BODY, &sftPairs->data[j].sftNum[0], &sftPairs->data[j].sftNum[1])==EOF){
	LogPrintf ( LOG_CRITICAL, "The length of SFT-pair list doesn't match!");
	XLAL_ERROR( XLAL_EFUNC );
      }
    }
    fclose(fp);

  }

  else { /* if not, construct the list of pairs */
    if ( ( XLALCreateSFTPairIndexList( &sftPairs, sftIndices, inputSFTs, uvar.maxLag, uvar.inclAutoCorr ) != XLAL_SUCCESS ) ) {
      LogPrintf ( LOG_CRITICAL, "%s: XLALCreateSFTPairIndexList() failed with errno=%d\n", __func__, xlalErrno );
      XLAL_ERROR( XLAL_EFUNC );
    }
  }

  if (XLALUserVarWasSet(&uvar.pairListOutputFilename)) { /* Write the list of pairs to a file, if a name was provided */
    if((fp = fopen(uvar.pairListOutputFilename, "w")) == NULL){
      LogPrintf ( LOG_CRITICAL, "Can't write in SFT-pair list \n");
      XLAL_ERROR( XLAL_EFUNC );
    }
    fprintf(fp,PCC_SFTPAIR_HEADER, sftPairs->length ); /*output the length of SFT-pair list to the header*/
    for(j = 0; j < sftPairs->length; j++){
      fprintf(fp,PCC_SFTPAIR_BODY, sftPairs->data[j].sftNum[0], sftPairs->data[j].sftNum[1]);
    }
    fclose(fp);
  }

  if (XLALUserVarWasSet(&uvar.sftListOutputFilename)) { /* Write the list of SFTs to a file for sanity-checking purposes */
    if((fp = fopen(uvar.sftListOutputFilename, "w")) == NULL){
      LogPrintf ( LOG_CRITICAL, "Can't write in flat SFT list \n");
      XLAL_ERROR( XLAL_EFUNC );
    }
    fprintf(fp,PCC_SFT_HEADER, sftIndices->length ); /*output the length of SFT list to the header*/
    for(j = 0; j < sftIndices->length; j++){ /*output the SFT list */
      fprintf(fp,PCC_SFT_BODY, inputSFTs->data[sftIndices->data[j].detInd]->data[sftIndices->data[j].sftInd].name, inputSFTs->data[sftIndices->data[j].detInd]->data[sftIndices->data[j].sftInd].epoch.gpsSeconds, inputSFTs->data[sftIndices->data[j].detInd]->data[sftIndices->data[j].sftInd].epoch.gpsNanoSeconds);
    }
    fclose(fp);
  }

  else if(XLALUserVarWasSet(&uvar.sftListInputFilename)){ /*do a sanity check of the order of SFTs list if the name of input SFT list is given*/
    UINT4 numofsft=0;
    if((fp = fopen(uvar.sftListInputFilename, "r")) == NULL){
      LogPrintf ( LOG_CRITICAL, "Can't read in flat SFT list \n");
      XLAL_ERROR( XLAL_EFUNC );
    }
    if (fscanf(fp, PCC_SFT_HEADER, &numofsft)==EOF){
      LogPrintf ( LOG_CRITICAL, "can't read in the length of SFT list from header\n");
      XLAL_ERROR( XLAL_EFUNC );
    }

    CHARVectorSequence *checkDet=NULL;
    if ((checkDet = XLALCreateCHARVectorSequence (numofsft, LALNameLength) ) == NULL){
      LogPrintf ( LOG_CRITICAL, "%s: XLALCreateCHARVector() failed with errno=%d\n", __func__, xlalErrno );
      XLAL_ERROR( XLAL_EFUNC );
    }
    INT4 checkGPS[numofsft], checkGPSns[numofsft];
    if(numofsft == sftIndices->length){
      for (j=0; j<numofsft; j++){
	if( fscanf(fp,PCC_SFT_BODY,&checkDet->data[j * LALNameLength], &checkGPS[j], &checkGPSns[j])==EOF){
	  LogPrintf ( LOG_CRITICAL, "The length of SFT list doesn't match\n");
	  XLAL_ERROR( XLAL_EFUNC );
	}
	if(strcmp( inputSFTs->data[sftIndices->data[j].detInd]->data[sftIndices->data[j].sftInd].name, &checkDet->data[j * LALNameLength] ) != 0
	   ||inputSFTs->data[sftIndices->data[j].detInd]->data[sftIndices->data[j].sftInd].epoch.gpsSeconds != checkGPS[j]
	   ||inputSFTs->data[sftIndices->data[j].detInd]->data[sftIndices->data[j].sftInd].epoch.gpsNanoSeconds != checkGPSns[j] ){
	  LogPrintf ( LOG_CRITICAL, "The order of SFTs has been changed, it's the end of civilization\n");
	  XLAL_ERROR( XLAL_EFUNC );
	}
      }
      fclose(fp);
      XLALDestroyCHARVectorSequence(checkDet);
    }
    else{
      LogPrintf ( LOG_CRITICAL, "Run for your life, the length of SFT list doesn't match");
      XLAL_ERROR( XLAL_EFUNC );
    }
  }
  else
    {

    }

  /* Get weighting factors for calculation of metric */
  /* note that the sigma-squared is now absorbed into the curly G
     because the AM coefficients are noise-weighted. */
  REAL8Vector *GammaAve = NULL;
  REAL8Vector *GammaCirc = NULL;
  if ( ( XLALCalculateCrossCorrGammas( &GammaAve, &GammaCirc, sftPairs, sftIndices, multiCoeffs)  != XLAL_SUCCESS ) ) {
    LogPrintf ( LOG_CRITICAL, "%s: XLALCalculateCrossCorrGammas() failed with errno=%d\n", __func__, xlalErrno );
    XLAL_ERROR( XLAL_EFUNC );
  }

#define PCC_GAMMA_HEADER "# The normalization Sinv_Tsft is %g #\n"
#define PCC_GAMMA_BODY "%.10g\n"
  if (XLALUserVarWasSet(&uvar.gammaAveOutputFilename)) { /* Write the aa+bb weight for each pair to a file, if a name was provided */
    if((fp = fopen(uvar.gammaAveOutputFilename, "w")) == NULL) {
      LogPrintf ( LOG_CRITICAL, "Can't write in Gamma_ave list \n");
      XLAL_ERROR( XLAL_EFUNC );
    }
    fprintf(fp,PCC_GAMMA_HEADER, multiWeights->Sinv_Tsft); /*output the normalization factor to the header*/
    for(j = 0; j < sftPairs->length; j++){
      fprintf(fp,PCC_GAMMA_BODY, GammaAve->data[j]);
    }
    fclose(fp);
  }
  if (XLALUserVarWasSet(&uvar.gammaCircOutputFilename)) { /* Write the ab-ba weight for each pair to a file, if a name was provided */
    if((fp = fopen(uvar.gammaCircOutputFilename, "w")) == NULL) {
      LogPrintf ( LOG_CRITICAL, "Can't write in Gamma_circ list \n");
      XLAL_ERROR( XLAL_EFUNC );
    }
    fprintf(fp,PCC_GAMMA_HEADER, multiWeights->Sinv_Tsft); /*output the normalization factor to the header*/
    for(j = 0; j < sftPairs->length; j++){
      fprintf(fp,PCC_GAMMA_BODY, GammaCirc->data[j]);
    }
    fclose(fp);
  }

  /*initialize binary parameters structure*/
  XLAL_INIT_MEM(minBinaryTemplate);
  XLAL_INIT_MEM(maxBinaryTemplate);
  XLAL_INIT_MEM(thisBinaryTemplate);
  XLAL_INIT_MEM(binaryTemplateSpacings);
  /*fill in minbinaryOrbitParams*/
  XLALGPSSetREAL8( &minBinaryTemplate.tp, uvar.orbitTimeAsc);
  minBinaryTemplate.argp = 0.0;
  minBinaryTemplate.asini = uvar.orbitAsiniSec;
  minBinaryTemplate.ecc = 0.0;
  minBinaryTemplate.period = uvar.orbitPSec;
  minBinaryTemplate.fkdot[0] = uvar.fStart;
  /*fill in maxBinaryParams*/
  XLALGPSSetREAL8( &maxBinaryTemplate.tp, uvar.orbitTimeAsc + uvar.orbitTimeAscBand);
  maxBinaryTemplate.argp = 0.0;
  maxBinaryTemplate.asini = uvar.orbitAsiniSec + uvar.orbitAsiniSecBand;
  maxBinaryTemplate.ecc = 0.0;
  maxBinaryTemplate.period = uvar.orbitPSec;
  maxBinaryTemplate.fkdot[0] = uvar.fStart + uvar.fBand;
  /*fill in thisBinaryTemplate*/
  XLALGPSSetREAL8( &thisBinaryTemplate.tp, uvar.orbitTimeAsc + 0.5 * uvar.orbitTimeAscBand);
  thisBinaryTemplate.argp = 0.0;
  thisBinaryTemplate.asini = 0.5*(minBinaryTemplate.asini + maxBinaryTemplate.asini);
  thisBinaryTemplate.ecc = 0.0;
  thisBinaryTemplate.period =0.5*(minBinaryTemplate.period + maxBinaryTemplate.period);
  thisBinaryTemplate.fkdot[0]=0.5*(minBinaryTemplate.fkdot[0] + maxBinaryTemplate.fkdot[0]);

  /*Get metric diagonal components, also estimate sensitivity i.e. E[rho]/(h0)^2 (4.13)*/
  if ( (XLALCalculateLMXBCrossCorrDiagMetric(&estSens, &diagff, &diagaa, &diagTT, thisBinaryTemplate, GammaAve, sftPairs, sftIndices, inputSFTs, multiWeights /*, kappaValues*/)  != XLAL_SUCCESS ) ) {
    LogPrintf ( LOG_CRITICAL, "%s: XLALCalculateLMXBCrossCorrDiagMetric() failed with errno=%d\n", __func__, xlalErrno );
    XLAL_ERROR( XLAL_EFUNC );
  }

  /* spacing in frequency from diagff */ /* set spacings in new dopplerparams struct */
  if (XLALUserVarWasSet(&uvar.spacingF)) /* If spacing was given by CMD line, use it, else calculate spacing by mismatch*/
    binaryTemplateSpacings.fkdot[0] = uvar.spacingF;
  else
    binaryTemplateSpacings.fkdot[0] = sqrt(uvar.mismatchF / diagff);

  if (XLALUserVarWasSet(&uvar.spacingA))
    binaryTemplateSpacings.asini = uvar.spacingA;
  else
    binaryTemplateSpacings.asini = sqrt(uvar.mismatchA / diagaa);
  /* this is annoying: tp is a GPS time while we want a difference
     in time which should be just REAL8 */
  if (XLALUserVarWasSet(&uvar.spacingT))
    XLALGPSSetREAL8( &binaryTemplateSpacings.tp, uvar.spacingT);
  else
    XLALGPSSetREAL8( &binaryTemplateSpacings.tp, sqrt(uvar.mismatchT / diagTT));

  if (XLALUserVarWasSet(&uvar.spacingP))
    binaryTemplateSpacings.period = uvar.spacingP;
  else
    binaryTemplateSpacings.period = sqrt(uvar.mismatchP / diagpp);

  /* metric elements for eccentric case not considered? */

  UINT8 fCount = 0, aCount = 0, tCount = 0 , pCount = 0;
  const UINT8 fSpacingNum = floor( uvar.fBand / binaryTemplateSpacings.fkdot[0]);
  const UINT8 aSpacingNum = floor( uvar.orbitAsiniSecBand / binaryTemplateSpacings.asini);
  const UINT8 tSpacingNum = floor( uvar.orbitTimeAscBand / XLALGPSGetREAL8(&binaryTemplateSpacings.tp));
  const UINT8 pSpacingNum = floor( uvar.orbitPSecBand / binaryTemplateSpacings.period);

  /*reset minbinaryOrbitParams to shift the first point a factor so as to make the center of all seaching points centers at the center of searching band*/
  minBinaryTemplate.fkdot[0] = uvar.fStart + 0.5 * (uvar.fBand - fSpacingNum * binaryTemplateSpacings.fkdot[0]);
  minBinaryTemplate.asini = uvar.orbitAsiniSec + 0.5 * (uvar.orbitAsiniSecBand - aSpacingNum * binaryTemplateSpacings.asini);
  XLALGPSSetREAL8( &minBinaryTemplate.tp, uvar.orbitTimeAsc + 0.5 * (uvar.orbitTimeAscBand - tSpacingNum * XLALGPSGetREAL8(&binaryTemplateSpacings.tp)));
  minBinaryTemplate.period = uvar.orbitPSec + 0.5 * (uvar.orbitPSecBand - pSpacingNum * binaryTemplateSpacings.period);

  /* initialize the doppler scan struct which stores the current template information */
  XLALGPSSetREAL8(&dopplerpos.refTime, config.refTime);
  dopplerpos.Alpha = uvar.alphaRad;
  dopplerpos.Delta = uvar.deltaRad;
  dopplerpos.fkdot[0] = minBinaryTemplate.fkdot[0];
  /* set all spindowns to zero */
  for (k=1; k < PULSAR_MAX_SPINS; k++)
    dopplerpos.fkdot[k] = 0.0;
  dopplerpos.asini = minBinaryTemplate.asini;
  dopplerpos.period = minBinaryTemplate.period;
  dopplerpos.tp = minBinaryTemplate.tp;
  dopplerpos.ecc = minBinaryTemplate.ecc;
  dopplerpos.argp = minBinaryTemplate.argp;

  /* now set the initial values of binary parameters */
  /*  thisBinaryTemplate.asini = uvar.orbitAsiniSec;
  thisBinaryTemplate.period = uvar.orbitPSec;
  XLALGPSSetREAL8( &thisBinaryTemplate.tp, uvar.orbitTimeAsc);
  thisBinaryTemplate.ecc = 0.0;
  thisBinaryTemplate.argp = 0.0;*/
  /* copy to dopplerpos */

  /* Calculate SSB times (can do this once since search is currently only for one sky position, and binary doppler shift is added later) */
  MultiSSBtimes *multiSSBTimes = NULL;
  if ((multiSSBTimes = XLALGetMultiSSBtimes ( multiStates, skyPos, dopplerpos.refTime, SSBPREC_RELATIVISTICOPT )) == NULL){
    LogPrintf ( LOG_CRITICAL, "%s: XLALGetMultiSSBtimes() failed with errno=%d\n", __func__, xlalErrno );
    XLAL_ERROR( XLAL_EFUNC );
  }

  /* "New" general metric computation */
  /* For now hard-code circular parameter space */

  const DopplerCoordinateSystem coordSys = {
    .dim = 4,
    .coordIDs = { DOPPLERCOORD_FREQ,
		  DOPPLERCOORD_ASINI,
		  DOPPLERCOORD_TASC,
		  DOPPLERCOORD_PORB, },
  };

  REAL8VectorSequence *phaseDerivs = NULL;
  if ( ( XLALCalculateCrossCorrPhaseDerivatives ( &phaseDerivs, &thisBinaryTemplate, config.edat, sftIndices, multiSSBTimes, &coordSys )  != XLAL_SUCCESS ) ) {
    LogPrintf ( LOG_CRITICAL, "%s: XLALCalculateCrossCorrPhaseDerivatives() failed with errno=%d\n", __func__, xlalErrno );
    XLAL_ERROR( XLAL_EFUNC );
  }

  /* fill in metric and parameter offsets */
  gsl_matrix *g_ij = NULL;
  gsl_vector *eps_i = NULL;
  REAL8 sumGammaSq = 0;
  if ( ( XLALCalculateCrossCorrPhaseMetric ( &g_ij, &eps_i, &sumGammaSq, phaseDerivs, sftPairs, GammaAve, GammaCirc, &coordSys ) != XLAL_SUCCESS ) ) {
    LogPrintf ( LOG_CRITICAL, "%s: XLALCalculateCrossCorrPhaseMetric() failed with errno=%d\n", __func__, xlalErrno );
    XLAL_ERROR( XLAL_EFUNC );
  }
  XLALDestroyREAL8VectorSequence ( phaseDerivs );
  XLALDestroyREAL8Vector ( GammaCirc );

  if ((fp = fopen("gsldata.dat","w"))==NULL){
    LogPrintf ( LOG_CRITICAL, "Can't write in gsl matrix file");
    XLAL_ERROR( XLAL_EFUNC );
  }

  XLALfprintfGSLvector(fp, "%g", eps_i);
  XLALfprintfGSLmatrix(fp, "%g", g_ij);

  /* Allocate structure for binary doppler-shifting information */
  if ((multiBinaryTimes = XLALDuplicateMultiSSBtimes ( multiSSBTimes )) == NULL){
    LogPrintf ( LOG_CRITICAL, "%s: XLALDuplicateMultiSSBtimes() failed with errno=%d\n", __func__, xlalErrno );
    XLAL_ERROR( XLAL_EFUNC );
  }

  UINT8 numSFTs = sftIndices->length;
  if ((shiftedFreqs = XLALCreateREAL8Vector ( numSFTs ) ) == NULL){
    LogPrintf ( LOG_CRITICAL, "%s: XLALCreateREAL8Vector() failed with errno=%d\n", __func__, xlalErrno );
    XLAL_ERROR( XLAL_EFUNC );
  }
  if ((lowestBins = XLALCreateUINT4Vector ( numSFTs ) ) == NULL){
    LogPrintf ( LOG_CRITICAL, "%s: XLALCreateUINT4Vector() failed with errno=%d\n", __func__, xlalErrno );
    XLAL_ERROR( XLAL_EFUNC );
  }

  if ((expSignalPhases = XLALCreateCOMPLEX8Vector ( numSFTs ) ) == NULL){
    LogPrintf ( LOG_CRITICAL, "%s: XLALCreateREAL8Vector() failed with errno=%d\n", __func__, xlalErrno );
    XLAL_ERROR( XLAL_EFUNC );
  }
  if ((sincList = XLALCreateREAL8VectorSequence ( numSFTs, uvar.numBins ) ) == NULL){
    LogPrintf ( LOG_CRITICAL, "%s: XLALCreateREAL8VectorSequence() failed with errno=%d\n", __func__, xlalErrno );
    XLAL_ERROR( XLAL_EFUNC );
  }

  /* args should be : spacings, min and max doppler params */
  BOOLEAN firstPoint = TRUE; /* a boolean to help to search at the beginning point in parameter space, after the search it is set to be FALSE to end the loop*/
  if ( (XLALAddMultiBinaryTimes( &multiBinaryTimes, multiSSBTimes, &dopplerpos )  != XLAL_SUCCESS ) ) {
    LogPrintf ( LOG_CRITICAL, "%s: XLALAddMultiBinaryTimes() failed with errno=%d\n", __func__, xlalErrno );
    XLAL_ERROR( XLAL_EFUNC );
  } /*Need to apply additional doppler shifting before the loop, or the first point in parameter space will be lost and return a wrong SNR when fBand!=0*/

  while ( GetNextCrossCorrTemplate(&dopplerShiftFlag, &firstPoint, &dopplerpos, &binaryTemplateSpacings, &minBinaryTemplate, &maxBinaryTemplate, &fCount, &aCount, &tCount, &pCount, fSpacingNum, aSpacingNum, tSpacingNum, pSpacingNum) == 0)
    {
      /* do useful stuff here*/

      /* Apply additional Doppler shifting using current binary orbital parameters */
      /* Might want to be clever about checking whether we've changed the orbital parameters or only the frequency */
      if (dopplerShiftFlag == TRUE)
	{
	  if ( (XLALAddMultiBinaryTimes( &multiBinaryTimes, multiSSBTimes, &dopplerpos )  != XLAL_SUCCESS ) ) {
	    LogPrintf ( LOG_CRITICAL, "%s: XLALAddMultiBinaryTimes() failed with errno=%d\n", __func__, xlalErrno );
	    XLAL_ERROR( XLAL_EFUNC );
	  }
	}

      if ( (XLALGetDopplerShiftedFrequencyInfo( shiftedFreqs, lowestBins, expSignalPhases, sincList, uvar.numBins, &dopplerpos, sftIndices, inputSFTs, multiBinaryTimes, Tsft )  != XLAL_SUCCESS ) ) {
	LogPrintf ( LOG_CRITICAL, "%s: XLALGetDopplerShiftedFrequencyInfo() failed with errno=%d\n", __func__, xlalErrno );
	XLAL_ERROR( XLAL_EFUNC );
      }

      if ( (XLALCalculatePulsarCrossCorrStatistic( &ccStat, &evSquared, GammaAve, expSignalPhases, lowestBins, sincList, sftPairs, sftIndices, inputSFTs, multiWeights, uvar.numBins)  != XLAL_SUCCESS ) ) {
	LogPrintf ( LOG_CRITICAL, "%s: XLALCalculatePulsarCrossCorrStatistic() failed with errno=%d\n", __func__, xlalErrno );
	XLAL_ERROR( XLAL_EFUNC );
      }

      /* fill candidate struct and insert into toplist if necessary */
      thisCandidate.freq = dopplerpos.fkdot[0];
      thisCandidate.tp = XLALGPSGetREAL8( &dopplerpos.tp );
      thisCandidate.argp = dopplerpos.argp;
      thisCandidate.asini = dopplerpos.asini;
      thisCandidate.ecc = dopplerpos.ecc;
      thisCandidate.period = dopplerpos.period;
      thisCandidate.rho = ccStat;
      thisCandidate.evSquared = evSquared;
      thisCandidate.estSens = estSens;

      insert_into_crossCorrBinary_toplist(ccToplist, thisCandidate);

    } /* end while loop over templates */

  /* write candidates to file */
  sort_crossCorrBinary_toplist( ccToplist );
  /* add error checking */

  final_write_crossCorrBinary_toplist_to_file( ccToplist, uvar.toplistFilename, &checksum);

  REAL8 h0Sens = sqrt((10 / sqrt(estSens))); /*for a SNR=10 signal, the h0 we can detect*/

  XLALGPSTimeNow (&computingEndGPSTime); /*record the rough end time*/
  UINT4 computingTime = computingEndGPSTime.gpsSeconds - computingStartGPSTime.gpsSeconds;
  /* make a meta-data file*/
  if(XLALUserVarWasSet(&uvar.logFilename)){
    CHAR *CMDInputStr = XLALUserVarGetLog ( UVAR_LOGFMT_CFGFILE );
    if ((fp = fopen(uvar.logFilename,"w"))==NULL){
    LogPrintf ( LOG_CRITICAL, "Can't write in logfile");
    XLAL_ERROR( XLAL_EFUNC );
    }
    fprintf(fp, "[UserInput]\n\n");
    fprintf(fp, "%s\n", CMDInputStr);
    fprintf(fp, "[CalculatedValues]\n\n");
    fprintf(fp, "g_ff = %.9f\n", diagff );
    fprintf(fp, "g_aa = %.9f\n", diagaa );
    fprintf(fp, "g_TT = %.9f\n", diagTT );
    fprintf(fp, "FSpacing = %.9g\n", binaryTemplateSpacings.fkdot[0]);
    fprintf(fp, "ASpacing = %.9g\n", binaryTemplateSpacings.asini);
    fprintf(fp, "TSpacing = %.9g\n", XLALGPSGetREAL8(&binaryTemplateSpacings.tp));
    /* fprintf(fp, "PSpacing = %.9g\n", binaryTemplateSpacings.period );*/
    fprintf(fp, "TemplatenumF = %" LAL_UINT8_FORMAT "\n", (fSpacingNum + 1));
    fprintf(fp, "TemplatenumA = %" LAL_UINT8_FORMAT "\n", (aSpacingNum + 1));
    fprintf(fp, "TemplatenumT = %" LAL_UINT8_FORMAT "\n", (tSpacingNum + 1));
    fprintf(fp, "TemplatenumP = %" LAL_UINT8_FORMAT "\n", (pSpacingNum + 1));
    fprintf(fp, "TemplatenumTotal = %" LAL_UINT8_FORMAT "\n",(fSpacingNum + 1) * (aSpacingNum + 1) * (tSpacingNum + 1) * (pSpacingNum + 1));
    fprintf(fp, "Sens = %.9g\n", estSens);/*(E[rho]/h0^2)^2*/
    fprintf(fp, "h0_min_SNR10 = %.9g\n", h0Sens);/*for rho = 10 in our pipeline*/
    fprintf(fp, "startTime = %" LAL_INT4_FORMAT "\n", computingStartGPSTime.gpsSeconds );/*start time in GPS-time*/
    fprintf(fp, "endTime = %" LAL_INT4_FORMAT "\n", computingEndGPSTime.gpsSeconds );/*end time in GPS-time*/
    fprintf(fp, "computingTime = %" LAL_UINT4_FORMAT "\n", computingTime );/*total time in sec*/
    fprintf(fp, "SFTnum = %" LAL_UINT4_FORMAT "\n", sftIndices->length);/*total number of SFT*/
    fprintf(fp, "pairnum = %" LAL_UINT4_FORMAT "\n", sftPairs->length);/*total number of pair of SFT*/
    fprintf(fp, "Tsft = %.6g\n", Tsft);/*SFT duration*/
    fprintf(fp, "\n[Version]\n\n");
    fprintf(fp, "%s",  VCSInfoString);
    fclose(fp);
    XLALFree(CMDInputStr);
  }

  XLALFree(VCSInfoString);
  XLALDestroyCOMPLEX8Vector ( expSignalPhases );
  XLALDestroyUINT4Vector ( lowestBins );
  XLALDestroyREAL8Vector ( shiftedFreqs );
  XLALDestroyREAL8VectorSequence ( sincList );
  XLALDestroyMultiSSBtimes ( multiBinaryTimes );
  XLALDestroyMultiSSBtimes ( multiSSBTimes );
  XLALDestroyREAL8Vector ( GammaAve );
  XLALDestroySFTPairIndexList( sftPairs );
  XLALDestroySFTIndexList( sftIndices );
  XLALDestroyMultiAMCoeffs ( multiCoeffs );
  XLALDestroyMultiDetectorStateSeries ( multiStates );
  XLALDestroyMultiTimestamps ( multiTimes );
  XLALDestroyMultiNoiseWeights ( multiWeights );
  XLALDestroyMultiPSDVector ( multiPSDs );
  XLALDestroyMultiSFTVector ( inputSFTs );

  /* de-allocate memory for configuration variables */
  XLALDestroyConfigVars ( &config );

  /* de-allocate memory for user input variables */
  XLALDestroyUserVars();

  /* free toplist memory */
  free_crossCorr_toplist(&ccToplist);

  /* check memory leaks if we forgot to de-allocate anything */
  LALCheckMemoryLeaks();

  LogPrintf (LOG_CRITICAL, "End time\n");/*for debug convenience to record calculating time*/

  return 0;


} /* main */


/* initialize and register user variables */
int XLALInitUserVars (UserInput_t *uvar)
{

  /* initialize with some defaults */
  uvar->help = FALSE;
  uvar->maxLag = 0.0;
  uvar->inclAutoCorr = FALSE;
  uvar->fStart = 100.0;
  uvar->fBand = 0.1;
  /* uvar->fdotStart = 0.0; */
  /* uvar->fdotBand = 0.0; */
  uvar->alphaRad = 0.0;
  uvar->deltaRad = 0.0;
  uvar->refTime = 0.0;
  uvar->rngMedBlock = 50;
  uvar->numBins = 1;

  /* zero binary orbital parameters means not a binary */
  uvar->orbitAsiniSec = 0.0;
  uvar->orbitAsiniSecBand = 0.0;
  uvar->orbitPSec = 0.0;
  uvar->orbitPSecBand = 0.0;
  uvar->orbitTimeAsc = 0;
  uvar->orbitTimeAscBand = 0;

  /*default mismatch values */
  /* set to 0.1 by default -- for no real reason */
  /* make 0.1 a macro? */
  uvar->mismatchF = 0.1;
  uvar->mismatchA = 0.1;
  uvar->mismatchT = 0.1;
  uvar->mismatchP = 0.1;

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

  uvar->sftLocation = XLALCalloc(1, MAXFILENAMELENGTH+1);

  /* initialize number of candidates in toplist -- default is just to return the single best candidate */
  uvar->numCand = 1;
  uvar->toplistFilename = XLALStringDuplicate("toplist_crosscorr.dat");
  uvar->version = FALSE;

  /* register  user-variables */
  XLALregBOOLUserStruct  ( help, 	   'h',  UVAR_HELP, "Print this message");
  XLALregINTUserStruct   ( startTime,       0,  UVAR_REQUIRED, "Desired start time of analysis in GPS seconds");
  XLALregINTUserStruct   ( endTime,         0,  UVAR_REQUIRED, "Desired end time of analysis in GPS seconds");
  XLALregREALUserStruct  ( maxLag,          0,  UVAR_OPTIONAL, "Maximum lag time in seconds between SFTs in correlation");
  XLALregBOOLUserStruct  ( inclAutoCorr,    0,  UVAR_OPTIONAL, "Include auto-correlation terms (an SFT with itself)");
  XLALregREALUserStruct  ( fStart,          0,  UVAR_OPTIONAL, "Start frequency in Hz");
  XLALregREALUserStruct  ( fBand,           0,  UVAR_OPTIONAL, "Frequency band to search over in Hz ");
  /* XLALregREALUserStruct  ( fdotStart,     0,  UVAR_OPTIONAL, "Start value of spindown in Hz/s"); */
  /* XLALregREALUserStruct  ( fdotBand,      0,  UVAR_OPTIONAL, "Band for spindown values in Hz/s"); */
  XLALregREALUserStruct  ( alphaRad,        0,  UVAR_OPTIONAL, "Right ascension for directed search (radians)");
  XLALregREALUserStruct  ( deltaRad,        0,  UVAR_OPTIONAL, "Declination for directed search (radians)");
  XLALregREALUserStruct  ( refTime,         0,  UVAR_OPTIONAL, "SSB reference time for pulsar-parameters [Default: midPoint]");
  XLALregREALUserStruct  ( orbitAsiniSec,   0,  UVAR_OPTIONAL, "Start of search band for projected semimajor axis (seconds) [0 means not a binary]");
  XLALregREALUserStruct  ( orbitAsiniSecBand, 0,  UVAR_OPTIONAL, "Width of search band for projected semimajor axis (seconds)");
  XLALregREALUserStruct  ( orbitPSec,       0,  UVAR_OPTIONAL, "Binary orbital period (seconds) [0 means not a binary]");
  XLALregREALUserStruct  ( orbitPSecBand,       0,  UVAR_OPTIONAL, "Band for binary orbital period (seconds) ");
  XLALregREALUserStruct  ( orbitTimeAsc,    0,  UVAR_OPTIONAL, "Start of orbital time-of-ascension band in GPS seconds");
  XLALregREALUserStruct  ( orbitTimeAscBand, 0,  UVAR_OPTIONAL, "Width of orbital time-of-ascension band (seconds)");
  XLALregSTRINGUserStruct( ephemEarth,      0,  UVAR_OPTIONAL, "Earth ephemeris file to use");
  XLALregSTRINGUserStruct( ephemSun,        0,  UVAR_OPTIONAL, "Sun ephemeris file to use");
  XLALregSTRINGUserStruct( sftLocation,     0,  UVAR_REQUIRED, "Filename pattern for locating SFT data");
  XLALregINTUserStruct   ( rngMedBlock,     0,  UVAR_OPTIONAL, "Running median block size for PSD estimation");
  XLALregINTUserStruct   ( numBins,         0,  UVAR_OPTIONAL, "Number of frequency bins to include in calculation");
  XLALregREALUserStruct  ( mismatchF,       0,  UVAR_OPTIONAL, "Desired mismatch for frequency spacing");
  XLALregREALUserStruct  ( mismatchA,       0,  UVAR_OPTIONAL, "Desired mismatch for asini spacing");
  XLALregREALUserStruct  ( mismatchT,       0,  UVAR_OPTIONAL, "Desired mismatch for periapse passage time spacing");
  XLALregREALUserStruct  ( mismatchP,       0,  UVAR_OPTIONAL, "Desired mismatch for period spacing");
  XLALregREALUserStruct  ( spacingF,       0,  UVAR_OPTIONAL, "Desired frequency spacing");
  XLALregREALUserStruct  ( spacingA,       0,  UVAR_OPTIONAL, "Desired asini spacing");
  XLALregREALUserStruct  ( spacingT,       0,  UVAR_OPTIONAL, "Desired periapse passage time spacing");
  XLALregREALUserStruct  ( spacingP,       0,  UVAR_OPTIONAL, "Desired period spacing");
  XLALregINTUserStruct   ( numCand,         0,  UVAR_OPTIONAL, "Number of candidates to keep in toplist");
  XLALregSTRINGUserStruct( pairListInputFilename, 0,  UVAR_OPTIONAL, "Name of file from which to read list of SFT pairs");
  XLALregSTRINGUserStruct( pairListOutputFilename, 0,  UVAR_OPTIONAL, "Name of file to which to write list of SFT pairs");
  XLALregSTRINGUserStruct( sftListOutputFilename, 0,  UVAR_OPTIONAL, "Name of file to which to write list of SFTs (for sanity checks)");
  XLALregSTRINGUserStruct( sftListInputFilename, 0,  UVAR_OPTIONAL, "Name of file to which to read in list of SFTs (for sanity checks)");
  XLALregSTRINGUserStruct( gammaAveOutputFilename, 0,  UVAR_OPTIONAL, "Name of file to which to write aa+bb weights (for e.g., false alarm estimation)");
  XLALregSTRINGUserStruct( gammaCircOutputFilename, 0,  UVAR_OPTIONAL, "Name of file to which to write ab-ba weights (for e.g., systematic error)");
  XLALregSTRINGUserStruct( toplistFilename, 0,  UVAR_OPTIONAL, "Output filename containing candidates in toplist");
  XLALregSTRINGUserStruct( logFilename, 0,  UVAR_OPTIONAL, "Output a meta-data file for the search");
  XLALregBOOLUserStruct  ( version, 	   'V',  UVAR_SPECIAL, "Output version(VCS) information");
  if ( xlalErrno ) {
    XLALPrintError ("%s: user variable initialization failed with errno = %d.\n", __func__, xlalErrno );
    XLAL_ERROR ( XLAL_EFUNC );
  }

  return XLAL_SUCCESS;
}
Esempio n. 19
0
/**
 * 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->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->computeBSGL = 1;
  uvar->Fstar0 = -LAL_REAL4_MAX; /* corresponding to OSL limit */
  uvar->oLGX = NULL;

  uvar->sqrtSX = NULL;
  uvar->useFReg = 0;

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

  if ( (uvar->IFOs = XLALCreateStringVector ( "H1", NULL )) == NULL ) {
    LogPrintf (LOG_CRITICAL, "Call to XLALCreateStringVector() failed with xlalErrno = %d\n", xlalErrno );
    XLAL_ERROR ( XLAL_ENOMEM );
  }
  uvar->lineIFO = NULL;

  /* ---------- transient window defaults ---------- */
#define DEFAULT_TRANSIENT "rect"

  /* register all our user-variables */
  /* signal Doppler parameters */
  XLALRegisterUvarMember( Alpha, 		REAL8, 'a', OPTIONAL, "Sky position alpha (equatorial coordinates) in radians [Default:allsky]");
  XLALRegisterUvarMember( Delta, 		REAL8, 'd', OPTIONAL, "Sky position delta (equatorial coordinates) in radians [Default:allsky]");

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

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

  XLALRegisterUvarMember( AmpPriorType,	 	 INT4, 0,  OPTIONAL, "Enumeration of types of amplitude-priors: 0=physical, 1=canonical");

  XLALRegisterUvarMember( IFOs,                  STRINGVector, 'I', OPTIONAL, "Comma-separated list of detectors, eg. \"H1,H2,L1,G1, ...\" ");
  XLALRegisterUvarMember( lineIFO,             STRING, 0,  OPTIONAL, "Insert a line (signal in this one IFO, pure gaussian noise in others), e.g. \"H1\"");
  XLALRegisterUvarMember( dataStartGPS,	 	 INT4, 0,  OPTIONAL, "data start-time in GPS seconds");
  XLALRegisterUvarMember( dataDuration,	 	 INT4, 0,  OPTIONAL, "data-span to generate (in seconds)");

  /* misc params */
  XLALRegisterUvarMember( computeBSGL,		 BOOLEAN, 0, OPTIONAL, "Compute line-robust statistic (BSGL)");
  XLALRegisterUvarMember( Fstar0,		 REAL8, 0, OPTIONAL, "BSGL: transition-scale parameter 'Fstar0'");
  XLALRegisterUvarMember( oLGX,			 STRINGVector, 0, OPTIONAL, "BSGL: prior per-detector line-vs-Gauss odds, length must be numDetectors. (Defaults to oLGX=1/Ndet)");

  XLALRegisterUvarMember( sqrtSX,		 STRINGVector, 0, OPTIONAL, "Per-detector noise PSD sqrt(SX). Only ratios relevant to compute noise weights. Defaults to 1,1,...");

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

  XLALRegisterUvarMember( outputStats,	STRING, 'o', OPTIONAL, "Output file containing 'numDraws' random draws of stats");
  XLALRegisterUvarMember( outputAtoms,	 STRING, 0,  OPTIONAL, "Output F-statistic atoms into a file with this basename");
  XLALRegisterUvarMember( outputInjParams,	 STRING, 0,  OPTIONAL, "Output injection parameters into this file");
  XLALRegisterUvarMember( outputMmunuX,        	 BOOLEAN, 0,  OPTIONAL, "Write the per-IFO antenna pattern matrices into the parameter file");

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

  XLALRegisterUvarMember( ephemEarth, 	 STRING, 0,  OPTIONAL, "Earth ephemeris file to use");
  XLALRegisterUvarMember( ephemSun, 	 	 STRING, 0,  OPTIONAL, "Sun ephemeris file to use");

  XLALRegisterUvarMember( version,        	BOOLEAN, 'V', SPECIAL,  "Output code version");

  /* 'hidden' stuff */
  XLALRegisterUvarMember( TAtom,		  	  INT4, 0, 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() */
Esempio n. 20
0
// ---------- main ----------
int
main ( int argc, char *argv[] )
{
  // ---------- handle user input ----------
  UserInput_t XLAL_INIT_DECL(uvar_s);
  UserInput_t *uvar = &uvar_s;

  uvar->FstatMethod = XLALStringDuplicate("ResampBest");
  uvar->Freq = 100;
  uvar->f1dot = -3e-9;
  uvar->FreqResolution = XLALCreateREAL8Vector ( 2 );
  uvar->FreqResolution->data[0] = 1;
  uvar->FreqResolution->data[1] = 10;
  uvar->numFreqBins = XLALCreateINT4Vector ( 2 );
  uvar->numFreqBins->data[0] = 1000;
  uvar->numFreqBins->data[1] = 100000;
  uvar->Tseg = 60 * 3600;
  uvar->numSegments = 90;
  uvar->numTrials = 1;

  uvar->Tsft = 1800;
  uvar->runBuffered = 0;

  XLAL_CHECK ( (uvar->IFOs = XLALCreateStringVector ( "H1", NULL )) != NULL, XLAL_EFUNC );
  uvar->outputInfo = NULL;

  XLAL_CHECK ( XLALRegisterUvarMember ( help,           BOOLEAN,        'h', HELP,    "Print help message" ) == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALRegisterUvarMember ( FstatMethod,    STRING,         0, OPTIONAL,  XLALFstatMethodHelpString() ) == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALRegisterUvarMember ( Freq,           REAL8,          0, OPTIONAL,  "Search frequency in Hz" ) == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALRegisterUvarMember ( f1dot,          REAL8,          0, OPTIONAL,  "Search spindown f1dot in Hz/s" ) == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALRegisterUvarMember ( FreqResolution, REAL8Vector,    0, OPTIONAL,  "Range of frequency resolution factor 'r' (st dFreq = 1/(r*T)) [2-number range input]" ) == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALRegisterUvarMember ( Tseg,           REAL8,          0, OPTIONAL,  "Coherent segment length" ) == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALRegisterUvarMember ( numSegments,    INT4,           0, OPTIONAL,  "Number of semi-coherent segment" ) == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALRegisterUvarMember ( numFreqBins,    INT4Vector,     0, OPTIONAL,  "Range of number of frequency bins to search [2-number range input]" ) == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALRegisterUvarMember ( IFOs,    	STRINGVector,   0, OPTIONAL,  "IFOs to use" ) == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALRegisterUvarMember ( numTrials,    	INT4,           0, OPTIONAL,  "Number of repeated trials to run (with potentially randomized parameters)" ) == XLAL_SUCCESS, XLAL_EFUNC );

  XLAL_CHECK ( XLALRegisterUvarMember ( outputInfo,     STRING,         0, OPTIONAL, "Append Resampling internal info into this file") == XLAL_SUCCESS, XLAL_EFUNC );

  XLAL_CHECK ( XLALRegisterUvarMember ( Tsft,           REAL8,          0, DEVELOPER, "SFT length" ) == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALRegisterUvarMember ( runBuffered,    BOOLEAN,        0, DEVELOPER, "Explicitly time buffered Fstat call (only useful for double-checking and Demod timing)" ) == XLAL_SUCCESS, XLAL_EFUNC );

  XLAL_CHECK ( XLALUserVarReadAllInput(argc, argv) == XLAL_SUCCESS, XLAL_EFUNC );
  if (uvar->help) {	// if help was requested, we're done here
    return XLAL_SUCCESS;
  }
  // check user input
  XLAL_CHECK ( uvar->numSegments >= 1, XLAL_EINVAL );
  XLAL_CHECK ( (uvar->FreqResolution->length == 1) || (uvar->FreqResolution->length == 2), XLAL_EINVAL );
  XLAL_CHECK ( uvar->FreqResolution->data[0] > 0, XLAL_EINVAL );
  REAL8 FreqResolutionMin, FreqResolutionMax;
  FreqResolutionMin = FreqResolutionMax = uvar->FreqResolution->data[0];
  if ( uvar->FreqResolution->length == 2 )
    {
      XLAL_CHECK ( uvar->FreqResolution->data[1] > 0, XLAL_EINVAL );
      XLAL_CHECK ( uvar->FreqResolution->data[1] > uvar->FreqResolution->data[0], XLAL_EINVAL );
      FreqResolutionMax = uvar->FreqResolution->data[1];
    }

  XLAL_CHECK ( uvar->Freq > 0, XLAL_EINVAL );
  XLAL_CHECK ( uvar->Tseg > uvar->Tsft, XLAL_EINVAL );
  XLAL_CHECK ( uvar->Tsft > 1, XLAL_EINVAL );
  XLAL_CHECK ( (uvar->numFreqBins->length == 1) || (uvar->numFreqBins->length == 2), XLAL_EINVAL );
  XLAL_CHECK ( uvar->numFreqBins->data[0] > 0, XLAL_EINVAL );
  UINT4 numFreqBinsMax, numFreqBinsMin;
  numFreqBinsMin = numFreqBinsMax = uvar->numFreqBins->data[0];
  if ( uvar->numFreqBins->length == 2 )
    {
      XLAL_CHECK ( uvar->numFreqBins->data[1] > 0, XLAL_EINVAL );
      XLAL_CHECK ( uvar->numFreqBins->data[1] > uvar->numFreqBins->data[0], XLAL_EINVAL );
      numFreqBinsMax = uvar->numFreqBins->data[1];
    }

  XLAL_CHECK ( uvar->numTrials >= 1, XLAL_EINVAL );
  // ---------- end: handle user input ----------

  // common setup over repeated trials
  FstatMethodType FstatMethod;
  XLAL_CHECK ( XLALParseFstatMethodString ( &FstatMethod, uvar->FstatMethod ) == XLAL_SUCCESS, XLAL_EFUNC );

  EphemerisData *ephem;
  XLAL_CHECK ( (ephem = XLALInitBarycenter ( TEST_DATA_DIR "earth00-19-DE405.dat.gz", TEST_DATA_DIR "sun00-19-DE405.dat.gz" )) != NULL, XLAL_EFUNC );
  REAL8 memBase = XLALGetPeakHeapUsageMB();

  UINT4 numDetectors = uvar->IFOs->length;
  // ----- setup injection and data parameters
  LIGOTimeGPS startTime = {711595934, 0};
  LIGOTimeGPS startTime_l = startTime;
  LIGOTimeGPS endTime_l;
  SFTCatalog **catalogs;
  XLAL_CHECK ( (catalogs = XLALCalloc ( uvar->numSegments, sizeof( catalogs[0] ))) != NULL, XLAL_ENOMEM );

  for ( INT4 l = 0; l < uvar->numSegments; l ++ )
    {
      endTime_l = startTime_l;
      XLALGPSAdd( &endTime_l, uvar->Tseg );
      MultiLIGOTimeGPSVector *multiTimestamps;
      XLAL_CHECK ( (multiTimestamps = XLALMakeMultiTimestamps ( startTime_l, uvar->Tseg, uvar->Tsft, 0, numDetectors )) != NULL, XLAL_EFUNC );
      XLAL_CHECK ( (catalogs[l] = XLALMultiAddToFakeSFTCatalog ( NULL, uvar->IFOs, multiTimestamps )) != NULL, XLAL_EFUNC );
      XLALDestroyMultiTimestamps ( multiTimestamps );
      startTime_l = endTime_l;
    } // for l < numSegments
  LIGOTimeGPS endTime = endTime_l;
  UINT4 numSFTsPerSeg = catalogs[0]->length;

  FILE *fpInfo = NULL;
  if ( (uvar->outputInfo != NULL) && (FstatMethod == FMETHOD_RESAMP_GENERIC) )
    {
      XLAL_CHECK ( (fpInfo = fopen (uvar->outputInfo, "ab")) != NULL, XLAL_ESYS, "Failed to open '%s' for appending\n", uvar->outputInfo );
      XLALAppendResampInfo2File ( fpInfo, NULL ); // create header comment line
    }

  PulsarSpinRange XLAL_INIT_DECL(spinRange);
  LIGOTimeGPS refTime = { startTime.gpsSeconds - 2.3 * uvar->Tseg, 0 };
  spinRange.refTime = refTime;
  spinRange.fkdot[0] = uvar->Freq;
  spinRange.fkdot[1] = uvar->f1dot;
  spinRange.fkdotBand[1] = 0;
  REAL8 asini = 0, Period = 0, ecc = 0;
  REAL8 minCoverFreq, maxCoverFreq;

  PulsarDopplerParams XLAL_INIT_DECL(Doppler);
  Doppler.refTime = refTime;
  Doppler.Alpha = 0.5;
  Doppler.Delta = 0.5;
  memcpy ( &Doppler.fkdot, &spinRange.fkdot, sizeof(Doppler.fkdot) );;
  Doppler.period = Period;
  Doppler.ecc = ecc;
  Doppler.asini = asini;

  // ----- setup optional Fstat arguments
  FstatOptionalArgs optionalArgs = FstatOptionalArgsDefaults;
  MultiNoiseFloor XLAL_INIT_DECL(injectSqrtSX);
  injectSqrtSX.length = numDetectors;
  for ( UINT4 X=0; X < numDetectors; X ++ ) {
    injectSqrtSX.sqrtSn[X] = 1;
  }
  optionalArgs.injectSqrtSX = &injectSqrtSX;
  optionalArgs.FstatMethod = FstatMethod;

  FstatWorkspace *sharedWorkspace = NULL;
  FstatInputVector *inputs;
  FstatQuantities whatToCompute = (FSTATQ_2F | FSTATQ_2F_PER_DET);
  FstatResults *results = NULL;
  REAL8 tauF1NoBuf = 0;
  REAL8 tauF1Buf = 0;
  // ---------- main loop over repeated trials ----------
  for ( INT4 i = 0; i < uvar->numTrials; i ++ )
    {
      // randomize numFreqBins
      UINT4 numFreqBins_i = numFreqBinsMin + (UINT4)round ( 1.0 * (numFreqBinsMax - numFreqBinsMin) * rand() / RAND_MAX );
      // randomize FreqResolution
      REAL8 FreqResolution_i = FreqResolutionMin + 1.0 * ( FreqResolutionMax - FreqResolutionMin ) * rand() / RAND_MAX;

      XLAL_CHECK ( (inputs = XLALCreateFstatInputVector ( uvar->numSegments )) != NULL, XLAL_EFUNC );

      REAL8 dFreq = 1.0 / ( FreqResolution_i * uvar->Tseg );

      REAL8 FreqBand = numFreqBins_i * dFreq;
      fprintf ( stderr, "trial %d/%d: Tseg = %.1f d, numSegments = %d, Freq = %.1f Hz, f1dot = %.1e Hz/s, FreqResolution r = %f, numFreqBins = %d [dFreq = %.2e Hz, FreqBand = %.2e Hz]\n",
                i+1, uvar->numTrials, uvar->Tseg / 86400.0, uvar->numSegments, uvar->Freq, uvar->f1dot, FreqResolution_i, numFreqBins_i, dFreq, FreqBand );

      spinRange.fkdotBand[0] = FreqBand;
      XLAL_CHECK ( XLALCWSignalCoveringBand ( &minCoverFreq, &maxCoverFreq, &startTime, &endTime, &spinRange, asini, Period, ecc ) == XLAL_SUCCESS, XLAL_EFUNC );

      UINT4 numBinsSFT = ceil ( (maxCoverFreq - minCoverFreq) * uvar->Tsft + 2 * 8 );
      REAL8 memSFTs = uvar->numSegments * numSFTsPerSeg * ( sizeof(SFTtype) + numBinsSFT * sizeof(COMPLEX8)) / 1e6;

      // create per-segment input structs
      for ( INT4 l = 0; l < uvar->numSegments; l ++ )
        {
          XLAL_CHECK ( (inputs->data[l] = XLALCreateFstatInput ( catalogs[l], minCoverFreq, maxCoverFreq, dFreq, ephem, &optionalArgs )) != NULL, XLAL_EFUNC );
          if ( l == 0 ) {
            sharedWorkspace = XLALGetSharedFstatWorkspace ( inputs->data[0] );
          }
          optionalArgs.sharedWorkspace = sharedWorkspace;
        }

      // ----- compute Fstatistics over segments
      REAL8 tauF1NoBuf_i = 0;
      REAL8 tauF1Buf_i = 0;
      for ( INT4 l = 0; l < uvar->numSegments; l ++ )
        {
          XLAL_CHECK ( XLALComputeFstat ( &results, inputs->data[l], &Doppler, numFreqBins_i, whatToCompute ) == XLAL_SUCCESS, XLAL_EFUNC );

          // ----- output timing details if requested
          if ( (fpInfo != NULL) ) {
            XLALAppendResampInfo2File ( fpInfo, inputs->data[l] );
          }
          REAL8 tauF1NoBuf_il, tauF1Buf_il;
          XLAL_CHECK ( XLALGetResampTimingInfo ( &tauF1NoBuf_il, &tauF1Buf_il, inputs->data[l] ) == XLAL_SUCCESS, XLAL_EFUNC );
          tauF1NoBuf_i += tauF1NoBuf_il;
          tauF1Buf_i   += tauF1Buf_il;
        } // for l < numSegments

      tauF1NoBuf_i /= uvar->numSegments;
      tauF1Buf_i   /= uvar->numSegments;
      REAL8 memMaxCompute = XLALGetPeakHeapUsageMB() - memBase;

      tauF1Buf   += tauF1Buf_i;
      tauF1NoBuf += tauF1NoBuf_i;

      fprintf (stderr, "%-15s: tauF1Buf = %.2g s, tauF1NoBuf = %.2g s, memSFTs = %.1f MB, memMaxCompute = %.1f MB\n",
               XLALGetFstatMethodName ( FstatMethod ), tauF1Buf_i, tauF1NoBuf_i, memSFTs, memMaxCompute  );

      XLALDestroyFstatInputVector ( inputs );
      XLALDestroyFstatWorkspace ( sharedWorkspace );
      optionalArgs.sharedWorkspace = NULL;

    } // for i < numTrials

  tauF1Buf   /= uvar->numTrials;
  tauF1NoBuf /= uvar->numTrials;

  fprintf (stderr, "\nAveraged timings: <tauF1Buf> = %.2g s, <tauF1NoBuf> = %.2g s\n", tauF1Buf, tauF1NoBuf );

  // ----- free memory ----------
  if ( fpInfo != NULL ) {
    fclose ( fpInfo );
  }

  for ( INT4 l = 0; l < uvar->numSegments; l ++ )
    {
      XLALDestroySFTCatalog ( catalogs[l] );
    }
  XLALFree ( catalogs );
  XLALDestroyFstatResults ( results );
  XLALDestroyUserVars();
  XLALDestroyEphemerisData ( ephem );

  LALCheckMemoryLeaks();

  return XLAL_SUCCESS;

} // main()
Esempio n. 21
0
/**
 * 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() */
void ReadInput(InputParams *inputParams, int argc, char *argv[]){
  struct LALoption long_options[] =
  {
    { "help",                     no_argument,        0, 'h' },
    { "detector",                 required_argument,  0, 'i' },
    { "channel",                  required_argument,  0, 'c' },
    { "epoch",                    required_argument,  0, 'e' },
    { "geocentre",                no_argument,        0, 'g' },
    { "duration",                 required_argument,  0, 'd' },
    { "pulsar-dir",               required_argument,  0, 'p' },
    { "output-dir",               required_argument,  0, 'o' },
    { "output-str",               required_argument,  0, 's' },
    { "ephem-dir",                required_argument,  0, 'm' },
    { "ephem-type",               required_argument,  0, 'y' },
    { "dbg-lvl",                  required_argument,  0, 'l' },
    { 0, 0, 0, 0 }
  };

  const CHAR *fn = __func__;
  CHAR args[] = "hi:c:e:gd:p:o:s:m:y:l:";
  CHAR *program = argv[0];

  /* default the debug level to 1 */

  /* default to no set the detector to the geocentre */
  inputParams->geocentre = 0;

  /* default ephemeris to use DE405 */
  inputParams->ephemType = XLALStringDuplicate( "DE405" );

  /* get input arguments */
  while(1){
    INT4 option_index = 0;
    INT4 c;

    c = LALgetopt_long( argc, argv, args, long_options, &option_index );
    if ( c == -1 ) /* end of options */
      break;

    switch(c){
      case 0: /* if option set a flag, nothing else to do */
        if ( long_options[option_index].flag )
          break;
        else
          fprintf(stderr, "Error parsing option %s with argument %s\n",
            long_options[option_index].name, LALoptarg );
      case 'h': /* help message */
        fprintf(stderr, USAGE, program);
        exit(0);
      case 'l': /* debug level */
        break;
      case 'i': /* interferometer/detector */
        inputParams->det = XLALStringDuplicate( LALoptarg );
        break;
      case 'c': /* channel name */
        inputParams->channel = XLALStringDuplicate( LALoptarg );
        break;
      case 'e': /* frame epoch */
        inputParams->epoch = atoi(LALoptarg);
        break;
      case 'g': /* geocentre flag */
        inputParams->geocentre = 1;
        break;
      case 'd': /* frame duration */
        inputParams->frDur = atoi(LALoptarg);
        break;
      case 'p': /* pulsar par file directory */
        inputParams->pulsarDir = XLALStringDuplicate( LALoptarg );
        break;
      case 'o': /* output directory */
        inputParams->outDir = XLALStringDuplicate( LALoptarg );
        break;
      case 's': /* output name string */
        inputParams->outStr = XLALStringDuplicate( LALoptarg );
        break;
      case 'm': /* ephemeris file directory */
        inputParams->ephemDir = XLALStringDuplicate( LALoptarg );
        break;
      case 'y': /* ephemeris file year */
        inputParams->ephemType = XLALStringDuplicate( LALoptarg );
        break;
      case '?':
        fprintf(stderr, "unknown error while parsing options\n" );
      default:
        fprintf(stderr, "unknown error while parsing options\n" );
    }
  }

  if( inputParams->epoch == 0 || inputParams->frDur == 0 ){
    XLALPrintError ("%s: Frame epoch or duration are 0!\n", fn );
    XLAL_ERROR_VOID ( XLAL_EFUNC );
  }
}
Esempio n. 23
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() */
Esempio n. 24
0
/** register all "user-variables" */
int
initUserVars (UserVariables_t *uvar)
{

  /* set a few defaults */
  uvar->help = FALSE;

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

  uvar->Freq = 100;
  uvar->f1dot = 0.0;
  uvar->f2dot = 0.0;
  uvar->f3dot = 0.0;
  uvar->h0 = 1;
  uvar->phi0 = 0;

  uvar->startTime.gpsSeconds = 714180733;
  uvar->duration = 10 * 3600;
  uvar->Nseg = 1;
  uvar->segmentList = NULL;

  uvar->refTime.gpsSeconds = -1;	/* default: use mid-time */

  uvar->projection = 0;
  if ( (uvar->IFOs = XLALCreateStringVector ( "H1", NULL )) == NULL ) {
    LogPrintf (LOG_CRITICAL, "Call to XLALCreateStringVector() failed with xlalErrno = %d\n", xlalErrno );
    XLAL_ERROR ( XLAL_ENOMEM );
  }

  uvar->sqrtSX = NULL;

  uvar->detMotionStr = XLALStringDuplicate(XLALDetectorMotionName(DETMOTION_SPIN | DETMOTION_ORBIT));
  uvar->metricType = 0;	/* by default: compute only phase metric */

  if ( (uvar->coords = XLALCreateStringVector ( "freq", "alpha", "delta", "f1dot", NULL )) == NULL ) {
    LogPrintf (LOG_CRITICAL, "Call to XLALCreateStringVector() failed with xlalErrno = %d\n", xlalErrno );
    XLAL_ERROR ( XLAL_ENOMEM );
  }

  uvar->approxPhase = FALSE;

  /* register all our user-variables */

  XLALRegisterUvarMember(help,		BOOLEAN, 'h', HELP,		"Print this help/usage message");
  XLALRegisterUvarMember(IFOs,		STRINGVector, 'I', OPTIONAL, 	"CSV list of detectors, eg. \"H1,H2,L1,G1, ...\" ");
  XLALRegisterUvarMember(sqrtSX,	 	 STRINGVector, 0,  OPTIONAL, 	"[for F-metric weights] CSV list of detectors' noise-floors sqrt{Sn}");
  XLALRegisterUvarMember(Alpha,		RAJ, 'a', OPTIONAL,	"Sky: equatorial J2000 right ascension (in radians or hours:minutes:seconds)");
  XLALRegisterUvarMember(Delta, 		DECJ, 'd', OPTIONAL,	"Sky: equatorial J2000 declination (in radians or degrees:minutes:seconds)");
  XLALRegisterUvarMember(Freq, 		REAL8, 'f', OPTIONAL, 	"Target frequency");
  XLALRegisterUvarMember(f1dot, 		REAL8, 's', OPTIONAL, 	"First spindown-value df/dt");
  XLALRegisterUvarMember(f2dot, 		 REAL8, 0 , OPTIONAL, 	"Second spindown-value d2f/dt2");
  XLALRegisterUvarMember(f3dot, 		 REAL8, 0 , OPTIONAL, 	"Third spindown-value d3f/dt3");

  XLALRegisterUvarMember ( orbitasini,	REAL8, 0, OPTIONAL, 	"Target projected semimajor axis of binary orbit (Units: light seconds)");
  XLALRegisterUvarMember ( orbitPeriod,	REAL8, 0, OPTIONAL, 	"Target period of binary orbit (Units: s).");
  XLALRegisterUvarMember ( orbitTp,	EPOCH, 0, OPTIONAL, 	"Target time of periapse passage of the CW source in a binary orbit (Units: GPS seconds)");
  XLALRegisterUvarMember ( orbitArgp,	REAL8, 0, OPTIONAL, 	"Target argument of periapse of binary orbit (Units: rad)");
  XLALRegisterUvarMember ( orbitEcc,	REAL8, 0, OPTIONAL, 	"Target eccentricity of binary orbit (Units: none)");

  XLALRegisterUvarMember(refTime,         EPOCH, 0,  OPTIONAL, 	"Reference epoch for phase-evolution parameters (format 'xx.yy[GPS|MJD]'). [0=startTime, default=mid-time]");
  XLALRegisterUvarMember(startTime,      EPOCH, 't', OPTIONAL, 	"Start time of observation (format 'xx.yy[GPS|MJD]')");

  XLALRegisterUvarMember(duration,	REAL8, 'T', OPTIONAL,	"Duration of observation in seconds");
  XLALRegisterUvarMember(Nseg,		INT4, 'N', OPTIONAL, 	"Compute semi-coherent metric for this number of segments within 'duration'" );
  XLALRegisterUvarMember(segmentList,   STRING, 0,  OPTIONAL,     "ALTERNATIVE: specify segment file with format: repeated lines <startGPS endGPS duration[h] NumSFTs>");
  XLALRegisterUvarMember( ephemEarth,   STRING, 0,  OPTIONAL,     "Earth ephemeris file to use");
  XLALRegisterUvarMember( ephemSun,     STRING, 0,  OPTIONAL,     "Sun ephemeris file to use");

  XLALRegisterUvarMember(h0,	 	 REAL8, 0, OPTIONAL,	"GW amplitude h0" );
  XLALRegisterUvarMember(cosi,	 	 REAL8, 0, OPTIONAL,	"Pulsar orientation-angle cos(iota) [-1,1]" );
  XLALRegisterUvarMember(psi,		 REAL8, 0, OPTIONAL,	"Wave polarization-angle psi [0, pi]" );
  XLALRegisterUvarMember(phi0,		 REAL8, 0, OPTIONAL,	"GW initial phase phi_0 [0, 2pi]" );

  XLALRegisterUvarMember(metricType,	 INT4, 0,  OPTIONAL,	"type of metric to compute: 0=phase-metric, 1=F-metric(s), 2=both" );
  XLALRegisterUvarMember(outputMetric,	STRING, 'o', OPTIONAL,	"Output the metric components (in octave format) into this file.");
  XLALRegisterUvarMember(projection,      INT4, 0,  OPTIONAL,     "Project onto subspace orthogonal to this axis: 0=none, 1=1st-coord, 2=2nd-coord etc");

  XLALRegisterUvarMember(coords,		STRINGVector, 'c', OPTIONAL, 	"Doppler-coordinates to compute metric in (see --coordsHelp)");
  XLALRegisterUvarMember(coordsHelp,      BOOLEAN, 0,  OPTIONAL,     "output help-string explaining all the possible Doppler-coordinate names for --coords");

  XLALRegisterUvarMember(detMotionStr,  STRING, 0,  DEVELOPER,	"Detector-motion string: S|O|S+O where S=spin|spinz|spinxy and O=orbit|ptoleorbit");
  XLALRegisterUvarMember(approxPhase,     BOOLEAN, 0,  DEVELOPER,	"Use an approximate phase-model, neglecting Roemer delay in spindown coordinates (or orders >= 1)");

  XLALRegisterUvarMember(version,        BOOLEAN, 'V', SPECIAL,      "Output code version");

  return XLAL_SUCCESS;

} /* initUserVars() */
Esempio n. 25
0
/**
 * 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. 26
0
/**
 * Put all the pieces together, and basically does everything:
 * get config-filename from cmd-line (if found),
 * then interpret config-file and then the command-line
 */
int
XLALUserVarReadAllInput ( int argc, char *argv[] )
{
  XLAL_CHECK ( argc > 0, XLAL_EINVAL );
  XLAL_CHECK ( argv != NULL, XLAL_EINVAL );
  XLAL_CHECK ( argv[0] != NULL, XLAL_EINVAL );
  XLAL_CHECK ( UVAR_vars.next != NULL, XLAL_EINVAL, "No UVAR memory allocated. Did you register any user-variables?" );

  program_name = argv[0];	// keep a modul-local pointer to the executable name

  // ---------- pre-process command-line: have we got a config-file ?
  CHAR* cfgfile_name = NULL;
  for ( INT4 i = 1; i < argc; i++ )
    {
      char *argi = argv[i];
      XLAL_CHECK ( argi != NULL, XLAL_EINVAL, "argc = %d, but argv[%d] == NULL!\n", argc, i );

      if ( argi[0] == '@' )
	{
	  XLAL_CHECK ( cfgfile_name == NULL, XLAL_EINVAL, "Can only handle *one* config-file passed on commandline!\n" );
	  argi ++;
          XLAL_CHECK ( (cfgfile_name = XLALStringDuplicate ( argi )) != NULL, XLAL_EFUNC );
	} // if argument starts with '@' -> config-file

    } // for i < argc

  // ---------- if config-file specified, read from that first
  if ( cfgfile_name != NULL )
    {
      XLAL_CHECK ( XLALUserVarReadCfgfile ( cfgfile_name ) == XLAL_SUCCESS, XLAL_EFUNC );
      XLALFree (cfgfile_name);
    }

  // ---------- now parse cmdline: overloads previous config-file settings
  XLAL_CHECK ( XLALUserVarReadCmdline ( argc, argv ) == XLAL_SUCCESS, XLAL_EFUNC );

  // ---------- handle special options that need some action ----------
  BOOLEAN skipCheckRequired = FALSE;
  LALUserVariable *ptr = &UVAR_vars;
  while ( (ptr=ptr->next) != NULL )
    {
      if ( (ptr->category == UVAR_CATEGORY_HELP) && ( *((BOOLEAN*)ptr->varp) ) )
	{
	  CHAR *helpstring;
	  XLAL_CHECK ( ( helpstring = XLALUserVarHelpString(argv[0])) != NULL, XLAL_EFUNC );
          printf ("\n%s\n", helpstring);
	  XLALFree (helpstring);
	  return XLAL_SUCCESS;
	} // if help requested

      // check 'special' category, which suppresses the CheckRequired test
      if ( (ptr->category == UVAR_CATEGORY_SPECIAL) && ptr->was_set ) {
	skipCheckRequired = TRUE;
      }

      // handle DEPRECATED options by outputting a warning:
      if ( ptr->category == UVAR_CATEGORY_DEPRECATED && ptr->was_set ) {
        XLALPrintError ("Option '%s' is DEPRECATED: %s\n", ptr->name, ptr->help );	// we output warning on error-level to make this very noticeable!
      }

      // handle DEPREC_ERROR options by throwing an error:
      if ( ptr->category == UVAR_CATEGORY_DEFUNCT && ptr->was_set ) {
        XLAL_ERROR ( XLAL_EINVAL, "Option '%s' is DEFUNCT: %s\n", ptr->name, ptr->help );
      }

    } // while ptr = ptr->next

  // check that all required input-variables have been specified
  if ( !skipCheckRequired ) {
    XLAL_CHECK ( XLALUserVarCheckRequired() == XLAL_SUCCESS, XLAL_EFUNC );
  }

  return XLAL_SUCCESS;

} // XLALUserVarReadAllInput()
Esempio n. 27
0
/**
 * Register all "user-variables", and initialized them from command-line and config-files
 */
int
XLALInitUserVars ( UserVariables_t *uvar, int argc, char *argv[] )
{

  XLAL_CHECK ( uvar != NULL, XLAL_EINVAL, "Invalid NULL input 'uvar'\n");
  XLAL_CHECK ( argv != NULL, XLAL_EINVAL, "Invalid NULL input 'argv'\n");

  // ---------- set a few defaults ----------
  uvar->ephemEarth = XLALStringDuplicate("earth00-19-DE405.dat.gz");
  uvar->ephemSun = XLALStringDuplicate("sun00-19-DE405.dat.gz");

  uvar->Tsft = 1800;
  uvar->fmin = 0;	/* no heterodyning by default */
  uvar->Band = 8192;	/* 1/2 LIGO sampling rate by default */

#define MISC_DEFAULT "mfdv5"
  XLAL_CHECK ( (uvar->outLabel = XLALStringDuplicate ( MISC_DEFAULT ))  != NULL, XLAL_EFUNC );

  // ---------- register all our user-variable ----------
  /* output options */
  XLALRegisterUvarMember(   outSingleSFT,       BOOLEAN, 's', OPTIONAL, "Write a single concatenated SFT file instead of individual files" );
  XLALRegisterUvarMember( outSFTdir,          STRING, 'n', OPTIONAL, "Output SFTs:  directory for output SFTs");
  XLALRegisterUvarMember(  outLabel,	         STRING, 0, OPTIONAL, "'misc' entry in SFT-filenames or 'description' entry of frame filenames" );
  XLALRegisterUvarMember( TDDfile,            STRING, 't', OPTIONAL, "Filename to output time-series into");

  XLALRegisterUvarMember( logfile,            STRING, 'l', OPTIONAL, "Filename for log-output");

  /* detectors and respective noise-floors */
  XLALRegisterUvarMember( IFOs,			STRINGVector, 'I', OPTIONAL, "CSV list of detectors, eg. \"H1,H2,L1,G1, ...\" ");
  XLALRegisterUvarMember( sqrtSX,	 	 STRINGVector, 0,  OPTIONAL, "Add Gaussian Noise: CSV list of detectors' noise-floors sqrt{Sn}");

  XLALRegisterUvarMember( ephemEarth, 	 	STRING, 0,  OPTIONAL, "Earth ephemeris file to use");
  XLALRegisterUvarMember( ephemSun, 	 	STRING, 0,  OPTIONAL, "Sun ephemeris file to use");

  /* start + duration of timeseries */
  XLALRegisterUvarMember(startTime,            EPOCH, 'G', OPTIONAL, "Start-time of requested signal in detector-frame (format 'xx.yy[GPS|MJD]')");
  XLALRegisterUvarMember(  duration,              INT4, 0,  OPTIONAL, "Duration of requested signal in seconds");
  XLALRegisterUvarMember( timestampsFiles,       STRINGVector, 0,  OPTIONAL, "ALTERNATIVE: File to read timestamps from (file-format: lines with <seconds> <nanoseconds>)");

  /* sampling and heterodyning frequencies */
  XLALRegisterUvarMember(  fmin,                 REAL8, 0, OPTIONAL, "Lowest frequency in output SFT (= heterodyning frequency)");
  XLALRegisterUvarMember(  Band,                 REAL8, 0, OPTIONAL, "Bandwidth of output SFT in Hz (= 1/2 sampling frequency)");

  /* SFT properties */
  XLALRegisterUvarMember(  Tsft,                 REAL8, 0, OPTIONAL, "Time baseline of one SFT in seconds");
  XLALRegisterUvarMember(  SFToverlap,           REAL8, 0, OPTIONAL, "Overlap between successive SFTs in seconds (conflicts with --noiseSFTs or --timestampsFiles)");
  XLALRegisterUvarMember( SFTWindowType,        STRING, 0, OPTIONAL, "Window function to be applied to the SFTs (required when using --noiseSFTs)");
  XLALRegisterUvarMember(  SFTWindowBeta,        REAL8, 0, OPTIONAL, "Window 'beta' parameter required for a few window-types (eg. 'tukey')");

  /* pulsar params */
  XLALRegisterUvarMember( injectionSources,     STRINGVector, 0, OPTIONAL,  "Source parameters to inject: comma-separated list of file-patterns and/or direct config-strings ('{...}')" );

  /* noise */
  XLALRegisterUvarMember( noiseSFTs,          STRING, 'D', OPTIONAL, "Noise-SFTs to be added to signal (Used also to set IFOs and timestamps)");

  /* frame input/output options */
#ifdef HAVE_LIBLALFRAME
  XLALRegisterUvarMember ( outFrameDir,	  STRING,      'F', OPTIONAL,  "Output Frames: directory for output timeseries frame files");
  XLALRegisterUvarMember ( inFrames, 	  STRINGVector,'C', OPTIONAL,  "CSV list (one per IFO) of input frame cache files");
  XLALRegisterUvarMember ( inFrChannels,  STRINGVector,'N', OPTIONAL,  "CSV list (one per IFO) of frame channels to read timeseries from");
  XLALRegisterUvarMember ( outFrChannels, STRINGVector, 0,  NODEFAULT, "CSV list (one per IFO) of output frame channel names [default: <inFrChannels>-<outLabel> or <IFO>:<outLabel>]");
#else
  XLALRegisterUvarMember ( outFrameDir,	 STRING,       'F', DEFUNCT, "Need to compile with lalframe support for this option to work");
  XLALRegisterUvarMember ( inFrames,     STRINGVector, 'C', DEFUNCT, "Need to compile with lalframe support for this option to work");
  XLALRegisterUvarMember ( inFrChannels, STRINGVector, 'N', DEFUNCT, "Need to compile with lalframe support for this option to work");
  XLALRegisterUvarMember ( outFrChannels, STRINGVector, 0,  DEFUNCT, "Need to compile with lalframe support for this option to work");
#endif

  XLALRegisterUvarMember(  version,             BOOLEAN, 'V', SPECIAL, "Output version information");

  // ----- 'expert-user/developer' options ----- (only shown in help at lalDebugLevel >= warning)
  XLALRegisterUvarMember(   randSeed,             INT4, 0, DEVELOPER, "Specify random-number seed for reproducible noise (0 means use /dev/urandom for seeding).");

  // ----- deprecated but still supported options [throw warning if used] (only shown in help at lalDebugLevel >= info) ----------
#ifdef HAVE_LIBLALFRAME
  XLALRegisterUvarMember ( TDDframedir,	STRING,  0,  DEPRECATED, "Use --outFrameDir instead");
#else
  XLALRegisterUvarMember ( TDDframedir,	 STRING, 0,  DEFUNCT,   "Need to compile with lalframe support. BUT this option is deprecated and --outFrameDir should be used instead");
#endif
  // ----- obsolete and unsupported options [throw error if used] (never shown in help) ----------


  /* read cmdline & cfgfile  */
  BOOLEAN should_exit = 0;
  XLAL_CHECK( XLALUserVarReadAllInput( &should_exit, argc, argv ) == XLAL_SUCCESS, XLAL_EFUNC );
  if ( should_exit ) {
    exit (1);
  }

  return XLAL_SUCCESS;

} /* XLALInitUserVars() */
Esempio n. 28
0
int main(int argc, char **argv){
  CHAR *filename = NULL;
  INT4 gzip = 0, gunzip = 0;

  struct LALoption long_options[] =
  {
    { "help",      no_argument,        0, 'h' },
    { "file",      required_argument,  0, 'f' },
    { "gzip",      no_argument,     NULL, 'g' },
    { "guzip",     no_argument,     NULL, 'u' },
    { 0, 0, 0, 0 }
  };

  CHAR args[] = "hf:gu";
  CHAR *program = argv[0];

  /* get input arguments */
  while(1){
    int option_index = 0;
    int c;

    c = LALgetopt_long( argc, argv, args, long_options, &option_index );
    if ( c == -1 ) /* end of options */
      break;

    switch(c){
      case 0: /* if option set a flag, nothing else to do */
        if ( long_options[option_index].flag )
          break;
        else
          fprintf(stderr, "Error parsing option %s with argument %s\n", long_options[option_index].name, LALoptarg );
      case 'h': /* help message */
        fprintf(stderr, USAGE, program);
        exit(0);
      case 'f': /* input file */
        filename = XLALStringDuplicate( LALoptarg );
        break;
      case 'g': /* gzip the file */
        gzip = 1;
        break;
      case 'u': /* gunzip the file */
        gunzip = 1;
        break;
      case '?':
        fprintf(stderr, "Unknown error while parsing options\n" );
        exit(0);
      default:
        fprintf(stderr, "Unknown error while parsing options\n" );
        exit(0);
    }
  }

  if ( filename == NULL ){
    fprintf(stderr, "Must specify an input file\n");
    fprintf(stderr, USAGE, program);
    exit(0);
  }

  if ( ( !gzip && !gunzip ) || ( gzip && gunzip ) ){
    fprintf(stderr, "Must specify whether you want to either gzip (-g) or gunzip (-u) the input file.\n");
    fprintf(stderr, USAGE, program);
    exit(0);
  }

  if ( gzip ){
    /* zip the file */
    if ( XLALGzipTextFile( filename ) != XLAL_SUCCESS ){
      fprintf(stderr, "Gzip of %s has failed\n", filename);
      exit(1);
    }
  }
  if ( gunzip ){
    /* unzip the file */
    if ( XLALGunzipTextFile( filename ) != XLAL_SUCCESS ){
      fprintf(stderr, "Guzip of %s has failed\n", filename);
      exit(1);
    }
  }

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

  MJDTime TrefTDBMJD;
  LIGOTimeGPS TrefSSB_TDB_GPS;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    } // for i < n

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

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

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

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

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

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

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

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

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

  return XLAL_SUCCESS;

} /* main() */
Esempio n. 30
0
/**
 * \brief Automatically set the solar system ephemeris file based on environment variables and data time span
 *
 * This function will attempt to find Earth and Sun ephemeris files based on LAL environment variables (as set up by
 * <code> lalpulsar-user-env.(c)sh </code>) and a given start and end GPS time (presumably taken from the data that is
 * to be analysed). It requires \c LALPULSAR is installed and the \c LALPULSAR_PREFIX variable is set, which should mean
 * that ephemeris files are installed in the directory \c ${LALPULSAR_PREFIX}/share/lalpulsar/.
 *
 * \param efile [in] a string that will return the Earth ephemeris file
 * \param sfile [in] a string that will return the Sun ephemeris file
 * \param tfile [in] a string that will return the time correction file
 * \param pulsar [in] the pulsar parameters read from a .par file
 * \param gpsstart [in] the GPS time of the start of the data
 * \param gpsend [in] the GPS time of the end of the data
 *
 * \return The TimeCorrectionType e.g. TDB or TCB
 */
TimeCorrectionType XLALAutoSetEphemerisFiles( CHAR *efile, CHAR *sfile, CHAR *tfile, BinaryPulsarParams  pulsar,
                                              INT4 gpsstart, INT4 gpsend ){
  /* set the times that the ephemeris files span */
  INT4 ephemstart = 630720013; /* GPS time of Jan 1, 2000, 00:00:00 UTC */
  INT4 ephemend = 1261872015; /* GPS time of Jan 1, 2020, 00:00:00 UTC */
  CHAR *eftmp = NULL, *sftmp = NULL, *tftmp = NULL;
  TimeCorrectionType ttype = TIMECORRECTION_NONE;

  CHAR *lalpath = NULL, *lalpulsarpath = NULL;

  if( gpsstart < ephemstart || gpsend < ephemstart || gpsstart > ephemend || gpsend > ephemend ){
    XLALPrintError("Start and end times are outside the ephemeris file ranges!\n");
    XLAL_ERROR(XLAL_EFUNC);
  }

  /* first check that the path to the Ephemeris files is available in the
     environment variables */
  if((lalpath = getenv("LALPULSAR_PREFIX")) == NULL){
    XLALPrintError("LALPULSAR_PREFIX environment variable not set. Cannot automatically generate ephemeris files!\n");
    XLAL_ERROR(XLAL_EFUNC);
  }

  lalpulsarpath = XLALStringDuplicate( lalpath );

  if ( (lalpulsarpath = XLALStringAppend(lalpulsarpath, "/share/lalpulsar/")) == NULL ) { XLAL_ERROR(XLAL_EFUNC); }

  eftmp = XLALStringDuplicate(lalpulsarpath);
  sftmp = XLALStringDuplicate(lalpulsarpath);
  tftmp = XLALStringDuplicate(lalpulsarpath);

  eftmp = XLALStringAppend(eftmp, "earth00-19-");
  sftmp = XLALStringAppend(sftmp, "sun00-19-");

  if( pulsar.ephem == NULL ){
    /* default to use DE405 */
    eftmp = XLALStringAppend(eftmp, "DE405");
    sftmp = XLALStringAppend(sftmp, "DE405");
  }
  else{
    if( !strcmp(pulsar.ephem, "DE405") || !strcmp(pulsar.ephem, "DE200") ||
        !strcmp(pulsar.ephem, "DE414") ){
      eftmp = XLALStringAppend(eftmp, pulsar.ephem);
      sftmp = XLALStringAppend(sftmp, pulsar.ephem);
    }
    else{
      XLALPrintError("Unknown ephemeris %s in par file\n", pulsar.ephem);
      XLAL_ERROR(XLAL_EFUNC);
    }
  }

  /* add .dat extension */
  eftmp = XLALStringAppend(eftmp, ".dat.gz");
  sftmp = XLALStringAppend(sftmp, ".dat.gz");

  if ( eftmp == NULL || sftmp == NULL ) { XLAL_ERROR(XLAL_EFUNC); }

  XLALStringCopy( efile, eftmp, strlen(eftmp)+1 );
  XLALStringCopy( sfile, sftmp, strlen(sftmp)+1 );

  /* double check that the files exist */
  if( fopen(sfile, "r") == NULL || fopen(efile, "r") == NULL ){
    XLALPrintError("Error... ephemeris files not, or incorrectly, defined!\n");
    XLAL_ERROR(XLAL_EFUNC);
  }

  if( pulsar.units == NULL ){
    /* default to using TCB units */
    tftmp = XLALStringAppend(tftmp, "te405_2000-2019.dat.gz");
    ttype = TIMECORRECTION_TCB;
  }
  else{
    if ( !strcmp( pulsar.units, "TDB" ) ){
      tftmp = XLALStringAppend(tftmp, "tdb_2000-2019.dat.gz");
      ttype = TIMECORRECTION_TDB;
    }
    else{
      XLALPrintError("Error... unknown units %s in par file!\n", pulsar.units);
      XLAL_ERROR(XLAL_EFUNC);
    }
  }

  if ( tftmp == NULL ) { XLAL_ERROR(XLAL_EFUNC); }

  XLALStringCopy( tfile, tftmp, strlen(tftmp)+1 );

  if( fopen(tfile, "r") == NULL ){
    XLALPrintError("Error... time ephemeris files not, or incorrectly, defined!\n");
    XLAL_ERROR(XLAL_EFUNC);
  }

  return ttype;
}