Exemple #1
0
int parseargs( int argc, char **argv )
{
	struct LALoption long_options[] = {
			{ "help", no_argument, 0, 'h' },
			{ "geo", no_argument, 0, 'G' },
			{ "hanford", no_argument, 0, 'H' },
			{ "livingston", no_argument, 0, 'L' },
			{ "virgo", no_argument, 0, 'V' },
			{ "start-time", required_argument, 0, 's' },
			{ "duration", required_argument, 0, 't' },
			{ "sample-rate", required_argument, 0, 'r' },
			{ "Omega0", required_argument, 0, 'W' },
			{ "low-frequency", required_argument, 0, 'f' },
			{ 0, 0, 0, 0 }
		};
	char args[] = "hGHLVs:t:r:W:f:";
	while (1) {
		int option_index = 0;
		int c;
	
		c = LALgetopt_long_only(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);
					exit(1);
				}
			case 'h': /* help */
				usage(argv[0]);
				exit(0);
			case 'G': /* geo */
				detectors[numDetectors++] = lalCachedDetectors[LAL_GEO_600_DETECTOR];
				break;
			case 'H': /* hanford */
				detectors[numDetectors++] = lalCachedDetectors[LAL_LHO_4K_DETECTOR];
				break;
			case 'L': /* livingston */
				detectors[numDetectors++] = lalCachedDetectors[LAL_LLO_4K_DETECTOR];
				break;
			case 'V': /* livingston */
				detectors[numDetectors++] = lalCachedDetectors[LAL_VIRGO_DETECTOR];
				break;
			case 's': /* start-time */
				tstart = atof(LALoptarg);
				break;
			case 't': /* duration */
				duration = atof(LALoptarg);
				break;
			case 'r': /* sample-rate */
				srate = atof(LALoptarg);
				break;
			case 'W': /* Omega0 */
				Omega0 = atof(LALoptarg);
				break;
			case 'f': /* low-frequency */
				flow = atof(LALoptarg);
				break;
			case '?':
			default:
				fprintf(stderr, "unknown error while parsing options\n");
				exit(1);
		}
	}
	
	if ( LALoptind < argc ) {
		fprintf(stderr, "extraneous command line arguments:\n");
		while (LALoptind < argc)
			fprintf(stderr, "%s\n", argv[LALoptind++]);
		exit(1);
	}

	if (duration == 0.0 || Omega0 == 0.0) {
		fprintf(stderr, "must select a duration and a value of Omega0\n");
		usage(argv[0]);
		exit(1);
	}
	
	return 0;
}
/*
 * Averager Routines
 */
void
LALappsTSAInitialize(
    int               argc,
    char*             argv[],
    TSAparams        *params)
{
    int C;

    struct LALoption long_options[] =
    {
        {"map_cache",            required_argument,  0,   'a'},
        {"new_t_bins",           required_argument,  0,   'b'},
        {"new_f_bins",           required_argument,  0,   'c'},
        {"merge_maps",           no_argument,        0,   'd'},
        {"multi_cache",          required_argument,  0,   'e'},
        {0,                      0,                  0,     0}
    };

    /*
     * Default Arguements
     */
    params->cacheFilename=NULL;
    params->multiCacheFilename=NULL;
    params->operation=Unknown;
    params->colParams.averageTBins=-1;
    params->colParams.averageFBins=-1;
    params->colParams.newTDim=-1;
    params->colParams.newFDim=-1;
    params->verbosity=printFiles;

    if (argc < TRACKSEARCHAVERAGERC_NARGS ) /* Not enough arguments to run */
    {
        fprintf(stderr,TRACKSEARCHAVERAGERC_MSGEARGS);
        fprintf(stderr,"\n");
        exit(TRACKSEARCHAVERAGERC_EARGS);
    }

    while (TRUE)
    {
        int option_index=0;
        C = LALgetopt_long_only(argc,
                                argv,
                                "a:b:c:d",
                                long_options,
                                &option_index);
        if ( C == -1)
        {
            break;
        }
        switch( C )
        {
        case 0 :
            if ( long_options[option_index].flag != 0 )
            {
                break;
            }
            else
            {
                fprintf(stderr, "error parsing option %s with argument %s\n",
                        long_options[option_index].name, LALoptarg );
                exit( 1 );
            }
            break;

        case 'a':
        {
            params->cacheFilename=XLALCreateCHARVector(maxFilenameLength);
            strcpy(params->cacheFilename->data,LALoptarg);
        }
        break;

        case 'b':
        {
            params->colParams.newTDim=(UINT4) atoi(LALoptarg);
        }
        break;

        case 'c':
        {
            params->colParams.newFDim=(UINT4) atoi(LALoptarg);
        }
        break;

        case 'd':
        {
            params->operation=Merge;
        }
        break;

        case 'e':
        {
            /*
             * If we are sending a txt cache of cache's
             */
            params->multiCacheFilename=XLALCreateCHARVector(maxFilenameLength);
            strcpy(params->multiCacheFilename->data,LALoptarg);
        }
        break;

        default :
        {
            fprintf(stderr,TRACKSEARCHAVERAGERC_MSGEMISC);
            exit(TRACKSEARCHAVERAGERC_EMISC);
        }
        break;
        }
    }
    /*
     * Simple argument consistency checking
     */
    LALappsTSassert((
                        (params->cacheFilename != NULL)
                        ||
                        (params->multiCacheFilename != NULL)
                    ),
                    TRACKSEARCHAVERAGERC_EVAL,
                    TRACKSEARCHAVERAGERC_MSGEVAL);

    return;
}
Exemple #3
0
int main( int argc, char *argv[] )
{
  /* lal initialization variables */
  static LALStatus stat;

  /*  program option variables */
  char *inputFileName = NULL;
  char *outputFileName = NULL;


  /* frame data structures */
  FrFile *iFile;
  FrEvent *frameEvent = NULL;
  FrSimEvent *frSimEvent = NULL;

  double tStart;
  double tEnd;
  double duration;
  double snrMin = SNR_MIN;
  double snrMax = SNR_MAX;

  double simMin = SIM_MIN;
  double simMax = SIM_MAX;

  int numEvt = 0;
  int numSim = 0;
  /* xml data structures */

  SnglInspiralTable    *snglInspiralEvent = NULL;
  SnglInspiralTable    *snglEvt = NULL;

  SimInspiralTable     *simInspiralEvent = NULL;
  SimInspiralTable     *simEvt = NULL;

  LIGOLwXMLStream       xmlStream;
  MetadataTable         outputTable;
  MetadataTable         searchsumm;

  /*
   *
   * parse command line arguments
   *
   */


  while (1)
  {
    /* LALgetopt arguments */
    static struct LALoption long_options[] = 
    {
      {"help",                    no_argument,            0,              'h'},
      {"input",                   required_argument,      0,              'i'},
      {"output",                  required_argument,      0,              'o'},
      {"snr-threshold",           required_argument,      0,              's'},
      {"ifo",                     required_argument,      0,              'd'},
      {0, 0, 0, 0}
    };
    int c;

    /* LALgetopt_long stores the option index here. */
    int option_index = 0;
    size_t LALoptarg_len;

    c = LALgetopt_long_only ( argc, argv, "hi:o:s:",
        long_options, &option_index );

    /* detect the end of the options */
    if ( c == - 1 )
      break;

    switch ( c )
    {
      case 0:
        /* if this option set a flag, do nothing else now */
        if ( long_options[option_index].flag != 0 )
        {
          break;
        }
        else
        {
          fprintf( stderr, "error parsing option %s with argument %s\n",
              long_options[option_index].name, LALoptarg );
          exit( 1 );
        }
        break;

      case 'h':
        fprintf( stdout, USAGE );
        exit( 0 );
        break;

      case 'i':
        /* create storage for the input file name */
        LALoptarg_len = strlen( LALoptarg ) + 1;
        inputFileName = (CHAR *) calloc( LALoptarg_len, sizeof(CHAR));
        memcpy( inputFileName, LALoptarg, LALoptarg_len );
        break;

      case 'o':
        /* create storage for the output file name */
        LALoptarg_len = strlen( LALoptarg ) + 1;
        outputFileName = (CHAR *) calloc( LALoptarg_len, sizeof(CHAR));
        memcpy( outputFileName, LALoptarg, LALoptarg_len );
        break;

    case 'd':
        /* create storage for the output file name */
        LALoptarg_len = strlen( LALoptarg ) + 1;
        ifo = (CHAR *) calloc( LALoptarg_len, sizeof(CHAR));
        memcpy( ifo, LALoptarg, LALoptarg_len );
        break;

      case 's':
        snrMin = (double) atof( LALoptarg );
        if ( snrMin < 0 )
        {
          fprintf( stdout, "invalid argument to --%s:\n"
              "threshold must be >= 0: "
              "(%f specified)\n",
              long_options[option_index].name, snrMin );
          exit( 1 );
        }
        break;

      case '?':
        exit( 1 );
        break;

      default:
        fprintf( stderr, "unknown error while parsing options\n" );
        exit( 1 );
    }   
  }

  if ( LALoptind < argc )
  {
    fprintf( stderr, "extraneous command line arguments:\n" );
    while ( LALoptind < argc )
    {
      fprintf ( stderr, "%s\n", argv[LALoptind++] );
    }
    exit( 1 );
  }

  /*
   *
   * read in the triggers from the input frame file
   *
   */

  iFile = FrFileINew(inputFileName);

  /* set start time, duration and amplitude window 
     this should be turned into command line arguments */

  tStart   = FrFileITStart(iFile);
  tEnd     = FrFileITEnd(iFile);
  duration = tEnd - tStart;

  /* read in the events */
  frameEvent = FrEventReadT(iFile, ignore_const("*clustered"), tStart, duration, 
      snrMin, snrMax);


  /*Write out details of events to SnglInspiralTable*/
  numEvt = frEvent2snglInspiral( &snglInspiralEvent, frameEvent); 

  fprintf( stdout, "Read in %d triggers from frEvent structure in %s\n",
      numEvt, inputFileName );
  
  /* free the frame events */
  FrEventFree(frameEvent);


  /*
   *
   * read in the simEvent from the input frame file
   *
   */

  frSimEvent  = FrSimEventReadT (iFile, ignore_const("cb*"), tStart, duration, 
      simMin, simMax);

  /*Write out details of events to SnglInspiralTable*/
  numSim = frSimEvent2simInspiral( &simInspiralEvent, frSimEvent); 

  fprintf( stdout, "Read in %d injections from frEvent structure in %s\n",
      numSim, inputFileName );

  /* free the frame events */
  FrSimEventFree(frSimEvent);


        /* 
         *
         * write a search summary table
         *
         */

        /* create the search summary and zero out the summvars table */
  searchsumm.searchSummaryTable = (SearchSummaryTable *)
    calloc( 1, sizeof(SearchSummaryTable) );

          
        /* create the search summary and zero out the summvars table */
  searchsumm.searchSummaryTable = (SearchSummaryTable *)
    calloc( 1, sizeof(SearchSummaryTable) );

        searchsumm.searchSummaryTable->in_start_time.gpsSeconds = tStart;
  searchsumm.searchSummaryTable->in_end_time.gpsSeconds = tEnd;
  
  searchsumm.searchSummaryTable->out_start_time.gpsSeconds = tStart;
        searchsumm.searchSummaryTable->out_end_time.gpsSeconds = tEnd;
  searchsumm.searchSummaryTable->nnodes = 1;
        if (numEvt)
        {
          searchsumm.searchSummaryTable->nevents = numEvt;
        }
        else if (numSim)
        {
          searchsumm.searchSummaryTable->nevents = numSim;
        }
        

  /*
   *
   * write output data to xml file
   *
   */

  /* write xml output file */
  memset( &xmlStream, 0, sizeof(LIGOLwXMLStream) );
  LALOpenLIGOLwXMLFile( &stat, &xmlStream, outputFileName );

        /* Write search_summary table */
    LALBeginLIGOLwXMLTable( &stat, &xmlStream, 
          search_summary_table );
    LALWriteLIGOLwXMLTable( &stat, &xmlStream, searchsumm, 
          search_summary_table );
    LALEndLIGOLwXMLTable ( &stat, &xmlStream );


  /* Write the results to the inspiral table */
  if ( snglInspiralEvent )
  {
    outputTable.snglInspiralTable = snglInspiralEvent;
    LALBeginLIGOLwXMLTable( &stat, &xmlStream, sngl_inspiral_table );
    LALWriteLIGOLwXMLTable( &stat, &xmlStream, outputTable, 
        sngl_inspiral_table );
    LALEndLIGOLwXMLTable( &stat, &xmlStream );
  }

  /* Write the results to the sim inspiral table */
  if ( simInspiralEvent )
  {
    outputTable.simInspiralTable = simInspiralEvent;
    LALBeginLIGOLwXMLTable( &stat, &xmlStream, sim_inspiral_table );
    LALWriteLIGOLwXMLTable( &stat, &xmlStream, outputTable, 
        sim_inspiral_table );
    LALEndLIGOLwXMLTable( &stat, &xmlStream );
  }

  /* close the output file */
  LALCloseLIGOLwXMLFile(&stat, &xmlStream);


  /*
   *
   * free memory and exit
   *
   */


  /* free the inspiral events we saved */
  while ( snglInspiralEvent )
  {
    snglEvt = snglInspiralEvent;
    snglInspiralEvent = snglInspiralEvent->next;
    LALFree( snglEvt );
  }

  /* free the sim inspiral events we saved */
  while ( simInspiralEvent )
  {
    simEvt = simInspiralEvent;
    simInspiralEvent = simInspiralEvent->next;
    LALFree( simEvt );
  }

  LALCheckMemoryLeaks();
  exit( 0 );
}
Exemple #4
0
int main( int argc, char *argv[] )
{
  static LALStatus      status;

  LALPlaygroundDataMask  dataType = unspecified_data_type;
  SnglInspiralParameterTest  test = unspecified_test;

  INT4  startTime = -1;
  LIGOTimeGPS startTimeGPS = {0,0};
  INT4  endTime = -1;
  LIGOTimeGPS endTimeGPS = {0,0};
  INT4  startChunkTime = -1;
  LIGOTimeGPS startChunkTimeGPS = {0,0};
  INT4  endChunkTime = -1;
  LIGOTimeGPS endChunkTimeGPS = {0,0};
  int   coherentRun = 0;
  INT4  coherentBuffer = 64;
  CHAR  inputIFO[LIGOMETA_IFO_MAX];
  CHAR  outputIFO[LIGOMETA_IFO_MAX];
  CHAR  comment[LIGOMETA_COMMENT_MAX];
  CHAR *userTag = NULL;
  CHAR *ifoTag = NULL;

  CHAR  fileName[FILENAME_MAX];

  INT4  numTriggers = 0;

  SnglInspiralTable    *inspiralEventList=NULL;
  SnglInspiralTable    *currentTrigger = NULL;

  SearchSummvarsTable  *inputFiles = NULL;
  SearchSummvarsTable  *thisInputFile = NULL;

  SearchSummaryTable   *searchSummList = NULL;
  SearchSummaryTable   *thisSearchSumm = NULL;

  MetadataTable         proctable;
  MetadataTable         processParamsTable;
  MetadataTable         searchsumm;
  MetadataTable         searchSummvarsTable;
  MetadataTable         inspiralTable;
  ProcessParamsTable   *this_proc_param = NULL;
  LIGOLwXMLStream       xmlStream;
  INT4                  outCompress = 0;

  INT4                  i;

  /* LALgetopt arguments */
  struct LALoption long_options[] =
  {
    {"verbose",                no_argument,     &vrbflg,                  1 },
    {"check-times",            no_argument, &checkTimes,                  1 },
    {"write-compress",         no_argument,           &outCompress,       1 },
    {"input-ifo",              required_argument,     0,                 'a'},
    {"output-ifo",             required_argument,     0,                 'b'},
    {"parameter-test",         required_argument,     0,                 'A'},
    {"data-type",              required_argument,     0,                 'D'},
    {"gps-start-time",         required_argument,     0,                 'q'},
    {"gps-end-time",           required_argument,     0,                 'r'},
    {"comment",                required_argument,     0,                 's'},
    {"coherent-run",           no_argument,           &coherentRun,       1 },
    {"coherent-buffer",        required_argument,     &coherentBuffer,   't'},
    {"user-tag",               required_argument,     0,                 'Z'},
    {"userTag",                required_argument,     0,                 'Z'},
    {"ifo-tag",                required_argument,     0,                 'I'},
    {"help",                   no_argument,           0,                 'h'},
    {"version",                no_argument,           0,                 'V'},
    {0, 0, 0, 0}
  };
  int c;

  /*
   * 
   * initialize things
   *
   */

  lal_errhandler = LAL_ERR_EXIT;
  setvbuf( stdout, NULL, _IONBF, 0 );

  /* create the process and process params tables */
  proctable.processTable = (ProcessTable *) calloc( 1, sizeof(ProcessTable) );
  XLALGPSTimeNow(&(proctable.processTable->start_time));
  XLALPopulateProcessTable(proctable.processTable, PROGRAM_NAME, lalAppsVCSIdentId,
      lalAppsVCSIdentStatus, lalAppsVCSIdentDate, 0);
  this_proc_param = processParamsTable.processParamsTable = 
    (ProcessParamsTable *) calloc( 1, sizeof(ProcessParamsTable) );
  memset( comment, 0, LIGOMETA_COMMENT_MAX * sizeof(CHAR) );

  /* create the search summary and zero out the summvars table */
  searchsumm.searchSummaryTable = (SearchSummaryTable *)
    calloc( 1, sizeof(SearchSummaryTable) );


  /* parse the arguments */
  while ( 1 )
  {
    /* LALgetopt_long stores long option here */
    int option_index = 0;
    long int gpstime;
    size_t LALoptarg_len;

    c = LALgetopt_long_only( argc, argv,
        "a:b:hq:r:s:t:A:I:VZ:", long_options,
        &option_index );

    /* detect the end of the options */
    if ( c == -1 )
    {
      break;
    }

    switch ( c )
    {
      case 0:
        /* if this option set a flag, do nothing else now */
        if ( long_options[option_index].flag != 0 )
        {
          break;
        }
        else
        {
          fprintf( stderr, "Error parsing option %s with argument %s\n",
              long_options[option_index].name, LALoptarg );
          exit( 1 );
        }
        break;

      case 'a':
        /* name of input ifo*/
        strncpy( inputIFO, LALoptarg, LIGOMETA_IFO_MAX );
        ADD_PROCESS_PARAM( "string", "%s", LALoptarg );
        break;

      case 'b':
        /* name of output ifo */
        strncpy( outputIFO, LALoptarg, LIGOMETA_IFO_MAX );
        ADD_PROCESS_PARAM( "string", "%s", LALoptarg );
        break;

      case 'A':
        /* comparison used to test for uniqueness of triggers */
        if ( ! strcmp( "m1_and_m2", LALoptarg ) )
        {
          test = m1_and_m2;
        }
        else if ( ! strcmp( "psi0_and_psi3", LALoptarg ) )
        {
          test = psi0_and_psi3;
        }
        else if ( ! strcmp( "mchirp_and_eta", LALoptarg ) )
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "mchirp_and_eta test specified, not implemented for trigbank: "
              "%s (must be m1_and_m2, psi0_and_psi3, no_test)\n",
              long_options[option_index].name, LALoptarg );
          exit( 1 );
        }
        else if ( ! strcmp( "no_test", LALoptarg ) )
        {
          test = no_test;
        }
        else
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "unknown test specified: "
              "%s (must be m1_and_m2, psi0_and_psi3,no_test, or mchirp_and_eta)\n",
              long_options[option_index].name, LALoptarg );
          exit( 1 );
        }
        ADD_PROCESS_PARAM( "string", "%s", LALoptarg );
        break;


      case 'D':
        /* type of data to analyze */
        if ( ! strcmp( "playground_only", LALoptarg ) )
        {
          dataType = playground_only;
        }
        else if ( ! strcmp( "exclude_play", LALoptarg ) )
        {
          dataType = exclude_play;
        }
        else if ( ! strcmp( "all_data", LALoptarg ) )
        {
          dataType = all_data;
        }
        else
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "unknown data type, %s, specified: "
              "(must be playground_only, exclude_play or all_data)\n",
              long_options[option_index].name, LALoptarg );
          exit( 1 );
        }
        ADD_PROCESS_PARAM( "string", "%s", LALoptarg );
        break;

      case 'q':
        /* start time */
        gpstime = atol( LALoptarg );
        if ( gpstime < 441417609 )
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "GPS start time is prior to " 
              "Jan 01, 1994  00:00:00 UTC:\n"
              "(%ld specified)\n",
              long_options[option_index].name, gpstime );
          exit( 1 );
        }
        startTime = (INT4) gpstime;
        startTimeGPS.gpsSeconds = startTime;
        ADD_PROCESS_PARAM( "int", "%" LAL_INT4_FORMAT, startTime );
        break;

      case 'r':
        /* end time  */
        gpstime = atol( LALoptarg );
        if ( gpstime < 441417609 )
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "GPS start time is prior to " 
              "Jan 01, 1994  00:00:00 UTC:\n"
              "(%ld specified)\n",
              long_options[option_index].name, gpstime );
          exit( 1 );
        }
        endTime = (INT4) gpstime;
        endTimeGPS.gpsSeconds = endTime;
        ADD_PROCESS_PARAM( "int", "%" LAL_INT4_FORMAT, endTime );
        break;

      case 's':
        if ( strlen( LALoptarg ) > LIGOMETA_COMMENT_MAX - 1 )
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "comment must be less than %d characters\n",
              long_options[option_index].name, LIGOMETA_COMMENT_MAX );
          exit( 1 );
        }
        else
        {
          snprintf( comment, LIGOMETA_COMMENT_MAX, "%s", LALoptarg);
        }
        break;

      case 't':
        coherentBuffer = (INT4) atoi( LALoptarg );
        if ( coherentBuffer < 0 )
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "coherent-buffer duration (sec) must be positive or zero: "
              "(%d specified)\n",
              long_options[option_index].name, coherentBuffer );
          exit( 1 );
        }
        ADD_PROCESS_PARAM( "int", "%d", coherentBuffer );
        break;

      case 'h':
        /* help message */
        print_usage(argv[0]);
        exit( 1 );
        break;

      case 'Z':
        /* create storage for the usertag */
        LALoptarg_len = strlen(LALoptarg) + 1;
        userTag = (CHAR *) calloc( LALoptarg_len, sizeof(CHAR) );
        memcpy( userTag, LALoptarg, LALoptarg_len );

        this_proc_param = this_proc_param->next = (ProcessParamsTable *)
          calloc( 1, sizeof(ProcessParamsTable) );
        snprintf( this_proc_param->program, LIGOMETA_PROGRAM_MAX, "%s", 
            PROGRAM_NAME );
        snprintf( this_proc_param->param, LIGOMETA_PARAM_MAX, "-userTag" );
        snprintf( this_proc_param->type, LIGOMETA_TYPE_MAX, "string" );
        snprintf( this_proc_param->value, LIGOMETA_VALUE_MAX, "%s",
            LALoptarg );
        break;

      case 'I':
        /* create storage for the ifo-tag */
        LALoptarg_len = strlen(LALoptarg) + 1;
        ifoTag = (CHAR *) calloc( LALoptarg_len, sizeof(CHAR) );
        memcpy( ifoTag, LALoptarg, LALoptarg_len );
        ADD_PROCESS_PARAM( "string", "%s", LALoptarg );
        break;

      case 'V':
        /* print version information and exit */
        fprintf( stdout, "Inspiral Triggered Bank Generator\n" 
            "Patrick Brady, Duncan Brown and Steve Fairhurst\n");
        XLALOutputVersionString(stderr, 0);
        exit( 0 );
        break;

      case '?':
        print_usage(argv[0]);
        exit( 1 );
        break;

      default:
        fprintf( stderr, "Error: Unknown error while parsing options\n" );
        print_usage(argv[0]);
        exit( 1 );
    }
  }

  /* check the values of the arguments */
  if ( startTime < 0 )
  {
    fprintf( stderr, "Error: --gps-start-time must be specified\n" );
    exit( 1 );
  }

  if ( endTime < 0 )
  {
    fprintf( stderr, "Error: --gps-end-time must be specified\n" );
    exit( 1 );
  }

  if ( dataType == unspecified_data_type )
  {
    fprintf( stderr, "Error: --data-type must be specified\n");
    exit(1);
  }
  
  if ( test == unspecified_test )
  {
      fprintf( stderr, "Error: --parameter-test must be specified\n");
      exit(1);
  }

  /* fill the comment, if a user has specified one, or leave it blank */
  if ( ! *comment )
  {
    snprintf( proctable.processTable->comment, LIGOMETA_COMMENT_MAX, " " );
    snprintf( searchsumm.searchSummaryTable->comment, LIGOMETA_COMMENT_MAX, 
        " " );
  } 
  else 
  {
    snprintf( proctable.processTable->comment, LIGOMETA_COMMENT_MAX,
        "%s", comment );
    snprintf( searchsumm.searchSummaryTable->comment, LIGOMETA_COMMENT_MAX,
        "%s", comment );
  }

  /* store the check-times in the process_params table */
  if ( checkTimes )
  {
    this_proc_param = this_proc_param->next = (ProcessParamsTable *)
      calloc( 1, sizeof(ProcessParamsTable) );
    snprintf( this_proc_param->program, LIGOMETA_PROGRAM_MAX, 
        "%s", PROGRAM_NAME );
    snprintf( this_proc_param->param, LIGOMETA_PARAM_MAX, "--check-times");
    snprintf( this_proc_param->type, LIGOMETA_TYPE_MAX, "string" );
    snprintf( this_proc_param->value, LIGOMETA_TYPE_MAX, " " );
  }

  /* delete the first, empty process_params entry */
  this_proc_param = processParamsTable.processParamsTable;
  processParamsTable.processParamsTable = 
    processParamsTable.processParamsTable->next;
  free( this_proc_param );

  /*
   *
   * read in the input data from the rest of the arguments
   *
   */


  if ( LALoptind < argc )
  {
    for( i = LALoptind; i < argc; ++i )
    {
      INT4 numFileTriggers = 0;

      numFileTriggers = XLALReadInspiralTriggerFile( &inspiralEventList,
          &currentTrigger, &searchSummList, &inputFiles, argv[i] );
      if (numFileTriggers < 0)
      {
        fprintf(stderr, "Error reading triggers from file %s",
            argv[i]);
        exit( 1 );
      }
      
      numTriggers += numFileTriggers;
    }
  }
  else
  {
    fprintf( stderr, "Error: No trigger files specified.\n" );
    exit( 1 );
  }

  if ( vrbflg ) fprintf( stdout, "Read in a total of %d triggers.\n",
      numTriggers );

  /* check that we have read in data for all the requested time */
  if ( checkTimes )
  {
    if ( vrbflg ) fprintf( stdout, 
        "Checking that we have data for all times from %s\n",
        inputIFO);
    LAL_CALL( LALCheckOutTimeFromSearchSummary ( &status, searchSummList, 
          inputIFO, &startTimeGPS, &endTimeGPS ), &status);
  }


  if ( ! inspiralEventList )
  {
    /* no triggers read in so triggered bank will be empty */
    fprintf( stdout, "No triggers read in\n");

    /* set numTriggers in case any cuts are made in future */
    numTriggers = 0;
    goto cleanexit;
  }


  /* keep only triggers from input ifo */
  LAL_CALL( LALIfoCutSingleInspiral( &status, &inspiralEventList, inputIFO ), 
      &status );

  /* time sort the triggers */
  if ( vrbflg ) fprintf( stdout, "Sorting triggers\n" );
  LAL_CALL( LALSortSnglInspiral( &status, &inspiralEventList,
        LALCompareSnglInspiralByTime ), &status );

  /* keep only triggers within the requested interval */
  if ( vrbflg ) fprintf( stdout, 
      "Discarding triggers outside requested interval\n" );
  if ( coherentRun ) {
    startChunkTime = startTimeGPS.gpsSeconds + coherentBuffer;
    startChunkTimeGPS.gpsSeconds = startChunkTime;
    endChunkTime = endTimeGPS.gpsSeconds - coherentBuffer;
    endChunkTimeGPS.gpsSeconds = endChunkTime;
    LAL_CALL( LALTimeCutSingleInspiral( &status, &inspiralEventList,
         &startChunkTimeGPS, &endChunkTimeGPS), &status );
  }
  else {
    LAL_CALL( LALTimeCutSingleInspiral( &status, &inspiralEventList,
         &startTimeGPS, &endTimeGPS), &status );
  }

  /* keep play/non-play/all triggers */
  if ( dataType == playground_only && vrbflg ) fprintf( stdout, 
      "Keeping only playground triggers\n" );
  else if ( dataType == exclude_play && vrbflg ) fprintf( stdout, 
      "Keeping only non-playground triggers\n" );
  else if ( dataType == all_data && vrbflg ) fprintf( stdout, 
      "Keeping all triggers\n" );
  LAL_CALL( LALPlayTestSingleInspiral( &status, &inspiralEventList,
        &dataType ), &status );

  if( !inspiralEventList )
  {
    if ( vrbflg ) fprintf( stdout, 
        "No triggers remain after time and playground cuts.\n" );

    /* set numTriggers after cuts were applied */
    numTriggers = 0;
    goto cleanexit;
  }

  /* Generate the triggered bank */
  if( test != no_test )
  {
    LAL_CALL( LALCreateTrigBank( &status, &inspiralEventList, &test ), 
        &status );
  }

  /* count the number of triggers  */
  for( currentTrigger = inspiralEventList, numTriggers = 0; currentTrigger; 
      currentTrigger = currentTrigger->next, ++numTriggers);

  if ( vrbflg ) fprintf( stdout, "%d triggers to be written to trigbank.\n",
      numTriggers );

  /*
   *
   * write the output xml file
   *
   */


cleanexit:

  /* search summary entries: */
  searchsumm.searchSummaryTable->in_start_time = startTimeGPS;
  searchsumm.searchSummaryTable->in_end_time = endTimeGPS;
  searchsumm.searchSummaryTable->out_start_time = startTimeGPS;
  searchsumm.searchSummaryTable->out_end_time = endTimeGPS;
  searchsumm.searchSummaryTable->nevents = numTriggers;

  if ( vrbflg ) fprintf( stdout, "writing output file... " );

  /* set the file name correctly */
  if ( userTag && ifoTag && !outCompress )
  {
    snprintf( fileName, FILENAME_MAX, "%s-TRIGBANK_%s_%s-%d-%d.xml", 
        outputIFO, ifoTag, userTag, startTime, endTime - startTime );
  }
  else if ( userTag && !ifoTag && !outCompress )
  {
    snprintf( fileName, FILENAME_MAX, "%s-TRIGBANK_%s-%d-%d.xml", 
        outputIFO, userTag, startTime, endTime - startTime );
  }
  else if ( !userTag && ifoTag && !outCompress )
  {
    snprintf( fileName, FILENAME_MAX, "%s-TRIGBANK_%s-%d-%d.xml", 
        outputIFO, ifoTag, startTime, endTime - startTime );
  }
  else if ( userTag && ifoTag && outCompress )
  {
    snprintf( fileName, FILENAME_MAX, "%s-TRIGBANK_%s_%s-%d-%d.xml.gz",
        outputIFO, ifoTag, userTag, startTime, endTime - startTime );
  }
  else if ( userTag && !ifoTag && outCompress )
  {
    snprintf( fileName, FILENAME_MAX, "%s-TRIGBANK_%s-%d-%d.xml.gz",
        outputIFO, userTag, startTime, endTime - startTime );
  }
  else if ( !userTag && ifoTag && outCompress )
  {
    snprintf( fileName, FILENAME_MAX, "%s-TRIGBANK_%s-%d-%d.xml.gz",
        outputIFO, ifoTag, startTime, endTime - startTime );
  }
  else if ( !userTag && !ifoTag && outCompress )
  {
    snprintf( fileName, FILENAME_MAX, "%s-TRIGBANK-%d-%d.xml.gz",
        outputIFO, startTime, endTime - startTime );
  }
  else 
  {
    snprintf( fileName, FILENAME_MAX, "%s-TRIGBANK-%d-%d.xml", 
        outputIFO, startTime, endTime - startTime );
  }


  memset( &xmlStream, 0, sizeof(LIGOLwXMLStream) );
  LAL_CALL( LALOpenLIGOLwXMLFile( &status , &xmlStream, fileName ), 
      &status );

  /* write process table */
  snprintf( proctable.processTable->ifos, LIGOMETA_IFOS_MAX, "%s", 
      inputIFO );
  XLALGPSTimeNow(&(proctable.processTable->end_time));
  LAL_CALL( LALBeginLIGOLwXMLTable( &status, &xmlStream, process_table ), 
      &status );
  LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, proctable, 
        process_table ), &status );
  LAL_CALL( LALEndLIGOLwXMLTable ( &status, &xmlStream ), &status );

  /* write process_params table */
  LAL_CALL( LALBeginLIGOLwXMLTable( &status, &xmlStream, 
        process_params_table ), &status );
  LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, processParamsTable, 
        process_params_table ), &status );
  LAL_CALL( LALEndLIGOLwXMLTable ( &status, &xmlStream ), &status );

  /* write search_summary table */
  LAL_CALL( LALBeginLIGOLwXMLTable( &status, &xmlStream, 
        search_summary_table ), &status );
  LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, searchsumm, 
        search_summary_table ), &status );
  LAL_CALL( LALEndLIGOLwXMLTable ( &status, &xmlStream ), &status );

  /* write the search_summvars tabls */
  LAL_CALL( LALBeginLIGOLwXMLTable( &status ,&xmlStream, 
        search_summvars_table), &status );
  searchSummvarsTable.searchSummvarsTable = inputFiles;
  LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, searchSummvarsTable,
        search_summvars_table), &status );
  LAL_CALL( LALEndLIGOLwXMLTable( &status, &xmlStream), &status );

  /* write the sngl_inspiral table */
  if ( inspiralEventList )
  {
    LAL_CALL( LALBeginLIGOLwXMLTable( &status ,&xmlStream, 
          sngl_inspiral_table), &status );
    inspiralTable.snglInspiralTable = inspiralEventList;
    LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, inspiralTable,
          sngl_inspiral_table), &status );
    LAL_CALL( LALEndLIGOLwXMLTable( &status, &xmlStream), &status );
  }

  LAL_CALL( LALCloseLIGOLwXMLFile( &status, &xmlStream), &status );


  if ( vrbflg ) fprintf( stdout, "done\n" );


  /*
   *
   * clean up the memory that has been allocated 
   *
   */


  if ( vrbflg ) fprintf( stdout, "freeing memory... " );

  free( proctable.processTable );
  free( searchsumm.searchSummaryTable );

  while ( processParamsTable.processParamsTable )
  {
    this_proc_param = processParamsTable.processParamsTable;
    processParamsTable.processParamsTable = this_proc_param->next;
    free( this_proc_param );
  }

  while ( inputFiles )
  {
    thisInputFile = inputFiles;
    inputFiles = thisInputFile->next;
    LALFree( thisInputFile );
  }

  while ( searchSummList )
  {
    thisSearchSumm = searchSummList;
    searchSummList = searchSummList->next;
    LALFree( thisSearchSumm );
  }


  while ( inspiralEventList )
  {
    currentTrigger = inspiralEventList;
    inspiralEventList = inspiralEventList->next;
    LAL_CALL( LALFreeSnglInspiral( &status, &currentTrigger ), &status );
  }

  if ( userTag ) free( userTag );
  if ( ifoTag ) free( ifoTag );

  if ( vrbflg ) fprintf( stdout, "done\n" );

  LALCheckMemoryLeaks();

  exit( 0 );
}
/* main program loop */
INT4 main(INT4 argc, CHAR *argv[])
{
  /* status */
  LALStatus status = blank_status;

  /* LALgetopt flags */
  static int text_flag;
  static int cat_flag;
  static int analyse_flag;
  static int powerlaw_flag;

  /* counters */
  INT4 i, j;

  /* combined statistics variables */
  REAL8 numerator = 0;
  REAL8 denominator = 0;
  REAL8 yOpt = 0;
  REAL8 sigmaOpt = 0;
  REAL8 confidence = 0.95;
  REAL8 zeta;
  REAL8 upperlimit;

  /* pdf */
  REAL8 exponent;
  REAL8 pdf[100];
  REAL8 min_omega;
  REAL8 max_omega;
  REAL8 min_alpha = -1;
  REAL8 max_alpha = 1;
  REAL8 omega;
  REAL8 alpha;

  /* powerlaw pdf */
  REAL8 pdf_powerlaw[100][100];
  REAL8 freq;
  REAL8 freq_ref = 100;
  REAL8 omega_numerator;
  REAL8 omega_denominator;
  REAL8 sigma2_denominator;
  REAL8 omega_hat[100];
  REAL8 sigma2_omega_hat[100];

  /* program option variables */
  CHAR *outputFileName = NULL;

  /* xml data structures */
  LIGOLwXMLStream xmlStream;
  INT4 numSegments = 0;
  StochasticTable *stochHead = NULL;
  StochasticTable *thisStoch = NULL;
  MetadataTable outputTable;
  StochasticTable **stochHandle = NULL;

  /* text output file */
  FILE *out;
  FILE *pdf_out;
  FILE *omega_out;
  FILE *sigma_out;

  /* parse command line arguments */
  while (1)
  {
    /* LALgetopt arguments */
    static struct LALoption long_options[] =
    {
      /* options that set a flag */
      {"verbose", no_argument, &vrbflg, 1},
      {"text", no_argument, &text_flag, 1},
      {"cat-only", no_argument, &cat_flag, 1},
      {"analyse-only", no_argument, &analyse_flag, 1},
      {"powerlaw-pdf", no_argument, &powerlaw_flag, 1},
      /* options that don't set a flag */
      {"help", no_argument, 0, 'h'},
      {"version", no_argument, 0, 'v'},
      {"output", required_argument, 0, 'o'},
      {"confidence", required_argument, 0, 'c'},
      {0, 0, 0, 0}
    };
    int c;

    /* LALgetopt_long stores the option index here. */
    int option_index = 0;
    size_t LALoptarg_len;

    c = LALgetopt_long_only(argc, argv, "hvo:c:", long_options, &option_index);

    /* detect the end of the options */
    if (c == - 1)
    {
      /* end of options, break loop */
      break;
    }

    switch (c)
    {
      case 0:
        /* If this option set a flag, do nothing else now. */
        if (long_options[option_index].flag != 0)
        {
          break;
        }
        else
        {
          fprintf(stderr, "error parseing option %s with argument %s\n", \
              long_options[option_index].name, LALoptarg);
          exit(1);
        }
        break;

      case 'h':
        fprintf(stdout, USAGE);
        exit(0);
        break;

      case 'v':
        /* display version info and exit */
        fprintf(stdout, "Stochastic Post Processing: Bayesian\n");
        XLALOutputVersionString(stderr,0);
        exit(0);
        break;

      case 'o':
        /* create storage for the output file name */
        LALoptarg_len = strlen(LALoptarg) + 1;
        outputFileName = (CHAR *)calloc(LALoptarg_len, sizeof(CHAR));
        memcpy(outputFileName, LALoptarg, LALoptarg_len);
        break;

      case 'c':
        /* confidence level */
        confidence = atof(LALoptarg);
        if ((confidence >= 1) || (confidence <= 0))
        {
          fprintf(stderr, "invalid argument to --%s\n" \
              "confidence must be between 0 and 1, exclusive " \
              "(%.2f specified)\n", long_options[option_index].name, \
              confidence);
          exit(1);
        }
        break;

      case '?':
        exit(1);
        break;

      default:
        fprintf(stderr, "Unknown error while parsing options\n");
        exit(1);
    }
  }

  /* read in the input data from the rest of the arguments */
  if (LALoptind < argc)
  {
    for (i = LALoptind; i < argc; ++i)
    {
      struct stat infileStatus;

      /* if the named file does not exist, exit with an error */
      if (stat(argv[i], &infileStatus) == -1)
      {
        fprintf(stderr, "Error opening input file \"%s\"\n", argv[i]);
        exit(1);
      }

      if (!stochHead)
      {
        stochHandle = &stochHead;
      }
      else
      {
        stochHandle = &thisStoch->next;
      }

      /* read in the stochastic table */
      numSegments = LALStochasticTableFromLIGOLw(stochHandle, argv[i]);

      if (numSegments < 0)
      {
        fprintf(stderr, "Unable to read stochastic_table from \"%s\"\n", \
            argv[i]);
        exit(1);
      }
      else if (numSegments > 0)
      {
        if (vrbflg)
        {
          fprintf(stdout, "Read in %d segments from file \"%s\"\n", \
              numSegments, argv[i]);
        }

        /* scroll to end of list */
        thisStoch = *stochHandle;
        while (thisStoch->next)
        {
          thisStoch = thisStoch->next;
        }
      }
    }
  }

  if (!cat_flag)
  {
    /* combine statistics */
    for (thisStoch = stochHead; thisStoch; thisStoch = thisStoch->next)
    {
      numerator += thisStoch->cc_stat / (thisStoch->cc_sigma * \
          thisStoch->cc_sigma);
      denominator += 1./(thisStoch->cc_sigma * thisStoch->cc_sigma);
    }
    yOpt = (1./stochHead->duration.gpsSeconds) * (numerator / denominator);
    sigmaOpt = (1./stochHead->duration.gpsSeconds) * (1./sqrt(denominator));

    /* report point estimate and sigma */
    fprintf(stdout, "yOpt       = %e\n", yOpt);
    fprintf(stdout, "sigmaOpt   = %e\n", sigmaOpt);

    /* calculate upperlimit */
    zeta = yOpt / (sqrt(2) * sigmaOpt);
    upperlimit = yOpt + (sqrt(2) * sigmaOpt * \
        stopp_erfcinv((1 - confidence) * gsl_sf_erfc(-zeta)));
    fprintf(stdout, "upperlimit = %e\n", upperlimit);
  }

  /* calculate pdf */
  if (!powerlaw_flag)
  {
    /* pdf for constant spectra */
    min_omega = 0;
    max_omega = yOpt + (3 * sigmaOpt);
    for (i = 0; i < 100; i++)
    {
      omega = min_omega + (((i - 1)/99.) * (max_omega - min_omega));
      exponent = ((omega - yOpt) / sigmaOpt) * ((omega - yOpt) / sigmaOpt);
      pdf[i] = exp(-0.5 * exponent);
    }
  }
  else
  {
    /* pdf for power law spectra */
    min_omega = 0;
    max_omega = 1; /*(10 * yOpt)/stochHead->duration.gpsSeconds;*/
    min_alpha = -4;
    max_alpha = 4;

    /* loop for \Omega_R */
    for (i = 0; i < 100; i++)
    {
      /* loop for \alpha */
      for (j = 0; j < 100; j++)
      {
        omega = min_omega + ((i/99.) * (max_omega - min_omega));
        alpha = min_alpha + ((j/99.) * (max_alpha - min_alpha));

        /* initialise numerator */
        omega_numerator = 0;
        omega_denominator = 0;
        sigma2_denominator = 0;

        /* loop over segments */
        for (thisStoch = stochHead; thisStoch; thisStoch = thisStoch->next)
        {
          /* get frequency of middle of the band */
          freq = thisStoch->f_min + ((thisStoch->f_max - \
                thisStoch->f_min) / 2.);

          /* \hat{\Omega}_R */
          omega_numerator += (thisStoch->cc_stat / (thisStoch->cc_sigma * \
                thisStoch->cc_sigma)) * pow((freq/freq_ref), alpha);
          omega_denominator += (1. / (thisStoch->cc_sigma * \
                thisStoch->cc_sigma)) * pow((freq/freq_ref), 2 * alpha);

          /* sigma^2_{\hat{\Omega}_R} */
          sigma2_denominator += (1. / (thisStoch->cc_sigma * \
                thisStoch->cc_sigma)) * pow((freq/freq_ref), 2 * alpha);
        }

        /* construct \hat{\Omega}_R */
        omega_hat[j] = omega_numerator / (stochHead->duration.gpsSeconds * \
            omega_denominator);

        /* construct sigma^2_{\hat{\Omega}_R} */
        sigma2_omega_hat[j] = 1. / (stochHead->duration.gpsSeconds * \
              stochHead->duration.gpsSeconds * sigma2_denominator);

        /* construct pdf */
        pdf_powerlaw[i][j] = exp(-0.5 * ((omega - omega_hat[j]) / \
              sqrt(sigma2_omega_hat[j])) * ((omega - omega_hat[j]) / \
                sqrt(sigma2_omega_hat[j])));
      }
    }
  }

  if (!cat_flag)
  {
    if (powerlaw_flag)
    {
      /* open omega and sigma output files */
      if ((omega_out = fopen("omega.dat", "w")) == NULL)
      {
        fprintf(stderr, "Can't open file for omega output...\n");
        exit(1);
      }
      if ((sigma_out = fopen("sigma.dat", "w")) == NULL)
      {
        fprintf(stderr, "Can't open file for sigma output...\n");
        exit(1);
      }

      /* save out omega and sigma */
      for (j = 0; j < 100; j++)
      {
        alpha = min_alpha + ((j/99.) * (max_alpha - min_alpha));
        fprintf(omega_out, "%e %e\n", alpha, omega_hat[j]);
        fprintf(sigma_out, "%e %e\n", alpha, sqrt(sigma2_omega_hat[j]));
      }

      /* close files */
      fclose(omega_out);
      fclose(sigma_out);
    }

    /* save out pdf */
    if ((pdf_out = fopen("pdf.dat", "w")) == NULL)
    {
      fprintf(stderr, "Can't open file for pdf output...\n");
      exit(1);
    }
    if (powerlaw_flag)
    {
      for (i = 0; i < 100; i++)
      {
        for (j = 0; j < 100; j++)
        {
          omega = min_omega + ((i/99.) * (max_omega - min_omega));
          alpha = min_alpha + ((j/99.) * (max_alpha - min_alpha));
          fprintf(pdf_out, "%e %e %e\n", omega, alpha, pdf_powerlaw[i][j]);
        }

        /* gnuplot */
        fprintf(pdf_out, "\n");
      }
    }
    else
    {
      for (i = 0; i < 100; i++)
      {
        omega = min_omega + (((i - 1)/99.) * (max_omega - min_omega));
        fprintf(pdf_out, "%e %e\n", omega, pdf[i]);
      }
    }
    fclose(pdf_out);
  }

  if (!analyse_flag)
  {
    /* output as text file */
    if (text_flag)
    {
      /* open output file */
      if ((out = fopen(outputFileName, "w")) == NULL)
      {
        fprintf(stderr, "Can't open file \"%s\" for output...\n", \
            outputFileName);
        exit(1);
      }

      /* write details of events */
      for (thisStoch = stochHead; thisStoch; thisStoch = thisStoch->next)
      {
        fprintf(out, "%d %e %e\n", thisStoch->start_time.gpsSeconds, \
            thisStoch->cc_stat, thisStoch->cc_sigma);
      }

      /* close output file */
      fclose(out);
    }

    /* output as xml file */
    else
    {
      /* open xml file stream */
      memset(&xmlStream, 0, sizeof(LIGOLwXMLStream));
      LAL_CALL(LALOpenLIGOLwXMLFile(&status, &xmlStream, outputFileName), \
          &status);

      /* write stochastic table */
      if (stochHead)
      {
        outputTable.stochasticTable = stochHead;
        LAL_CALL(LALBeginLIGOLwXMLTable(&status, &xmlStream, \
              stochastic_table), &status);
        LAL_CALL(LALWriteLIGOLwXMLTable(&status, &xmlStream, outputTable, \
              stochastic_table), &status);
        LAL_CALL(LALEndLIGOLwXMLTable(&status, &xmlStream), &status);
      }

      /* close xml file */
      LAL_CALL(LALCloseLIGOLwXMLFile(&status, &xmlStream), &status);
    }
  }

  /* check for memory leaks and exit */
  LALCheckMemoryLeaks();
  exit(0);
}
Exemple #6
0
/* sets params to default values and parses the command line arguments */
struct params parseargs(int argc, char **argv)
{
    int degrees = 1;
    int phaseO;
    char *inclination_string = NULL;
    char *phiRef_string = NULL;
    char *meanPerAno_string = NULL;
    char *longAscNodes_string = NULL;
    char *kv;
    struct params p = {
        .verbose = 0,
        .approx = XLALSimInspiralGetApproximantFromString(DEFAULT_APPROX),
        .condition = 0,
        .freq_dom = 0,
        .amp_phase = 0,
        .domain = DEFAULT_DOMAIN,
        .phiRef = DEFAULT_PHIREF * LAL_PI_180,
        .meanPerAno = DEFAULT_MEANPERANO * LAL_PI_180,
        .longAscNodes = DEFAULT_LONGASCNODE * LAL_PI_180,
        .eccentricity = DEFAULT_ECCENTRICITY,
        .fRef = DEFAULT_FREF,
        .srate = DEFAULT_SRATE,
        .m1 = DEFAULT_M1 * LAL_MSUN_SI,
        .m2 = DEFAULT_M2 * LAL_MSUN_SI,
        .f_min = DEFAULT_F_MIN,
        .distance = DEFAULT_DISTANCE * 1e6 * LAL_PC_SI,
        .inclination = DEFAULT_INCLINATION * LAL_PI_180,
        .s1x = DEFAULT_S1X,
        .s1y = DEFAULT_S1Y,
        .s1z = DEFAULT_S1Z,
        .s2x = DEFAULT_S2X,
        .s2y = DEFAULT_S2Y,
        .s2z = DEFAULT_S2Z,
        .params = NULL
    };
    struct LALoption long_options[] = {
        {"help", no_argument, 0, 'h'},
        {"verbose", no_argument, 0, 'v'},
        {"radians", no_argument, 0, 'C'},
        {"frequency-domain", no_argument, 0, 'F'},
        {"condition-waveform", no_argument, 0, 'c'},
        {"amp-phase", no_argument, 0, 'P'},
        {"approximant", required_argument, 0, 'a'},
        {"waveform", required_argument, 0, 'w'},
        {"domain", required_argument, 0, 'D'},
        {"phase-order", required_argument, 0, 'O'},
        {"amp-order", required_argument, 0, 'o'},
        {"phiRef", required_argument, 0, 'u'},
        {"periastron-anomaly", required_argument, 0, 'U'},
        {"longitude-ascending-node", required_argument, 0, 'W'},
        {"eccentricity", required_argument, 0, 'e'},
        {"fRef", required_argument, 0, 'r'},
        {"sample-rate", required_argument, 0, 'R'},
        {"m1", required_argument, 0, 'M'},
        {"m2", required_argument, 0, 'm'},
        {"spin1x", required_argument, 0, 'X'},
        {"spin1y", required_argument, 0, 'Y'},
        {"spin1z", required_argument, 0, 'Z'},
        {"spin2x", required_argument, 0, 'x'},
        {"spin2y", required_argument, 0, 'y'},
        {"spin2z", required_argument, 0, 'z'},
        {"tidal-lambda1", required_argument, 0, 'L'},
        {"tidal-lambda2", required_argument, 0, 'l'},
        {"delta-quad-mon1", required_argument, 0, 'q'},
        {"delta-quad-mon2", required_argument, 0, 'Q'},
        {"spin-order", required_argument, 0, 's'},
        {"tidal-order", required_argument, 0, 't'},
        {"f-min", required_argument, 0, 'f'},
        {"f-max", required_argument, 0, 'F'},
        {"distance", required_argument, 0, 'd'},
        {"inclination", required_argument, 0, 'i'},
        {"axis", required_argument, 0, 'A'},
        {"modes", required_argument, 0, 'n'},
        {"params", required_argument, 0, 'p'},
        {0, 0, 0, 0}
    };
    char args[] = "hvCFcPa:w:D:O:o:u:U:W:e:r:R:M:m:X:x:Y:y:Z:z:L:l:q:Q:s:t:f:d:i:A:n:p:";

    while (1) {
        int option_index = 0;
        int c;

        c = LALgetopt_long_only(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);
                exit(1);
            }
        case 'h':      /* help */
            usage(argv[0]);
            exit(0);
        case 'v':      /* verbose */
            p.verbose = 1;
            break;
        case 'C':      /* radians */
            degrees = 0;
            break;
        case 'F':      /* frequency-domain */
            p.freq_dom = 1;
            break;
        case 'c':      /* condition-waveform */
            p.condition = 1;
            break;
        case 'P':      /* amp-phase */
            p.amp_phase = 1;
            break;
        case 'a':      /* approximant */
            p.approx = XLALSimInspiralGetApproximantFromString(LALoptarg);
            if ((int)p.approx == XLAL_FAILURE) {
                fprintf(stderr, "error: invalid value %s for %s\n", LALoptarg, long_options[option_index].name);
                exit(1);
            }
            break;
        case 'w':      /* waveform */
            p.approx = XLALSimInspiralGetApproximantFromString(LALoptarg);
            if ((int)p.approx == XLAL_FAILURE) {
                fprintf(stderr, "error: could not parse approximant from %s for %s\n", LALoptarg, long_options[option_index].name);
                exit(1);
            }
            phaseO = XLALSimInspiralGetPNOrderFromString(LALoptarg);
            if ((int)phaseO == XLAL_FAILURE) {
                fprintf(stderr, "error: could not parse order from %s for %s\n", LALoptarg, long_options[option_index].name);
                exit(1);
            }
            if (p.params == NULL)
                p.params = XLALCreateDict();
            XLALSimInspiralWaveformParamsInsertPNPhaseOrder(p.params, phaseO);
            break;
        case 'D':      /* domain */
            switch (*LALoptarg) {
            case 'T':
            case 't':
                p.domain = LAL_SIM_DOMAIN_TIME;
                break;
            case 'F':
            case 'f':
                p.domain = LAL_SIM_DOMAIN_FREQUENCY;
                break;
            default:
                fprintf(stderr, "error: invalid value %s for %s\n", LALoptarg, long_options[option_index].name);
                exit(1);
            }
        case 'O':      /* phase-order */
            if (p.params == NULL)
                p.params = XLALCreateDict();
            XLALSimInspiralWaveformParamsInsertPNPhaseOrder(p.params, atoi(LALoptarg));
            break;
        case 'o':      /* amp-order */
            if (p.params == NULL)
                p.params = XLALCreateDict();
            XLALSimInspiralWaveformParamsInsertPNAmplitudeOrder(p.params, atoi(LALoptarg));
            break;
        case 'u':      /* phiRef */
            phiRef_string = LALoptarg;
            break;
        case 'U':      /* mean-periastron-anomaly */
            meanPerAno_string = LALoptarg;
            break;
        case 'W':      /* longitude-ascending-node */
            longAscNodes_string = LALoptarg;
            break;
        case 'e':      /* eccentricity */
            p.eccentricity = atof(LALoptarg);
            break;
        case 'r':      /* fRef */
            p.fRef = atof(LALoptarg);
            break;
        case 'R':      /* sample-rate */
            p.srate = atof(LALoptarg);
            break;
        case 'M':      /* m1 */
            p.m1 = atof(LALoptarg) * LAL_MSUN_SI;
            break;
        case 'm':      /* m2 */
            p.m2 = atof(LALoptarg) * LAL_MSUN_SI;
            break;
        case 'X':      /* spin1x */
            p.s1x = atof(LALoptarg);
            break;
        case 'Y':      /* spin1y */
            p.s1y = atof(LALoptarg);
            break;
        case 'Z':      /* spin1z */
            p.s1z = atof(LALoptarg);
            break;
        case 'x':      /* spin2x */
            p.s2x = atof(LALoptarg);
            break;
        case 'y':      /* spin2y */
            p.s2y = atof(LALoptarg);
            break;
        case 'z':      /* spin2z */
            p.s2z = atof(LALoptarg);
            break;
        case 'L':      /* tidal-lambda1 */
            if (p.params == NULL)
                p.params = XLALCreateDict();
            XLALSimInspiralWaveformParamsInsertTidalLambda1(p.params, atoi(LALoptarg));
            break;
        case 'l':      /* tidal-lambda2 */
            if (p.params == NULL)
                p.params = XLALCreateDict();
            XLALSimInspiralWaveformParamsInsertTidalLambda2(p.params, atoi(LALoptarg));
            break;
        case 'q':      /* diff-quad-mon1 */
            if (p.params == NULL)
                p.params = XLALCreateDict();
            XLALSimInspiralWaveformParamsInsertdQuadMon1(p.params, atoi(LALoptarg));
            break;
        case 'Q':      /* diff-quad-mon2 */
            if (p.params == NULL)
                p.params = XLALCreateDict();
            XLALSimInspiralWaveformParamsInsertdQuadMon2(p.params, atoi(LALoptarg));
            break;
        case 's':      /* spin-order */
            if (p.params == NULL)
                p.params = XLALCreateDict();
            XLALSimInspiralWaveformParamsInsertPNSpinOrder(p.params, atoi(LALoptarg));
            break;
        case 't':      /* tidal-order */
            if (p.params == NULL)
                p.params = XLALCreateDict();
            XLALSimInspiralWaveformParamsInsertPNTidalOrder(p.params, atoi(LALoptarg));
            break;
        case 'f':      /* f-min */
            p.f_min = atof(LALoptarg);
            break;
        case 'd':      /* distance */
            p.distance = atof(LALoptarg) * 1e6 * LAL_PC_SI;
            break;
        case 'i':      /* inclination */
            inclination_string = LALoptarg;
            break;
        case 'A':      /* axis */
            if (p.params == NULL)
                p.params = XLALCreateDict();
            XLALSimInspiralWaveformParamsInsertFrameAxis(p.params, XLALSimInspiralGetFrameAxisFromString(LALoptarg));
            break;
        case 'n':      /* modes */
            if (p.params == NULL)
                p.params = XLALCreateDict();
            XLALSimInspiralWaveformParamsInsertModesChoice(p.params, XLALSimInspiralGetHigherModesFromString(LALoptarg));
            break;
        case 'p':      /* params */
            if (p.params == NULL)
                p.params = XLALCreateDict();
            while ((kv = XLALStringToken(&LALoptarg, ",", 0))) {
                char *key = XLALStringToken(&kv, "=", 0);
                if (kv == NULL || key == NULL || *key == '\0') {
                    fprintf(stderr, "error: invalid key-value pair for %s\n", long_options[option_index].name);
                    exit(1);
                }
                XLALDictInsertREAL8Value(p.params, key, atof(kv));
            }
            break;
        case '?':
        default:
            fprintf(stderr, "unknown error while parsing options\n");
            exit(1);
        }
    }
    if (LALoptind < argc) {
        fprintf(stderr, "extraneous command line arguments:\n");
        while (LALoptind < argc)
            fprintf(stderr, "%s\n", argv[LALoptind++]);
        exit(1);
    }

    /* set angles, converting to degrees to radians if needed */
    if (phiRef_string) {
        p.phiRef = atof(phiRef_string);
        if (degrees)
            p.phiRef *= LAL_PI_180;
    }
    if (inclination_string) {
        p.inclination = atof(inclination_string);
        if (degrees)
            p.inclination *= LAL_PI_180;
    }
    if (meanPerAno_string) {
        p.meanPerAno = atof(meanPerAno_string);
        if (degrees)
            p.meanPerAno *= LAL_PI_180;
    }
    if (longAscNodes_string) {
        p.longAscNodes = atof(longAscNodes_string);
        if (degrees)
            p.longAscNodes *= LAL_PI_180;
    }

    return p;
}
Exemple #7
0
int main( int argc, char *argv[] )
{
  /* lal initialization variables */
  LALStatus status = blank_status;

  /*  program option variables */
  CHAR *userTag = NULL;
  CHAR comment[LIGOMETA_COMMENT_MAX];
  char *ifoName = NULL;
  char *inputGlob = NULL;
  char *inputFileName = NULL;
  char *outputFileName = NULL;
  char *tamaFileName = NULL;
  char *summFileName = NULL;
  REAL4 snrStar = -1;
  SnglInspiralClusterChoice clusterchoice = none;
  INT8 cluster_dt = -1;
  char *injectFileName = NULL;
  INT8 inject_dt = -1;
  char *missedFileName = NULL;
  INT4 hardware = 0;
  int  enableTrigStartTime = 1;
  int j;
  FILE *fp = NULL;
  glob_t globbedFiles;
  int numInFiles = 0;
  char **inFileNameList;
  char line[MAX_PATH];
  int  errnum;

  UINT8 triggerInputTimeNS = 0;

  MetadataTable         proctable;
  MetadataTable         procparams;
  ProcessParamsTable   *this_proc_param;

  UINT4                 numSimEvents = 0;
  UINT4                 numSimInData = 0;
  UINT4                 numSimFound  = 0;
  UINT4                 numSimMissed = 0;
  UINT4                 numSimDiscard = 0;
  UINT4                 numSimProcessed = 0;

  SimRingdownTable     *simEventHead = NULL;
  SimRingdownTable     *thisSimEvent = NULL;
  SimRingdownTable     *missedSimHead = NULL;
  SimRingdownTable     *thisMissedSim = NULL;
  SimRingdownTable     *tmpSimEvent = NULL;
  SimRingdownTable     *prevSimEvent = NULL;

  SearchSummaryTable   *searchSummaryTable = NULL;

  UINT4                 numEvents = 0;
  UINT4                 numEventsKept = 0;
  UINT4                 numEventsInIFO = 0;
  UINT4                 numEventsCoinc = 0;
  UINT4                 numEventsDiscard = 0;
  UINT4                 numEventsProcessed = 0;
  UINT4                 numClusteredEvents = 0;

  SnglRingdownTable   **eventHandle = NULL;      
  SnglRingdownTable    *eventHead = NULL;
  SnglRingdownTable    *thisEvent = NULL;
  SnglRingdownTable    *tmpEvent = NULL;
  SnglRingdownTable    *prevEvent = NULL;

  LIGOLwXMLStream       xmlStream;
  MetadataTable         outputTable;


  /*
   *
   * initialization
   *
   */


  /* set up inital debugging values */
  lal_errhandler = LAL_ERR_EXIT;

  /* create the process and process params tables */
  proctable.processTable = (ProcessTable *) 
    calloc( 1, sizeof(ProcessTable) );
  XLALGPSTimeNow(&(proctable.processTable->start_time));

  XLALPopulateProcessTable(proctable.processTable, PROGRAM_NAME,
      lalAppsVCSIdentId, lalAppsVCSIdentStatus, lalAppsVCSIdentDate, 0);

  this_proc_param = procparams.processParamsTable = (ProcessParamsTable *) 
    calloc( 1, sizeof(ProcessParamsTable) );
  memset( comment, 0, LIGOMETA_COMMENT_MAX * sizeof(CHAR) );


  /*
   *
   * parse command line arguments
   *
   */


  while (1)
  {
    /* LALgetopt arguments */
    static struct LALoption long_options[] = 
    {
      {"verbose",             no_argument,           &vrbflg,              1 },
      {"sort-triggers",       no_argument,     &sortTriggers,              1 },
      {"help",                    no_argument,            0,              'h'},
      {"user-tag",                required_argument,      0,              'Z'},
      {"userTag",                 required_argument,      0,              'Z'},
      {"comment",                 required_argument,      0,              'c'},
      {"version",                 no_argument,            0,              'V'},
      {"glob",                    required_argument,      0,              'g'},
      {"input",                   required_argument,      0,              'i'},
      {"output",                  required_argument,      0,              'o'},
      {"data-type",               required_argument,      0,              'k'},
      {"tama-output",             required_argument,      0,              'j'},
      {"summary-file",            required_argument,      0,              'S'},
      {"snr-threshold",           required_argument,      0,              's'},
      {"cluster-algorithm",       required_argument,      0,              'C'},
      {"cluster-time",            required_argument,      0,              't'},
      {"ifo-cut",                 required_argument,      0,              'd'},
      {"injection-file",          required_argument,      0,              'I'},
      {"injection-coincidence",   required_argument,      0,              'T'},
      {"missed-injections",       required_argument,      0,              'm'},
      {"hardware-injections",     required_argument,      0,              'H'},
      {"disable-trig-start-time", no_argument,            0,              'D'},
      {0, 0, 0, 0}
    };
    int c;

    /* LALgetopt_long stores the option index here. */
    int option_index = 0;
    size_t LALoptarg_len;

    c = LALgetopt_long_only ( argc, argv, "hZ:c:d:g:i:o:j:S:s:C:Vt:I:T:m:H:D",
        long_options, &option_index );

    /* detect the end of the options */
    if ( c == - 1 )
      break;

    switch ( c )
    {
      case 0:
        /* if this option set a flag, do nothing else now */
        if ( long_options[option_index].flag != 0 )
        {
          break;
        }
        else
        {
          fprintf( stderr, "error parsing option %s with argument %s\n",
              long_options[option_index].name, LALoptarg );
          exit( 1 );
        }
        break;

      case 'h':
        fprintf( stdout, USAGE );
        exit( 0 );
        break;

      case 'Z':
        /* create storage for the usertag */
        LALoptarg_len = strlen( LALoptarg ) + 1;
        userTag = (CHAR *) calloc( LALoptarg_len, sizeof(CHAR) );
        memcpy( userTag, LALoptarg, LALoptarg_len );

        this_proc_param = this_proc_param->next = (ProcessParamsTable *)
          calloc( 1, sizeof(ProcessParamsTable) );
        snprintf( this_proc_param->program, LIGOMETA_PROGRAM_MAX, "%s", 
            PROGRAM_NAME );
        snprintf( this_proc_param->param, LIGOMETA_PARAM_MAX, "-userTag" );
        snprintf( this_proc_param->type, LIGOMETA_TYPE_MAX, "string" );
        snprintf( this_proc_param->value, LIGOMETA_VALUE_MAX, "%s",
            LALoptarg );
        break;

      case 'c':
        if ( strlen( LALoptarg ) > LIGOMETA_COMMENT_MAX - 1 )
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "comment must be less than %d characters\n",
              long_options[option_index].name, LIGOMETA_COMMENT_MAX );
          exit( 1 );
        }
        else
        {
          snprintf( comment, LIGOMETA_COMMENT_MAX, "%s", LALoptarg);
        }
        break;

      case 'V':
        fprintf( stdout, "Single Ringdown Reader and Injection Analysis\n"
            "Patrick Brady, Duncan Brown and Steve Fairhurst\n");
        XLALOutputVersionString(stderr, 0);
        exit( 0 );
        break;

      case 'g':
        /* create storage for the input file glob */
        LALoptarg_len = strlen( LALoptarg ) + 1;
        inputGlob = (CHAR *) calloc( LALoptarg_len, sizeof(CHAR));
        memcpy( inputGlob, LALoptarg, LALoptarg_len );
        ADD_PROCESS_PARAM( "string", "'%s'", LALoptarg );
        break;

      case 'i':
        /* create storage for the input file name */
        LALoptarg_len = strlen( LALoptarg ) + 1;
        inputFileName = (CHAR *) calloc( LALoptarg_len, sizeof(CHAR));
        memcpy( inputFileName, LALoptarg, LALoptarg_len );
        ADD_PROCESS_PARAM( "string", "%s", LALoptarg );
        break;

      case 'o':
        /* create storage for the output file name */
        LALoptarg_len = strlen( LALoptarg ) + 1;
        outputFileName = (CHAR *) calloc( LALoptarg_len, sizeof(CHAR));
        memcpy( outputFileName, LALoptarg, LALoptarg_len );
        ADD_PROCESS_PARAM( "string", "%s", LALoptarg );
        break;

      case 'j':
        /* create storage of the TAMA file name */
        LALoptarg_len = strlen( LALoptarg ) + 1;
        tamaFileName = (CHAR *) calloc( LALoptarg_len, sizeof(CHAR));
        memcpy( tamaFileName, LALoptarg, LALoptarg_len );
        ADD_PROCESS_PARAM( "string", "%s", LALoptarg );
        break;

      case 'S':
        /* create storage for the summ file name */
        LALoptarg_len = strlen( LALoptarg ) + 1;
        summFileName = (CHAR *) calloc( LALoptarg_len, sizeof(CHAR));
        memcpy( summFileName, LALoptarg, LALoptarg_len );
        ADD_PROCESS_PARAM( "string", "%s", LALoptarg );
        break;

      case 's':
        snrStar = (REAL4) atof( LALoptarg );
        if ( snrStar < 0 )
        {
          fprintf( stdout, "invalid argument to --%s:\n"
              "threshold must be >= 0: "
              "(%f specified)\n",
              long_options[option_index].name, snrStar );
          exit( 1 );
        }
        ADD_PROCESS_PARAM( "float", "%e", snrStar );
        break;

      case 'k':
        /* type of data to analyze */
        if ( ! strcmp( "playground_only", LALoptarg ) )
        {
          dataType = playground_only;
        }
        else if ( ! strcmp( "exclude_play", LALoptarg ) )
        {
          dataType = exclude_play;
        }
        else if ( ! strcmp( "all_data", LALoptarg ) )
        {
          dataType = all_data;
        }
        else
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "unknown data type, %s, specified: "
              "(must be playground_only, exclude_play or all_data)\n",
              long_options[option_index].name, LALoptarg );
          exit( 1 );
        }
        ADD_PROCESS_PARAM( "string", "%s", LALoptarg );
        break;

      case 'C':
        /* choose the clustering algorithm */
        {        
          if ( ! strcmp( "snr_and_chisq", LALoptarg ) )
          {
            clusterchoice = snr_and_chisq;
          }
          else if ( ! strcmp( "snrsq_over_chisq", LALoptarg) )
          {
            clusterchoice = snrsq_over_chisq;
          }
          else if ( ! strcmp( "snr", LALoptarg) )
          {
            clusterchoice = snr;
          }        
          else
          {
            fprintf( stderr, "invalid argument to  --%s:\n"
                "unknown clustering specified:\n "
                "%s (must be one of: snr_and_chisq, \n"
                "   snrsq_over_chisq or snr)\n",
                long_options[option_index].name, LALoptarg);
            exit( 1 );
          }
          ADD_PROCESS_PARAM( "string", "%s", LALoptarg );
        }
        break;

      case 't':
        /* cluster time is specified on command line in ms */
        cluster_dt = (INT8) atoi( LALoptarg );
        if ( cluster_dt <= 0 )
        {
          fprintf( stdout, "invalid argument to --%s:\n"
              "custer window must be > 0: "
              "(%" LAL_INT8_FORMAT " specified)\n",
              long_options[option_index].name, cluster_dt );
          exit( 1 );
        }
        ADD_PROCESS_PARAM( "int", "%" LAL_INT8_FORMAT "", cluster_dt );
        /* convert cluster time from ms to ns */
        cluster_dt *= LAL_INT8_C(1000000);
        break;

      case 'I':
        /* create storage for the injection file name */
        LALoptarg_len = strlen( LALoptarg ) + 1;
        injectFileName = (CHAR *) calloc( LALoptarg_len, sizeof(CHAR));
        memcpy( injectFileName, LALoptarg, LALoptarg_len );
        ADD_PROCESS_PARAM( "string", "%s", LALoptarg );
        break;

      case 'd':
        LALoptarg_len = strlen( LALoptarg ) + 1;
        ifoName = (CHAR *) calloc( LALoptarg_len, sizeof(CHAR));
        memcpy( ifoName, LALoptarg, LALoptarg_len );
        ADD_PROCESS_PARAM( "string", "%s", LALoptarg );
        break;

      case 'T':
        /* injection coincidence time is specified on command line in ms */
        inject_dt = (INT8) atoi( LALoptarg );
        if ( inject_dt < 0 )
        {
          fprintf( stdout, "invalid argument to --%s:\n"
              "injection coincidence window must be >= 0: "
              "(%" LAL_INT8_FORMAT " specified)\n",
              long_options[option_index].name, inject_dt );
          exit( 1 );
        }
        ADD_PROCESS_PARAM( "int", "%" LAL_INT8_FORMAT " ", inject_dt );
        /* convert inject time from ms to ns */
        inject_dt *= LAL_INT8_C(1000000);
        break;

      case 'm':
        /* create storage for the missed injection file name */
        LALoptarg_len = strlen( LALoptarg ) + 1;
        missedFileName = (CHAR *) calloc( LALoptarg_len, sizeof(CHAR));
        memcpy( missedFileName, LALoptarg, LALoptarg_len );
        ADD_PROCESS_PARAM( "string", "%s", LALoptarg );
        break;

      case 'H':
        hardware = (INT4) atoi( LALoptarg );
        if ( hardware <= 0 )
        {
          fprintf( stdout, "invalid argument to --%s:\n"
              "GPS start time of hardware injections must be > 0: "
              "(%d specified)\n",
              long_options[option_index].name, hardware );
          exit( 1 );
        }
        ADD_PROCESS_PARAM( "int", "%" LAL_INT4_FORMAT " ", hardware );
        break;

      case 'D':
        enableTrigStartTime = 0;
        ADD_PROCESS_PARAM( "string", "%s", " " );
        break;

      case '?':
        exit( 1 );
        break;

      default:
        fprintf( stderr, "unknown error while parsing options\n" );
        exit( 1 );
    }   
  }

  if ( LALoptind < argc )
  {
    fprintf( stderr, "extraneous command line arguments:\n" );
    while ( LALoptind < argc )
    {
      fprintf ( stderr, "%s\n", argv[LALoptind++] );
    }
    exit( 1 );
  }


  /*
   *
   * can use LALCalloc() / LALMalloc() from here
   *
   */


  /* don't buffer stdout if we are in verbose mode */
  if ( vrbflg ) setvbuf( stdout, NULL, _IONBF, 0 );

  /* fill the comment, if a user has specified it, or leave it blank */
  if ( ! *comment )
  {
    snprintf( proctable.processTable->comment, LIGOMETA_COMMENT_MAX, " " );
  }
  else
  {
    snprintf( proctable.processTable->comment, LIGOMETA_COMMENT_MAX,
        "%s", comment );
  }

  /* check that the input and output file names have been specified */
  if ( (! inputGlob && ! inputFileName) || (inputGlob && inputFileName) )
  {
    fprintf( stderr, "exactly one of --glob or --input must be specified\n" );
    exit( 1 );
  }
  if ( ! outputFileName )
  {
    fprintf( stderr, "--output must be specified\n" );
    exit( 1 );
  }

  /* check that Data Type has been specified */
  if ( dataType == unspecified_data_type )
  {
    fprintf( stderr, "Error: --data-type must be specified\n");
    exit(1);
  }

  /* check that if clustering is being done that we have all the options */
  if ( clusterchoice && cluster_dt < 0 )
  {
    fprintf( stderr, "--cluster-time must be specified if --cluster-algorithm "
        "is given\n" );
    exit( 1 );
  }
  else if ( ! clusterchoice && cluster_dt >= 0 )
  {
    fprintf( stderr, "--cluster-algorithm must be specified if --cluster-time "
        "is given\n" );
    exit( 1 );
  }

  /* check that we have all the options to do injections */
  if ( injectFileName && inject_dt < 0 )
  {
    fprintf( stderr, "--injection-coincidence must be specified if "
        "--injection-file is given\n" );
    exit( 1 );
  }
  else if ( ! injectFileName && inject_dt >= 0 )
  {
    fprintf( stderr, "--injection-file must be specified if "
        "--injection-coincidence is given\n" );
    exit( 1 );
  }

  /* save the sort triggers flag */
  if ( sortTriggers )
  {
    this_proc_param = this_proc_param->next = (ProcessParamsTable *) 
      calloc( 1, sizeof(ProcessParamsTable) ); 
    snprintf( this_proc_param->program, LIGOMETA_PROGRAM_MAX, "%s",
        PROGRAM_NAME ); 
    snprintf( this_proc_param->param, LIGOMETA_PARAM_MAX, 
        "--sort-triggers" );
    snprintf( this_proc_param->type, LIGOMETA_TYPE_MAX, "string" ); 
    snprintf( this_proc_param->value, LIGOMETA_VALUE_MAX, " " );
  }

  switch ( dataType )
  {
    case playground_only:
      if ( vrbflg )
        fprintf( stdout, "using data from playground times only\n" );
      snprintf( procparams.processParamsTable->program, 
          LIGOMETA_PROGRAM_MAX, "%s", PROGRAM_NAME );
      snprintf( procparams.processParamsTable->param,
          LIGOMETA_PARAM_MAX, "--playground-only" );
      snprintf( procparams.processParamsTable->type, 
          LIGOMETA_TYPE_MAX, "string" );
      snprintf( procparams.processParamsTable->value, 
          LIGOMETA_TYPE_MAX, " " );
      break;

    case exclude_play:
      if ( vrbflg )
        fprintf( stdout, "excluding all triggers in playground times\n" );
      snprintf( procparams.processParamsTable->program, 
          LIGOMETA_PROGRAM_MAX, "%s", PROGRAM_NAME );
      snprintf( procparams.processParamsTable->param,
          LIGOMETA_PARAM_MAX, "--exclude-play" );
      snprintf( procparams.processParamsTable->type, 
          LIGOMETA_TYPE_MAX, "string" );
      snprintf( procparams.processParamsTable->value, 
          LIGOMETA_TYPE_MAX, " " );
      break;

    case all_data:
      if ( vrbflg )
        fprintf( stdout, "using all input data\n" );
      snprintf( procparams.processParamsTable->program, 
          LIGOMETA_PROGRAM_MAX, "%s", PROGRAM_NAME );
      snprintf( procparams.processParamsTable->param,
          LIGOMETA_PARAM_MAX, "--all-data" );
      snprintf( procparams.processParamsTable->type, 
          LIGOMETA_TYPE_MAX, "string" );
      snprintf( procparams.processParamsTable->value, 
          LIGOMETA_TYPE_MAX, " " );
      break;

    default:
      fprintf( stderr, "data set not defined\n" );
      exit( 1 );
  }


  /*
   *
   * read in the injection XML file, if we are doing an injection analysis
   *
   */


  if ( injectFileName )
  {
    if ( vrbflg ) 
      fprintf( stdout, "reading injections from %s... ", injectFileName );

    simEventHead = XLALSimRingdownTableFromLIGOLw( injectFileName, 0, 0 );

    if ( vrbflg ) fprintf( stdout, "got %d injections\n", numSimEvents );

    if ( ! simEventHead )
    {
      fprintf( stderr, "error: unable to read sim_ringdown table from %s\n", 
          injectFileName );
      exit( 1 );
    }

    /* if we are doing hardware injections, increment all the start times */
    if ( hardware )
    {
      if ( vrbflg ) fprintf( stdout, 
          "incrementing GPS times of injections by %d seconds\n", hardware );

      for ( thisSimEvent = simEventHead; 
          thisSimEvent; thisSimEvent = thisSimEvent->next )
      {
        thisSimEvent->geocent_start_time.gpsSeconds += hardware;
        thisSimEvent->h_start_time.gpsSeconds       += hardware;
        thisSimEvent->l_start_time.gpsSeconds       += hardware;
      }
    }

    /* discard all injection events that are not in the data we want */
    if ( dataType != all_data )
    {
      numSimDiscard = 0;

      thisSimEvent = simEventHead;
      simEventHead = NULL;
      prevSimEvent = NULL;

      if ( vrbflg ) fprintf( stdout, "discarding injections not in data\n" );

      while ( thisSimEvent )
      {
        INT4 isPlayground = XLALINT8NanoSecIsPlayground(XLALGPSToINT8NS(&(thisSimEvent->geocent_start_time)));

        if ( (dataType == playground_only && isPlayground) || 
            (dataType == exclude_play && ! isPlayground) )
        {
          /* store the head of the linked list */
          if ( ! simEventHead ) simEventHead = thisSimEvent;

          /* keep this event */
          prevSimEvent = thisSimEvent;
          thisSimEvent = thisSimEvent->next;
          ++numSimInData;
          if ( vrbflg ) fprintf( stdout, "+" );
        }
        else
        {
          /* throw this event away */
          tmpSimEvent = thisSimEvent;
          if ( prevSimEvent ) prevSimEvent->next = thisSimEvent->next;
          thisSimEvent = thisSimEvent->next;
          LALFree( tmpSimEvent );
          ++numSimDiscard;
          if ( vrbflg ) fprintf( stdout, "-" );
        }
      }

      if ( vrbflg ) 
        fprintf( stdout, "\nusing %d (discarded %d) of %d injections\n",
            numSimInData, numSimDiscard, numSimEvents );
    }
    else
    {
      if ( vrbflg ) 
        fprintf( stdout, "using all %d injections\n", numSimInData );
      numSimInData = numSimEvents;
    }
  }


  /*
   *
   * read in the input triggers from the xml files
   *
   */


  if ( inputGlob )
  {
    /* use glob() to get a list of the input file names */
    if ( glob( inputGlob, GLOB_ERR, NULL, &globbedFiles ) )
    {
      fprintf( stderr, "error globbing files from %s\n", inputGlob );
      perror( "error:" );
      exit( 1 );
    }

    numInFiles = globbedFiles.gl_pathc;
    inFileNameList = (char **) LALCalloc( numInFiles, sizeof(char *) );

    for ( j = 0; j < numInFiles; ++j )
    {
      inFileNameList[j] = globbedFiles.gl_pathv[j];
    }
  }
  else if ( inputFileName )
  {
    /* read the list of input filenames from a file */
    fp = fopen( inputFileName, "r" );
    if ( ! fp )
    {
      fprintf( stderr, "could not open file containing list of xml files\n" );
      perror( "error:" );
      exit( 1 );
    }

    /* count the number of lines in the file */
    while ( get_next_line( line, sizeof(line), fp ) )
    {
      ++numInFiles;
    }
    rewind( fp );

    /* allocate memory to store the input file names */
    inFileNameList = (char **) LALCalloc( numInFiles, sizeof(char *) );

    /* read in the input file names */
    for ( j = 0; j < numInFiles; ++j )
    {
      inFileNameList[j] = (char *) LALCalloc( MAX_PATH, sizeof(char) );
      get_next_line( line, sizeof(line), fp );
      strncpy( inFileNameList[j], line, strlen(line) - 1);
    }

    fclose( fp );
  }
  else
  {
    fprintf( stderr, "no input file mechanism specified\n" );
    exit( 1 );
  }

  if ( vrbflg )
  {
    fprintf( stdout, "reading input triggers from:\n" );
    for ( j = 0; j < numInFiles; ++j )
    {
      fprintf( stdout, "%s\n", inFileNameList[j] );
    }
  }


  /*
   *
   * read in the triggers from the input xml files
   *
   */


  if ( injectFileName )
  {
    thisSimEvent = simEventHead;
    simEventHead = NULL;
    prevSimEvent = NULL;
    numSimDiscard = 0;
    numSimInData = 0;

    if ( vrbflg ) 
      fprintf( stdout, "discarding injections not in input data\n" );
  }

  for ( j = 0; j < numInFiles; ++j )
  {
    LIGOTimeGPS inPlay, outPlay;
    UINT8 outPlayNS, outStartNS, outEndNS, triggerTimeNS;
    INT4 trigStartTimeArg = 0;

    searchSummaryTable = XLALSearchSummaryTableFromLIGOLw( inFileNameList[j] );
    if ( ( ! searchSummaryTable ) || searchSummaryTable->next )
    {
      fprintf( stderr, 
          "error: zero or multiple search_summary tables in %s\n",
          inFileNameList[j] );
      exit( 1 );
    }

    if ( enableTrigStartTime )
    {
      /* override the value of out_start_time if there is a non-zero */
      /* --trig-start-time option in the process_params table        */
      /* this is necessary to get round a bug in early versions of   */
      /* the ringdown code                                           */

      int mioStatus;
      int pParParam;
      int pParValue;
      struct MetaioParseEnvironment parseEnv;
      const  MetaioParseEnv env = &parseEnv;

      /* open the procress_params table from the input file */
      mioStatus = MetaioOpenTable( env, inFileNameList[j], "process_params" );
      if ( mioStatus )
      {
        fprintf( stderr, "error opening process_params table from file %s\n", 
            inFileNameList[j] );
        exit( 1 );
      }

      /* figure out where the param and value columns are */
      if ( (pParParam = MetaioFindColumn( env, "param" )) < 0 )
      {
        fprintf( stderr, "unable to find column param in process_params\n" );
        MetaioClose(env);
        exit( 1 );
      }
      if ( (pParValue = MetaioFindColumn( env, "value" )) < 0 )
      {
        fprintf( stderr, "unable to find column value in process_params\n" );
        MetaioClose(env);
        exit( 1 );
      }

      /* get the trigger start time from the process params */
      while ( (mioStatus = MetaioGetRow(env)) == 1 )
      {
        if ( ! strcmp( env->ligo_lw.table.elt[pParParam].data.lstring.data, 
              "--trig-start-time" ) )
        {
          trigStartTimeArg = (INT4) 
            atoi( env->ligo_lw.table.elt[pParValue].data.lstring.data );
        }
      }

      MetaioClose( env );

      if ( trigStartTimeArg )
      {
        searchSummaryTable->out_start_time.gpsSeconds = trigStartTimeArg;
        searchSummaryTable->out_start_time.gpsNanoSeconds = 0;
        if ( vrbflg ) fprintf( stdout, "file %s has --trig-start-time %d\n",
            inFileNameList[j], trigStartTimeArg );
      }
    }

    /* compute the out time from the search summary table */
    outStartNS = XLALGPSToINT8NS ( &(searchSummaryTable->out_start_time) );
    outEndNS = XLALGPSToINT8NS ( &(searchSummaryTable->out_end_time) );
    triggerTimeNS = outEndNS - outStartNS;

    /* check for events and playground */
    if ( dataType != all_data )
    {
      LAL_CALL( LALPlaygroundInSearchSummary( &status, searchSummaryTable,
            &inPlay, &outPlay ), &status );
      outPlayNS = XLALGPSToINT8NS ( &outPlay );

      if ( dataType == playground_only )
      {
        if ( outPlayNS )
        {
          /* increment the total trigger time by the amount of playground */
          triggerInputTimeNS += outPlayNS;
        }
        else
        {
          /* skip this file as it does not contain any playground data */
          if ( vrbflg )
          {
            fprintf( stdout, "file %s not in playground, continuing\n", 
                inFileNameList[j] );
          }
          LALFree( searchSummaryTable );
          searchSummaryTable = NULL;
          continue;
        }
      }
      else if ( dataType == exclude_play )
      {
        /* increment the total trigger time by the out time minus */
        /* the time that is in the playground                     */
        triggerInputTimeNS += triggerTimeNS - outPlayNS;
      }
    }
    else
    {
      /* increment the total trigger time by the out time minus */
      triggerInputTimeNS += triggerTimeNS;
    }

    if ( injectFileName )
    {
      if ( vrbflg ) fprintf( stdout, "discarding injections not in file: " );

      /* throw away injections that are outside analyzed times */
      while ( thisSimEvent && thisSimEvent->geocent_start_time.gpsSeconds < 
          searchSummaryTable->out_end_time.gpsSeconds )
      {
        /* check if injection is before file start time */
        if ( thisSimEvent->geocent_start_time.gpsSeconds < 
            searchSummaryTable->out_start_time.gpsSeconds )
        {
          /* discard the current injection */
          if ( prevSimEvent ) prevSimEvent->next = thisSimEvent->next;
          tmpSimEvent = thisSimEvent;
          thisSimEvent = thisSimEvent->next;
          LALFree( tmpSimEvent );
          ++numSimDiscard;
          if ( vrbflg ) fprintf( stdout, "-" );
        }
        else
        {
          /* store the head of the linked list */
          if ( ! simEventHead ) simEventHead = thisSimEvent;

          /* keep this injection */
          prevSimEvent = thisSimEvent;
          thisSimEvent = thisSimEvent->next;
          ++numSimInData;
          if ( vrbflg ) fprintf( stdout, "+" );
        }
      }
      if ( vrbflg ) fprintf( stdout, "\n" );
    }


    /*
     *
     * if there are any events in the file, read them in
     *
     */


    if ( searchSummaryTable->nevents )
    {
      INT4 isPlay;

      if ( vrbflg ) fprintf( stdout, "file %s contains %d events, processing\n",
          inFileNameList[j], searchSummaryTable->nevents );

      if ( ! prevEvent )
      {
        eventHandle = &thisEvent;
      }
      else
      {
        eventHandle = &(prevEvent->next);
      }

      /* read the events from the file into a temporary list */
      XLAL_TRY( *eventHandle = XLALSnglRingdownTableFromLIGOLw( inFileNameList[j] ), errnum);
      if ( ! *eventHandle )
        switch ( errnum )
        {
          case XLAL_EDATA:
            XLALPrintError("Unable to read sngl_ringdown table from %s\n", inFileNameList[j] );
            /*LALFree(thisInputFile);*/
            XLALClearErrno();
            break;
          default:
            XLALSetErrno( errnum );
            XLAL_ERROR(XLAL_EFUNC );
        }
      
      /* only keep triggers from the data that we want to analyze */
      thisEvent = *eventHandle;
      while ( thisEvent )
      {
        numEvents++;

        isPlay = XLALINT8NanoSecIsPlayground( XLALGPSToINT8NS( &(thisEvent->start_time) ) );

        if ( (dataType == all_data || 
              (dataType == playground_only && isPlay) ||
              (dataType == exclude_play && ! isPlay))
            && ( snrStar < 0 || thisEvent->snr > snrStar) )
        {
          /* keep the trigger and increment the count of triggers */
          if ( ! eventHead ) eventHead = thisEvent;
          prevEvent = thisEvent;
          thisEvent = thisEvent->next;
          ++numEventsKept;
        }
        else
        {
          /* discard the trigger and move to the next one */
          if ( prevEvent ) prevEvent->next = thisEvent->next;
          tmpEvent = thisEvent;
          thisEvent = thisEvent->next;
          LAL_CALL ( LALFreeSnglRingdown ( &status, &tmpEvent ), &status);
        }
      }

      /* make sure that the linked list is properly terminated */
      if ( prevEvent && prevEvent->next ) prevEvent->next->next = NULL;
    }
    else
    {
      if ( vrbflg ) fprintf( stdout, "file %s contains no events, skipping\n",
          inFileNameList[j] );
    }

    LALFree( searchSummaryTable );
    searchSummaryTable = NULL;
  }

  /* discard the remaining injections which occured after the last file */
  if ( injectFileName )
  {
    if ( vrbflg ) fprintf( stdout, "kept %d injections, discarded %d\n",
        numSimInData, numSimDiscard );

    if ( prevSimEvent ) prevSimEvent->next = NULL;

    numSimDiscard = 0;
    while ( thisSimEvent )
    {
      tmpSimEvent = thisSimEvent;
      thisSimEvent = thisSimEvent->next;
      LALFree( tmpSimEvent );
      ++numSimDiscard;
      if ( vrbflg ) fprintf( stdout, "-" );
    }

    if ( vrbflg ) fprintf( stdout, "\ndiscarded %d injections at end of list\n",
        numSimDiscard );
  }


  /*
   *
   * sort the ringdown events by time
   *
   */


  if ( injectFileName || sortTriggers )
  {
    if ( vrbflg ) fprintf( stdout, "sorting ringdown trigger list..." );
    LAL_CALL( LALSortSnglRingdown( &status, &eventHead, 
          *LALCompareSnglRingdownByTime ), &status );
    if ( vrbflg ) fprintf( stdout, "done\n" );
  }


  /*
   *
   * keep only event from requested ifo
   *
   */

  if ( ifoName )
  {
    if ( vrbflg ) fprintf( stdout, 
        "keeping only triggers from %s, discarding others...", ifoName );
    LAL_CALL( LALIfoCutSingleRingdown( &status, &eventHead, ifoName ), &status );
    LALIfoCountSingleRingdown( &status, &numEventsInIFO, eventHead, 
        XLALIFONumber(ifoName) );

    if ( vrbflg ) fprintf( stdout, "done\n" );
  }

  /*
   *
   * check for events that are coincident with injections
   *
   */


  if ( injectFileName )
  {
    int coincidence = 0;
    UINT8 simTime, ringdownTime;

    if ( vrbflg ) fprintf( stdout, 
        "checking for events that are coincident with injections\n" );

    /* Note: we are assuming that both the ringdown and */
    /* injection events are time sorted                 */
    thisSimEvent = simEventHead;
    thisEvent    = eventHead;

    simEventHead = NULL;
    eventHead    = NULL;
    prevSimEvent = NULL;
    prevEvent    = NULL;

    numSimFound      = 0;
    numSimDiscard    = 0;
    numEventsDiscard = 0;
    numEventsCoinc   = 0;

    if ( ! thisEvent )
    {
      /* no triggers in the input data, so all injections are missed */
      if ( vrbflg ) fprintf( stdout, "no triggers in input data\n" );

      thisMissedSim = missedSimHead = thisSimEvent;

      while ( thisMissedSim )
      {
        /* count the number of injections just stuck in the missed list */
        if ( vrbflg ) fprintf( stdout, "M" );
        ++numSimMissed;
        ++numSimProcessed;
        thisMissedSim = thisMissedSim->next;
      }
    }
    else
    {
      /* begin loop over the sim_ringdown events */
      while ( thisSimEvent )
      {
        /* compute the end time in nanosec for the injection */
        /* at the relevant detector                          */
        if ( ! strcmp( "L1", thisEvent->ifo ) )
        {
          simTime = XLALGPSToINT8NS ( &(thisSimEvent->l_start_time) );
        }
        else if ( ! strcmp( "H1", thisEvent->ifo ) || 
            ! strcmp( "H2", thisEvent->ifo ) )
        {
          simTime = XLALGPSToINT8NS ( &(thisSimEvent->h_start_time) );
        }
        else
        {
          fprintf( stderr, "unknown detector found in event list: %s\n", 
              thisEvent->ifo );
          fprintf( stderr, "Detector must be one of (G1|H1|H2|L1|T1|V1)\n");
          exit( 1 );
        }

        /* find the first ringdown event after the current sim event */
        while ( thisEvent )
        {
          coincidence = 0;

          /* compute the time in nanosec for the ringdown */
          ringdownTime = XLALGPSToINT8NS ( &(thisEvent->start_time) );

          if ( ringdownTime < (simTime - inject_dt) )
          {
            /* discard this event and move on to the next one */
            if ( prevEvent ) prevEvent->next = thisEvent->next;
            tmpEvent = thisEvent;
            thisEvent = thisEvent->next;
            LAL_CALL ( LALFreeSnglRingdown ( &status, &tmpEvent ), &status);
            ++numEventsProcessed;
            ++numEventsDiscard;
            if ( vrbflg ) fprintf( stdout, "-" );
          }
          else
          {
            /* we have reached the negative coincincidence window */
            break;
          }
        }

        while ( thisEvent )
        {
          /* compute the time in nanosec for the ringdown */
          ringdownTime = XLALGPSToINT8NS ( &(thisEvent->start_time) );

          if ( ringdownTime < (simTime + inject_dt) )
          {
            /* this event is within the coincidence window  */
            /* store this event and move on to the next one */
            if ( ! eventHead ) eventHead = thisEvent;
            prevEvent = thisEvent;
            thisEvent = thisEvent->next;
            coincidence = 1;
            ++numEventsProcessed;
            ++numEventsCoinc;
            if ( vrbflg ) fprintf( stdout, "+" );
          }
          else
          {
            /* we have reached the end of the positive coincincidence window */
            break;
          }
        }

        if ( coincidence )
        {
          /* keep this event in the list and move to the next sim event */
          if ( ! simEventHead ) simEventHead = thisSimEvent;
          prevSimEvent = thisSimEvent;
          ++numSimFound;
          ++numSimProcessed;
          thisSimEvent = thisSimEvent->next;
          if ( vrbflg ) fprintf( stdout, "F" );
        }
        else
        {
          /* save this sim event in the list of missed events... */
          if ( ! missedSimHead )
          {
            missedSimHead = thisMissedSim = thisSimEvent;
          }
          else
          {
            thisMissedSim = thisMissedSim->next = thisSimEvent;
          }

          /* ...and remove it from the list of found events */
          if ( prevSimEvent ) prevSimEvent->next = thisSimEvent->next;
          ++numSimMissed;
          if ( vrbflg ) fprintf( stdout, "M" );

          /* move to the next sim in the list */
          ++numSimProcessed;
          thisSimEvent = thisSimEvent->next;

          /* make sure the missed sim list is terminated */
          thisMissedSim->next = NULL;
        }

        if ( ! thisEvent )
        {
          /* these are no more events to process so all the rest of the */
          /* injections must be put in the missed injections list       */
          if ( ! missedSimHead )
          {
            /* this and any subsequent events are in the missed sim list */
            if ( thisSimEvent ) thisMissedSim = missedSimHead = thisSimEvent;
          }
          else
          {
            if ( thisSimEvent )
            {
              /* append the rest of the list to the list of missed injections */
              thisMissedSim = thisMissedSim->next = thisSimEvent;
            }
            else
            {
              /* there are no injections after this one */
              thisMissedSim = thisMissedSim->next = NULL;
            }
          }

          /* terminate the list of found injections correctly */
          if ( prevSimEvent ) prevSimEvent->next = NULL;

          while ( thisMissedSim )
          {
            /* count the number of injections just stuck in the missed list */
            if ( vrbflg ) fprintf( stdout, "M" );
            ++numSimMissed;
            ++numSimProcessed;
            thisMissedSim = thisMissedSim->next;
          }
          thisSimEvent = NULL;
          break;
        }
      }

      if ( thisEvent )
      {
        /* discard any remaining ringdown triggers -- including thisEvent */
        /* as we have run out of injections */
        tmpEvent = thisEvent;
        if ( prevEvent ) prevEvent->next = NULL;
        while ( tmpEvent )
        {
          thisEvent = tmpEvent;
          tmpEvent = tmpEvent->next;
          LAL_CALL ( LALFreeSnglRingdown ( &status, &thisEvent ), &status);
          ++numEventsDiscard;
          ++numEventsProcessed;
          if ( vrbflg ) fprintf( stdout, "-" );
        }
      }
    }

    if ( vrbflg )
    {
      fprintf( stdout, "\nfound %d injections, missed %d injections "
          "(%d injections processed)\n",
          numSimFound, numSimMissed, numSimProcessed );

      fprintf( stdout, "found %d coincident events, %d events discarded "
          "(%d events processed)\n",
          numEventsCoinc, numEventsDiscard, numEventsProcessed );
    }

  } /* end if ( injectFileName ) */


  /*
   *
   * cluster the remaining events
   *
   */


  if ( eventHead && clusterchoice )
  {
    if ( vrbflg ) fprintf( stdout, "clustering remaining triggers... " );
    LAL_CALL( LALClusterSnglRingdownTable( &status, eventHead,
          cluster_dt, clusterchoice ), &status );
    if ( vrbflg ) fprintf( stdout, "done\n" );

    /* count the number of triggers surviving the clustering */
    thisEvent = eventHead;
    numClusteredEvents = 0;
    while ( thisEvent )
    {
      ++numClusteredEvents;
      thisEvent = thisEvent->next;
    }
  }


  /*
   *
   * write output data
   *
   */


  /* write the main output file containing found injections */
  if ( vrbflg ) fprintf( stdout, "writing output xml files... " );
  memset( &xmlStream, 0, sizeof(LIGOLwXMLStream) );
  LAL_CALL( LALOpenLIGOLwXMLFile( &status, &xmlStream, outputFileName ), &status );

  /* write out the process and process params tables */
  if ( vrbflg ) fprintf( stdout, "process... " );
  XLALGPSTimeNow(&(proctable.processTable->start_time));
  LAL_CALL( LALBeginLIGOLwXMLTable( &status, &xmlStream, process_table ), 
      &status );
  LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, proctable, 
        process_table ), &status );
  LAL_CALL( LALEndLIGOLwXMLTable ( &status, &xmlStream ), &status );
  free( proctable.processTable );

  /* write the process params table */
  if ( vrbflg ) fprintf( stdout, "process_params... " );
  LAL_CALL( LALBeginLIGOLwXMLTable( &status, &xmlStream, 
        process_params_table ), &status );
  LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, procparams, 
        process_params_table ), &status );
  LAL_CALL( LALEndLIGOLwXMLTable ( &status, &xmlStream ), &status );

  /* Write the found injections to the sim table */
  if ( simEventHead )
  {
    if ( vrbflg ) fprintf( stdout, "sim_ringdown... " );
    outputTable.simRingdownTable = simEventHead;
    LAL_CALL( LALBeginLIGOLwXMLTable( &status, &xmlStream, 
          sim_ringdown_table ), &status );
    LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, outputTable, 
          sim_ringdown_table ), &status );
    LAL_CALL( LALEndLIGOLwXMLTable( &status, &xmlStream ), &status );
  }

  /* Write the results to the ringdown table */
  if ( eventHead )
  {
    if ( vrbflg ) fprintf( stdout, "sngl_ringdown... " );
    outputTable.snglRingdownTable = eventHead;
    LAL_CALL( LALBeginLIGOLwXMLTable( &status, &xmlStream, 
          sngl_ringdown_table ), &status );
    LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, outputTable, 
          sngl_ringdown_table ), &status );
    LAL_CALL( LALEndLIGOLwXMLTable( &status, &xmlStream ), &status);
  }

  /* close the output file */
  LAL_CALL( LALCloseLIGOLwXMLFile(&status, &xmlStream), &status);
  if ( vrbflg ) fprintf( stdout, "done\n" );

  /* write out the TAMA file if it is requested */
  if ( tamaFileName )
  {
    /* FIXME */
    REAL8 UNUSED trigtime;

    fp = fopen( tamaFileName, "w" );
    if ( ! fp )
    {
      perror( "TAMA file" );
      exit( 1 );
    }

    fprintf( fp, "IFO   trigger time       snr         chisq       "
        " total mass     eta       eff dist (kpc)\n" );

    for ( thisEvent = eventHead; thisEvent; thisEvent = thisEvent->next )
    {
      trigtime = XLALGPSGetREAL8(&(thisEvent->start_time));
    }

    fclose( fp );
  }

  if ( missedFileName )
  {
    /* open the missed injections file and write the missed injections to it */
    if ( vrbflg ) fprintf( stdout, "writing missed injections... " );
    memset( &xmlStream, 0, sizeof(LIGOLwXMLStream) );
    LAL_CALL( LALOpenLIGOLwXMLFile( &status, &xmlStream, missedFileName ), 
        &status );

    if ( missedSimHead )
    {
      outputTable.simRingdownTable = missedSimHead;
      LAL_CALL( LALBeginLIGOLwXMLTable( &status, &xmlStream, sim_ringdown_table ),
          &status );
      LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, outputTable, 
            sim_ringdown_table ), &status );
      LAL_CALL( LALEndLIGOLwXMLTable( &status, &xmlStream ), &status );
    }

    LAL_CALL( LALCloseLIGOLwXMLFile( &status, &xmlStream ), &status );
    if ( vrbflg ) fprintf( stdout, "done\n" );
  }

  if ( summFileName )
  {
    LIGOTimeGPS triggerTime;

    /* write out a summary file */
    fp = fopen( summFileName, "w" );

    switch ( dataType )
    {
      case playground_only:
        fprintf( fp, "using data from playground times only\n" );
        break;
      case exclude_play:
        fprintf( fp, "excluding all triggers in playground times\n" );
        break;
      case all_data:
        fprintf( fp, "using all input data\n" );
        break;
      default:
        fprintf( stderr, "data set not defined\n" );
        exit( 1 );
    }

    fprintf( fp, "read triggers from %d files\n", numInFiles );
    fprintf( fp, "number of triggers in input files: %d \n", numEvents );
    if ( snrStar >= 0 )
    {
      fprintf( fp, "number of triggers in input data with snr above %f: %d \n",
          snrStar, numEventsKept );
    }
    else
    {
      fprintf( fp, "number of triggers in input data %d \n", numEventsKept );
    }

    if ( ifoName )
    {
      fprintf( fp, "number of triggers from %s ifo %d \n", ifoName, 
          numEventsInIFO );
    }

    XLALINT8NSToGPS( &triggerTime, triggerInputTimeNS );
    fprintf( fp, "amount of time analysed for triggers %d sec %d ns\n", 
        triggerTime.gpsSeconds, triggerTime.gpsNanoSeconds );

    if ( injectFileName )
    {
      fprintf( fp, "read %d injections from file %s\n", 
          numSimEvents, injectFileName );

      fprintf( fp, "number of injections in input data: %d\n", numSimInData );
      fprintf( fp, "number of injections found in input data: %d\n", 
          numSimFound );
      fprintf( fp, 
          "number of triggers found within %" LAL_INT8_FORMAT "msec of injection: %d\n",
          (inject_dt / LAL_INT8_C(1000000) ), numEventsCoinc );

      fprintf( fp, "efficiency: %f \n", 
          (REAL4) numSimFound / (REAL4) numSimInData );
    }

    if ( clusterchoice )
    {
      fprintf( fp, "number of event clusters with %" LAL_INT8_FORMAT " msec window: %d\n",
          cluster_dt/ LAL_INT8_C(1000000), numClusteredEvents ); 
    }

    fclose( fp ); 
  }


  /*
   *
   * free memory and exit
   *
   */


  /* free the ringdown events we saved */
  while ( eventHead )
  {
    thisEvent = eventHead;
    eventHead = eventHead->next;
    LAL_CALL ( LALFreeSnglRingdown ( &status, &thisEvent ), &status);
  }

  /* free the process params */
  while( procparams.processParamsTable )
  {
    this_proc_param = procparams.processParamsTable;
    procparams.processParamsTable = this_proc_param->next;
    free( this_proc_param );
  }

  /* free the found injections */
  while ( simEventHead )
  {
    thisSimEvent = simEventHead;
    simEventHead = simEventHead->next;
    LALFree( thisSimEvent );
  }

  /* free the temporary memory containing the missed injections */
  while ( missedSimHead )
  {
    tmpSimEvent = missedSimHead;
    missedSimHead = missedSimHead->next;
    LALFree( tmpSimEvent );
  }

  /* free the input file name data */
  if ( inputGlob )
  {
    LALFree( inFileNameList ); 
    globfree( &globbedFiles );
  }
  else
  {
    for ( j = 0; j < numInFiles; ++j )
    {
      LALFree( inFileNameList[j] );
    }
    LALFree( inFileNameList );
  }

  if ( vrbflg ) fprintf( stdout, "checking memory leaks and exiting\n" );
  LALCheckMemoryLeaks();
  exit( 0 );
}
Exemple #8
0
int main ( int argc, char *argv[] )
{
  /* xml output data */
  CHAR                  fname[256];
  CHAR                 *userTag = NULL;
  LALStatus             status = blank_status;
  MetadataTable         proctable;
  MetadataTable         procparams;
  MetadataTable         injections;
  SimInspiralTable      injParams;
  ProcessParamsTable   *this_proc_param;
  LIGOLwXMLStream       xmlfp;

  /* default sky position */
  SkyPosition           binaryPosition;

  struct LALoption long_options[] =
  {
    {"help",                    no_argument,       0,                'H'},
    {"end-time",                required_argument, 0,                'a'},
    {"end-time-ns",             required_argument, 0,                'b'},
    {"mass-1",                  required_argument, 0,                'c'},
    {"mass-2",                  required_argument, 0,                'd'},
    {"distance",                required_argument, 0,                'e'},
    {"longitude",               required_argument, 0,                'f'},
    {"latitude",                required_argument, 0,                'g'},
    {"coordinate-system",       required_argument, 0,                'h'},
    {"inclinaton",              required_argument, 0,                'i'},
    {"coalescence-phase",       required_argument, 0,                'j'},
    {"polarization",            required_argument, 0,                'k'},
    {"waveform,"                required_argument, 0,                'l'},
    {"user-tag",                required_argument, 0,                'Z'},
    {"userTag",                 required_argument, 0,                'Z'},
    {0, 0, 0, 0}
  };
  int c;

  /* set up inital debugging values */
  lal_errhandler = LAL_ERR_EXIT;

  /* create the process and process params tables */
  proctable.processTable = (ProcessTable *) 
    calloc( 1, sizeof(ProcessTable) );
  XLALGPSTimeNow(&(proctable.processTable->start_time));
  if (strcmp(CVS_REVISION,"$Revi" "sion$"))
    {
      XLALPopulateProcessTable(proctable.processTable, PROGRAM_NAME,
          CVS_REVISION, CVS_SOURCE, CVS_DATE, 0);
    }
  else
    {
      XLALPopulateProcessTable(proctable.processTable, PROGRAM_NAME,
          lalappsGitCommitID, lalappsGitGitStatus, lalappsGitCommitDate, 0);
    }
  snprintf( proctable.processTable->comment, LIGOMETA_COMMENT_MAX, " " );
  this_proc_param = procparams.processParamsTable = (ProcessParamsTable *) 
    calloc( 1, sizeof(ProcessParamsTable) );

  /* clear the waveform field */
  memset( &(injParams.waveform), 0, LIGOMETA_WAVEFORM_MAX * sizeof(CHAR) );

  /* set the default values */
  injParams.mass1 = 1.4;
  injParams.mass2 = 1.4;
  injParams.eta = 0.25;
  injParams.distance = 1.0;
  injParams.inclination = 0;
  injParams.coa_phase = 0;
  injParams.polarization = 0;

  /* parse the arguments */
  while ( 1 )
  {
    /* LALgetopt_long stores long option here */
    int option_index = 0;
    long int gpsinput;
    size_t LALoptarg_len;

    c = LALgetopt_long_only( argc, argv,
        "Ha:b:c:d:e:f:g:h:i:j:k:l:Z:", long_options, &option_index );

    /* detect the end of the options */
    if ( c == - 1 )
    {
      break;
    }

    switch ( c )
    {
      case 0:
        /* if this option set a flag, do nothing else now */
        if ( long_options[option_index].flag != 0 )
        {
          break;
        }
        else
        {
          fprintf( stderr, "error parsing option %s with argument %s\n",
              long_options[option_index].name, LALoptarg );
          exit( 1 );
        }
        break;

      case 'a':
        {
          long int gendsec = atol( LALoptarg );
          if ( gendsec < 441417609 )
          {
            fprintf( stderr, "invalid argument to --%s:\n"
                "GPS start time is prior to " 
                "Jan 01, 1994  00:00:00 UTC:\n"
                "(%ld specified)\n",
                long_options[option_index].name, gendsec );
            exit( 1 );
          }
          injParams.geocent_end_time.gpsSeconds = (INT4) gendsec;
          this_proc_param = this_proc_param->next = 
            next_process_param( long_options[option_index].name, "int", 
                "%ld", gendsec );
        }
        break;

      case 'b':
        {
          long int gendnansec = atol( LALoptarg );
          if ( gendnansec < 0 )
          {
            fprintf( stderr, "invalid argument to --%s:\n"
                "GPS start time nanoseconds is negative\n",
                long_options[option_index].name );
            exit( 1 );
          }
          if ( gendnansec > 999999999 )
          {
            fprintf( stderr, "invalid argument to --%s:\n"
                "GPS start time nanoseconds is greater than unity:\n" 
                "Must be <= 999999999 (%ld specified)\n", 
                long_options[option_index].name, gendnansec );
            exit( 1 );
          }
          injParams.geocent_end_time.gpsNanoSeconds = (INT4) gendnansec;
          this_proc_param = this_proc_param->next = 
            next_process_param( long_options[option_index].name, "int", 
                "%ld", gendnansec );
        }
        break;

      case 'c':
        injParams.mass1 = (REAL4) atof( LALoptarg );
        this_proc_param = this_proc_param->next = 
          next_process_param( long_options[option_index].name, "real_4", 
              "%d", rand_seed );
        break;

      case 'd':
        injParams.mass2 = (REAL4) atof( LALoptarg );
        this_proc_param = this_proc_param->next = 
          next_process_param( long_options[option_index].name, "real_4", 
              "%d", rand_seed );
        break;

      case 'e':
        injParams.distance = (REAL4) atof( LALoptarg );
        this_proc_param = this_proc_param->next = 
          next_process_param( long_options[option_index].name, "real_4", 
              "%d", rand_seed );
        break;

      case 'f':
        abort();
        break;

      case 'g':
        abort();
        break;

      case 'h':
        abort();
        break;

      case 'i':
        injParams.inclination = (REAL4) atof( LALoptarg );
        this_proc_param = this_proc_param->next = 
          next_process_param( long_options[option_index].name, "real_4", 
              "%d", rand_seed );
        break;

      case 'j':
        injParams.coa_phase= (REAL4) atof( LALoptarg );
        this_proc_param = this_proc_param->next = 
          next_process_param( long_options[option_index].name, "real_4", 
              "%d", rand_seed );
        break;

      case 'k':
        injParams.polarization = (REAL4) atof( LALoptarg );
        this_proc_param = this_proc_param->next = 
          next_process_param( long_options[option_index].name, "real_4", 
              "%d", rand_seed );
        break;

      case 'l':
        snprintf( &(injParams.waveform), 
                  LIGOMETA_WAVEFORM_MAX, "%s", LALoptarg );
        this_proc_param = this_proc_param->next = 
          next_process_param( long_options[option_index].name, "string", 
              "%s", LALoptarg );
        break;

      case 'Z':
        /* create storage for the usertag */
        LALoptarg_len = strlen( LALoptarg ) + 1;
        userTag = (CHAR *) calloc( LALoptarg_len, sizeof(CHAR) );
        memcpy( userTag, LALoptarg, LALoptarg_len );

        this_proc_param = this_proc_param->next = (ProcessParamsTable *)
          calloc( 1, sizeof(ProcessParamsTable) );
        snprintf( this_proc_param->program, LIGOMETA_PROGRAM_MAX, "%s", 
                  PROGRAM_NAME );
        snprintf( this_proc_param->param, LIGOMETA_PARAM_MAX, "-userTag" );
        snprintf( this_proc_param->type, LIGOMETA_TYPE_MAX, "string" );
        snprintf( this_proc_param->value, LIGOMETA_VALUE_MAX, "%s",
                  LALoptarg );
        break;

      case 'h':
        fprintf( stderr, USAGE );
        exit( 0 );
        break;

      case '?':
        fprintf( stderr, USAGE );
        exit( 1 );
        break;

      default:
        fprintf( stderr, "unknown error while parsing options\n" );
        fprintf( stderr, USAGE );
        exit( 1 );
    }
  }

  if ( ! *waveform )
  {
    /* default to Tev's GeneratePPNInspiral as used in */
    snprintf( waveform, LIGOMETA_WAVEFORM_MAX, "GeneratePPNtwoPN" );
  }
Exemple #9
0
int main( int argc, char *argv[] )
{
  static LALStatus      status;

  INT4  startTime = -1;
  LIGOTimeGPS startTimeGPS = {0,0};
  INT4  endTime = -1;
  LIGOTimeGPS endTimeGPS = {0,0};
  CHAR  inputIFO[LIGOMETA_IFO_MAX];
  CHAR  outputIFO[LIGOMETA_IFO_MAX];
  CHAR  comment[LIGOMETA_COMMENT_MAX];
  CHAR *userTag = NULL;
  CHAR *ifoTag = NULL;

  CHAR  fileName[FILENAME_MAX];

  INT4  numTriggers = 0;

  SnglInspiralTable    *inspiralEventList=NULL;
  SnglInspiralTable    *currentTrigger = NULL;

  SearchSummvarsTable  *inputFiles = NULL;
  SearchSummvarsTable  *thisInputFile = NULL;

  SearchSummaryTable   *searchSummList = NULL;
  SearchSummaryTable   *thisSearchSumm = NULL;

  MetadataTable         proctable;
  MetadataTable         processParamsTable;
  MetadataTable         searchsumm;
  MetadataTable         searchSummvarsTable;
  MetadataTable         inspiralTable;
  ProcessParamsTable   *this_proc_param = NULL;
  LIGOLwXMLStream       xmlStream;
  INT4                  outCompress = 0;

  long int              gpstime;

  trigScanType trigScanMethod = trigScanNone;
                                          /* Switch for clustering        */
                                          /* triggers in template         */
                                          /* parameters and end time      */
  REAL8  trigScanMetricScalingFac = -1.0;
  /* Use this scaling factor for the volume spanned by a trigger in the   */
  /* parameter space. When set to x, the volume is taken to be that of the*/
  /* ambiguity ellipsoid at a 'minimal match' of (1.0-x).                 */
                                          /* original bank entered at the */
                                          /* command line                 */
  INT2  trigScanAppendStragglers = -1;    /* Switch to append cluster     */
                                          /* out-liers (stragglers)       */

  INT4                  i;

  /* LALgetopt arguments */
  struct LALoption long_options[] =
  {
    {"verbose",                no_argument,           &vrbflg,            1 },
    {"write-compress",         no_argument,           &outCompress,       1 },
    {"gps-start-time",         required_argument,     0,                 'q'},
    {"gps-end-time",           required_argument,     0,                 'r'},
    {"help",                   no_argument,           0,                 'h'}, 
    {"version",                no_argument,           0,                 'V'},
    {"user-tag",               required_argument,     0,                 'Z'},
    {"ifo",                    required_argument,     0,                 'I'},
    {"ts-cluster",             required_argument,     0,                 '*'},
    {"ts-metric-scaling",      required_argument,     0,                 '>'},
    {0, 0, 0, 0}
  };
  int c;

  /*
   * 
   * initialize things
   *
   */

  lal_errhandler = LAL_ERR_EXIT;
  setvbuf( stdout, NULL, _IONBF, 0 );

  /* create the process and process params tables */
  proctable.processTable = (ProcessTable *) calloc( 1, sizeof(ProcessTable) );
  XLALGPSTimeNow(&(proctable.processTable->start_time));
  XLALPopulateProcessTable(proctable.processTable, PROGRAM_NAME, lalAppsVCSIdentId,
      lalAppsVCSIdentStatus, lalAppsVCSIdentDate, 0);
  this_proc_param = processParamsTable.processParamsTable = 
    (ProcessParamsTable *) calloc( 1, sizeof(ProcessParamsTable) );
  memset( comment, 0, LIGOMETA_COMMENT_MAX * sizeof(CHAR) );

  /* create the search summary and zero out the summvars table */
  searchsumm.searchSummaryTable = (SearchSummaryTable *)
    calloc( 1, sizeof(SearchSummaryTable) );


  /* parse the arguments */
  while ( 1 )
  {
    /* LALgetopt_long stores long option here */
    int option_index = 0;
    size_t LALoptarg_len;

    c = LALgetopt_long_only( argc, argv,
        "a:b:hq:r:s:A:I:VZ:", long_options, 
        &option_index );

    /* detect the end of the options */
    if ( c == -1 )
    {
      break;
    }

    switch ( c )
    {
      case 0:
        /* if this option set a flag, do nothing else now */
        if ( long_options[option_index].flag != 0 )
        {
          break;
        }
        else
        {
          fprintf( stderr, "Error parsing option %s with argument %s\n",
              long_options[option_index].name, LALoptarg );
          exit( 1 );
        }
        break;

      case 's':
        if ( strlen( LALoptarg ) > LIGOMETA_COMMENT_MAX - 1 )
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "comment must be less than %d characters\n",
              long_options[option_index].name, LIGOMETA_COMMENT_MAX );
          exit( 1 );
        }
        else
        {
          snprintf( comment, LIGOMETA_COMMENT_MAX, "%s", LALoptarg);
        }
        break;

      case 'h':
        /* help message */
        print_usage(argv[0]);
        exit( 1 );
        break;

      case 'Z':
        /* create storage for the usertag */
        LALoptarg_len = strlen(LALoptarg) + 1;
        userTag = (CHAR *) calloc( LALoptarg_len, sizeof(CHAR) );
        memcpy( userTag, LALoptarg, LALoptarg_len );

        this_proc_param = this_proc_param->next = (ProcessParamsTable *)
          calloc( 1, sizeof(ProcessParamsTable) );
        snprintf( this_proc_param->program, LIGOMETA_PROGRAM_MAX, "%s", 
            PROGRAM_NAME );
        snprintf( this_proc_param->param, LIGOMETA_PARAM_MAX, "-userTag" );
        snprintf( this_proc_param->type, LIGOMETA_TYPE_MAX, "string" );
        snprintf( this_proc_param->value, LIGOMETA_VALUE_MAX, "%s",
            LALoptarg );
        break;

      case 'I':
        /* create storage for the ifo-tag */
        LALoptarg_len = strlen(LALoptarg) + 1;
        ifoTag = (CHAR *) calloc( LALoptarg_len, sizeof(CHAR) );
        memcpy( ifoTag, LALoptarg, LALoptarg_len );
        ADD_PROCESS_PARAM( "string", "%s", LALoptarg );

        snprintf(inputIFO,  LIGOMETA_IFO_MAX, "%s", LALoptarg);
        snprintf(outputIFO, LIGOMETA_IFO_MAX, "%s", LALoptarg);
        break;
      case 'V':
        /* print version information and exit */
        fprintf( stdout, "TrigScan Cluster \n" 
            "Larne Pekowsky\n"
            "Based on trigbank and inspiral by Patrick Brady, Duncan Brown and Steve Fairhurst\n");
        XLALOutputVersionString(stderr, 0);
        exit( 0 );
        break;

      case '?':
        print_usage(argv[0]);
        exit( 1 );
        break;
      case 'q':
        /* start time */
        gpstime = atol( LALoptarg );
        if ( gpstime < 441417609 )
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "GPS start time is prior to " 
              "Jan 01, 1994  00:00:00 UTC:\n"
              "(%ld specified)\n",
              long_options[option_index].name, gpstime );
          exit( 1 );
        }
        startTime = (INT4) gpstime;
        startTimeGPS.gpsSeconds = startTime;
        ADD_PROCESS_PARAM( "int", "%" LAL_INT4_FORMAT, startTime );
        break;

      case 'r':
        /* end time  */
        gpstime = atol( LALoptarg );
        if ( gpstime < 441417609 )
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "GPS start time is prior to " 
              "Jan 01, 1994  00:00:00 UTC:\n"
              "(%ld specified)\n",
              long_options[option_index].name, gpstime );
          exit( 1 );
        }
        endTime = (INT4) gpstime;
        endTimeGPS.gpsSeconds = endTime;
        ADD_PROCESS_PARAM( "int", "%" LAL_INT4_FORMAT, endTime );
        break;

      case '*':
        /* store trigSanClustering method */
        if ( ! strcmp( "T0T3Tc", LALoptarg ) )
        {
            trigScanMethod = T0T3Tc;
            trigScanAppendStragglers = 0;
        }
        else if ( ! strcmp( "T0T3TcAS", LALoptarg ) )
        {
            trigScanMethod = T0T3Tc;
            trigScanAppendStragglers = 1;
        }
        else if ( ! strcmp( "Psi0Psi3Tc", LALoptarg ) )
        {
            trigScanMethod = Psi0Psi3Tc;
            trigScanAppendStragglers = 0;
        }
        else if ( ! strcmp( "Psi0Psi3TcAS", LALoptarg ) )
        {
            trigScanMethod = Psi0Psi3Tc;
            trigScanAppendStragglers = 1;
        }
        else
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "unknown scan method specified: %s\n"
              "(Must be one of T0T3Tc, T0T3TcAS, Psi0Psi3Tc, Psi0Psi3TcAS)\n",
              long_options[option_index].name, LALoptarg );
          exit( 1 );
        }
        ADD_PROCESS_PARAM( "string", "%s", LALoptarg );
        break;

      case '>':
        /* TrigScan Template Metric Scaling Factor */
        trigScanMetricScalingFac = atof( LALoptarg );
        if ( trigScanMetricScalingFac <= 0.0 )
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "ts-volume-safety must be > 0.0 : "
              "(%f specified)\n",
              long_options[option_index].name, trigScanMetricScalingFac );
          exit( 1 );
        }
        ADD_PROCESS_PARAM( "float", "%s", LALoptarg );
        break;
      default:
        fprintf( stderr, "Error: Unknown error while parsing options\n" );
        print_usage(argv[0]);
        exit( 1 );
    }
  }


  /* check the values of the arguments */
  if ( startTime < 0 )
  {
    fprintf( stderr, "Error: --gps-start-time must be specified\n" );
    exit( 1 );
  }

  if ( endTime < 0 )
  {
    fprintf( stderr, "Error: --gps-end-time must be specified\n" );
    exit( 1 );
  }

  /* Check the trigScan input parameters */
  if ( ! trigScanMethod )
  {
      fprintf ( stderr, "You must specify --ts-method\n" );
      exit(1);
  }

  if ( trigScanMetricScalingFac <= 0.0 )
  {
    fprintf ( stderr, "You must specify --ts-metric-scaling\n" );
    exit(1);
  }


  /* fill the comment, if a user has specified one, or leave it blank */
  if ( ! *comment )
  {
    snprintf( proctable.processTable->comment, LIGOMETA_COMMENT_MAX, " " );
    snprintf( searchsumm.searchSummaryTable->comment, LIGOMETA_COMMENT_MAX, 
        " " );
  } 
  else 
  {
    snprintf( proctable.processTable->comment, LIGOMETA_COMMENT_MAX,
        "%s", comment );
    snprintf( searchsumm.searchSummaryTable->comment, LIGOMETA_COMMENT_MAX,
        "%s", comment );
  }

  /* delete the first, empty process_params entry */
  this_proc_param = processParamsTable.processParamsTable;
  processParamsTable.processParamsTable = 
    processParamsTable.processParamsTable->next;
  free( this_proc_param );

  /*
   *
   * read in the input data from the rest of the arguments
   *
   */

  if ( LALoptind < argc )
  {
    for( i = LALoptind; i < argc; ++i )
    {
      INT4 numFileTriggers = 0;

      numFileTriggers = XLALReadInspiralTriggerFile( &inspiralEventList,
          &currentTrigger, &searchSummList, &inputFiles, argv[i] );
      if (numFileTriggers < 0)
      {
        fprintf(stderr, "Error reading triggers from file %s",
            argv[i]);
        exit( 1 );
      }
      
      numTriggers += numFileTriggers;
    }
  }
  else
  {
    fprintf( stderr, "Error: No trigger files specified.\n" );
    exit( 1 );
  }

  if ( vrbflg ) fprintf( stdout, "Read in a total of %d triggers.\n",
      numTriggers );


  if ( ! inspiralEventList )
  {
    /* no triggers read in so triggered bank will be empty */
    fprintf( stdout, "No triggers read in\n");
    exit( 0 );
  }


  /* trigScanClustering */ 
  /* Call the clustering routine */ 
  if (XLALTrigScanClusterTriggers( &(inspiralEventList),
                                 trigScanMethod,
                                 trigScanMetricScalingFac,
                                 trigScanAppendStragglers ) == XLAL_FAILURE )
  {
    fprintf( stderr, "New trig scan has failed!!\n" );
    exit(1);
  }

  /* time sort the triggers */
  if ( vrbflg ) fprintf( stdout, "Sorting triggers\n" );
  LAL_CALL( LALSortSnglInspiral( &status, &inspiralEventList,
        LALCompareSnglInspiralByTime ), &status );

  if( !inspiralEventList )
  {
    if ( vrbflg ) fprintf( stdout, 
        "No triggers remain after time and playground cuts.\n" );

    /* set numTriggers after cuts were applied */
    numTriggers = 0;
  }

  /*
   *
   * write the output xml file
   *
   */

  /* search summary entries: */
  searchsumm.searchSummaryTable->in_start_time = startTimeGPS;
  searchsumm.searchSummaryTable->in_end_time = endTimeGPS;
  searchsumm.searchSummaryTable->out_start_time = startTimeGPS;
  searchsumm.searchSummaryTable->out_end_time = endTimeGPS;
  searchsumm.searchSummaryTable->nevents = numTriggers;

  if ( vrbflg ) fprintf( stdout, "writing output file... " );

  /* set the file name correctly */
  if ( userTag && !outCompress )
 {
    snprintf( fileName, FILENAME_MAX, "%s-TRIGSCAN_%s-%d-%d.xml", 
        outputIFO, userTag, startTime, endTime - startTime );
  }
  else if ( !userTag && !outCompress )
  {
    snprintf( fileName, FILENAME_MAX, "%s-TRIGSCAN_%d-%d.xml", 
        outputIFO, startTime, endTime - startTime );
  }
  else if ( userTag && outCompress )
  {
    snprintf( fileName, FILENAME_MAX, "%s-TRIGSCAN_%s-%d-%d.xml.gz",
        outputIFO, userTag, startTime, endTime - startTime );
  }
  else 
  {
    snprintf( fileName, FILENAME_MAX, "%s-TRIGSCAN_%d-%d.xml.gz",
        outputIFO, startTime, endTime - startTime );
  }

  memset( &xmlStream, 0, sizeof(LIGOLwXMLStream) );
  LAL_CALL( LALOpenLIGOLwXMLFile( &status , &xmlStream, fileName ), 
      &status );

  /* write process table */
  snprintf( proctable.processTable->ifos, LIGOMETA_IFOS_MAX, "%s", 
      inputIFO );
  XLALGPSTimeNow(&(proctable.processTable->end_time));
  LAL_CALL( LALBeginLIGOLwXMLTable( &status, &xmlStream, process_table ), 
      &status );
  LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, proctable, 
        process_table ), &status );
  LAL_CALL( LALEndLIGOLwXMLTable ( &status, &xmlStream ), &status );

  /* write process_params table */
  LAL_CALL( LALBeginLIGOLwXMLTable( &status, &xmlStream, 
        process_params_table ), &status );
  LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, processParamsTable, 
        process_params_table ), &status );
  LAL_CALL( LALEndLIGOLwXMLTable ( &status, &xmlStream ), &status );

  /* write search_summary table */
  LAL_CALL( LALBeginLIGOLwXMLTable( &status, &xmlStream, 
        search_summary_table ), &status );
  LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, searchsumm, 
        search_summary_table ), &status );
  LAL_CALL( LALEndLIGOLwXMLTable ( &status, &xmlStream ), &status );

  /* write the search_summvars tabls */
  LAL_CALL( LALBeginLIGOLwXMLTable( &status ,&xmlStream, 
        search_summvars_table), &status );
  searchSummvarsTable.searchSummvarsTable = inputFiles;
  LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, searchSummvarsTable,
        search_summvars_table), &status );
  LAL_CALL( LALEndLIGOLwXMLTable( &status, &xmlStream), &status );

  /* write the sngl_inspiral table */
  if ( inspiralEventList )
  {
    LAL_CALL( LALBeginLIGOLwXMLTable( &status ,&xmlStream, 
          sngl_inspiral_table), &status );
    inspiralTable.snglInspiralTable = inspiralEventList;
    LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, inspiralTable,
          sngl_inspiral_table), &status );
    LAL_CALL( LALEndLIGOLwXMLTable( &status, &xmlStream), &status );
  }

  LAL_CALL( LALCloseLIGOLwXMLFile( &status, &xmlStream), &status );


  if ( vrbflg ) fprintf( stdout, "done\n" );


  /*
   *
   * clean up the memory that has been allocated 
   *
   */


  if ( vrbflg ) fprintf( stdout, "freeing memory... " );

  free( proctable.processTable );
  free( searchsumm.searchSummaryTable );

  while ( processParamsTable.processParamsTable )
  {
    this_proc_param = processParamsTable.processParamsTable;
    processParamsTable.processParamsTable = this_proc_param->next;
    free( this_proc_param );
  }

  while ( inputFiles )
  {
    thisInputFile = inputFiles;
    inputFiles = thisInputFile->next;
    LALFree( thisInputFile );
  }

  while ( searchSummList )
  {
    thisSearchSumm = searchSummList;
    searchSummList = searchSummList->next;
    LALFree( thisSearchSumm );
  }


  while ( inspiralEventList )
  {
    currentTrigger = inspiralEventList;
    inspiralEventList = inspiralEventList->next;
    LAL_CALL( LALFreeSnglInspiral( &status, &currentTrigger ), &status );
  }

  if ( userTag ) free( userTag );
  if ( ifoTag ) free( ifoTag );

  if ( vrbflg ) fprintf( stdout, "done\n" );

  LALCheckMemoryLeaks();

  exit( 0 );
}
Exemple #10
0
int parseargs(int argc, char **argv)
{
    struct LALoption long_options[] = {
        { "help", no_argument, 0, 'h' },
        { "spin", required_argument, 0, 'a' },
        { "inclination", required_argument, 0, 'i' },
        { "l", required_argument, 0, 'l' },
        { "m", required_argument, 0, 'm' },
        { "s", required_argument, 0, 's' },
        { 0, 0, 0, 0 }
    };
    char args[] = "ha:i:l:m:s:";
    while (1) {
        int option_index = 0;
        int c;

        c = LALgetopt_long_only(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);
                exit(1);
            }
        case 'h': /* help */
            usage(argv[0]);
            exit(0);
        case 'a': /* spin */
            a = atof(LALoptarg);
            break;
        case 'i': /* inclination */
            theta = atof(LALoptarg);
            break;
        case 'l':
            l = atoi(LALoptarg);
            break;
        case 'm':
            m = atoi(LALoptarg);
            break;
        case 's':
            s = atoi(LALoptarg);
            break;
        case '?':
        default:
            fprintf(stderr, "unknown error while parsing options\n");
            exit(1);
        }
    }

    if (LALoptind < argc) {
        fprintf( stderr, "extraneous command line arguments:\n" );
        while (LALoptind < argc)
            fprintf(stderr, "%s\n", argv[LALoptind++]);
        exit(1);
    }

    if (a == a_invalid || l == l_invalid || m == m_invalid || s == s_invalid) {
        fprintf(stderr, "must specify a, l, m, and s\n");
        usage(argv[0]);
        exit(1);
    }

    if (fabs(a) >= 1.0) {
        fprintf(stderr, "must specify |a| < 1\n");
        exit(1);
    }

    if (l < abs(s)) {
        fprintf(stderr, "must specify l >= |s|\n");
        exit(1);
    }

    if (abs(m) > l) {
        fprintf(stderr, "must specify |m| <= l\n");
        exit(1);
    }

    return 0;
}
Exemple #11
0
/*
 * main program entry point
 */
INT4 main(INT4 argc, CHAR **argv)
{
  /* status */
  LALStatus status = blank_status;

  /* counters */
  int c;
  UINT4 i;

  /* mode counters */
  UINT4 l, m;

  /* metadata file/directory */
  CHAR *nrMetaFile = NULL;
  CHAR *nrDataDir = NULL;
  CHAR file_path[FILENAME_MAX];

  /* metadata format */
  CHAR *metadata_format = NULL;

  /* metadata parsing variables */
  LALParsedDataFile *meta_file = NULL;
  BOOLEAN wasRead = 0;
  CHAR field[HISTORY_COMMENT];
  CHAR *wf_name[MAX_L+1][(2*MAX_L) + 1];

  /* common metadata */
  CHAR *md_mass_ratio = NULL;
  CHAR *md_spin1x = NULL;
  CHAR *md_spin1y = NULL;
  CHAR *md_spin1z = NULL;
  CHAR *md_spin2x = NULL;
  CHAR *md_spin2y = NULL;
  CHAR *md_spin2z = NULL;
  CHAR *md_freq_start_22 = NULL;

  /* NINJA1 metadata */
  CHAR *md_simulation_details = NULL;
  CHAR *md_nr_group = NULL;
  CHAR *md_email = NULL;

  /* NINJA2 metadata */
  CHAR *md_waveform_name = NULL;
  CHAR *md_initial_separation = NULL;
  CHAR *md_eccentricity = NULL;
  CHAR *md_number_of_cycles_22 = NULL;
  CHAR *md_code = NULL;
  CHAR *md_submitter_email = NULL;
  CHAR *md_authors_emails = NULL;

  /* common metadata strings */
  CHAR str_mass_ratio[HISTORY_COMMENT];
  CHAR str_spin1x[HISTORY_COMMENT];
  CHAR str_spin1y[HISTORY_COMMENT];
  CHAR str_spin1z[HISTORY_COMMENT];
  CHAR str_spin2x[HISTORY_COMMENT];
  CHAR str_spin2y[HISTORY_COMMENT];
  CHAR str_spin2z[HISTORY_COMMENT];
  CHAR str_freq_start_22[HISTORY_COMMENT];
  CHAR str_creator[HISTORY_COMMENT];

  /* NINJA1 metadata strings */
  CHAR str_simulation_details[HISTORY_COMMENT];
  CHAR str_nr_group[HISTORY_COMMENT];
  CHAR str_email[HISTORY_COMMENT];

  /* NINJA2 metadata strings */
  CHAR str_waveform_name[HISTORY_COMMENT];
  CHAR str_initial_separation[HISTORY_COMMENT];
  CHAR str_eccentricity[HISTORY_COMMENT];
  CHAR str_number_of_cycles_22[HISTORY_COMMENT];
  CHAR str_code[HISTORY_COMMENT];
  CHAR str_submitter_email[HISTORY_COMMENT];
  CHAR str_authors_emails[HISTORY_COMMENT];

  /* channel names */
  CHAR *plus_channel[MAX_L+1][(2*MAX_L) + 1];
  CHAR *cross_channel[MAX_L+1][(2*MAX_L) + 1];

  /* waveforms */
  UINT4 wf_length;
  REAL4TimeVectorSeries *waveforms[MAX_L][(2*MAX_L) + 1];
  REAL4TimeSeries *hplus[MAX_L+1][(2*MAX_L) + 1];
  REAL4TimeSeries *hcross[MAX_L+1][(2*MAX_L) + 1];

  REAL8TimeVectorSeries *waveformsREAL8[MAX_L][(2*MAX_L) + 1];
  REAL8TimeSeries *hplusREAL8[MAX_L+1][(2*MAX_L) + 1];
  REAL8TimeSeries *hcrossREAL8[MAX_L+1][(2*MAX_L) + 1];

  /* frame variables */
  LALFrameH *frame;
  CHAR *frame_name = NULL;
  LIGOTimeGPS epoch;
  INT4 duration;
  INT4 detector_flags;

  INT4 generatingREAL8 = 0;

  /* LALgetopt arguments */
  struct LALoption long_options[] =
  {
    /* options that set a flag */
    {"verbose", no_argument, &vrbflg, 1},
    /* options that don't set a flag */
    {"format", required_argument, 0, 'f'},
    {"nr-meta-file", required_argument, 0, 'm'},
    {"nr-data-dir", required_argument, 0, 'd'},
    {"output", required_argument, 0, 'o'},
    {"double-precision", no_argument, 0, 'p'},
    {"help", no_argument, 0, 'h'},
    {"version", no_argument, 0, 'V'},
    {0, 0, 0, 0}
  };

  /* default debug level */
  lal_errhandler = LAL_ERR_EXIT;

  /* parse the arguments */
  while(1)
  {
    /* LALgetopt_long stores long option here */
    int option_index = 0;
    size_t LALoptarg_len;

    c = LALgetopt_long_only(argc, argv, "f:m:d:o:phV", long_options, &option_index);

    /* detect the end of the options */
    if (c == -1)
      break;

    switch(c)
    {
      case 0:
        /* if this option sets a flag, do nothing else for now */
        if (long_options[option_index].flag != 0)
          break;
        else
        {
          fprintf(stderr, "Error parsing option %s with argument %s\n", long_options[option_index].name, LALoptarg);
          exit(1);
        }
        break;

      case 'h':
        /* help message */
        print_usage(stdout, argv[0]);
        exit(0);
        break;

      case 'V':
        /* print version information and exit */
        fprintf(stdout, "Numerical Relativity Frame Generation\n");
        XLALOutputVersionString(stderr, 0);
        exit(0);
        break;

      case 'f':
        /* create storage for the metadata format */
        LALoptarg_len = strlen(LALoptarg) + 1;
        metadata_format = (CHAR *)calloc(LALoptarg_len, sizeof(CHAR));
        memcpy(metadata_format, LALoptarg, LALoptarg_len);
        break;

      case 'm':
        /* create storage for the meta file name */
        LALoptarg_len = strlen(LALoptarg) + 1;
        nrMetaFile = (CHAR *)calloc(LALoptarg_len, sizeof(CHAR));
        memcpy(nrMetaFile, LALoptarg, LALoptarg_len);
        break;

      case 'd':
        /* create storage for the meta data directory name */
        LALoptarg_len = strlen(LALoptarg) + 1;
        nrDataDir = (CHAR *)calloc(LALoptarg_len, sizeof(CHAR));
        memcpy(nrDataDir, LALoptarg, LALoptarg_len);
        break;

      case 'o':
        /* create storage for the output frame file name */
        LALoptarg_len = strlen(LALoptarg) + 1;
        frame_name = (CHAR *)calloc(LALoptarg_len, sizeof(CHAR));
        memcpy(frame_name, LALoptarg, LALoptarg_len);
        break;

      case 'p':
        /* We're generating a double-precision frame */
        generatingREAL8 = 1;
        break;

      case '?':
        print_usage(stderr, argv[0]);
        exit(1);
        break;

      default:
        fprintf(stderr, "Unknown error while parsing arguments\n");
        print_usage(stderr, argv[0]);
        exit(1);
        break;
    }
  }

  /* check for extraneous command line arguments */
  if (LALoptind < argc)
  {
    fprintf(stderr, "Extraneous command line arguments:\n");
    while(LALoptind < argc)
      fprintf(stderr, "%s\n", argv[LALoptind++]);
    exit(1);
  }

  /*
   * check validity of arguments
   */

  /* metadata format specified */
  if (metadata_format == NULL)
  {
    fprintf(stderr, "warning: --format not specified, assuming NINJA1\n");
    metadata_format = (CHAR *)calloc(7, sizeof(CHAR));
    memcpy(metadata_format, "NINJA1", 7);
  }

  /* check for supported metadata format */
  if (strcmp(metadata_format, "NINJA1") == 0);
  else if (strcmp(metadata_format, "NINJA2") == 0);
  else
  {
    fprintf(stderr, "Supported metadata formats are NINJA1 and NINJA2 (%s specified)\n", metadata_format);
    exit(1);
  }

  /* meta file specified */
  if (nrMetaFile == NULL)
  {
    fprintf(stderr, "--nr-meta-file must be specified\n");
    exit(1);
  }

  /* data directory specified */
  if (nrDataDir == NULL)
  {
    fprintf(stderr, "--nr-data-dir must be specified\n");
    exit(1);
  }

  /* output frame filename specified */
  if (frame_name == NULL)
  {
    fprintf(stderr, "--output must be specified\n");
    exit(1);
  }

  /*
   * main code
   */

  /* frame metadata */
  /* TODO: set these to something sensible */
  duration = 0;
  epoch.gpsSeconds = 0;
  epoch.gpsNanoSeconds = 0;
  detector_flags = 0;

  if (vrbflg)
    fprintf(stdout, "reading metadata: %s\n", nrMetaFile);

  /* open metadata file */
  XLAL_CHECK ( XLALParseDataFile(&meta_file, nrMetaFile) == XLAL_SUCCESS, XLAL_EFUNC );

  /*
   * get metadata
   */

  /* common metadata */
  XLAL_CHECK ( XLALReadConfigSTRINGVariable( &md_mass_ratio, meta_file, NULL, "mass-ratio", &wasRead) == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALReadConfigSTRINGVariable( &md_spin1x, meta_file, NULL, "spin1x", &wasRead) == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALReadConfigSTRINGVariable( &md_spin1y, meta_file, NULL, "spin1y", &wasRead) == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALReadConfigSTRINGVariable( &md_spin1z, meta_file, NULL, "spin1z", &wasRead) == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALReadConfigSTRINGVariable( &md_spin2x, meta_file, NULL, "spin2x", &wasRead) == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALReadConfigSTRINGVariable( &md_spin2y, meta_file, NULL, "spin2y", &wasRead) == XLAL_SUCCESS, XLAL_EFUNC );
  XLAL_CHECK ( XLALReadConfigSTRINGVariable( &md_spin2z, meta_file, NULL, "spin2z", &wasRead) == XLAL_SUCCESS, XLAL_EFUNC );

  /* format specific metadata */
  if (strcmp(metadata_format, "NINJA1") == 0)
  {
    /* NINJA1 */
    XLAL_CHECK ( XLALReadConfigSTRINGVariable( &md_simulation_details, meta_file, NULL, "simulation-details", &wasRead) == XLAL_SUCCESS, XLAL_EFUNC );
    XLAL_CHECK ( XLALReadConfigSTRINGVariable( &md_nr_group, meta_file, NULL, "nr-group", &wasRead) == XLAL_SUCCESS, XLAL_EFUNC );
    XLAL_CHECK ( XLALReadConfigSTRINGVariable( &md_email, meta_file, NULL, "email", &wasRead) == XLAL_SUCCESS, XLAL_EFUNC );
    XLAL_CHECK ( XLALReadConfigSTRINGVariable( &md_freq_start_22, meta_file, NULL, "freqStart22", &wasRead) == XLAL_SUCCESS, XLAL_EFUNC );
  }
  else if (strcmp(metadata_format, "NINJA2") == 0)
  {
    /* NINJA2 */
    XLAL_CHECK ( XLALReadConfigSTRINGVariable( &md_waveform_name, meta_file, NULL, "waveform-name", &wasRead) == XLAL_SUCCESS, XLAL_EFUNC );
    XLAL_CHECK ( XLALReadConfigSTRINGVariable( &md_initial_separation, meta_file, NULL, "initial-separation", &wasRead) == XLAL_SUCCESS, XLAL_EFUNC );
    XLAL_CHECK ( XLALReadConfigSTRINGVariable( &md_eccentricity, meta_file, NULL, "eccentricity", &wasRead) == XLAL_SUCCESS, XLAL_EFUNC );
    XLAL_CHECK ( XLALReadConfigSTRINGVariable( &md_number_of_cycles_22, meta_file, NULL, "number-of-cycles-22", &wasRead) == XLAL_SUCCESS, XLAL_EFUNC );
    XLAL_CHECK ( XLALReadConfigSTRINGVariable( &md_code, meta_file, NULL, "code", &wasRead) == XLAL_SUCCESS, XLAL_EFUNC );
    XLAL_CHECK ( XLALReadConfigSTRINGVariable( &md_submitter_email, meta_file, NULL, "submitter-email", &wasRead) == XLAL_SUCCESS, XLAL_EFUNC );
    XLAL_CHECK ( XLALReadConfigSTRINGVariable( &md_authors_emails, meta_file, NULL, "authors-emails", &wasRead) == XLAL_SUCCESS, XLAL_EFUNC );
    XLAL_CHECK ( XLALReadConfigSTRINGVariable( &md_freq_start_22, meta_file, NULL, "freq-start-22", &wasRead) == XLAL_SUCCESS, XLAL_EFUNC );
  }
  else
  {
    /* unknown metadata format - should not be executed */
    fprintf(stderr, "error: unsupported metadata format: %s\n", metadata_format);
    exit(1);
  }

  /*
   * set metadata strings
   */

  /* common waveform */
  snprintf(str_mass_ratio, HISTORY_COMMENT, "mass-ratio:%s", md_mass_ratio);
  snprintf(str_spin1x, HISTORY_COMMENT, "spin1x:%s", md_spin1x);
  snprintf(str_spin1y, HISTORY_COMMENT, "spin1y:%s", md_spin1y);
  snprintf(str_spin1z, HISTORY_COMMENT, "spin1z:%s", md_spin1z);
  snprintf(str_spin2x, HISTORY_COMMENT, "spin2x:%s", md_spin2x);
  snprintf(str_spin2y, HISTORY_COMMENT, "spin2y:%s", md_spin2y);
  snprintf(str_spin2z, HISTORY_COMMENT, "spin2z:%s", md_spin2z);
  snprintf(str_creator, HISTORY_COMMENT, "creator:%s(git:%s)", PROGRAM_NAME, lalAppsVCSId);

  /* format specific metadata */
  if (strcmp(metadata_format, "NINJA1") == 0)
  {
    /* NINJA1 */
    snprintf(str_freq_start_22, HISTORY_COMMENT, "freqStart22:%s", md_freq_start_22);
    snprintf(str_simulation_details, HISTORY_COMMENT, "simulation-details:%s", md_simulation_details);
    snprintf(str_nr_group, HISTORY_COMMENT, "nr-group:%s", md_nr_group);
    snprintf(str_email, HISTORY_COMMENT, "email:%s", md_email);
  }
  else if (strcmp(metadata_format, "NINJA2") == 0)
  {
    /* NINJA2 */
    snprintf(str_waveform_name, HISTORY_COMMENT, "waveform-name:%s", md_waveform_name);
    snprintf(str_initial_separation, HISTORY_COMMENT, "inital-separation:%s", md_initial_separation);
    snprintf(str_eccentricity, HISTORY_COMMENT, "eccentricity:%s", md_eccentricity);
    snprintf(str_freq_start_22, HISTORY_COMMENT, "freq_start_22:%s", md_freq_start_22);
    snprintf(str_number_of_cycles_22, HISTORY_COMMENT, "number-of-cycles-22:%s", md_number_of_cycles_22);
    snprintf(str_code, HISTORY_COMMENT, "code:%s", md_code);
    snprintf(str_submitter_email, HISTORY_COMMENT, "submitter-email:%s", md_submitter_email);
    snprintf(str_authors_emails, HISTORY_COMMENT, "authors-emails:%s", md_authors_emails);
  }
  else
  {
    /* unknown metadata format - should not be executed */
    fprintf(stderr, "error: unsupported metadata format: %s\n", metadata_format);
    exit(1);
  }

  /* define frame */
  frame = XLALFrameNew(&epoch, duration, "NR", 0, 1, detector_flags);

  /*
   * add metadata as FrHistory structures
   */

  /* common metadata */
  XLALFrameAddFrHistory(frame, "creator", str_creator);
  XLALFrameAddFrHistory(frame, "mass-ratio", str_mass_ratio);
  XLALFrameAddFrHistory(frame, "spin1x", str_spin1x);
  XLALFrameAddFrHistory(frame, "spin1y", str_spin1y);
  XLALFrameAddFrHistory(frame, "spin1z", str_spin1z);
  XLALFrameAddFrHistory(frame, "spin2x", str_spin2x);
  XLALFrameAddFrHistory(frame, "spin2y", str_spin2y);
  XLALFrameAddFrHistory(frame, "spin2z", str_spin2z);

  /* format specific metadata */
  if (strcmp(metadata_format, "NINJA1") == 0)
  {
    /* NINJA1 */
    XLALFrameAddFrHistory(frame, "simulation-details", str_simulation_details);
    XLALFrameAddFrHistory(frame, "nr-group", str_nr_group);
    XLALFrameAddFrHistory(frame, "email", str_email);
    XLALFrameAddFrHistory(frame, "freqStart22", str_freq_start_22);
  }
  else if (strcmp(metadata_format, "NINJA2") == 0)
  {
    /* NINJA2 */
    XLALFrameAddFrHistory(frame, "waveform-name", str_waveform_name);
    XLALFrameAddFrHistory(frame, "initial-separation", str_initial_separation);
    XLALFrameAddFrHistory(frame, "eccentricity", str_eccentricity);
    XLALFrameAddFrHistory(frame, "freq_start_22", str_freq_start_22);
    XLALFrameAddFrHistory(frame, "number-of-cycles-22", str_number_of_cycles_22);
    XLALFrameAddFrHistory(frame, "code", str_code);
    XLALFrameAddFrHistory(frame, "submitter-email", str_code);
    XLALFrameAddFrHistory(frame, "authors-emails", str_authors_emails);
  }
  else
  {
    /* unknown metadata format - should not be executed */
    fprintf(stderr, "error: unsupported metadata format: %s\n", metadata_format);
    exit(1);
  }

  /* loop over l & m values */
  for (l = MIN_L; l <= MAX_L; l++)
  {
    for (m = (MAX_L - l); m <= MAX_L + l; m++)
    {
      /* ensure pointers are NULL */
      wf_name[l][m] = NULL;
      plus_channel[l][m] = NULL;
      cross_channel[l][m] = NULL;

      /* generate channel names */
      plus_channel[l][m] = XLALGetNinjaChannelName("plus", l, m - MAX_L);
      cross_channel[l][m] = XLALGetNinjaChannelName("cross", l, m - MAX_L);

      if (generatingREAL8)
      {
        hplusREAL8[l][m] = NULL;
        hcrossREAL8[l][m] = NULL;
        waveformsREAL8[l][m] = NULL;
        
        /* initilise waveform time series */
        hplusREAL8[l][m] = XLALCreateREAL8TimeSeries(plus_channel[l][m], &epoch, 0, 0, &lalDimensionlessUnit, 0);
        hcrossREAL8[l][m] = XLALCreateREAL8TimeSeries(cross_channel[l][m], &epoch, 0, 0, &lalDimensionlessUnit, 0);
      }
      else
      {
        hplus[l][m] = NULL;
        hcross[l][m] = NULL;
        waveforms[l][m] = NULL;
      
        /* initilise waveform time series */
        hplus[l][m] = XLALCreateREAL4TimeSeries(plus_channel[l][m], &epoch, 0, 0, &lalDimensionlessUnit, 0);
        hcross[l][m] = XLALCreateREAL4TimeSeries(cross_channel[l][m], &epoch, 0, 0, &lalDimensionlessUnit, 0);
      }

      /* read ht-data section of metadata file */
      snprintf(field, HISTORY_COMMENT, "%d,%d", l, m - MAX_L);
      XLAL_CHECK ( XLALReadConfigSTRINGVariable( &wf_name[l][m], meta_file, NULL, field, &wasRead) == XLAL_SUCCESS, XLAL_EFUNC );

      /* read waveform */
      if (wf_name[l][m] != NULL)
      {
        /* get full path to waveform data file */
        snprintf(file_path, FILENAME_MAX, "%s/%s", nrDataDir, wf_name[l][m]);

        if (vrbflg)
          fprintf(stdout, "reading waveform: %s\n", file_path);

        /* read waveforms */
        if (generatingREAL8)
        {
          LAL_CALL(LALReadNRWave_raw_real8(&status, &waveformsREAL8[l][m], file_path), &status);
        }
        else
        {
          LAL_CALL(LALReadNRWave_raw(&status, &waveforms[l][m], file_path), &status);
        }
      }

      /* generate waveform time series from vector series */
      /* TODO: should use pointer arithmetic here and update the data
       * pointer in the REAL4TimeSeries to point to the appropriate
       * location within the REAL4TimeVector Series */
      if (generatingREAL8) {
        if (waveformsREAL8[l][m])
        {
          /* get length of waveform */
          wf_length = waveformsREAL8[l][m]->data->vectorLength;

          /* allocate memory for waveform */
          XLALResizeREAL8TimeSeries(hplusREAL8[l][m], 0, wf_length);
          XLALResizeREAL8TimeSeries(hcrossREAL8[l][m], 0, wf_length);

          /* set time spacing */
          hplusREAL8[l][m]->deltaT = waveformsREAL8[l][m]->deltaT;
          hcrossREAL8[l][m]->deltaT = waveformsREAL8[l][m]->deltaT;

          /* copy waveforms into appropriate series */
          for (i = 0; i < wf_length; i ++) {
            hplusREAL8[l][m]->data->data[i] = waveformsREAL8[l][m]->data->data[i];
            hcrossREAL8[l][m]->data->data[i] = waveformsREAL8[l][m]->data->data[wf_length + i];
          }

          /* Done with waveformsREAL8, clean up here to limit memory usage */
          LALFree(waveformsREAL8[l][m]->data->data);
          LALFree(waveformsREAL8[l][m]->data);
          LALFree(waveformsREAL8[l][m]);
        }
      }
      else /* REAL4 */
      {
        if (waveforms[l][m])
        {
          /* get length of waveform */
          wf_length = waveforms[l][m]->data->vectorLength;

          /* allocate memory for waveform */
          XLALResizeREAL4TimeSeries(hplus[l][m], 0, wf_length);
          XLALResizeREAL4TimeSeries(hcross[l][m], 0, wf_length);

          /* set time spacing */
          hplus[l][m]->deltaT = waveforms[l][m]->deltaT;
          hcross[l][m]->deltaT = waveforms[l][m]->deltaT;

          /* copy waveforms into appropriate series */
          for (i = 0; i < wf_length; i ++) {
            hplus[l][m]->data->data[i] = waveforms[l][m]->data->data[i];
            hcross[l][m]->data->data[i] = waveforms[l][m]->data->data[wf_length + i];
          }
        }
      }

      /* add channels to frame */
      if (generatingREAL8)
      {
        if ((hplusREAL8[l][m]->data->length) && (hcrossREAL8[l][m]->data->length))
        {
          XLALFrameAddREAL8TimeSeriesSimData(frame, hplusREAL8[l][m]);
          XLALFrameAddREAL8TimeSeriesSimData(frame, hcrossREAL8[l][m]);
        }
      }
      else
      {
        if ((hplus[l][m]->data->length) && (hcross[l][m]->data->length))
        {
          XLALFrameAddREAL4TimeSeriesSimData(frame, hplus[l][m]);
          XLALFrameAddREAL4TimeSeriesSimData(frame, hcross[l][m]);
        }
      }
    }
  }

  if (vrbflg)
    fprintf(stdout, "writing frame: %s\n", frame_name);

  /* write frame */
  if (XLALFrameWrite(frame, frame_name) != 0 )
  {
    fprintf(stderr, "Error: Cannot save frame file '%s'\n", frame_name);
    exit(1);
  }

  /*
   * clear memory
   */

  /* strings */
  if(nrMetaFile) free(nrMetaFile);
  if(nrDataDir)  free(nrDataDir);
  if(frame_name) free(frame_name);
  if(metadata_format) free(metadata_format);

  /* common metadata */
  if(md_mass_ratio) LALFree(md_mass_ratio);
  if(md_spin1x) LALFree(md_spin1x);
  if(md_spin1y) LALFree(md_spin1y);
  if(md_spin1z) LALFree(md_spin1z);
  if(md_spin2x) LALFree(md_spin2x);
  if(md_spin2y) LALFree(md_spin2y);
  if(md_spin2z) LALFree(md_spin2z);
  if(md_freq_start_22) LALFree(md_freq_start_22);

  /* NINJA1 metadata */
  if(md_simulation_details) LALFree(md_simulation_details);
  if(md_nr_group)           LALFree(md_nr_group);
  if(md_email)              LALFree(md_email);

  /* NINJA2 metadata */
  if(md_waveform_name)       LALFree(md_waveform_name);
  if(md_initial_separation)  LALFree(md_initial_separation);
  if(md_eccentricity)        LALFree(md_eccentricity);
  if(md_number_of_cycles_22) LALFree(md_number_of_cycles_22);
  if(md_code)                LALFree(md_code);
  if(md_submitter_email)     LALFree(md_submitter_email);
  if(md_authors_emails)      LALFree(md_authors_emails);

  /* config file */
  if(meta_file->lines->list->data) LALFree(meta_file->lines->list->data);
  if(meta_file->lines->list)   LALFree(meta_file->lines->list);
  if(meta_file->lines->tokens) LALFree(meta_file->lines->tokens);
  if(meta_file->lines)   LALFree(meta_file->lines);
  if(meta_file->wasRead) LALFree(meta_file->wasRead);
  if(meta_file)          LALFree(meta_file);

  /* waveforms */
  if (generatingREAL8)
  {
    for (l = MIN_L; l <= MAX_L; l++)
    {
      for (m = (MAX_L - l); m <= MAX_L + l; m++)
      {
        /* channel names */
        if (plus_channel[l][m])
          LALFree(plus_channel[l][m]);

        if (cross_channel[l][m])
          LALFree(cross_channel[l][m]);

        if (wf_name[l][m])
          LALFree(wf_name[l][m]);

        /* hplus */
        if (hplusREAL8[l][m])
          XLALDestroyREAL8TimeSeries(hplusREAL8[l][m]);

        /* hcross */
        if (hcrossREAL8[l][m])
          XLALDestroyREAL8TimeSeries(hcrossREAL8[l][m]);
      }
    }
  }
  else
  {
    for (l = MIN_L; l <= MAX_L; l++)
    {
      for (m = (MAX_L - l); m <= MAX_L + l; m++)
      {
        /* channel names */
        if (plus_channel[l][m])
          LALFree(plus_channel[l][m]);

        if (cross_channel[l][m])
          LALFree(cross_channel[l][m]);

        if (wf_name[l][m])
          LALFree(wf_name[l][m]);

        /* raw waveforms */
        if (waveforms[l][m]) {
          LALFree(waveforms[l][m]->data->data);
          LALFree(waveforms[l][m]->data);
          LALFree(waveforms[l][m]);
        }

        /* hplus */
        if (hplus[l][m])
          XLALDestroyREAL4TimeSeries(hplus[l][m]);

        /* hcross */
        if (hcross[l][m])
          XLALDestroyREAL4TimeSeries(hcross[l][m]);
      }
    }
  }

  /* clear frame */
  XLALFrameFree(frame);

  /* check for memory leaks */
  LALCheckMemoryLeaks();

  exit(0);
}
int parseargs( int argc, char **argv )
{
	struct LALoption long_options[] = {
			{ "help", no_argument, 0, 'h' },
			{ "verbose", no_argument, 0, 1 },
			{ "0noise", no_argument, 0, '0' },
			{ "aligo-nosrm", no_argument, 0, 'A' },
			{ "aligo-zerodet-lowpower", no_argument, 0, 'B' },
			{ "aligo-zerodet-highpower", no_argument, 0, 'C' },
			{ "aligo-nsnsopt", no_argument, 0, 'D' },
			{ "aligo-bhbh20deg", no_argument, 0, 'E' },
			{ "aligo-highfreq", no_argument, 0, 'F' },
			{ "iligo-srd", no_argument, 0, 'I' },
			{ "virgo", no_argument, 0, 'v' },
			{ "advvirgo", no_argument, 0, 'V' },
			{ "geo", no_argument, 0, 'g' },
			{ "geohf", no_argument, 0, 'G' },
			{ "tama", no_argument, 0, 'T' },
			{ "kagra", no_argument, 0, 'K' },
			{ "official", no_argument, 0, 'O' },
			{ "psd-only", no_argument, 0, 'P' },
			{ "psd-file", no_argument, 0, 'p' },
			{ "start-time", required_argument, 0, 's' },
			{ "duration", required_argument, 0, 't' },
			{ "sample-rate", required_argument, 0, 'r' },
			{ "segment-duration", required_argument, 0, 'd' },
			{ "low-frequency", required_argument, 0, 'f' },
			{ 0, 0, 0, 0 }
		};
	char args[] = "h\1I0ABCDEFOPvVgGTKa:s:t:r:d:f:";
	while (1) {
		int option_index = 0;
		int c;

		c = LALgetopt_long_only(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);
					exit(1);
				}
			case 'h': /* help */
				usage(argv[0]);
				exit(0);
			case 1: /* verbose */
				verbose = 1;
				break;
			case '0': /* 0noise */
				/* psdfunc and opsdfunc are ignored so just choose anything */
				psdfunc = XLALSimNoisePSDaLIGONoSRMLowPower;
				opsdfunc = XLALSimNoisePSDaLIGONoSRMLowPowerGWINC;
				flow = 9.0;
				detector = "0noise";
				break;
			case 'A': /* aligo-nosrm */
				psdfunc = XLALSimNoisePSDaLIGONoSRMLowPower;
				opsdfunc = XLALSimNoisePSDaLIGONoSRMLowPowerGWINC;
				flow = 9.0;
				detector = "aLIGO_NoSRM";
				break;
			case 'B': /* aligo-zerodet-lowpower */
				psdfunc = XLALSimNoisePSDaLIGOZeroDetLowPower;
				opsdfunc = XLALSimNoisePSDaLIGOZeroDetLowPowerGWINC;
				flow = 9.0;
				detector = "aLIGO_ZeroDet_LowPower";
				break;
			case 'C': /* aligo-zerodet-highpower */
				psdfunc = XLALSimNoisePSDaLIGOZeroDetHighPower;
				opsdfunc = XLALSimNoisePSDaLIGOZeroDetHighPowerGWINC;
				flow = 9.0;
				detector = "aLIGO_ZeroDet_HighPower";
				break;
			case 'D': /* aligo-nsnsopt */
				psdfunc = XLALSimNoisePSDaLIGONSNSOpt;
				opsdfunc = XLALSimNoisePSDaLIGONSNSOptGWINC;
				flow = 9.0;
				detector = "aLIGO_NSNSopt";
				break;
			case 'E': /* aligo-bhbh20deg */
				psdfunc = XLALSimNoisePSDaLIGOBHBH20Deg;
				opsdfunc = XLALSimNoisePSDaLIGOBHBH20DegGWINC;
				flow = 9.0;
				detector = "aLIGO_BHBH20deg";
				break;
			case 'F': /* aligo-highfreq */
				psdfunc = XLALSimNoisePSDaLIGOHighFrequency;
				opsdfunc = XLALSimNoisePSDaLIGOHighFrequencyGWINC;
				flow = 9.0;
				detector = "aLIGO_HighFreq";
				break;
			case 'I': /* iligo-srd */
				psdfunc = XLALSimNoisePSDiLIGOSRD;
				flow = 30.0;
				detector = "LIGO_SRD";
				break;
			case 'v': /* initial Virgo */
				psdfunc = XLALSimNoisePSDVirgo;
				flow = 5.0;
				detector = "Virgo";
				break;
			case 'V': /* Advanced Virgo */
				psdfunc = XLALSimNoisePSDAdvVirgo;
				flow = 1.0;
				detector = "AdvVirgo";
				break;
			case 'g': /* GEO600 */
				psdfunc = XLALSimNoisePSDGEO;
				flow = 30.0;
				detector = "GEO600";
				break;
			case 'G': /* GEO-HF */
				psdfunc = XLALSimNoisePSDGEOHF;
				flow = 50.0;
				detector = "GEOHF";
				break;
			case 'T': /* TAMA300 */
				psdfunc = XLALSimNoisePSDTAMA;
				flow = 30.0;
				detector = "TAMA300";
				break;
			case 'K': /* KAGRA (formerly LCGT) */
				psdfunc = XLALSimNoisePSDKAGRA;
				flow = 5.0;
				detector = "KAGRA";
				break;
			case 'O': /* official */
				official = 1;
				break;
			case 'P': /* start-time */
				psdonly = 1;
				break;
			case 'a': /* asd-file */
				flow = 0.0;
				asdfile = LALoptarg;
				detector = LALoptarg;
				break;
			case 's': /* start-time */
				{
					char *endp = NULL;
					if (XLALStrToGPS(&tstart, LALoptarg, &endp) < 0 || strlen(endp)) {
						fprintf(stderr, "could not parse GPS string `%s'\n", LALoptarg);
						exit(1);
					}
					break;
				}
			case 't': /* duration */
				duration = atof(LALoptarg);
				break;
			case 'r': /* sample-rate */
				srate = atof(LALoptarg);
				break;
			case 'd': /* segment duration */
				segdur = atof(LALoptarg);
				break;
			case 'f': /* low frequency */
				overrideflow = atof(LALoptarg);
				break;
			case '?':
			default:
				fprintf(stderr, "unknown error while parsing options\n");
				exit(1);
		}
	}

	if ( LALoptind < argc ) {
		fprintf(stderr, "extraneous command line arguments:\n");
		while (LALoptind < argc)
			fprintf(stderr, "%s\n", argv[LALoptind++]);
		exit(1);
	}

	if ((!psdfunc && !asdfile) || (!psdonly && duration == 0.0)) {
		fprintf(stderr, "must select a noise model and a duration\n");
		usage(argv[0]);
		exit(1);
	}

	return 0;
}
Exemple #13
0
int main( int argc, char *argv[] )
{
  LALStatus             status = blank_status;
  const INT4            S2StartTime = 729273613; /* Feb 14 2003 16:00:00 UTC */
  const INT4            S2StopTime  = 734367613; /* Apr 14 2003 15:00:00 UTC */

  /* command line options */
  LIGOTimeGPS   gpsStartTime = {S2StartTime, 0};
  LIGOTimeGPS   gpsEndTime   = {S2StopTime, 0};
  REAL8         meanTimeStep = 2630 / LAL_PI;
  REAL8         timeInterval = 0;
  UINT4         randSeed = 1;
  CHAR         *userTag = NULL;
  REAL4         minMass = 0.1;
  REAL4         maxMass = 1.0;
  REAL4         r_core = 5.0;     /* kpc core radius */
  REAL4         r_max = 50.0;     /* kpc halo radius */
  REAL4         q = 1.0;          /* flatten halo */

  /* program variables */
  RandomParams *randParams = NULL;
  REAL4  u;
  REAL4  deltaM;

  int i, stat;
  const int maxIter = 1000;
  const double tol = 1e-6;
  const gsl_root_fsolver_type *solver_type;
  gsl_root_fsolver *solver;
  gsl_function pdf;

  struct halo_pdf_params pdf_params;

  double r_lo, r_hi, r;
  double cosphi, sinphi;
  double pdf_norm;

  GalacticInspiralParamStruc galacticPar;

  /* xml output data */
  CHAR                  fname[256];
  MetadataTable         proctable;
  MetadataTable         procparams;
  MetadataTable         injections;
  ProcessParamsTable   *this_proc_param;
  SimInspiralTable     *this_inj = NULL;
  LIGOLwXMLStream       xmlfp;
  UINT4                 outCompress = 0;

  /* LALgetopt arguments */
  struct LALoption long_options[] =
  {
    {"help",                    no_argument,       0,                'h'},
    {"verbose",                 no_argument,       &vrbflg,           1 },
    {"write-compress",          no_argument,       &outCompress,      1 },
    {"gps-start-time",          required_argument, 0,                'a'},
    {"gps-end-time",            required_argument, 0,                'b'},
    {"time-step",               required_argument, 0,                't'},
    {"time-interval",                required_argument, 0,                     'i'},
    {"seed",                    required_argument, 0,                's'},
    {"minimum-mass",            required_argument, 0,                'A'},
    {"maximum-mass",            required_argument, 0,                'B'},
    {"core-radius",             required_argument, 0,                'p'},
    {"flatten-halo",            required_argument, 0,                'q'},
    {"halo-radius",             required_argument, 0,                'r'},
    {"user-tag",                required_argument, 0,                'Z'},
    {"userTag",                 required_argument, 0,                'Z'},
    {0, 0, 0, 0}
  };
  int c;

  /* set up inital debugging values */
  lal_errhandler = LAL_ERR_EXIT;

  /* create the process and process params tables */
  proctable.processTable = (ProcessTable *) 
    calloc( 1, sizeof(ProcessTable) );
  XLALGPSTimeNow(&(proctable.processTable->start_time));
  if (strcmp(CVS_REVISION,"$Revi" "sion$"))
    {
      XLALPopulateProcessTable(proctable.processTable, PROGRAM_NAME,
          CVS_REVISION, CVS_SOURCE, CVS_DATE, 0);
    }
  else
    {
      XLALPopulateProcessTable(proctable.processTable, PROGRAM_NAME,
          lalappsGitCommitID, lalappsGitGitStatus, lalappsGitCommitDate, 0);
    }
  snprintf( proctable.processTable->comment, LIGOMETA_COMMENT_MAX, " " );
  this_proc_param = procparams.processParamsTable = (ProcessParamsTable *) 
    calloc( 1, sizeof(ProcessParamsTable) );
  

  /*
   *
   * parse command line arguments
   *
   */

     
  while ( 1 )
  {
    /* LALgetopt_long stores long option here */
    int option_index = 0;
    long int gpsinput;
    size_t LALoptarg_len;

    c = LALgetopt_long_only( argc, argv,
        "a:A:b:B:hi:p:q:r:s:t:vZ:", long_options, &option_index );

    /* detect the end of the options */
    if ( c == - 1 )
    {
      break;
    }

    switch ( c )
    {
      case 0:
        /* if this option set a flag, do nothing else now */
        if ( long_options[option_index].flag != 0 )
        {
          break;
        }
        else
        {
          fprintf( stderr, "error parsing option %s with argument %s\n",
              long_options[option_index].name, LALoptarg );
          exit( 1 );
        }
        break;

      case 'a':
        gpsinput = atol( LALoptarg );
        if ( gpsinput < 441417609 )
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "GPS start time is prior to " 
              "Jan 01, 1994  00:00:00 UTC:\n"
              "(%ld specified)\n",
              long_options[option_index].name, gpsinput );
          exit( 1 );
        }
        gpsStartTime.gpsSeconds = gpsinput;

        this_proc_param = this_proc_param->next = 
          next_process_param( long_options[option_index].name, "int", 
              "%ld", gpsinput );
        break;

      case 'b':
        gpsinput = atol( LALoptarg );
        if ( gpsinput < 441417609 )
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "GPS start time is prior to " 
              "Jan 01, 1994  00:00:00 UTC:\n"
              "(%ld specified)\n",
              long_options[option_index].name, gpsinput );
          exit( 1 );
        }
        gpsEndTime.gpsSeconds = gpsinput;
        this_proc_param = this_proc_param->next = 
          next_process_param( long_options[option_index].name, "int", 
              "%ld", gpsinput );
        break;

      case 's':
        randSeed = atoi( LALoptarg );
        this_proc_param = this_proc_param->next = 
          next_process_param( long_options[option_index].name, "int", 
              "%d", randSeed );
        break;

      case 't':
        meanTimeStep = (REAL8) atof( LALoptarg );
        if ( meanTimeStep <= 0 )
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "time step must be > 0: (%le seconds specified)\n",
              long_options[option_index].name, meanTimeStep );
          exit( 1 );
        }
        this_proc_param = this_proc_param->next = 
          next_process_param( long_options[option_index].name, "float", 
              "%le", meanTimeStep );
        break;

      case 'i':
        timeInterval = atof( LALoptarg );
        if ( timeInterval < 0 )
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "time interval must be >= 0: (%le seconds specified)\n",
              long_options[option_index].name, meanTimeStep );
          exit( 1 );
        }
        this_proc_param = this_proc_param->next = 
          next_process_param( long_options[option_index].name, 
              "float", "%le", timeInterval );
        break;

      case 'A':
        minMass = (REAL4) atof( LALoptarg );
        if ( minMass <= 0 )
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "miniumum component mass must be > 0: "
              "(%f solar masses specified)\n",
              long_options[option_index].name, minMass );
          exit( 1 );
        }
        this_proc_param = this_proc_param->next = 
          next_process_param( long_options[option_index].name, 
              "float", "%e", minMass );
        break;

      case 'B':
        maxMass = (REAL4) atof( LALoptarg );
        if ( maxMass <= 0 )
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "maxiumum component mass must be > 0: "
              "(%f solar masses specified)\n",
              long_options[option_index].name, maxMass );
          exit( 1 );
        }
        this_proc_param = this_proc_param->next = 
          next_process_param( long_options[option_index].name, 
              "float", "%e", maxMass );
        break;

      case 'p':
        /* core-radius */
        r_core = (REAL4) atof( LALoptarg );
        if ( r_core <= 0 )
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "galactic core radius must be > 0: "
              "(%f kpc specified)\n",
              long_options[option_index].name, r_core );
          exit( 1 );
        }
        this_proc_param = this_proc_param->next = 
          next_process_param( long_options[option_index].name, 
              "float", "%e", r_core );
        break;

      case 'q':
        /* flatten-halo */
        q = (REAL4) atof( LALoptarg );
        if ( q <= 0 || q > 1 )
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "halo flattening parameter must be in range (0,1]: "
              "(%f specified)\n",
              long_options[option_index].name, q );
          exit( 1 );
        }
        this_proc_param = this_proc_param->next = 
          next_process_param( long_options[option_index].name, 
              "float", "%e", q );
        break;

      case 'r':
        /* max halo radius */
        r_max = (REAL4) atof( LALoptarg );
        if ( r_max <= 0 )
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "halo radius must be greater than 0: "
              "(%f kpc specified)\n",
              long_options[option_index].name, r_max );
          exit( 1 );
        }
        this_proc_param = this_proc_param->next = 
          next_process_param( long_options[option_index].name, 
              "float", "%e", r_max );
        break;

      case 'Z':
        /* create storage for the usertag */
        LALoptarg_len = strlen( LALoptarg ) + 1;
        userTag = (CHAR *) calloc( LALoptarg_len, sizeof(CHAR) );
        memcpy( userTag, LALoptarg, LALoptarg_len );
        this_proc_param = this_proc_param->next = 
          next_process_param( long_options[option_index].name, 
              "string", "%s", LALoptarg );
        break;

      case 'v':
        vrbflg = 1;
        break;

      case 'h':
        fprintf( stderr, USAGE );
        exit( 0 );
        break;

      case '?':
        fprintf( stderr, USAGE );
        exit( 1 );
        break;

      default:
        fprintf( stderr, "unknown error while parsing options\n" );
        fprintf( stderr, USAGE );
        exit( 1 );
    }
  }

  if ( LALoptind < argc )
  {
    fprintf( stderr, "extraneous command line arguments:\n" );
    while ( LALoptind < argc )
    {
      fprintf ( stderr, "%s\n", argv[LALoptind++] );
    }
    exit( 1 );
  }


  /*
   *
   * initialization
   *
   */


  /* initialize the random number generator */
  LAL_CALL( LALCreateRandomParams( &status, &randParams, randSeed ), &status );

  /* initialize the gsl solver with the spatial pdf */
  pdf.function = &halo_pdf;
  pdf.params   = &pdf_params;
  solver_type = gsl_root_fsolver_bisection;
  solver = gsl_root_fsolver_alloc( solver_type );
  pdf_params.a = r_core;

  /* normalization for the spatial pdf */
  pdf_norm = r_max - r_core * atan2( r_max, r_core );

  /* mass range */
  deltaM = maxMass - minMass;

  /* null out the head of the linked list */
  injections.simInspiralTable = NULL;

  /* create the output file name */
  if ( userTag && outCompress )
  {
    snprintf( fname, sizeof(fname), "HL-INJECTIONS_%d_%s-%d-%d.xml.gz",
        randSeed, userTag, gpsStartTime.gpsSeconds,
        gpsEndTime.gpsSeconds - gpsStartTime.gpsSeconds );
  }
  else if ( userTag && !outCompress )
  {
    snprintf( fname, sizeof(fname), "HL-INJECTIONS_%d_%s-%d-%d.xml", 
        randSeed, userTag, gpsStartTime.gpsSeconds, 
        gpsEndTime.gpsSeconds - gpsStartTime.gpsSeconds );
  }
  else if ( !userTag && outCompress )
  {
    snprintf( fname, sizeof(fname), "HL-INJECTIONS_%d-%d-%d.xml.gz",
        randSeed, gpsStartTime.gpsSeconds,
        gpsEndTime.gpsSeconds - gpsStartTime.gpsSeconds );
  }
  else
  {
    snprintf( fname, sizeof(fname), "HL-INJECTIONS_%d-%d-%d.xml", 
        randSeed, gpsStartTime.gpsSeconds, 
        gpsEndTime.gpsSeconds - gpsStartTime.gpsSeconds );
  }


  /*
   *
   * loop over duration of desired output times
   *
   */


  while ( XLALGPSCmp( &gpsStartTime, &gpsEndTime ) < 0 )
  {
    /* uniformly distributed masses */
    LAL_CALL( LALUniformDeviate( &status, &u, randParams ), &status );
    galacticPar.m1 = minMass + u * deltaM;
    LAL_CALL( LALUniformDeviate( &status, &u, randParams ), &status );
    galacticPar.m2 = minMass + u * deltaM;
    
    /* spatial distribution */
    LAL_CALL( LALUniformDeviate( &status, &u, randParams ), &status );
    pdf_params.u = u * pdf_norm;

    r_lo = 0.0;
    r_hi = r_max;
    gsl_root_fsolver_set( solver, &pdf, r_lo, r_hi );

    for ( i = 0; i < maxIter; ++i )
    {
      gsl_root_fsolver_iterate( solver );
      r = gsl_root_fsolver_root( solver );
      r_lo = gsl_root_fsolver_x_lower( solver );
      r_hi = gsl_root_fsolver_x_upper( solver );
      stat = gsl_root_test_interval( r_lo, r_hi, 0, tol );
      if ( stat == GSL_SUCCESS )
        break;
    }

    if ( stat != GSL_SUCCESS )
    {
      fprintf( stderr, "could not find root after %d iterations\n", maxIter );
      exit( 1 );
    }

    LAL_CALL( LALUniformDeviate( &status, &u, randParams ), &status );
    sinphi = 2.0 * u - 1.0;
    cosphi = sqrt( 1.0 - sinphi*sinphi );
    
    galacticPar.rho = r * cosphi;
    galacticPar.z   = q * r * sinphi;

    LAL_CALL( LALUniformDeviate( &status, &u, randParams ), &status );
    galacticPar.lGal = LAL_TWOPI * u;    

    if ( vrbflg ) fprintf( stdout, "%e %e %e %e %e\n", 
        galacticPar.m1, galacticPar.m2,
        galacticPar.rho * cos( galacticPar.lGal ),
        galacticPar.rho * sin( galacticPar.lGal ),
        galacticPar.z );

    /* create the sim_inspiral table */
    if ( injections.simInspiralTable )
    {
      this_inj = this_inj->next = (SimInspiralTable *)
        LALCalloc( 1, sizeof(SimInspiralTable) );
    }
    else
    {
      injections.simInspiralTable = this_inj = (SimInspiralTable *)
        LALCalloc( 1, sizeof(SimInspiralTable) );
    }

    /* set the geocentric end time of the injection */
    galacticPar.geocentEndTime = gpsStartTime;
    if ( timeInterval )
    {
      LAL_CALL( LALUniformDeviate( &status, &u, randParams ), &status );
      XLALGPSAdd( &(galacticPar.geocentEndTime), u * timeInterval );
    }

    /* populate the sim_inspiral table */
    LAL_CALL( LALGalacticInspiralParamsToSimInspiralTable( &status,
          this_inj, &galacticPar, randParams ), &status );

    /* set the source and waveform fields */
    snprintf( this_inj->source, LIGOMETA_SOURCE_MAX, "MW" );
    snprintf( this_inj->waveform, LIGOMETA_WAVEFORM_MAX, 
        "GeneratePPNtwoPN" );

    /* increment the injection time */
    XLALGPSAdd( &gpsStartTime, meanTimeStep );
  } /* end loop over injection times */

  /* destroy random parameters */
  LAL_CALL( LALDestroyRandomParams( &status, &randParams ), &status );


  /*
   *
   * write output to LIGO_LW XML file
   *
   */


  /* open the xml file */
  memset( &xmlfp, 0, sizeof(LIGOLwXMLStream) );
  LAL_CALL( LALOpenLIGOLwXMLFile( &status, &xmlfp, fname ), &status );

  /* write the process table */
  snprintf( proctable.processTable->ifos, LIGOMETA_IFOS_MAX, "H1H2L1" );
  XLALGPSTimeNow(&(proctable.processTable->end_time));
  LAL_CALL( LALBeginLIGOLwXMLTable( &status, &xmlfp, process_table ), 
      &status );
  LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlfp, proctable, 
        process_table ), &status );
  LAL_CALL( LALEndLIGOLwXMLTable ( &status, &xmlfp ), &status );
  free( proctable.processTable );

  /* free the unused process param entry */
  this_proc_param = procparams.processParamsTable;
  procparams.processParamsTable = procparams.processParamsTable->next;
  free( this_proc_param );

  /* write the process params table */
  if ( procparams.processParamsTable )
  {
    LAL_CALL( LALBeginLIGOLwXMLTable( &status, &xmlfp, process_params_table ), 
        &status );
    LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlfp, procparams, 
          process_params_table ), &status );
    LAL_CALL( LALEndLIGOLwXMLTable ( &status, &xmlfp ), &status );
    while( procparams.processParamsTable )
    {
      this_proc_param = procparams.processParamsTable;
      procparams.processParamsTable = this_proc_param->next;
      free( this_proc_param );
    }
  }

  /* write the sim_inspiral table */
  if ( injections.simInspiralTable )
  {
    LAL_CALL( LALBeginLIGOLwXMLTable( &status, &xmlfp, sim_inspiral_table ), 
        &status );
    LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlfp, injections, 
          sim_inspiral_table ), &status );
    LAL_CALL( LALEndLIGOLwXMLTable ( &status, &xmlfp ), &status );
  }
  while ( injections.simInspiralTable )
  {
    this_inj = injections.simInspiralTable;
    injections.simInspiralTable = injections.simInspiralTable->next;
    LALFree( this_inj );
  }

  /* close the injection file */
  LAL_CALL( LALCloseLIGOLwXMLFile ( &status, &xmlfp ), &status );

  /* check for memory leaks and exit */
  LALCheckMemoryLeaks();
  return 0;
}
Exemple #14
0
/*
 * Begin MAIN
 */
int main (int argc, char *argv[])
{
  CHARVector *file2convert=NULL;
  LALStatus   status=blank_status;
  TSAMap     *map=NULL;

  /*
   *Sleep for Attaching DDD 
   */
  unsigned int doze = 0;
  pid_t myPID;
  myPID = getpid( );
  fprintf( stdout, "pid %d sleeping for %d seconds\n", myPID, doze );
  fflush( stdout );
  sleep( doze );
  fprintf( stdout, "pid %d awake\n", myPID );
  fflush( stdout );

 /* SET LAL DEBUG STUFF */
  memset(&status, 0, sizeof(status));
  lal_errhandler = LAL_ERR_ABRT;


  struct LALoption long_options[] =
    {
      {"filename",            required_argument,  0,    'a'},
      {0,                     0,                  0,      0}
    };
  int  C;
  while (TRUE)
    {
      int option_index=0;
      C = LALgetopt_long_only(argc,
			   argv,
			   "a:b:c:d:e:f:h:i:j:k:l:m:o:p:q:r:s:t:u",
			   long_options, 
			   &option_index);
      /* The end of the arguments is C = -1 */
      if ( C == -1)
	{
	  break;
	}
      switch( C )
	{
	case 0:
	  /* if this option set a flag, do nothing else now */
	  if ( long_options[option_index].flag != 0 )
	    {
	      break;
	    }
	  else
	    {
	      fprintf( stderr, "error parsing option %s with argument %s\n",
		       long_options[option_index].name, LALoptarg );
	      exit( 1 );
	    }
	  break;
	  
	case 'a':
	  /* Setting the GPS start time parameter */
	  {
	    file2convert=XLALCreateCHARVector(512);
	    strncpy(file2convert->data,LALoptarg,strlen(LALoptarg)+1);
	  }
	  break;
	};
    };
  /*
   * Open the dat file
   */
  LALappsTSAReadMapFile(&status,
			&map,
			file2convert);
  /*
   * Write the corresponding files
   */
  LALappsTSAWritePGM(
		     map,
		     NULL);
  /*
   * Free RAM
   */
  if (map)
    {
      LALappsTSADestroyMap(&status,&map);
    }
  if (file2convert)
    {
      XLALDestroyCHARVector(file2convert);
    }
   LALCheckMemoryLeaks();
  return 0;
}
Exemple #15
0
int main ( int argc, char *argv[] )
{
  /* lal function variables */
  LALStatus             status = blank_status;

  /* template bank generation parameters */
  CHAR   *bankFileName = NULL;
  INT4    numOutBanks = 0;
  REAL4   minMatch = -1;

  /* output data */
  MetadataTable         inputBank;
  MetadataTable         outputBank;
  MetadataTable         proctable;
  MetadataTable         procparams;
  ProcessParamsTable   *this_proc_param = NULL;
  LIGOLwXMLStream       xmlStream;

  /* counters and other variables */
  INT4 i, j;
  INT4 numTmplts = 0;
  INT4 numTmpltsWritten = 0;
  INT4 numPerFile = 0;
  CHAR *gpsHyphen;
  char outBankFileName[FILENAME_MAX];
  CHAR bankFileNameHead[FILENAME_MAX];
  CHAR bankFileNameTail[FILENAME_MAX];
  CHAR comment[LIGOMETA_COMMENT_MAX];  
  CHAR *userTag = NULL;
  SnglInspiralTable *thisTmplt = NULL;
  SnglInspiralTable *tmpTmplt = NULL;

  /* LALgetopt arguments */
  struct LALoption long_options[] =
  {
    {"verbose",                 no_argument,       &vrbflg,           1 },
    {"version",                 no_argument,       0,                'V'},
    {"user-tag",                required_argument, 0,                'Z'},
    {"userTag",                 required_argument, 0,                'Z'},
    {"comment",                 required_argument, 0,                's'},    
    {"help",                    no_argument,       0,                'h'}, 
    {"bank-file",               required_argument, 0,                'v'},
    {"number-of-banks",         required_argument, 0,                'n'},
    {"minimal-match",           required_argument, 0,                'M'},
    {0, 0, 0, 0}
  };
  int c;


  /*
   * 
   * initialize things
   *
   */


  lal_errhandler = LAL_ERR_EXIT;
  setvbuf( stdout, NULL, _IONBF, 0 );

  /* create the process and process params tables */
  proctable.processTable = (ProcessTable *) calloc( 1, sizeof(ProcessTable) );
  XLALGPSTimeNow(&(proctable.processTable->start_time));
  XLALPopulateProcessTable(proctable.processTable, PROGRAM_NAME, lalAppsVCSIdentInfo.vcsId,
      lalAppsVCSIdentInfo.vcsStatus, lalAppsVCSIdentInfo.vcsDate, 0);
  this_proc_param = procparams.processParamsTable = 
    (ProcessParamsTable *) calloc( 1, sizeof(ProcessParamsTable) );
  memset( comment, 0, LIGOMETA_COMMENT_MAX * sizeof(CHAR) );


  /*
   *
   * parse command line arguments
   *
   */


  while ( 1 )
  {
    /* LALgetopt_long stores long option here */
    int option_index = 0;
    size_t LALoptarg_len;

    c = LALgetopt_long_only( argc, argv,
        "i:n:VZ:hs:M:", 
        long_options, &option_index );

    /* detect the end of the options */
    if ( c == - 1 )
    {
      break;
    }

    switch ( c )
    {
      case 0:
        /* if this option set a flag, do nothing else now */
        if ( long_options[option_index].flag != 0 )
        {
          break;
        }
        else
        {
          fprintf( stderr, "error parsing option %s with argument %s\n",
              long_options[option_index].name, LALoptarg );
          exit( 1 );
        }
        break;

      case 'v':
        LALoptarg_len = strlen( LALoptarg ) + 1;
        bankFileName = (CHAR *) calloc( LALoptarg_len, sizeof(CHAR));
        memcpy( bankFileName, LALoptarg, LALoptarg_len );
        snprintf( procparams.processParamsTable->program, 
            LIGOMETA_PROGRAM_MAX, "%s", PROGRAM_NAME );
        snprintf( procparams.processParamsTable->type, 
            LIGOMETA_TYPE_MAX, "string" );
        snprintf( procparams.processParamsTable->param, 
            LIGOMETA_PARAM_MAX, "--%s", long_options[option_index].name );
        snprintf( procparams.processParamsTable->value, 
            LIGOMETA_VALUE_MAX, "%s", LALoptarg );
        break;

      case 'n':
        numOutBanks = (INT4) atoi( LALoptarg );
        if ( numOutBanks < 0 )
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "Number of output banks must be greater than zero:" 
              "(%d specified)\n",
              long_options[option_index].name, numOutBanks );
          exit( 1 );
        }
        else if ( numOutBanks > 99 )
        {
          fprintf( stderr, 
              "Warning: generating more than 99 banks is not reccomended!\n" );
        }
        this_proc_param = this_proc_param->next = (ProcessParamsTable *)
          calloc( 1, sizeof(ProcessParamsTable) );
        snprintf( this_proc_param->program, LIGOMETA_PROGRAM_MAX, 
            "%s", PROGRAM_NAME );
        snprintf( this_proc_param->type, LIGOMETA_TYPE_MAX, "int" );
        snprintf( this_proc_param->param, LIGOMETA_PARAM_MAX, 
            "--%s", long_options[option_index].name );
        snprintf( this_proc_param->value, LIGOMETA_VALUE_MAX, "%d", 
            numOutBanks );
        break;

      case 's':
        if ( strlen( LALoptarg ) > LIGOMETA_COMMENT_MAX - 1 )
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "comment must be less than %d characters\n",
              long_options[option_index].name, LIGOMETA_COMMENT_MAX );
          exit( 1 );
        }
        else
        {
          snprintf( comment, LIGOMETA_COMMENT_MAX, "%s", LALoptarg );
        }
        break;

      case 'Z':
        /* create storage for the usertag */
        LALoptarg_len = strlen( LALoptarg ) + 1;
        userTag = (CHAR *) calloc( LALoptarg_len, sizeof(CHAR) );
        memcpy( userTag, LALoptarg, LALoptarg_len );

        this_proc_param = this_proc_param->next = (ProcessParamsTable *)
          calloc( 1, sizeof(ProcessParamsTable) );
        snprintf( this_proc_param->program, LIGOMETA_PROGRAM_MAX, "%s", 
            PROGRAM_NAME );
        snprintf( this_proc_param->type, LIGOMETA_TYPE_MAX, "string" );
        snprintf( this_proc_param->param, LIGOMETA_PARAM_MAX, "-userTag" );
        snprintf( this_proc_param->value, LIGOMETA_VALUE_MAX, "%s",
            LALoptarg );
        break;

      case 'M':
        minMatch = (REAL4) atof( LALoptarg );
        if ( minMatch <= 0 )
        {
          fprintf( stdout, "invalid argument to --%s:\n"
              "minimal match of bank must be > 0: "
              "(%f specified)\n",
              long_options[option_index].name, minMatch );
          exit( 1 );
        }
        this_proc_param = this_proc_param->next = (ProcessParamsTable *)
          calloc( 1, sizeof(ProcessParamsTable) );
        snprintf( this_proc_param->program, LIGOMETA_PROGRAM_MAX, "%s", 
            PROGRAM_NAME );
        snprintf( this_proc_param->type, LIGOMETA_TYPE_MAX, "float" );
        snprintf( this_proc_param->param, LIGOMETA_PARAM_MAX, "--%s",
            long_options[option_index].name );
        snprintf( this_proc_param->value, LIGOMETA_VALUE_MAX, "%e",
            minMatch );
        break;

      case 'V':
        /* print version information and exit */
        fprintf( stdout, "Inspiral Template Bank Splitter\n" 
            "Duncan Brown <*****@*****.**>\n");
        XLALOutputVersionString(stderr, 0);
        exit( 0 );
        break;

      case '?':
        fprintf( stderr, USAGE, argv[0] );
        exit( 1 );
        break;

      default:
        fprintf( stderr, "unknown error while parsing options\n" );
        fprintf( stderr, USAGE, argv[0] );
        exit( 1 );
    }
  }

  if ( LALoptind < argc )
  {
    fprintf( stderr, "extraneous command line arguments:\n" );
    while ( LALoptind < argc )
    {
      fprintf ( stderr, "%s\n", argv[LALoptind++] );
    }
    exit( 1 );
  }

  /* check the values of the arguments */
  if ( ! bankFileName )
  {
    fprintf( stderr, "Error: --bank-file must be specified\n" );
    exit( 1 );
  }

  if ( ! numOutBanks )
  {
    fprintf( stderr, "Error: --number-of-banks must be specified\n" );
    exit( 1 );
  }

  if ( minMatch < 0 )
  {
    fprintf( stderr, "Error: --minimal-match must be specified\n" );
    exit( 1 );
  }


  /*
   *
   * read in the template bank from the input file
   *
   */


  /* read in the template bank from a ligo lw xml file */
  inputBank.snglInspiralTable = NULL;
  numTmplts = LALSnglInspiralTableFromLIGOLw( &(inputBank.snglInspiralTable), 
      bankFileName, 0, -1 );
  if ( numTmplts < 0 )
  {
    fprintf( stderr, "error: unable to read templates from %s\n", 
        bankFileName );
    exit( 1 );
  }
  
  if ( vrbflg ) fprintf( stdout, "read %d templates from %s\n", 
      numTmplts, bankFileName );

  /* find the hypen just before the GPS start time of the bank */
  gpsHyphen = NULL;
  gpsHyphen = strstr( bankFileName, "-" );
  if ( ! gpsHyphen )
  {
    fprintf( stderr, "Error: could not find first hypen in file name %s\n",
        bankFileName );
    exit( 1 );
  }
  gpsHyphen = strstr( gpsHyphen + 1, "-" );
  if ( ! gpsHyphen )
  {
    fprintf( stderr, "Error: could not find second hypen in file name %s\n",
        bankFileName );
    exit( 1 );
  }

  /* store the name of the template bank file */
  memcpy( bankFileNameHead, bankFileName, 
      (size_t) gpsHyphen - (size_t) bankFileName < FILENAME_MAX ? 
      (gpsHyphen - bankFileName) * sizeof(CHAR) : FILENAME_MAX * sizeof(CHAR) );
  strncpy( bankFileNameTail, gpsHyphen + 1, FILENAME_MAX - 1 );

  if ( vrbflg )
  {
    fprintf( stdout, "head of bank file name is %s\n", bankFileNameHead );
    fprintf( stdout, "tail of bank file name is %s\n", bankFileNameTail );
  }

  
  /*
   *
   * write out the individual tempate bank files
   *
   */
  

  /* compute the number of templates per output file */
  numPerFile = floor( ( numTmplts - 0.5 )/ numOutBanks + 1 );
  thisTmplt = inputBank.snglInspiralTable;
  if ( vrbflg ) fprintf( stdout, "writing around %d templates per file\n", 
      numPerFile );

  for ( i = 0; i < numOutBanks; ++i )
  {
    /* open the output xml file */
    memset( outBankFileName, 0, FILENAME_MAX * sizeof(CHAR) );
    if(snprintf( outBankFileName, FILENAME_MAX, "%s_%02d-%s", 
        bankFileNameHead, i, bankFileNameTail ) >= FILENAME_MAX)
      abort();
    memset( &xmlStream, 0, sizeof(LIGOLwXMLStream) );
    LAL_CALL( LALOpenLIGOLwXMLFile( &status , &xmlStream, outBankFileName), 
        &status );

    if ( vrbflg ) 
      fprintf( stdout, "writing templates to %s... ", outBankFileName );

    /* write process table */
    XLALGPSTimeNow(&(proctable.processTable->end_time));
    LAL_CALL( LALBeginLIGOLwXMLTable( &status, &xmlStream, process_table ), 
        &status );
    LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, proctable, 
          process_table ), &status );
    LAL_CALL( LALEndLIGOLwXMLTable ( &status, &xmlStream ), &status );
    
    /* write process_params table */
    LAL_CALL( LALBeginLIGOLwXMLTable( &status, &xmlStream, 
          process_params_table ), &status );
    LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, procparams, 
          process_params_table ), &status );
    LAL_CALL( LALEndLIGOLwXMLTable ( &status, &xmlStream ), &status );

    /* write the templates to the file */
    outputBank.snglInspiralTable = thisTmplt;
    numTmpltsWritten = 0;

    if ( thisTmplt )
    {
      LAL_CALL( LALBeginLIGOLwXMLTable( &status ,&xmlStream, 
            sngl_inspiral_table), &status );

      for ( j = 0; j < numPerFile - 1 && thisTmplt->next; ++j )
      {
        thisTmplt = thisTmplt->next;
      }
      tmpTmplt = thisTmplt->next;
      thisTmplt->next = NULL;
      thisTmplt = tmpTmplt;

      LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, outputBank,
            sngl_inspiral_table), &status );
      LAL_CALL( LALEndLIGOLwXMLTable( &status, &xmlStream), &status );
    }

    while ( outputBank.snglInspiralTable )
    {
      ++numTmpltsWritten;
      tmpTmplt = outputBank.snglInspiralTable;
      outputBank.snglInspiralTable = outputBank.snglInspiralTable->next;
      LALFree( tmpTmplt );
    }

    LAL_CALL( LALCloseLIGOLwXMLFile( &status, &xmlStream), &status );

    if ( vrbflg ) fprintf( stdout, "%d templates\n", numTmpltsWritten );
  }

  LALCheckMemoryLeaks();
  exit( 0 );
}
Exemple #16
0
int parseargs( int argc, char **argv )
{
	struct LALoption long_options[] = {
			{ "help", no_argument, 0, 'h' },
			{ "leaver", no_argument, 0, 'L' },
			{ "mass", required_argument, 0, 'M' },
			{ "spin", required_argument, 0, 'a' },
			{ "inclination", required_argument, 0, 'i' },
			{ "azimuth", required_argument, 0, 'q' },
			{ "energy", required_argument, 0, 'e' },
			{ "distance", required_argument, 0, 'r' },
			{ "l", required_argument, 0, 'l' },
			{ "m", required_argument, 0, 'm' },
			{ 0, 0, 0, 0 }
		};
	char args[] = "hM:a:i:q:e:r:l:m:";
	while (1) {
		int option_index = 0;
		int c;
	
		c = LALgetopt_long_only(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);
					exit(1);
				}
			case 'h': /* help */
				usage(argv[0]);
				exit(0);
			case 'M': /* mass */
				M = LAL_MSUN_SI * atof(LALoptarg);
				break;
			case 'a': /* spin */
				a = atof(LALoptarg);
				break;
			case 'i': /* inclination */
				i = LAL_PI_180 * atof(LALoptarg);
				break;
			case 'q': /* azimuth */
				q = LAL_PI_180 * atof( LALoptarg );
				break;
			case 'e': /* energy */
				e = atof(LALoptarg);
				break;
			case 'r': /* distance */
				r = 1e6 * LAL_PC_SI * atof(LALoptarg);
				break;
			case 'l':
				l = atoi(LALoptarg);
				break;
			case 'm':
				m = atoi(LALoptarg);
				break;
			case '?':
			default:
				fprintf(stderr, "unknown error while parsing options\n");
				exit(1);
		}
	}
	
	if ( LALoptind < argc ) {
		fprintf(stderr, "extraneous command line arguments:\n");
		while (LALoptind < argc)
			fprintf(stderr, "%s\n", argv[LALoptind++]);
		exit(1);
	}
	
	if (a == a_invalid || l == l_invalid || m == m_invalid || M <= 0.0 || e <= 0.0 || e >= 1.0 || r <= 0.0 || i == i_invalid) {
		fprintf(stderr, "must specify mass, spin, distance, frac. energy loss, l, m\n");
		usage(argv[0]);
		exit(1);
	}

	if (l < 2) {
		fprintf(stderr, "must specify l >= 2\n");
		exit(1);
	}

	if (abs(m) > l) {
		fprintf(stderr, "must specify m <= l\n");
		exit(1);
	}
	
	return 0;
}
Exemple #17
0
/* parse command line options */
static void parse_options(INT4 argc, CHAR *argv[])
{
  int c = -1;
  struct stat fileStatus;

  /* tempory variables */
  CHAR *channelOneTemp = NULL;
  CHAR *channelTwoTemp = NULL;

  while(1)
  {
    static struct LALoption long_options[] =
    {
      /* options that set a flag */
      {"middle-segment", no_argument, &middle_segment_flag, 1},
      {"apply-mask", no_argument, &apply_mask_flag, 1},
      {"high-pass-filter", no_argument, &high_pass_flag, 1},
      {"overlap-hann", no_argument, &overlap_hann_flag, 1},
      {"verbose", no_argument, &vrbflg, 1},
      {"recentre", no_argument, &recentre_flag, 1},
      {"cc-spectra", no_argument, &cc_spectra_flag, 1},
      {"debug", no_argument, &debug_flag, 1},
      /* options that don't set a flag */
      {"help", no_argument, 0, 'a'},
      {"version", no_argument, 0, 'b'},
      {"user-tag", required_argument, 0, 'd'},
      {"comment", required_argument, 0, 'e'},
      {"output-dir", required_argument, 0, 'f'},
      {"gps-start-time", required_argument, 0, 'g'},
      {"gps-end-time", required_argument, 0, 'h'},
      {"interval-duration", required_argument, 0, 'i'},
      {"segment-duration", required_argument, 0, 'j'},
      {"resample-rate", required_argument, 0, 'k'},
      {"f-min", required_argument, 0, 'l'},
      {"f-max", required_argument, 0, 'm'},
      {"ifo-one", required_argument, 0, 'n'},
      {"ifo-two", required_argument, 0, 'o'},
      {"channel-one", required_argument, 0, 'p'},
      {"channel-two", required_argument, 0, 'q'},
      {"frame-cache-one", required_argument, 0, 'r'},
      {"frame-cache-two", required_argument, 0, 's'},
      {"calibration-cache-one", required_argument, 0, 't'},
      {"calibration-cache-two", required_argument, 0, 'u'},
      {"calibration-offset", required_argument, 0, 'v'},
      {"mask-bin", required_argument, 0, 'w'},
      {"hann-duration", required_argument, 0, 'x'},
      {"hpf-frequency", required_argument, 0, 'y'},
      {"hpf-attenuation", required_argument, 0, 'z'},
      {"hpf-order", required_argument, 0, 'A'},
      {"geo-hpf-frequency", required_argument, 0, 'B'},
      {"geo-hpf-attenuation", required_argument, 0, 'C'},
      {"geo-hpf-order", required_argument, 0, 'D'},
      {"alpha", required_argument, 0, 'E'},
      {"f-ref", required_argument, 0, 'F'},
      {"omega0", required_argument, 0, 'G'},
      {0, 0, 0, 0}
    };

    /* LALgetopt_long stores the option here */
    int option_index = 0;
    size_t LALoptarg_len;

    c = LALgetopt_long_only(argc, argv, \
        "abd:e:f:g:h:i:j:k:l:m:n:o:p:q:r:s:t:u:v:w:x:y:z:" \
        "A:B:C:D:E:F:G:", long_options, &option_index);

    if (c == -1)
    {
      /* end of options, break loop */
      break;
    }

    switch(c)
    {
      case 0:
        /* If this option set a flag, do nothing else now. */
        if (long_options[option_index].flag != 0)
        {
          break;
        }
        else
        {
          fprintf(stderr, "error parseing option %s with argument %s\n", \
              long_options[option_index].name, LALoptarg);
          exit(1);
        }
        break;

      case 'a':
        /* help */
        display_usage();
        exit(0);
        break;

      case 'b':
        /* display version info and exit */
        fprintf(stdout, "Standalone SGWB Search Engine\n");
        XLALOutputVersionString(stderr,0);
        exit(0);
        break;

      case 'd':
        /* user tag */
        LALoptarg_len = strlen(LALoptarg) + 1;
        userTag = (CHAR*)calloc(LALoptarg_len, sizeof(CHAR));
        memcpy(userTag, LALoptarg, LALoptarg_len);

        /* add to process_params table */
        this_proc_param = this_proc_param->next = (ProcessParamsTable *) \
                          calloc(1, sizeof(ProcessParamsTable));
        snprintf(this_proc_param->program, LIGOMETA_PROGRAM_MAX, "%s", prog_name);
        snprintf(this_proc_param->param, LIGOMETA_PARAM_MAX, "--user-tag");
        snprintf(this_proc_param->type, LIGOMETA_TYPE_MAX, "string");
        snprintf(this_proc_param->value, LIGOMETA_VALUE_MAX, "%s", LALoptarg);
        break;

      case 'e':
        /* xml comment */
        if (strlen(LALoptarg) > LIGOMETA_COMMENT_MAX - 1)
        {
          fprintf(stderr, "invalid argument to --%s:\n" \
              "comment must be less than %d characters\n", \
              long_options[option_index].name, LIGOMETA_COMMENT_MAX);
          exit(1);
        }
        else
        {
          snprintf(comment, LIGOMETA_COMMENT_MAX, "%s", LALoptarg);
        }
        break;

      case 'f':
        /* directory for output files */
        LALoptarg_len = strlen(LALoptarg) + 1;
        outputPath = (CHAR*)calloc(LALoptarg_len, sizeof(CHAR));
        memcpy(outputPath, LALoptarg, LALoptarg_len);
        if (stat(outputPath, &fileStatus) == -1)
        {
          fprintf(stderr, "Invalid argument to --%s:\n" \
              "Directory does not exist: (%s specified)\n", \
              long_options[option_index].name, outputPath);
          exit(1);
        }
        ADD_PROCESS_PARAM("string", "%s", outputPath);
        break;

      case 'g':
        /* start time */
        startTime = atoi(LALoptarg);
        if (startTime < 441217609)
        {
          fprintf(stderr, "Invalid argument to --%s:\n" \
              "GPS start time is prior to 1 January 1994 00:00:00 UTC " \
              "(%d specified)\n", long_options[option_index].name, \
              startTime);
          exit(1);
        }
        if (startTime > 999999999)
        {
          fprintf(stderr, "Invalid argument to --%s:\n" \
              "GPS start time is after 14 September 2011 01:46:26 UTC " \
              "(%d specified)\n", long_options[option_index].name, \
              startTime);
          exit(1);
        }
        ADD_PROCESS_PARAM("int", "%"LAL_INT4_FORMAT, startTime);
        break;

      case 'h':
        /* end time */
        endTime = atoi(LALoptarg);
        if (endTime < 441217609)
        {
          fprintf(stderr, "Invalid argument to --%s:\n" \
              "GPS end time is prior to 1 January 1994 00:00:00 UTC " \
              "(%d specified)\n", long_options[option_index].name, \
              endTime);
          exit(1);
        }
        if (endTime > 999999999)
        {
          fprintf(stderr, "Invalid argument to --%s:\n" \
              "GPS end time is after 14 September 2011 01:46:26 UTC " \
              "(%d specified)\n", long_options[option_index].name, \
              endTime);
          exit(1);
        }
        ADD_PROCESS_PARAM("int", "%"LAL_INT4_FORMAT, endTime);
        break;

      case 'i':
        /* interval duration */
        intervalDuration = atoi(LALoptarg);
        if (intervalDuration <= 0)
        {
          fprintf(stderr, "Invalid argument to --%s:\n" \
              "Interval duration must be greater than 0: (%d specified)\n", \
              long_options[option_index].name, intervalDuration);
          exit(1);
        }
        ADD_PROCESS_PARAM("int", "%d", intervalDuration);
        break;

      case 'j':
        /* segment duration */
        segmentDuration = atoi(LALoptarg);
        if (segmentDuration <= 0)
        {
          fprintf(stderr, "Invalid argument to --%s:\n" \
              "Segment duration must be greater than 0: (%d specified)\n", \
              long_options[option_index].name, segmentDuration);
          exit(1);
        }
        ADD_PROCESS_PARAM("int", "%d", segmentDuration);
        break;

      case 'k':
        /* resample rate */
        resampleRate = atoi(LALoptarg);
        if (resampleRate < 2 || resampleRate > 16384 || resampleRate % 2)
        {
          fprintf(stderr, "Invalid argument to --%s:\n" \
              "Resample rate must be a power of 2 between 2 and 16384: " \
              "inclusive: (%d specified)\n", long_options[option_index].name, \
              resampleRate);
          exit(1);
        }
        ADD_PROCESS_PARAM("int", "%d", resampleRate);

        break;

      case 'l':
        /* minimal frequency */
        fMin = atof(LALoptarg);
        if (fMin < 0)
        {
          fprintf(stderr, "Invalid argument to --%s:\n" \
              "Minimum frequency is less than 0 Hz (%f specified)\n", \
              long_options[option_index].name, fMin);
          exit(1);
        }
        /* check that min frequency can be represented by the
         * sampling rate of the data and round accordingly */
        if (fMin != round(fMin * PSD_WINDOW_DURATION) / PSD_WINDOW_DURATION)
        {
          fMin = round(fMin * PSD_WINDOW_DURATION) / PSD_WINDOW_DURATION;
          fprintf(stderr, "warning: fMin has been rounded to %f\n", fMin);
        }
        ADD_PROCESS_PARAM("float", "%e", fMin);
        break;

      case 'm':
        /* maximal frequency */
        fMax = atof(LALoptarg);
        if (fMax < 0)
        {
          fprintf(stderr, "Invalid argument to --%s:\n" \
              "Maximum frequency is less than 0 Hz (%f specified)\n", \
              long_options[option_index].name, fMax);
          exit(1);
        }
        /* check that the max frequency can be represented by the
         * sampling rate of the data and round accordingly */
        if (fMax != round(fMax * PSD_WINDOW_DURATION) / PSD_WINDOW_DURATION)
        {
          fMax = round(fMax * PSD_WINDOW_DURATION) / PSD_WINDOW_DURATION;
          fprintf(stderr, "warning: fMax has been rounded to %f\n", fMax);
        }
        ADD_PROCESS_PARAM("float", "%e", fMax);
        break;

      case 'n':
        /* ifo for first stream */
        LALoptarg_len = strlen(LALoptarg) + 1;
        ifoOne = (CHAR*)calloc(LALoptarg_len, sizeof(CHAR));
        memcpy(ifoOne, LALoptarg, LALoptarg_len);

        /* set site id for ifo one */
        if (strncmp(ifoOne, "H1", 2) == 0)
          siteOne = 0;
        else if (strncmp(ifoOne, "H2", 2) == 0)
          siteOne = 0;
        else if (strncmp(ifoOne, "L1", 2) == 0)
          siteOne = 1;
        else if (strncmp(ifoOne, "G1", 2) == 0)
          siteOne = 3;
        else
        {
          fprintf(stderr, "First IFO not recognised...\n");
          exit(1);
        }
        ADD_PROCESS_PARAM("string", "%s", ifoOne);
        break;

      case 'o':
        /* ifo for second stream */
        LALoptarg_len = strlen(LALoptarg) + 1;
        ifoTwo = (CHAR*)calloc(LALoptarg_len, sizeof(CHAR));
        memcpy(ifoTwo, LALoptarg, LALoptarg_len);

        /* set site id for ifo two */
        if (strncmp(ifoTwo, "H1", 2) == 0)
          siteTwo = 0;
        else if (strncmp(ifoTwo, "H2", 2) == 0)
          siteTwo = 0;
        else if (strncmp(ifoTwo, "L1", 2) == 0)
          siteTwo = 1;
        else if (strncmp(ifoTwo, "G1", 2) == 0)
          siteOne = 3;
        else
        {
          fprintf(stderr, "Second IFO not recognised...\n");
          exit(1);
        }
        ADD_PROCESS_PARAM("string", "%s", ifoTwo);
        break;

      case 'p':
        /* channel one */
        LALoptarg_len = strlen(LALoptarg) + 4;
        channelOneTemp = (CHAR*)calloc(LALoptarg_len, sizeof(CHAR));
        channelOne = (CHAR*)calloc(LALoptarg_len, sizeof(CHAR));
        memcpy(channelOneTemp, LALoptarg, LALoptarg_len);
        ADD_PROCESS_PARAM("string", "%s", channelOneTemp);
        break;

      case 'q':
        /* channel two */
        LALoptarg_len = strlen(LALoptarg) + 4;
        channelTwoTemp = (CHAR*)calloc(LALoptarg_len, sizeof(CHAR));
        channelTwo = (CHAR*)calloc(LALoptarg_len, sizeof(CHAR));
        memcpy(channelTwoTemp, LALoptarg, LALoptarg_len);
        ADD_PROCESS_PARAM("string", "%s", channelTwoTemp);
        break;

      case 'r':
        /* frame cache one */
        LALoptarg_len = strlen(LALoptarg) + 1;
        frameCacheOne = (CHAR*)calloc(LALoptarg_len, sizeof(CHAR));
        memcpy(frameCacheOne, LALoptarg, LALoptarg_len);
        if (stat(frameCacheOne, &fileStatus) == -1)
        {
          fprintf(stderr, "Invalid argument to --%s:\n" \
              "File does not exist: (%s specified)\n", \
              long_options[option_index].name, frameCacheOne);
          exit(1);
        }
        ADD_PROCESS_PARAM("string", "%s", frameCacheOne);
        break;

      case 's':
        /* frame cache two */
        LALoptarg_len = strlen(LALoptarg) + 1;
        frameCacheTwo = (CHAR*)calloc(LALoptarg_len, sizeof(CHAR));
        memcpy(frameCacheTwo, LALoptarg, LALoptarg_len);
        if (stat(frameCacheTwo, &fileStatus) == -1)
        {
          fprintf(stderr, "Invalid argument to --%s:\n" \
              "File does not exist: (%s specified)\n", \
              long_options[option_index].name, frameCacheTwo);
          exit(1);
        }
        ADD_PROCESS_PARAM("string", "%s", frameCacheTwo);
        break;

      case 't':
        /* calibration cache one */
        LALoptarg_len = strlen(LALoptarg) + 1;
        calCacheOne = (CHAR*)calloc(LALoptarg_len, sizeof(CHAR));
        memcpy(calCacheOne, LALoptarg, LALoptarg_len);
        if (stat(calCacheOne, &fileStatus) == -1)
        {
          fprintf(stderr, "Invalid argument to --%s:\n" \
              "File does not exist: (%s specified)\n", \
              long_options[option_index].name, calCacheOne);
          exit(1);
        }
        ADD_PROCESS_PARAM("string", "%s", calCacheOne);
        break;

      case 'u':
        /* calibration cache two */
        LALoptarg_len = strlen(LALoptarg) + 1;
        calCacheTwo = (CHAR*)calloc(LALoptarg_len, sizeof(CHAR));
        memcpy(calCacheTwo, LALoptarg, LALoptarg_len);
        if (stat(calCacheTwo, &fileStatus) == -1)
        {
          fprintf(stderr, "Invalid argument to --%s:\n" \
              "File does not exist: (%s specified)\n", \
              long_options[option_index].name, calCacheTwo);
          exit(1);
        }
        ADD_PROCESS_PARAM("string", "%s", calCacheTwo);
        break;

      case 'v':
        /* calibration time offset */
        calibOffset = atoi(LALoptarg);
        ADD_PROCESS_PARAM("int", "%d", calibOffset);
        break;

      case 'w':
        /* number of bins to mask for frequency mask */
        maskBin = atoi(LALoptarg);
        if (maskBin <= 0)
        {
          fprintf(stderr, "Invalid argument to --%s:\n" \
              "Number of bins to mask must be greater than 0: " \
              "(%d specified)\n", long_options[option_index].name, maskBin);
          exit(1);
        }
        ADD_PROCESS_PARAM("int", "%d", maskBin);
        break;

      case 'x':
        /* hann window duration */
        hannDuration = atoi(LALoptarg);
        if (hannDuration < 0)
        {
          fprintf(stderr, "Invalid argument to --%s:\n" \
              "Hann duartion is less than 0: (%d specified)\n", \
              long_options[option_index].name, hannDuration);
          exit(1);
        }
        ADD_PROCESS_PARAM("int", "%d", hannDuration);
        break;

      case 'y':
        /* high pass knee filter frequency  */
        highPassFreq = atof(LALoptarg);
        if (highPassFreq < 0)
        {
          fprintf(stderr, "Invalid argument tp --%s:\n" \
              "High pass filter knee frequency is less than 0 Hz: "\
              "(%f specified)\n", long_options[option_index].name, \
              highPassFreq);
          exit(1);
        }
        ADD_PROCESS_PARAM("float", "%e", highPassFreq);
        break;

      case 'z':
        /* high pass filter attenuation  */
        highPassAtten = atof(LALoptarg);
        if ((highPassAtten < 0.0) || (highPassAtten > 1.0))
        {
          fprintf(stderr, "Invalid argument to --%s:\n" \
              "High pass filter attenuation must be in the range [0:1]: " \
              "(%f specified)\n", long_options[option_index].name, \
              highPassAtten);
          exit(1);
        }
        ADD_PROCESS_PARAM("float", "%e", highPassAtten);
        break;

      case 'A':
        /* high pass filter order  */
        highPassOrder = atoi(LALoptarg);
        if (highPassOrder <= 0)
        {
          fprintf(stderr, "Invalid argument to --%s:\n" \
              "High pass filter order must be greater than 0: " \
              "(%d specified)\n", long_options[option_index].name,
              highPassOrder);
          exit(1);
        }
        ADD_PROCESS_PARAM("int", "%d", highPassOrder);
        break;

      case 'B':
        /* GEO high pass knee filter frequency */
        geoHighPassFreq = atof(LALoptarg);
        if (geoHighPassFreq < 0)
        {
          fprintf(stderr, "Invalid argument tp --%s:\n" \
              "GEO high pass filter knee frequency is less than 0 Hz: "\
              "(%f specified)\n", long_options[option_index].name, \
              geoHighPassFreq);
          exit(1);
        }
        ADD_PROCESS_PARAM("float", "%e", geoHighPassFreq);
        break;

      case 'C':
        /* GEO high pass filter attenuation */
        geoHighPassAtten = atof(LALoptarg);
        if ((geoHighPassAtten < 0.0) || (geoHighPassAtten > 1.0))
        {
          fprintf(stderr, "Invalid argument to --%s:\n" \
              "GEO high pass filter attenuation must be in the range [0:1]: " \
              "(%f specified)\n", long_options[option_index].name, \
              geoHighPassAtten);
          exit(1);
        }
        ADD_PROCESS_PARAM("float", "%e", geoHighPassAtten);
        break;

      case 'D':
        /* GEO high pass filter order */
        geoHighPassOrder = atoi(LALoptarg);
        if (geoHighPassOrder <= 0)
        {
          fprintf(stderr, "Invalid argument to --%s:\n" \
              "GEO high pass filter order must be greater than 0: " \
              "(%d specified)\n", long_options[option_index].name,
              geoHighPassOrder);
          exit(1);
        }
        ADD_PROCESS_PARAM("int", "%d", geoHighPassOrder);
        break;

      case 'E':
        /* filter spectrum exponent */
        alpha = atof(LALoptarg);
        ADD_PROCESS_PARAM("float", "%e", alpha);
        break;

      case 'F':
        /* filter reference frequency */
        fRef = atof(LALoptarg);
        if (fRef < 0)
        {
          fprintf(stderr, "Invalid argument to --%s:\n" \
              "Reference frequency must be greater than 0: " \
              "(%f specified)\n", long_options[option_index].name, fRef);
          exit(1);
        }
        ADD_PROCESS_PARAM("float", "%e", fRef);
        break;

      case 'G':
        /* filter reference omega */
        omegaRef = atof(LALoptarg);
        if (omegaRef <= 0)
        {
          fprintf(stderr, "Invalid argument to --%s:\n" \
              "Reference omega_0 must be positive: (%f specified)\n", \
              long_options[option_index].name, omegaRef);
          exit(1);
        }
        ADD_PROCESS_PARAM("float", "%e", omegaRef);
        break;

      case '?':
        exit(1);
        break;

      default:
        fprintf(stderr, "Unknown error while parsing options\n");
        exit(1);
    }
  }

  if (LALoptind < argc)
  {
    fprintf(stderr, "Extraneous command line arguments:\n");
    while(LALoptind < argc)
    {
      fprintf(stderr, "%s\n", argv[LALoptind++]);
    }
    exit(1);
  }

  /* check for required arguments */

  /* start/end time */
  if (startTime == 0)
  {
    fprintf(stderr, "--gps-start-time must be specified\n");
    exit(1);
  }
  if (endTime == 0)
  {
    fprintf(stderr, "--gps-end-time must be specified\n");
    exit(1);
  }

  /* interval duration */
  if (intervalDuration == -1)
  {
    fprintf(stderr, "--interval-duration must be specified\n");
    exit(1);
  }

  /* segment duration */
  if (segmentDuration == -1)
  {
    fprintf(stderr, "--segment-duration must be specified\n");
    exit(1);
  }

  /* min/max frequency */
  if (fMin == -1)
  {
    fprintf(stderr, "--f-min must be specified\n");
    exit(1);
  }
  if (fMax == -1)
  {
    fprintf(stderr, "--f-max must be specified\n");
    exit(1);
  }

  /* ifos */
  if (ifoOne == NULL)
  {
    fprintf(stderr, "--ifo-one must be specified\n");
    exit(1);
  }
  if (ifoTwo == NULL)
  {
    fprintf(stderr, "--ifo-two must be specified\n");
    exit(1);
  }

  /* channels */
  if (channelOne == NULL)
  {
    fprintf(stderr, "--channel-one must be specified\n");
    exit(1);
  }
  if (channelTwo == NULL)
  {
    fprintf(stderr, "--channel-two must be specified\n");
    exit(1);
  }

  /* frame cache */
  if (frameCacheOne == NULL)
  {
    fprintf(stderr, "--frame-cache-one must be specified\n");
    exit(1);
  }
  if (siteOne != siteTwo)
  {
    /* only need second frame cache if ifos differ */
    if (frameCacheTwo == NULL)
    {
      fprintf(stderr, "--frame-cache-two must be specified\n");
      exit(1);
    }
  }
  else
  {
    /* if site ids are the same then the frames for the different
     * detectors are in the same frame cache */
    frameCacheTwo = frameCacheOne;
  }

  /* calibration cache */
  if (strncmp(ifoOne, "G1", 2) != 0)
  {
    if (calCacheOne == NULL)
    {
      fprintf(stderr, "--calibration-cache-one must be specified\n");
      exit(1);
    }
  }
  if (strncmp(ifoTwo, "G1", 2) != 0)
  {
    if (calCacheTwo == NULL)
    {
      fprintf(stderr, "--calibration-cache-two must be specified\n");
      exit(1);
    }
  }

  /* calibration offset */
  if (calibOffset == -1)
  {
    fprintf(stderr, "--calibration-offset must be specified\n");
    exit(1);
  }

  /* mask */
  if (apply_mask_flag)
  {
    if (maskBin == -1)
    {
      fprintf(stderr, "--mask-bin must be specified\n");
      exit(1);
    }
  }

  /* hann duration */
  if (overlap_hann_flag)
  {
    if (hannDuration != -1)
    {
      fprintf(stderr, "Overlapping Hann windows specified, --hann-duration " \
          "will be ignored\n");
    }
  }
  else
  {
    if (hannDuration == -1)
    {
      fprintf(stderr, "--hann-duration must be specified\n");
      exit(1);
    }
  }

  /* high pass filter */
  if (high_pass_flag)
  {
    if (highPassFreq == -1)
    {
      fprintf(stderr, "--hpf-frequency must be specified\n");
      exit(1);
    }
    if (highPassAtten == -1)
    {
      fprintf(stderr, "--hpf-attenuation must be specified\n");
      exit(1);
    }
    if (highPassOrder == -1)
    {
      fprintf(stderr, "--hpf-order must be specified\n");
      exit(1);
    }
  }

  /* GEO high pass filter */
  if ((strncmp(ifoOne, "G1", 2) == 0) || (strncmp(ifoTwo, "G1", 2) == 0))
  {
    if (geoHighPassFreq == -1)
    {
      fprintf(stderr, "--geo-hpf-frequency must be specified\n");
      exit(1);
    }
    if (geoHighPassAtten == -1)
    {
      fprintf(stderr, "--geo-hpf-attenuation must be specified\n");
      exit(1);
    }
    if (geoHighPassOrder == -1)
    {
      fprintf(stderr, "--geo-hpf-order must be specified\n");
      exit(1);
    }
  }

  /* check for sensible arguments */

  /* start time same as stop time */
  if (startTime == endTime)
  {
    fprintf(stderr, "Start time same as end time; no analysis to perform\n");
    exit(1);
  }

  /* stop time before start time */
  if (startTime > endTime)
  {
    fprintf(stderr, "Invalid start/end time; end time (%d) is before " \
        "start time (%d)\n", endTime, startTime);
    exit(1);
  }

  /* interval duration must be a least 3 times the segment duration */
  if ((intervalDuration / segmentDuration) < 3)
  {
    fprintf(stderr, "Invalid interval duration (%d): must be a least 3 times " \
        "the segment\nduration (%d)\n", intervalDuration, segmentDuration);
    exit(1);
  }

  /* interval duration must be an odd mutliple of segment duration */
  if (((intervalDuration / segmentDuration) % 2) != 1)
  {
    fprintf(stderr, "Invalid interval duration (%d): must be an odd " \
        "multiple of the segment\nduration (%d)\n", intervalDuration, \
        segmentDuration);
    exit(1);
  }

  /* min frequency same as max */
  if (fMin == fMax)
  {
    fprintf(stderr, "Minimum frequency same as maximum; no analysis to " \
        "perform\n");
    exit(1);
  }

  /* max frequency less than min */
  if (fMin > fMax)
  {
    fprintf(stderr, "Invalid frequency band; maximum frequency (%f Hz) is " \
        "before minimum\nfrequency (%f Hz)\n", fMax, fMin);
    exit(1);
  }

  /* filter reference frequency less than min */
  if (fRef < fMin)
  {
    fprintf(stderr, "Reference frequency (%f Hz) is less than minimum " \
        "frequency (%f Hz)\n", fRef, fMin);
    exit(1);
  }

  /* filter reference frequency greater than max */
  if (fRef > fMax)
  {
    fprintf(stderr, "Reference frequency (%f Hz) is greater than maximum " \
        "frequency (%f Hz)\n", fRef, fMax);
    exit(1);
  }

  /* set channels */
  strcpy(channelOne, ifoOne);
  strcpy(channelTwo, ifoTwo);
  strcat(channelOne, ":");
  strcat(channelTwo, ":");
  strcat(channelOne, channelOneTemp);
  strcat(channelTwo, channelTwoTemp);
  free(channelOneTemp);
  free(channelTwoTemp);

  return;
}
Exemple #18
0
int ReadCommandLine(int argc,char *argv[],struct CommandLineArgsTag *CLA)
{
  int errflg = 0;
  LALoptarg = NULL;

  struct LALoption long_options[] = {
    {"frequency",                   required_argument, NULL,           'a'},
    {"log-Gmustart",                required_argument, NULL,           'b'},
    {"log-Gmuend",                  required_argument, NULL,           'c'},
    {"nGmu",                        required_argument, NULL,           'd'},
    {"log-epsilonstart",            required_argument, NULL,           'e'},
    {"log-epsilonend",              required_argument, NULL,           'f'},
    {"nepsilon",                    required_argument, NULL,           'g'},
    {"index",                       required_argument, NULL,           'i'},
    {"log-pstart",                  required_argument, NULL,           'j'},
    {"log-pend",                    required_argument, NULL,           'k'},
    {"np",                          required_argument, NULL,           'l'},
    {"efficiency-file",             required_argument, NULL,           'm'},
    {"help",                        no_argument, NULL,                 'h'},
    {0, 0, 0, 0}
  };
  char args[] = "ha:b:c:d:e:f:g:i:j:k:l:";

  CLA->f=               -300;     
  CLA->logGmustart=     -300;      
  CLA->logGmuend=       -300;        
  CLA->nGmu=            -1;
  CLA->logepsilonstart= -300;  
  CLA->logepsilonend=   -300;
  CLA->nepsilon=        -1;
  CLA->n=               -1;
  CLA->logpstart=       -300;
  CLA->logpend=         -300;
  CLA->np=              -1;
  CLA->efficiencyfile=  NULL;
  

  /* Scan through list of command line arguments */
  while ( 1 )
  {
    int option_index = 0; /* LALgetopt_long stores long option here */
    int c;

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

    switch ( c )
    {

    case 'a':
      /* lowest frequency  */
      CLA->f=atof(LALoptarg);
      break;
    case 'b':
      /* lowest frequency  */
      CLA->logGmustart=atof(LALoptarg);
      break;
    case 'c':
      /* highest frequency */
      CLA->logGmuend=atof(LALoptarg);
      break;
    case 'd':
      /* number of frequencies to do */
      CLA->nGmu=atoi(LALoptarg);
      break;
    case 'e':
      /* lowest frequency  */
      CLA->logepsilonstart=atof(LALoptarg);
      break;
    case 'f':
      /* highest frequency */
      CLA->logepsilonend=atof(LALoptarg);
      break;
    case 'g':
      /* number of frequencies to do */
      CLA->nepsilon=atoi(LALoptarg);
      break;
    case 'i':
      /* number of frequencies to do */
      CLA->n=atof(LALoptarg);
      break;
    case 'j':
      /* highest frequency */
      CLA->logpstart=atof(LALoptarg);
      break;
    case 'k':
      /* number of frequencies to do */
      CLA->logpend=atof(LALoptarg);
      break;
    case 'l':
      /* number of frequencies to do */
      CLA->np=atoi(LALoptarg);
      break;
    case 'm':
      /* number of frequencies to do */
      CLA->efficiencyfile=LALoptarg;
      break;

    case 'h':
      /* print usage/help message */
      fprintf(stdout,"Arguments are :\n");
      fprintf(stdout,"\t--frequency (-a)\t\tFLOAT\t Lowest frequency.\n");
      fprintf(stdout,"\t--log-Gmustart (-b)\t\tFLOAT\t Lowest Gmu.\n");
      fprintf(stdout,"\t--log-Gmuend (-c)\t\tFLOAT\t Largest Gmu.\n");
      fprintf(stdout,"\t--nGmu (-d)\t\t\tINTEGER\t Number of Gmu bins to do.\n");
      fprintf(stdout,"\t--log-epsilonstart (-e)\t\tFLOAT\t Lowest epsilon.\n");
      fprintf(stdout,"\t--log-epsilonend (-f)\t\tFLOAT\t Largest epsilon.\n");
      fprintf(stdout,"\t--nepsilon (-g)\t\t\tINTEGER\t Number of epsilon bins to do.\n");
      fprintf(stdout,"\t--index (-i)\t\t\tFLOAT\t Index for alpha as function of Gmu.\n");
      fprintf(stdout,"\t--log-pstart (-j)\t\tFLOAT\t Lowest p.\n");
      fprintf(stdout,"\t--log-pend (-k)\t\t\tFLOAT\t Largest p.\n");
      fprintf(stdout,"\t--np (-l)\t\t\tINTEGER\t Number of p bins to do.\n");
      fprintf(stdout,"\t--efficiency-file (-m)\t\t\tSTRING\t File with efficiency values and errors.\n");
      fprintf(stdout,"\t--help (-h)\t\t\tFLAG\t Print this message.\n");
      exit(0);
      break;
    default:
      /* unrecognized option */
      errflg++;
      fprintf(stderr,"Unrecognized option argument %c\n",c);
      exit(1);
      break;
    }
    }

  if(CLA->f == -300)
    {
      fprintf(stderr,"No lowest frequency specified.\n");
      fprintf(stderr,"Try %s -h \n",argv[0]);
      return 1;
    }
  if(CLA->logGmustart == -300)
    {
      fprintf(stderr,"No lowest Gmu specified.\n");
      fprintf(stderr,"Try %s -h \n",argv[0]);
      return 1;
    }
  if(CLA->logGmuend == -300)
    {
      fprintf(stderr,"No highest Gmu specified.\n");
      fprintf(stderr,"Try %s -h \n",argv[0]);
      return 1;
    }
  if(CLA->nGmu == -1)
    {
      fprintf(stderr,"No number of Gmu bins specified.\n");
      fprintf(stderr,"Try %s -h \n",argv[0]);
      return 1;
    }
  if(CLA->logepsilonstart == -300)
    {
      fprintf(stderr,"No lowest epsilon specified.\n");
      fprintf(stderr,"Try %s -h \n",argv[0]);
      return 1;
    }
  if(CLA->logepsilonend == -300)
    {
      fprintf(stderr,"No highest epsilon specified.\n");
      fprintf(stderr,"Try %s -h \n",argv[0]);
      return 1;
    }
  if(CLA->nepsilon == -1)
    {
      fprintf(stderr,"No number of epsilon bins specified.\n");
      fprintf(stderr,"Try %s -h \n",argv[0]);
      return 1;
    }

  if(CLA->logpstart == -300)
    {
      fprintf(stderr,"No lowest p specified.\n");
      fprintf(stderr,"Try %s -h \n",argv[0]);
      return 1;
    }
  if(CLA->logpend == -300)
    {
      fprintf(stderr,"No highest p specified.\n");
      fprintf(stderr,"Try %s -h \n",argv[0]);
      return 1;
    }
  if(CLA->np == -1)
    {
      fprintf(stderr,"No number of p bins specified.\n");
      fprintf(stderr,"Try %s -h \n",argv[0]);
      return 1;
    }
  if(CLA->n == -1)
    {
      fprintf(stderr,"No index for alpha specified.\n");
      fprintf(stderr,"Try %s -h \n",argv[0]);
      return 1;
    }
  if(CLA->efficiencyfile == NULL)
    {
      fprintf(stderr,"No efficiency file specified.\n");
      fprintf(stderr,"Try %s -h \n",argv[0]);
      return 1;
    }

  return errflg;
}
Exemple #19
0
int arg_parse_check( int argc, char *argv[], MetadataTable procparams )
{
  /* LALgetopt arguments */
  struct LALoption long_options[] =
  {
    /* these options set a flag */
    {"verbose",                 no_argument,       &vrbflg,           1 },
    {"write-compress",          no_argument,       &outCompress,      1 },
    {"help",                    no_argument,       0,                'h'},
    {"gps-start-time",          required_argument, 0,                'a'},
    {"gps-end-time",            required_argument, 0,                'b'},
    {"low-frequency-cutoff",    required_argument, 0,                'i'},
    {"minimum-mass",            required_argument, 0,                'A'},
    {"maximum-mass",            required_argument, 0,                'B'},
    {"number-of-templates",     required_argument, 0,                'K'},
    {"random-seed",             required_argument, 0,                'J'},
    {"user-tag",                required_argument, 0,                'Z'},
    {"userTag",                 required_argument, 0,                'Z'},
    {0, 0, 0, 0}
  };
  int c;
  ProcessParamsTable *this_proc_param = procparams.processParamsTable;


  /*
   *
   * parse command line arguments
   *
   */


  while ( 1 )
  {
    /* LALgetopt_long stores long option here */
    int option_index = 0;
    size_t LALoptarg_len;

    c = LALgetopt_long_only( argc, argv, "hs:a:b:i:A:B:K:J:Z:",
        long_options, &option_index );

    /* detect the end of the options */
    if ( c == - 1 )
    {
      break;
    }

    switch ( c )
    {
      case 0:
        /* if this option set a flag, do nothing else now */
        if ( long_options[option_index].flag != 0 )
        {
          break;
        }
        else
        {
          fprintf( stderr, "error parsing option %s with argument %s\n",
              long_options[option_index].name, LALoptarg );
          exit( 1 );
        }
        break;

      case 'h':
        fprintf( stdout, USAGE );
        exit( 0 );
        break;

      case 'Z':
        /* create storage for the usertag */
        LALoptarg_len = strlen( LALoptarg ) + 1;
        userTag = (CHAR *) calloc( LALoptarg_len, sizeof(CHAR) );
        memcpy( userTag, LALoptarg, LALoptarg_len );

        this_proc_param = this_proc_param->next = (ProcessParamsTable *)
          calloc( 1, sizeof(ProcessParamsTable) );
        snprintf( this_proc_param->program, LIGOMETA_PROGRAM_MAX, "%s",
            PROGRAM_NAME );
        snprintf( this_proc_param->param, LIGOMETA_PARAM_MAX, "-userTag" );
        snprintf( this_proc_param->type, LIGOMETA_TYPE_MAX, "string" );
        snprintf( this_proc_param->value, LIGOMETA_VALUE_MAX, "%s",
            LALoptarg );
        break;

      case 'A':
        minMass = (REAL4) atof( LALoptarg );
        if ( minMass <= 0 )
        {
          fprintf( stdout, "invalid argument to --%s:\n"
              "miniumum component mass must be > 0: "
              "(%f solar masses specified)\n",
              long_options[option_index].name, minMass );
          exit( 1 );
        }
        ADD_PROCESS_PARAM( "float", "%e", minMass );
        break;

      case 'B':
        maxMass = (REAL4) atof( LALoptarg );
        if ( maxMass <= 0 )
        {
          fprintf( stdout, "invalid argument to --%s:\n"
              "maxiumum component mass must be > 0: "
              "(%f solar masses specified)\n",
              long_options[option_index].name, maxMass );
          exit( 1 );
        }
        ADD_PROCESS_PARAM( "float", "%e", maxMass );
        break;

      case 'J':
        if ( ! strcmp( "urandom", LALoptarg ) )
        {
          randSeedType = urandom;
          ADD_PROCESS_PARAM( "string", "%s", LALoptarg );
        }
        else
        {
          randSeedType = user;
          randomSeed = (INT4) atoi( LALoptarg );
          ADD_PROCESS_PARAM( "int", "%d", randomSeed );
        }
        break;

      case 'K':
        numTmplts = (INT4) atoi( LALoptarg );
        if ( numTmplts < 1 )
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "number of template bank simulations"
              "must be greater than 1: (%d specified)\n",
              long_options[option_index].name, numTmplts );
          exit( 1 );
        }
        ADD_PROCESS_PARAM( "int", "%d", numTmplts );
        break;

      case 'a':
        {
          long int gstartt = atol( LALoptarg );
          if ( gstartt < 441417609 )
          {
            fprintf( stderr, "invalid argument to --%s:\n"
                "GPS start time is prior to "
                "Jan 01, 1994  00:00:00 UTC:\n"
                "(%ld specified)\n",
                long_options[option_index].name, gstartt );
            exit( 1 );
          }
          gpsStartTime.gpsSeconds = (INT4) gstartt;
          gpsStartTime.gpsNanoSeconds = 0;
          ADD_PROCESS_PARAM( "int", "%ld", gstartt );
        }
        break;

      case 'b':
        {
          long int gendt = atol( LALoptarg );
          if ( gendt < 441417609 )
          {
            fprintf( stderr, "invalid argument to --%s:\n"
                "GPS end time is prior to "
                "Jan 01, 1994  00:00:00 UTC:\n"
                "(%ld specified)\n",
                long_options[option_index].name, gendt );
            exit( 1 );
          }
          gpsEndTime.gpsSeconds = (INT4) gendt;
          gpsEndTime.gpsNanoSeconds = 0;
          ADD_PROCESS_PARAM( "int", "%ld", gendt );
        }
        break;

      case 'i':
        fLow = (REAL4) atof( LALoptarg );
        if ( fLow < 0 )
        {
          fprintf( stdout, "invalid argument to --%s:\n"
              "low frequency cutoff is less than 0 Hz: "
              "(%f Hz specified)\n",
              long_options[option_index].name, fLow );
          exit( 1 );
        }
        ADD_PROCESS_PARAM( "float", "%e", fLow );
        break;

      case '?':
        fprintf( stderr, USAGE );
        exit( 1 );
        break;

      default:
        fprintf( stderr, "unknown error while parsing options\n" );
        fprintf( stderr, USAGE );
        exit( 1 );
    }
  }

  if ( LALoptind < argc )
  {
    fprintf( stderr, "extraneous command line arguments:\n" );
    while ( LALoptind < argc )
    {
      fprintf ( stderr, "%s\n", argv[LALoptind++] );
    }
    exit( 1 );
  }

  /*
   *
   * check validity of arguments
   *
   */


  if ( minMass < 0 )
  {
    fprintf( stderr, "--minimum-mass must be specified\n" );
    exit( 1 );
  }
  if ( maxMass < 0 )
  {
    fprintf( stderr, "--maximum-mass must be specified\n" );
    exit( 1 );
  }

  /* check that the bank parameters have been specified */
  if ( numTmplts < 0 )
  {
    fprintf( stderr, "--number-of-templates must be specified\n" );
    exit( 1 );
  }

  return 0;
}
/* parse command line arguments using LALgetopt_long to get ring params */
int coh_PTF_parse_options(struct coh_PTF_params *params,int argc,char **argv )
{

  CHAR                         ifo[LIGOMETA_IFO_MAX];
  UINT4                        ifoNumber;
  static struct coh_PTF_params localparams;
  memset( &localparams.haveTrig, 0, LAL_NUM_IFO * sizeof(int) );
  struct LALoption                long_options[] =
  {
    { "verbose",            no_argument, &vrbflg, 1 },
    { "strain-data",        no_argument, &localparams.strainData, 1 },
    { "zero-data",          no_argument, &localparams.zeroData, 1 },
    { "theoretical-spectrum",     no_argument, &localparams.whiteSpectrum, 1 },
    { "write-raw-data",     no_argument, &localparams.writeRawData, 1 },
    { "write-data",         no_argument, &localparams.writeProcessedData, 1 },
    { "write-inv-spectrum", no_argument, &localparams.writeInvSpectrum, 1 },
    { "write-segment",      no_argument, &localparams.writeSegment, 1 },
    { "write-filter-output",no_argument, &localparams.writeFilterOutput, 1 },
    { "analyze-inj-segs-only",no_argument, &localparams.analyzeInjSegsOnly, 1 },
    { "do-null-stream",     no_argument, &localparams.doNullStream, 1 },
    { "do-trace-snr",       no_argument, &localparams.doTraceSNR, 1 },
    { "do-bank-veto",       no_argument, &localparams.doBankVeto, 1 },
    { "do-auto-veto",       no_argument, &localparams.doAutoVeto, 1 },
    { "do-chi-square",      no_argument, &localparams.doChiSquare, 1 },
    { "do-sngl-chi-tests",  no_argument, &localparams.doSnglChiSquared, 1},
    { "do-clustering",      no_argument, &localparams.clusterFlag, 1},
/*    {"g1-data",             no_argument, &(haveTrig[LAL_IFO_G1]), 1 },*/
    {"h1-data",             no_argument, &(localparams.haveTrig[LAL_IFO_H1]),1},
    {"h2-data",             no_argument, &(localparams.haveTrig[LAL_IFO_H2]),1},
    {"l1-data",             no_argument, &(localparams.haveTrig[LAL_IFO_L1]),1},
/*    {"t1-data",             no_argument, &(haveTrig[LAL_IFO_T1]), 1 },*/
    {"v1-data",             no_argument, &(localparams.haveTrig[LAL_IFO_V1]),1},
    {"face-on-analysis",    no_argument, &(localparams.faceOnAnalysis),1},
    {"face-away-analysis",    no_argument, &(localparams.faceAwayAnalysis),1},
    {"dynamic-template-length",no_argument, &(localparams.dynTempLength),1},
    {"store-amplitude-params",no_argument, &(localparams.storeAmpParams),1},
    {"analyse-segment-end", no_argument, &(localparams.analSegmentEnd),1},
    {"do-short-slides", no_argument, &(localparams.doShortSlides),1},
    { "write-sngl-inspiral-table", no_argument, &(localparams.writeSnglInspiralTable),1},
    { "help",               no_argument, 0, 'h' },
    { "version",            no_argument, 0, 'V' },
    { "simulated-data",          required_argument, 0, '6' },
    { "gps-start-time",          required_argument, 0, 'a' },
    { "gps-start-time-ns",       required_argument, 0, 'A' },
    { "gps-end-time",            required_argument, 0, 'b' },
    { "gps-end-time-ns",         required_argument, 0, 'B' },
    { "trigger-time",            required_argument, 0, '<' },
    { "trigger-time-ns",         required_argument, 0, '>' },
    { "h1-channel-name",         required_argument, 0, 'c' },
    { "h1-frame-cache",          required_argument, 0, 'D' },
    { "h2-channel-name",         required_argument, 0, 'x' },
    { "h2-frame-cache",          required_argument, 0, 'X' },
    { "l1-channel-name",         required_argument, 0, 'y' },
    { "l1-frame-cache",          required_argument, 0, 'Y' },
    { "v1-channel-name",         required_argument, 0, 'z' },
    { "v1-frame-cache",          required_argument, 0, 'Z' },
    { "low-template-freq",       required_argument, 0, 'e' },
    { "low-filter-freq",         required_argument, 0, 'H' },
    { "high-filter-freq",        required_argument, 0, 'I' },
    { "highpass-frequency",      required_argument, 0, 'E' },
    { "injection-file",          required_argument, 0, 'i' },
    { "snr-threshold",           required_argument, 0, 'j' },
    { "spin-snr-threshold",      required_argument, 0, '2' },
    { "sngl-snr-threshold",      required_argument, 0, '1' },
    { "trig-time-window",        required_argument, 0, 'J' },
    { "user-tag",                required_argument, 0, 'k' },
    { "ifo-tag",                 required_argument, 0, 'K' },
    { "non-spin-snr2-threshold", required_argument, 0, 'l' },
    { "spin-snr2-threshold",     required_argument, 0, 'L' },
    { "spin-bank",               required_argument, 0, 'm' },
    { "non-spin-bank",           required_argument, 0, 'M' },
    { "only-segment-numbers",    required_argument, 0, 'n' },
    { "only-template-numbers",   required_argument, 0, 'N' },
    { "output-file",             required_argument, 0, 'o' },
    { "bank-file",               required_argument, 0, 'O' },
    { "num-auto-chisq-points",   required_argument, 0, 'p' },
    { "auto-veto-time-step",     required_argument, 0, 'P' },
    { "num-chi-square-bins",     required_argument, 0, 'q' },
    { "chi-square-threshold",    required_argument, 0, 'Q' },
    { "random-seed",             required_argument, 0, 'r' },
    { "dynamic-range-factor",    required_argument, 0, 'R' },
    { "sample-rate",             required_argument, 0, 's' },
    { "segment-duration",        required_argument, 0, 'S' },
    { "psd-segment-duration",        required_argument, 0, '9' },
    { "bank-veto-templates",     required_argument, 0, 't' },
    { "inverse-spec-length",     required_argument, 0, 'T' },
    { "trig-start-time",         required_argument, 0, 'u' },
    { "trig-end-time",           required_argument, 0, 'U' },
    { "block-duration",          required_argument, 0, 'w' },
    { "pad-data",                required_argument, 0, 'W' },
    { "right-ascension",         required_argument, 0, 'f' },
    { "declination",             required_argument, 0, 'F' },
    { "sky-error",               required_argument, 0, 'g' },
    { "timing-accuracy",         required_argument, 0, 'G' },
    { "approximant",             required_argument, 0, 'C' },
    { "order",                   required_argument, 0, 'v' },
    { "h1-slide-segment",        required_argument, 0, '!' }, 
    { "h2-slide-segment",        required_argument, 0, '&' },
    { "l1-slide-segment",        required_argument, 0, '(' },
    { "v1-slide-segment",        required_argument, 0, ')' },
    { "sky-positions-file",      required_argument, 0, '#' },
    { "fft-level",               required_argument, 0, '|' },
    { "cluster-window",          required_argument, 0, '4' },
    { "inj-search-window",       required_argument, 0, '3' },
    { "inj-mchirp-window",       required_argument, 0, '5' },
    { "ligo-calibrated-data",    required_argument, 0, '7' }, 
    { "virgo-calibrated-data",   required_argument, 0, '8' }, 
    { "short-slide-offset",      required_argument, 0, '@' },
    { 0, 0, 0, 0 }
  };
  char args[] = "a:A:b:B:c:C:D:e:E:f:F:g:G:h:H:i:I:j:J:k:K:l:L:m:M:n:N:o:O:p:P:q:Q:r:R:s:S:t:T:u:U:v:V:w:W:x:X:y:Y:z:Z:1:2:3:4:5:6:7:8:9:<:>:!:&:(:):#:|:@";
  char *program = argv[0];

  /* set default values for parameters before parsing arguments */
  coh_PTF_default_params( &localparams );

  while ( 1 )
  {
    int option_index = 0;
    int c;

    c = LALgetopt_long_only( 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
          error( "error parsing option %s with argument %s\n",
              long_options[option_index].name, LALoptarg );
      case 'a': /* gps-start-time */
        localparams.startTime.gpsSeconds = atol( LALoptarg );
        break;
      case 'A': /* gps-start-time-ns */
        localparams.startTime.gpsNanoSeconds = atol( LALoptarg );
        break;
      case 'b': /* gps-end-time */
        localparams.endTime.gpsSeconds = atol( LALoptarg );
        break;
      case 'B': /* gps-end-time-ns */
        localparams.endTime.gpsNanoSeconds = atol( LALoptarg );
        break;
      case '<': /* trigger-time */
        localparams.trigTime.gpsSeconds = atol( LALoptarg );
        break;
      case '>': /* trigger-time-ns */ 
        localparams.trigTime.gpsNanoSeconds = atol( LALoptarg );
        break;
      case 'c': /* h1 channel-name */
        localparams.channel[LAL_IFO_H1] = LALoptarg;
        break;
      case 'D': /* h1 frame-cache */
        localparams.dataCache[LAL_IFO_H1] = LALoptarg;
        break;
      case 'y': /* l1 channel-name */
        localparams.channel[LAL_IFO_L1] = LALoptarg;
        break;
      case 'Y': /* l1 frame-cache */
        localparams.dataCache[LAL_IFO_L1] = LALoptarg;
        break;
      case 'z': /* v1 channel-name */
        localparams.channel[LAL_IFO_V1] = LALoptarg;
        break;
      case 'Z': /* v1 frame-cache */
        localparams.dataCache[LAL_IFO_V1] = LALoptarg;
        break;
      case 'x': /* h2 channel-name */
        localparams.channel[LAL_IFO_H2] = LALoptarg;
        break;
      case 'X': /* h2 frame-cache */
        localparams.dataCache[LAL_IFO_H2] = LALoptarg;
        break;
      case 'e': /* start frequency of template generation */
        localparams.lowTemplateFrequency = atof( LALoptarg );
        break;
      case 'H': /* start frequency of matched filter */
        localparams.lowFilterFrequency = atof( LALoptarg );
        break;
      case 'I': /* End frequency of matched filter */
        localparams.highFilterFrequency = atof( LALoptarg );
        break;
      case 'E': /* highpass-frequency */
        localparams.highpassFrequency = atof( LALoptarg );
        break;
      case 'C': /* waveform approximant */
        /* This will directly fail if the approximant is not a valid one.
           However the user may get to a call to FindChirpTDTemplate and find
           out only then that the approximant is not supported in there. */
        localparams.approximant =  XLALSimInspiralGetApproximantFromString(LALoptarg);
        break;
      case '6': /* Simulated data option */
        localparams.simData = 1;
        if ( ! strcmp( "WhiteNoise",LALoptarg))
        {
          localparams.simDataType = WHITE_PSD;
        }
        else if ( ! strcmp( "ILIGONoise",LALoptarg))
        {
          localparams.simDataType = ILIGO_PSD;
        }
        else if ( ! strcmp( "ALIGONoise",LALoptarg))
        {
          localparams.simDataType = ALIGO_PSD;
        }
        else
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "unknown data type specified:"
              "%s valid options are WhiteNoise, ILIGONoise or ALIGONoise",
              long_options[option_index].name, LALoptarg );
          exit(1);
        }
        break;
      case 'v': /* PN order of waveform */        
        if ( ! strcmp( "twoPN", LALoptarg ) )
        {
          localparams.order = LAL_PNORDER_TWO;
        }
        else if ( ! strcmp( "twoPointFivePN", LALoptarg ) )
        {
          localparams.order = LAL_PNORDER_TWO_POINT_FIVE;
        }
        else if ( ! strcmp( "threePN", LALoptarg ) )
        {
          localparams.order = LAL_PNORDER_THREE;
        }
        else if ( ! strcmp( "threePointFivePN", LALoptarg ) )
        {
          localparams.order = LAL_PNORDER_THREE_POINT_FIVE;
        }
        else if ( ! strcmp( "pseudoFourPN", LALoptarg ) )
        {
          localparams.order = LAL_PNORDER_PSEUDO_FOUR;
        }
        else
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "unknown order specified: "
              "%s (must be one of twoPN, twoPointFivePN, threePN, threePointFivePN, pseudoFourPN)\n",
              long_options[option_index].name, LALoptarg );
          exit( 1 );
        }
        break;
      case 'f': /* right-ascension */
        localparams.rightAscension = atof( LALoptarg ) * LAL_PI_180;
        break;
      case 'F': /* Declination */
        localparams.declination = atof( LALoptarg ) * LAL_PI_180;
        break;
      case 'g': /* Error in declination */
        localparams.skyError = atof( LALoptarg ) * LAL_PI_180;
        break;
      case 'G': /* timing accuracy of network */
        localparams.timingAccuracy = atof( LALoptarg );
        break;
      case 'h': /* help */
        coh_PTF_usage( program );
        exit( 0 );
      case 'i': /* injection-file */
        localparams.injectFile = LALoptarg;
        break;
      case 'j':
        localparams.threshold = atof(LALoptarg);
        break;
      case '2':
        localparams.spinThreshold = atof(LALoptarg);
        break;
      case '1':
        localparams.snglSNRThreshold = atof(LALoptarg);
        break;
      case 'J':
        localparams.timeWindow = atof(LALoptarg);
        break;
      case 'k': /* user-tag */
        strncpy( localparams.userTag, LALoptarg, sizeof( localparams.userTag ) - 1 );
        break;
      case 'K': /* ifo-tag */
        strncpy( localparams.ifoTag, LALoptarg, sizeof( localparams.ifoTag ) - 1 );
        break;
      case 'l':
        localparams.nonspinSNR2threshold = atof(LALoptarg);
        break;
      case 'L':
        localparams.spinSNR2threshold = atof(LALoptarg);
        break;
      case 'm': /* spin bank */
        localparams.spinBank = 1;
        strncpy( localparams.spinBankName, LALoptarg, sizeof( localparams.spinBankName ) - 1 );
        break;
      case 'M': /* non spin bank */
        localparams.noSpinBank = 1;
        strncpy( localparams.noSpinBankName, LALoptarg, sizeof( localparams.noSpinBankName ) - 1 );
        break;
      case 'n': /* only-segment-numbers */
        localparams.segmentsToDoList = LALoptarg;
        break;
      case 'N': /* only-template-number */
        localparams.templatesToDoList = LALoptarg;
        break;
      case 'o': /* output-file */
        strncpy( localparams.outputFile, LALoptarg, sizeof( localparams.outputFile ) - 1 );
        break;
      case 'O': /* bank-file */
        localparams.bankFile = LALoptarg;
        break;
      case 'p': /* num auto chisq points */
        localparams.numAutoPoints = atoi( LALoptarg );
        break;
      case 'P': /* Auto veto time step */
        localparams.autoVetoTimeStep = atof( LALoptarg );
        break;
      case 'q': /* num chi square bins */
        localparams.numChiSquareBins = atoi( LALoptarg );
        break;
      case 'Q': 
        localparams.chiSquareCalcThreshold = atof( LALoptarg );
        break;
      case 'r': /* random seed */
        localparams.randomSeed = atoi( LALoptarg );
        break;
      case 'R': /* dynamic range factor */
        localparams.dynRangeFac = atof( LALoptarg );
        break;
      case 's': /* sample rate */
        localparams.sampleRate = atof( LALoptarg );
        break;
      case 'S': /* segment-duration */
        localparams.segmentDuration = atof( LALoptarg );
        break;
      case '9': /* PSD segment-duration */
        localparams.psdSegmentDuration = atof( LALoptarg );
        break;
      case 't': /* bank veto template bank */
        localparams.bankVetoBankName = LALoptarg;
        break;
      case 'T': /* inverse-spec-length */
        localparams.truncateDuration = atof( LALoptarg );
        break;
      case 'u': /* trig-start-time */
        localparams.trigStartTimeNS = (INT8) atol( LALoptarg ) * LAL_INT8_C(1000000000);
        break;
      case 'U': /* trig-end-time */
        localparams.trigEndTimeNS = (INT8) atol( LALoptarg ) * LAL_INT8_C(1000000000);
        break;
      case 'w': /* block-duration */
        localparams.duration = atof( LALoptarg );
        break;
      case 'W': /* pad-data */
        localparams.padData = atof( LALoptarg );
        break;
      case '!': /* h1-slide-segment */
        localparams.slideSegments[LAL_IFO_H1] = atoi( LALoptarg );
        break;
      case '&': /* h2-slide-segments */
        localparams.slideSegments[LAL_IFO_H2] = atoi( LALoptarg );
        break;
      case '(': /* l1-slide-segments */
        localparams.slideSegments[LAL_IFO_L1] = atoi( LALoptarg );
        break;
      case ')': /* v1-slide-segments */
        localparams.slideSegments[LAL_IFO_V1] = atoi( LALoptarg );
        break;
      case '@': /* Short slide offset time */
        localparams.shortSlideOffset = atoi( LALoptarg );
        break;
      case 'V': /* version */
        XLALOutputVersionString(stderr, 0);
        exit( 0 );
     case '#': /* sky grid file */
        localparams.skyPositionsFile = LALoptarg;
        break;
     case '|': /* FFT-level for plans */
        localparams.fftLevel = atoi( LALoptarg );
        break;
      case '4': /* Cluster window */
        localparams.clusterWindow = atof(LALoptarg);
        break;
      case '3': /* Injection search window */
        localparams.injSearchWindow = atof( LALoptarg );
        break;
      case '5': /* Injection search window */
        localparams.injMchirpWindow = atof( LALoptarg );
        break;
      case '7':
        if (!strcmp("real_4", LALoptarg))
        {
          localparams.ligoDoubleData = 0;
        }
        else if (!strcmp("real_8", LALoptarg))
        {
          localparams.ligoDoubleData = 1;
        }
        else
        {
          fprintf(stderr, "invalid argument to --%s:\n"
                  "unknown data type specified;\n"
                  "%s (must be one of: real_4, real_8)\n",
                  long_options[option_index].name, LALoptarg);
        }
        break;
      case '8':
        if (!strcmp("real_4", LALoptarg))
        {
          localparams.virgoDoubleData = 0;
        }
        else if (!strcmp("real_8", LALoptarg))
        {
          localparams.virgoDoubleData = 1;
        }
        else
        {
          fprintf(stderr, "invalid argument to --%s:\n"
                  "unknown data type specified;\n"
                  "%s (must be one of: real_4, real_8)\n",
                  long_options[option_index].name, LALoptarg);
        }
        break;
      case '?':
        error( "unknown error while parsing options\n" );
      default:
        error( "unknown error while parsing options\n" );
    }
  }

  if ( LALoptind < argc )
  {
    fprintf( stderr, "extraneous command line arguments:\n" );
    while ( LALoptind < argc )
      fprintf( stderr, "%s\n", argv[LALoptind++] );
    exit( 1 );
  }

  /* set number of ifos */
  localparams.numIFO = 0;

  for ( ifoNumber = 0; ifoNumber < LAL_NUM_IFO; ifoNumber++ )
  {
    if ( localparams.haveTrig[ifoNumber] )
    {
      XLALReturnIFO(ifo,ifoNumber);
      snprintf( localparams.ifoName[localparams.numIFO], LIGOMETA_IFO_MAX,\
                "%s", ifo );
      localparams.numIFO++;
    }
  }
  
  /* check for H1H2 */
  if (localparams.numIFO == 2)
  {
    if (! strcmp(localparams.ifoName[0],"H1"))
    {
      if (! strcmp(localparams.ifoName[1],"H2"))
      {
        localparams.singlePolFlag = 1;
      }
    }
  }
  /* Set the faceOn-faceAway flag */
  /* Otherwise it takes default value of 0 */
  if (localparams.faceOnAnalysis)
  {
    localparams.faceOnStatistic = 1;
  }
  else if (localparams.faceAwayAnalysis)
  {
    localparams.faceOnStatistic = 2;
  }

  /* Set the number of points in the time arrays */
  localparams.numTimePoints = floor(\
          localparams.segmentDuration * localparams.sampleRate + 0.5);
  /* Set the number of points in the frequency arrays */
  localparams.numFreqPoints = localparams.numTimePoints / 2 + 1;

  /* For now we stick to only analysing half of each segment */
  localparams.strideDuration = 0.5 * localparams.segmentDuration;

  /* FIXME: Hardcoded to 1s */
  localparams.numBufferPoints = floor(localparams.sampleRate + 0.5);

  /* Choose the start and end point of each segment for analysis */
  if (localparams.analSegmentEnd)
  { /* Want to analyse from the end of the segment */
    /* Start from the end */
    localparams.analEndPoint = localparams.numTimePoints;
    /* Remove the spectrum truncation */
    localparams.analEndPoint -= floor(\
        0.5 * localparams.truncateDuration * localparams.sampleRate + 0.5); 
    /* Remove the buffer points */
    localparams.analEndPoint -= localparams.numBufferPoints;
    /* And set the start point */
    localparams.analStartPoint = localparams.analEndPoint - \
        0.5*localparams.numTimePoints;
  }
  else
  { /* DEFAULT: Analyse the middle of the segment */
    localparams.analStartPoint = 1*localparams.numTimePoints/4;
    localparams.analEndPoint = (3*localparams.numTimePoints)/4;
  }

  localparams.analStartTime = localparams.analStartPoint / \
                                localparams.sampleRate;
  localparams.analStartPointBuf = localparams.analStartPoint\
                                  - localparams.numBufferPoints;
  localparams.analEndTime = localparams.analEndPoint / \
                                localparams.sampleRate;
  localparams.analEndPointBuf = localparams.analEndPoint\
                               + localparams.numBufferPoints;
  localparams.numAnalPoints = localparams.analEndPoint\
                             - localparams.analStartPoint;
  localparams.numAnalPointsBuf = localparams.analEndPointBuf\
                                - localparams.analStartPointBuf;
  /* Max template length is start length minus PSD truncation */
  localparams.maxTempLength = localparams.analStartTime;
  localparams.maxTempLength -= localparams.truncateDuration/2.;

  /* Determine the number of short slides */
  if (localparams.doShortSlides)
  {
    localparams.numShortSlides = 1 + localparams.numIFO * (int) floor( \
        localparams.strideDuration / \
        (localparams.shortSlideOffset * (localparams.numIFO-1)) );
  }
  else
  {
    localparams.numShortSlides = 1;
  }

  /* Set the template correction factor */
  if ( localparams.approximant == FindChirpSP)
  {
    /* Most of this gets stored in fcTmplt->fcTmpltNorm which is computed on
     * the fly. This is the correction needed to that. */
    /* First need to add ( (df)**-7./6. )**2 */
    localparams.tempCorrFac = pow(localparams.segmentDuration,14./6.); 
    /* For some reason FindChirp multiplies by a dt factor, take this out */
    localparams.tempCorrFac *= pow(localparams.sampleRate,2./6.);
  }
  else
  {
    /* Sigmasq factors are not yet available for all approximants */
    /* Set values to 1 (so this factor has no effect) and warn user */
    verbose("warning: Sigmasq correction factor is not yet available for this approximant: setting it to 1.\n");
    localparams.tempCorrFac = 1.0;
  }

  *params = localparams;

  return 0;
}
Exemple #21
0
static struct params parseargs(int argc, char **argv)
{
	struct params p = {
		.waveform = -1,				/* invalid */
		.duration = INVALID_DOUBLE,		/* invalid */
		.frequency = INVALID_DOUBLE,	 	/* invalid */
		.bandwidth = INVALID_DOUBLE,		/* invalid */
		.q = INVALID_DOUBLE,			/* invalid */
		.phase = DEFAULT_PHASE,
		.eccentricity = DEFAULT_ECCENTRICITY,
		.amplitude = INVALID_DOUBLE,		/* invalid */
		.hrss = INVALID_DOUBLE,			/* invalid */
		.fluence = INVALID_DOUBLE,		/* invalid */
		.srate = DEFAULT_SRATE
	};
	struct LALoption long_options[] = {
		{"help", no_argument, 0, 'h'},
		{"verbose", no_argument, 0, 'v'},
		{"waveform", required_argument, 0, 'w'},
		{"duration", required_argument, 0, 't'},
		{"frequency", required_argument, 0, 'f'},
		{"bandwidth", required_argument, 0, 'b'},
		{"quality-factor", required_argument, 0, 'q'},
		{"eccentricity", required_argument, 0, 'e'},
		{"phase", required_argument, 0, 'p'},
		{"amplitude", required_argument, 0, 'A'},
		{"hrss", required_argument, 0, 'H'},
		{"fluence", required_argument, 0, 'F'},
		{"sample-rate", required_argument, 0, 'R'},
		{0, 0, 0, 0}
	};
	char args[] = "hvw:t:f:b:q:e:A:H:F:d:R:";

	while (1) {
		int option_index = 0;
		int c;

		c = LALgetopt_long_only(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);
				exit(1);
			}
		case 'h':	/* help */
			usage(argv[0]);
			exit(0);
		case 'v':	/* verbose */
			verbose = 1;
			break;
		case 'w':	/* waveform */
			p.waveform = waveform_value(LALoptarg);
			break;
		case 't':	/* duration */
			p.duration = my_atof(LALoptarg);
			break;
		case 'f':	/* frequency */
			p.frequency = my_atof(LALoptarg);
			break;
		case 'b':	/* bandwidth */
			p.bandwidth = my_atof(LALoptarg);
			break;
		case 'q':	/* quality-factor */
			p.q = my_atof(LALoptarg);
			break;
		case 'e':	/* eccentricity */
			p.eccentricity = my_atof(LALoptarg);
			break;
		case 'p':	/* phase */
			/* convert phase from degrees to radians */
			p.phase = my_atof(LALoptarg) * LAL_PI_180;
			break;
		case 'A':	/* amplitude */
			p.amplitude = my_atof(LALoptarg);
			break;
		case 'H':	/* hrss */
			p.hrss = my_atof(LALoptarg);
			break;
		case 'F':	/* fluence */
			/* convert fluence to sum-squared hdot */
			p.fluence = my_atof(LALoptarg);
			break;
		case 'R':	/* sample-rate */
			p.srate = my_atof(LALoptarg);
			break;
		case '?':
		default:
			fprintf(stderr, "unknown error while parsing options\n");
			exit(1);
		}
	}
	if (LALoptind < argc) {
		fprintf(stderr, "extraneous command line arguments:\n");
		while (LALoptind < argc)
			fprintf(stderr, "%s\n", argv[LALoptind++]);
		exit(1);
	}
	return p;
}
Exemple #22
0
int parseargs(int argc, char **argv)
{
    struct LALoption long_options[] = {
        {"help", no_argument, 0, 'h'},
        {"channel", required_argument, 0, 'c'},
        {"frame-cache", required_argument, 0, 'f'},
        {"frame-glob", required_argument, 0, 'g'},
        {"output", required_argument, 0, 'o'},
        {"start-time", required_argument, 0, 's'},
        {"duration", required_argument, 0, 't'},
        {"highpass", required_argument, 0, 'H'},
        {"lowpass", required_argument, 0, 'L'},
        {"pad", required_argument, 0, 'P'},
        {"resample", required_argument, 0, 'R'},
        {"spectrum", required_argument, 0, 'S'},
        {0, 0, 0, 0}
    };
    char args[] = "hc:f:g:o:s:t:H:L:P:R:S:";
    while (1) {
        int option_index = 0;
        int c;

        c = LALgetopt_long_only(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);
                exit(1);
            }
        case 'h':      /* help */
            usage(argv[0]);
            exit(0);
        case 'c':      /* channel */
            channel = strdup(LALoptarg);
            break;
        case 'f':      /* frame-cache */
            cache = XLALCacheImport(LALoptarg);
            break;
        case 'g':      /* frame-glob */
            cache = XLALCacheGlob(NULL, LALoptarg);
            break;
        case 'o':      /* output */
            outfile = strdup(LALoptarg);
            break;
        case 's':      /* start-time */
            t0 = atof(LALoptarg);
            break;
        case 't':      /* duration */
            dt = atof(LALoptarg);
            break;
        case 'H':      /* highpass */
            minfreq = atof(LALoptarg);
            break;
        case 'L':      /* lowpass */
            maxfreq = atof(LALoptarg);
            break;
        case 'P':      /* pad */
            pad = atof(LALoptarg);
            break;
        case 'R':      /* start-time */
            srate = atof(LALoptarg);
            break;
        case 'S':      /* spectrum */
            df = atof(LALoptarg);
            break;
        case '?':
        default:
            fprintf(stderr, "unknown error while parsing options\n");
            exit(1);
        }
    }

    if (LALoptind < argc) {
        fprintf(stderr, "extraneous command line arguments:\n");
        while (LALoptind < argc)
            fprintf(stderr, "%s\n", argv[LALoptind++]);
        exit(1);
    }

    /* sanity check parameters */

    if (!channel) {
        fprintf(stderr, "must specify a channel\n");
        usage(argv[0]);
        exit(1);
    }
    if (!cache) {
        fprintf(stderr, "must specify a frame cache or frame files\n");
        usage(argv[0]);
        exit(1);
    }

    return 0;
}
Exemple #23
0
int main( int argc, char *argv[] )
{
  /* lal initialization variables */
  LALStatus status = blank_status;

  /*  program option variables */
  CHAR *userTag = NULL;
  CHAR comment[LIGOMETA_COMMENT_MAX];
  char *ifos = NULL;
  char *ifoName = NULL;
  char *outputFileName = NULL;
  char *summFileName = NULL;
  char *injectFileName = NULL;
  char *vetoFileName = NULL;
  char *missedFileName = NULL;
  REAL4 snrStar = -1;
  REAL4 rsqVetoThresh = -1;
  REAL4 rsqMaxSnr     = -1;
  REAL4 rsqAboveSnrCoeff = -1;
  REAL4 rsqAboveSnrPow     = -1;
  LALSegList vetoSegs;
  MultiInspiralClusterChoice clusterchoice = no_statistic;
  INT8 cluster_dt = -1;
  INT8 injectWindowNS = -1;
  int j;
  FILE *fp = NULL;
  int numInFiles = 0;

  UINT8 triggerInputTimeNS = 0;

  MetadataTable         proctable;
  MetadataTable         procparams;
  ProcessParamsTable   *this_proc_param;

  SimInspiralTable     *simEventHead = NULL;
  SimInspiralTable     *thisSimEvent = NULL;
  SimInspiralTable     *missedSimHead = NULL;
  SimInspiralTable     *tmpSimEvent = NULL;

  SearchSummvarsTable  *inputFiles = NULL;

  SearchSummaryTable   *searchSummList = NULL;
  SearchSummaryTable   *thisSearchSumm = NULL;
  SummValueTable       *summValueList = NULL;

  int                   extractSlide = 0;
  int                   numSlides = 0;
  int                   numEvents = 0;
  int                   numEventsKept = 0;
  int                   numEventsInIFO = 0;
  int                   numEventsAboveSNRThresh = 0;
  int                   numEventsBelowRsqThresh = 0;
  int                   numEventsSurvivingVeto = 0;
  int                   numClusteredEvents = 0;
  int                   numEventsInIfos = 0;

  int                   numSimEvents = 0;
  int                   numSimInData = 0;
  int                   numSimFound  = 0;
  int                   numMultiFound  = 0;

  MultiInspiralTable   *missedHead = NULL;
  MultiInspiralTable   *thisEvent = NULL;
  MultiInspiralTable   *thisInspiralTrigger = NULL;
  MultiInspiralTable   *inspiralEventList = NULL;
  MultiInspiralTable   *slideEvent = NULL;

  LIGOLwXMLStream       xmlStream;
  MetadataTable         outputTable;
  MetadataTable         UNUSED savedEvents;
  MetadataTable         searchSummvarsTable;

  /*
   *
   * initialization
   *
   */


  /* set up inital debugging values */
  lal_errhandler = LAL_ERR_EXIT;

  /* create the process and process params tables */
  proctable.processTable = (ProcessTable *)
    calloc( 1, sizeof(ProcessTable) );
  XLALGPSTimeNow(&(proctable.processTable->start_time));
  XLALPopulateProcessTable(proctable.processTable, PROGRAM_NAME, lalAppsVCSIdentId,
      lalAppsVCSIdentStatus, lalAppsVCSIdentDate, 0);
  this_proc_param = procparams.processParamsTable = (ProcessParamsTable *)
    calloc( 1, sizeof(ProcessParamsTable) );
  memset( comment, 0, LIGOMETA_COMMENT_MAX * sizeof(CHAR) );

  savedEvents.multiInspiralTable = NULL;


  /*
   *
   * parse command line arguments
   *
   */


  while (1)
  {
    /* LALgetopt arguments */
    static struct LALoption long_options[] =
    {
      {"verbose",             no_argument,           &vrbflg,              1 },
      {"sort-triggers",       no_argument,     &sortTriggers,              1 },
      {"help",                    no_argument,            0,              'h'},
      {"user-tag",                required_argument,      0,              'Z'},
      {"userTag",                 required_argument,      0,              'Z'},
      {"comment",                 required_argument,      0,              'c'},
      {"version",                 no_argument,            0,              'V'},
      {"data-type",               required_argument,      0,              'k'},
      {"output",                  required_argument,      0,              'o'},
      {"summary-file",            required_argument,      0,              'S'},
      {"extract-slide",           required_argument,      0,              'e'},
      {"num-slides",              required_argument,      0,              'N'},
      {"snr-threshold",           required_argument,      0,              's'},
      {"rsq-threshold",           required_argument,      0,              'r'},
      {"rsq-max-snr",             required_argument,      0,              'R'},
      {"rsq-coeff",               required_argument,      0,              'p'},
      {"rsq-power",               required_argument,      0,              'P'},
      {"cluster-algorithm",       required_argument,      0,              'C'},
      {"cluster-time",            required_argument,      0,              't'},
      {"ifo-cut",                 required_argument,      0,              'd'},
      {"coinc-cut",               required_argument,      0,              'D'},
      {"veto-file",               required_argument,      0,              'v'},
      {"injection-file",          required_argument,      0,              'I'},
      {"injection-window",        required_argument,      0,              'T'},
      {"missed-injections",       required_argument,      0,              'm'},
      {0, 0, 0, 0}
    };
    int c;

    /* LALgetopt_long stores the option index here. */
    int option_index = 0;
    size_t LALoptarg_len;

    c = LALgetopt_long_only ( argc, argv,
        "c:d:D:hj:k:m:o:r:s:t:v:C:DH:I:R:ST:VZ:",
        long_options, &option_index );

    /* detect the end of the options */
    if ( c == - 1 )
      break;

    switch ( c )
    {
      case 0:
        /* if this option set a flag, do nothing else now */
        if ( long_options[option_index].flag != 0 )
        {
          break;
        }
        else
        {
          fprintf( stderr, "error parsing option %s with argument %s\n",
              long_options[option_index].name, LALoptarg );
          exit( 1 );
        }
        break;

      case 'h':
        print_usage(argv[0]);
        exit( 0 );
        break;

      case 'Z':
        /* create storage for the usertag */
        LALoptarg_len = strlen( LALoptarg ) + 1;
        userTag = (CHAR *) calloc( LALoptarg_len, sizeof(CHAR) );
        memcpy( userTag, LALoptarg, LALoptarg_len );

        this_proc_param = this_proc_param->next = (ProcessParamsTable *)
          calloc( 1, sizeof(ProcessParamsTable) );
        snprintf( this_proc_param->program, LIGOMETA_PROGRAM_MAX, "%s",
            PROGRAM_NAME );
        snprintf( this_proc_param->param, LIGOMETA_PARAM_MAX, "-userTag" );
        snprintf( this_proc_param->type, LIGOMETA_TYPE_MAX, "string" );
        snprintf( this_proc_param->value, LIGOMETA_VALUE_MAX, "%s",
            LALoptarg );
        break;

      case 'c':
        if ( strlen( LALoptarg ) > LIGOMETA_COMMENT_MAX - 1 )
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "comment must be less than %d characters\n",
              long_options[option_index].name, LIGOMETA_COMMENT_MAX );
          exit( 1 );
        }
        else
        {
          snprintf( comment, LIGOMETA_COMMENT_MAX, "%s", LALoptarg);
        }
        break;

      case 'V':
        fprintf( stdout, "Coherent Inspiral Reader and Injection Analysis\n"
            "Sukanta Bose\n");
        XLALOutputVersionString(stderr, 0);
        exit( 0 );
        break;

      case 'o':
        /* create storage for the output file name */
        LALoptarg_len = strlen( LALoptarg ) + 1;
        outputFileName = (CHAR *) calloc( LALoptarg_len, sizeof(CHAR));
        memcpy( outputFileName, LALoptarg, LALoptarg_len );
        ADD_PROCESS_PARAM( "string", "%s", LALoptarg );
        break;

      case 'e':
        /* store the number of slides */
        extractSlide = atoi( LALoptarg );
        if ( extractSlide == 0 )
        {
          fprintf( stdout, "invalid argument to --%s:\n"
              "extractSlide must be non-zero: "
              "(%d specified)\n",
              long_options[option_index].name, extractSlide );
          exit( 1 );
        }
        ADD_PROCESS_PARAM( "int", "%d", extractSlide );
        break;

      case 'N':
        /* store the number of slides */
        numSlides = atoi( LALoptarg );
        if ( numSlides < 0 )
        {
          fprintf( stdout, "invalid argument to --%s:\n"
              "numSlides >= 0: "
              "(%d specified)\n",
              long_options[option_index].name, numSlides );
          exit( 1 );
        }
        ADD_PROCESS_PARAM( "int", "%d", numSlides );
        break;

      case 'S':
        /* create storage for the summ file name */
        LALoptarg_len = strlen( LALoptarg ) + 1;
        summFileName = (CHAR *) calloc( LALoptarg_len, sizeof(CHAR));
        memcpy( summFileName, LALoptarg, LALoptarg_len );
        ADD_PROCESS_PARAM( "string", "%s", LALoptarg );
        break;

      case 'k':
        /* type of data to analyze */
        if ( ! strcmp( "playground_only", LALoptarg ) )
        {
          dataType = playground_only;
        }
        else if ( ! strcmp( "exclude_play", LALoptarg ) )
        {
          dataType = exclude_play;
        }
        else if ( ! strcmp( "all_data", LALoptarg ) )
        {
          dataType = all_data;
        }
        else
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "unknown data type, %s, specified: "
              "(must be playground_only, exclude_play or all_data)\n",
              long_options[option_index].name, LALoptarg );
          exit( 1 );
        }
        ADD_PROCESS_PARAM( "string", "%s", LALoptarg );
        break;

      case 's':
        snrStar = (REAL4) atof( LALoptarg );
        if ( snrStar < 0 )
        {
          fprintf( stdout, "invalid argument to --%s:\n"
              "threshold must be >= 0: "
              "(%f specified)\n",
              long_options[option_index].name, snrStar );
          exit( 1 );
        }
        ADD_PROCESS_PARAM( "float", "%e", snrStar );
        break;

      case 'r':
        rsqVetoThresh = (REAL4) atof( LALoptarg );
        if ( rsqVetoThresh < 0 )
        {
          fprintf( stdout, "invalid argument to --%s:\n"
              "threshold must be >= 0: "
              "(%f specified)\n",
              long_options[option_index].name, rsqVetoThresh );
          exit( 1 );
        }
        ADD_PROCESS_PARAM( "float", "%e", rsqVetoThresh );
        break;

      case 'R':
        rsqMaxSnr = (REAL4) atof( LALoptarg );
        if ( rsqMaxSnr < 0 )
        {
          fprintf( stdout, "invalid argument to --%s:\n"
              "threshold must be >= 0: "
              "(%f specified)\n",
              long_options[option_index].name, rsqMaxSnr );
          exit( 1 );
        }
        ADD_PROCESS_PARAM( "float", "%e", rsqMaxSnr );
        break;

      case 'p':
        rsqAboveSnrCoeff = (REAL4) atof( LALoptarg );
        if ( rsqAboveSnrCoeff < 0 )
        {
          fprintf( stdout, "invalid argument to --%s:\n"
              "coefficient must be >= 0: "
              "(%f specified)\n",
              long_options[option_index].name, rsqAboveSnrCoeff );
          exit( 1 );
        }
        ADD_PROCESS_PARAM( "float", "%e", rsqAboveSnrCoeff );
        break;

      case 'P':
        rsqAboveSnrPow = (REAL4) atof( LALoptarg );
        if ( rsqAboveSnrPow < 0 )
        {
          fprintf( stdout, "invalid argument to --%s:\n"
              "power must be >= 0: "
              "(%f specified)\n",
              long_options[option_index].name, rsqAboveSnrPow );
          exit( 1 );
        }
        ADD_PROCESS_PARAM( "float", "%e", rsqAboveSnrPow );
        break;

      case 'C':
        /* choose the clustering algorithm */
        {
          if ( ! strcmp( "nullstat", LALoptarg) )
          {
            clusterchoice = nullstat;
          }
          else if ( ! strcmp( "cohsnr", LALoptarg) )
          {
            clusterchoice = cohsnr;
          }
          else if ( ! strcmp( "effCohSnr", LALoptarg) )
          {
            clusterchoice = effCohSnr;
          }
          else if ( ! strcmp( "snrByNullstat", LALoptarg) )
          {
            clusterchoice = snrByNullstat;
          }
          else if ( ! strcmp( "autoCorrCohSqByNullstat", LALoptarg) )
          {
            clusterchoice = autoCorrCohSqByNullstat;
          }
          else if ( ! strcmp( "crossCorrCohSqByNullstat", LALoptarg) )
          {
            clusterchoice = autoCorrCohSqByNullstat;
          }
          else if ( ! strcmp( "autoCorrNullSqByNullstat", LALoptarg) )
          {
            clusterchoice = autoCorrCohSqByNullstat;
          }
          else if ( ! strcmp( "crossCorrNullSqByNullstat", LALoptarg) )
          {
            clusterchoice = crossCorrCohSqByNullstat;
          }
          else
          {
            fprintf( stderr, "invalid argument to  --%s:\n"
                "unknown clustering specified:\n "
                "%s (must be one of: cohsnr, effCohSnr, nullstat, snrByNullstat, autoCorrCohSqByNullstat, \n"
                "crossCorrCohSqByNullstat, autoCorrNullSqByNullstat, or crossCorrNullSqByNullstat)\n",
                long_options[option_index].name, LALoptarg);
            exit( 1 );
          }
          ADD_PROCESS_PARAM( "string", "%s", LALoptarg );
        }
        break;

      case 't':
        /* cluster time is specified on command line in ms */
        cluster_dt = (INT8) atoi( LALoptarg );
        if ( cluster_dt <= 0 )
        {
          fprintf( stdout, "invalid argument to --%s:\n"
              "cluster window must be > 0: "
              "(%" LAL_INT8_FORMAT " specified)\n",
              long_options[option_index].name, cluster_dt );
          exit( 1 );
        }
        ADD_PROCESS_PARAM( "int", "%" LAL_INT8_FORMAT, cluster_dt );
        /* convert cluster time from ms to ns */
        cluster_dt *= 1000000LL;
        break;

      case 'v':
        /* create storage for the injection file name */
        LALoptarg_len = strlen( LALoptarg ) + 1;
        vetoFileName = (CHAR *) calloc( LALoptarg_len, sizeof(CHAR));
        memcpy( vetoFileName, LALoptarg, LALoptarg_len );
        ADD_PROCESS_PARAM( "string", "%s", LALoptarg );
        break;

      case 'I':
        /* create storage for the injection file name */
        LALoptarg_len = strlen( LALoptarg ) + 1;
        injectFileName = (CHAR *) calloc( LALoptarg_len, sizeof(CHAR));
        memcpy( injectFileName, LALoptarg, LALoptarg_len );
        ADD_PROCESS_PARAM( "string", "%s", LALoptarg );
        break;

      case 'd':
        LALoptarg_len = strlen( LALoptarg ) + 1;
        ifoName = (CHAR *) calloc( LALoptarg_len, sizeof(CHAR));
        memcpy( ifoName, LALoptarg, LALoptarg_len );
        ADD_PROCESS_PARAM( "string", "%s", LALoptarg );
        break;

      case 'D':
        /* keep only coincs found in ifos */
        LALoptarg_len = strlen( LALoptarg ) + 1;
        ifos = (CHAR *) calloc( LALoptarg_len, sizeof(CHAR));
        memcpy( ifos, LALoptarg, LALoptarg_len );
        ADD_PROCESS_PARAM( "string", "%s", LALoptarg );
        break;

      case 'T':
        /* injection coincidence time is specified on command line in ms */
        injectWindowNS = (INT8) atoi( LALoptarg );
        if ( injectWindowNS < 0 )
        {
          fprintf( stdout, "invalid argument to --%s:\n"
              "injection coincidence window must be >= 0: "
              "(%" LAL_INT8_FORMAT " specified)\n",
              long_options[option_index].name, injectWindowNS );
          exit( 1 );
        }
        ADD_PROCESS_PARAM( "int", "%" LAL_INT8_FORMAT, injectWindowNS );
        /* convert inject time from ms to ns */
        injectWindowNS *= 1000000LL;
        break;

      case 'm':
        /* create storage for the missed injection file name */
        LALoptarg_len = strlen( LALoptarg ) + 1;
        missedFileName = (CHAR *) calloc( LALoptarg_len, sizeof(CHAR));
        memcpy( missedFileName, LALoptarg, LALoptarg_len );
        ADD_PROCESS_PARAM( "string", "%s", LALoptarg );
        break;

      case '?':
        exit( 1 );
        break;

      default:
        fprintf( stderr, "unknown error while parsing options\n" );
        exit( 1 );
    }
  }


  /*
   *
   * can use LALCalloc() / LALMalloc() from here
   *
   */


  /* don't buffer stdout if we are in verbose mode */
  if ( vrbflg ) setvbuf( stdout, NULL, _IONBF, 0 );

  /* fill the comment, if a user has specified it, or leave it blank */
  if ( ! *comment )
  {
    snprintf( proctable.processTable->comment, LIGOMETA_COMMENT_MAX, " " );
  }
  else
  {
    snprintf( proctable.processTable->comment, LIGOMETA_COMMENT_MAX,
        "%s", comment );
  }

  /* check that the output file name has been specified */
  if ( ! outputFileName )
  {
    fprintf( stderr, "--output must be specified\n" );
    exit( 1 );
  }

  /* check that Data Type has been specified */
  if ( dataType == unspecified_data_type )
  {
    fprintf( stderr, "Error: --data-type must be specified\n");
    exit(1);
  }

  /* check that if clustering is being done that we have all the options */
  if ( clusterchoice && cluster_dt < 0 )
  {
    fprintf( stderr, "--cluster-time must be specified if --cluster-algorithm "
        "is given\n" );
    exit( 1 );
  }
  else if ( ! clusterchoice && cluster_dt >= 0 )
  {
    fprintf( stderr, "--cluster-algorithm must be specified if --cluster-time "
        "is given\n" );
    exit( 1 );
  }

  /* check that if the rsq veto is being preformed,
                         we have the required options */
  if ( ( (rsqVetoThresh > 0) || (rsqMaxSnr > 0) ) && ( (rsqVetoThresh < 0)
    || (rsqMaxSnr < 0) ) )
  {
    fprintf( stderr, "--rsq-threshold and --rsq-max-snr and must be "
      "specified together" );
    exit( 1 );
  }
  else if ( (rsqAboveSnrCoeff > 0) && ( (rsqMaxSnr < 0) || (rsqVetoThresh < 0)
    || (rsqAboveSnrPow < 0) ) )
  {
    fprintf( stderr, "--rsq-max-snr --rsq-threshold and --rsq-power "
      "must be specified if --rsq-coeff is given\n" );
    exit( 1 );
  }
  else if ( (rsqAboveSnrPow > 0) && ( (rsqMaxSnr < 0) || (rsqVetoThresh < 0)
    || (rsqAboveSnrCoeff < 0) ) )
  {
    fprintf( stderr, "--rsq-max-snr --rsq-threshold and --rsq-coeff "
      "must be specified if --rsq-power is given\n" );
    exit( 1 );
  }

  /* check that we have all the options to do injections */
  if ( injectFileName && injectWindowNS < 0 )
  {
    fprintf( stderr, "--injection-coincidence must be specified if "
        "--injection-file is given\n" );
    exit( 1 );
  }
  else if ( ! injectFileName && injectWindowNS >= 0 )
  {
    fprintf( stderr, "--injection-file must be specified if "
        "--injection-coincidence is given\n" );
    exit( 1 );
  }

  if ( numSlides && extractSlide )
  {
    fprintf( stderr, "--num-slides and --extract-slide both specified\n"
        "this doesn't make sense\n" );
    exit( 1 );
  }

  /* save the sort triggers flag */
  if ( sortTriggers )
  {
    this_proc_param = this_proc_param->next = (ProcessParamsTable *)
      calloc( 1, sizeof(ProcessParamsTable) );
    snprintf( this_proc_param->program, LIGOMETA_PROGRAM_MAX, "%s",
        PROGRAM_NAME );
    snprintf( this_proc_param->param, LIGOMETA_PARAM_MAX,
        "--sort-triggers" );
    snprintf( this_proc_param->type, LIGOMETA_TYPE_MAX, "string" );
    snprintf( this_proc_param->value, LIGOMETA_VALUE_MAX, " " );
  }

  /* read in the veto file (if specified */

  if ( vetoFileName )
  {
    XLALSegListInit( &vetoSegs );
    LAL_CALL( LALSegListRead( &status, &vetoSegs, vetoFileName, NULL ),
        &status );
    XLALSegListCoalesce( &vetoSegs );
  }


  /*
   *
   * read in the input triggers from the xml files
   *
   */


  /* if we have run out of arguments on the command line, throw an error */
  if ( ! (LALoptind < argc) )
  {
    fprintf( stderr, "Error: No input trigger files specified.\n" );
    exit( 1 );
  }

  /* read in the triggers */
  for( j = LALoptind; j < argc; ++j )
  {
    INT4 numFileTriggers = 0;
    MultiInspiralTable   *inspiralFileList = NULL;
    MultiInspiralTable   *thisFileTrigger  = NULL;

    numInFiles++;

    numFileTriggers = XLALReadMultiInspiralTriggerFile( &inspiralFileList,
        &thisFileTrigger, &searchSummList, &inputFiles, argv[j] );
    numEvents += numFileTriggers;

    if (numFileTriggers < 0)
    {
      fprintf(stderr, "Error reading triggers from file %s\n",
          argv[j]);
      exit( 1 );
    }
    else
    {
      if ( vrbflg )
      {
        fprintf(stdout, "Read %d reading triggers from file %s\n",
            numFileTriggers, argv[j]);
      }
    }

    /* read the summ value table as well. */
    XLALReadSummValueFile(&summValueList, argv[j]);

    /*
     *
     *  keep only relevant triggers
     *
     */

    if( ifos )
    {
      numFileTriggers = XLALMultiInspiralIfosCut( &inspiralFileList, ifos );
      if ( vrbflg ) fprintf( stdout,
          "Kept %d coincs from %s instruments\n", numFileTriggers, ifos );
      numEventsInIfos += numFileTriggers;
    }

    /* Do playground_only or exclude_play cut */
    if ( dataType != all_data )
    {
      inspiralFileList = XLALPlayTestMultiInspiral( inspiralFileList,
          &dataType );
      /* count the triggers */
      numFileTriggers = XLALCountMultiInspiralTable( inspiralFileList );

      if ( dataType == playground_only && vrbflg ) fprintf( stdout,
          "Have %d playground triggers\n", numFileTriggers );
      else if ( dataType == exclude_play && vrbflg ) fprintf( stdout,
          "Have %d non-playground triggers\n", numFileTriggers );
    }
    numEventsKept += numFileTriggers;

    /*  Do snr cut */
    if ( snrStar > 0 )
    {
      inspiralFileList = XLALSNRCutMultiInspiral( inspiralFileList,
          snrStar );
      /* count the triggers  */
      numFileTriggers = XLALCountMultiInspiral( inspiralFileList );

      if ( vrbflg ) fprintf( stdout, "Have %d triggers after snr cut\n",
          numFileTriggers );
      numEventsAboveSNRThresh += numFileTriggers;
    }

    /* NOTE: Add vetoing:
       if ( vetoFileName )
       {
       inspiralFileList = XLALVetoMultiInspiral( inspiralFileList, &vetoSegs , ifoName);
       count the triggers
       numFileTriggers = XLALCountMultiInspiral( inspiralFileList );
       if ( vrbflg ) fprintf( stdout, "Have %d triggers after applying veto\n",
       numFileTriggers );
       numEventsSurvivingVeto += numFileTriggers;

       }
     */

    /* If there are any remaining triggers ... */
    if ( inspiralFileList )
    {
      /* add inspirals to list */
      if ( thisInspiralTrigger )
      {
        thisInspiralTrigger->next = inspiralFileList;
      }
      else
      {
        inspiralEventList = thisInspiralTrigger = inspiralFileList;
      }
      for( ; thisInspiralTrigger->next;
          thisInspiralTrigger = thisInspiralTrigger->next);
    }
  }

  for ( thisSearchSumm = searchSummList; thisSearchSumm;
      thisSearchSumm = thisSearchSumm->next )
  {
    UINT8 outPlayNS, outStartNS, outEndNS, triggerTimeNS;
    LIGOTimeGPS inPlay, outPlay;
    outStartNS = XLALGPSToINT8NS( &(thisSearchSumm->out_start_time) );
    outEndNS = XLALGPSToINT8NS( &(thisSearchSumm->out_end_time) );
    triggerTimeNS = outEndNS - outStartNS;

    /* check for events and playground */
    if ( dataType != all_data )
    {
      XLALPlaygroundInSearchSummary( thisSearchSumm, &inPlay, &outPlay );
      outPlayNS = XLALGPSToINT8NS( &outPlay );

      if ( dataType == playground_only )
      {
        /* increment the total trigger time by the amount of playground */
        triggerInputTimeNS += outPlayNS;
      }
      else if ( dataType == exclude_play )
      {
        /* increment the total trigger time by the out time minus */
        /* the time that is in the playground                     */
        triggerInputTimeNS += triggerTimeNS - outPlayNS;
      }
    }
    else
    {
      /* increment the total trigger time by the out time minus */
      triggerInputTimeNS += triggerTimeNS;
    }
  }


  /*
   *
   * sort the inspiral events by time
   *
   */


  if ( injectFileName || sortTriggers )
  {
    inspiralEventList = XLALSortMultiInspiral( inspiralEventList,
        *LALCompareMultiInspiralByTime );
  }

  /*
   *
   * read in the injection XML file, if we are doing an injection analysis
   *
   */

  if ( injectFileName )
  {
    if ( vrbflg )
      fprintf( stdout, "reading injections from %s... ", injectFileName );

    numSimEvents = SimInspiralTableFromLIGOLw( &simEventHead,
        injectFileName, 0, 0 );

    if ( vrbflg ) fprintf( stdout, "got %d injections\n", numSimEvents );

    if ( numSimEvents < 0 )
    {
      fprintf( stderr, "error: unable to read sim_inspiral table from %s\n",
          injectFileName );
      exit( 1 );
    }

    /* keep play/non-play/all injections */
    if ( dataType == playground_only && vrbflg ) fprintf( stdout,
        "Keeping only playground injections\n" );
    else if ( dataType == exclude_play && vrbflg ) fprintf( stdout,
        "Keeping only non-playground injections\n" );
    else if ( dataType == all_data && vrbflg ) fprintf( stdout,
        "Keeping all injections\n" );
    XLALPlayTestSimInspiral( &simEventHead, &dataType );

    /* keep only injections in times analyzed */
    numSimInData = XLALSimInspiralInSearchedData( &simEventHead,
        &searchSummList );

    if ( vrbflg ) fprintf( stdout, "%d injections in analyzed data\n",
        numSimInData );


    /* check for events that are coincident with injections */
    numSimFound = XLALMultiSimInspiralTest( &simEventHead,
        &inspiralEventList, &missedSimHead, &missedHead, injectWindowNS );

    if ( vrbflg ) fprintf( stdout, "%d injections found in the ifos\n",
        numSimFound );

    if ( numSimFound )
    {
      for ( thisEvent = inspiralEventList; thisEvent;
          thisEvent = thisEvent->next, numMultiFound++ );
      if ( vrbflg ) fprintf( stdout,
          "%d triggers found at times of injection\n", numMultiFound );
    }

    /* free the missed singles  */
    while ( missedHead )
    {
      thisEvent = missedHead;
      missedHead = missedHead->next;
      XLALFreeMultiInspiral( &thisEvent );
    }
  }


  /*
   *
   * extract specified slide
   *
   */

  if ( extractSlide )
  {
    slideEvent = XLALMultiInspiralSlideCut( &inspiralEventList, extractSlide );
    /* free events from other slides */
    while ( inspiralEventList )
    {
      thisEvent = inspiralEventList;
      inspiralEventList = inspiralEventList->next;
      XLALFreeMultiInspiral( &thisEvent );
    }

    /* move events to inspiralEventList */
    inspiralEventList = slideEvent;
    slideEvent = NULL;
  }


  /*
   *
   * cluster the remaining events
   *
   */


  if ( inspiralEventList && clusterchoice )
  {
    if ( vrbflg ) fprintf( stdout, "clustering remaining triggers... " );

    if ( !numSlides ) {
      numClusteredEvents = XLALClusterMultiInspiralTable( &inspiralEventList,
        cluster_dt, clusterchoice );
    }
    else
    {
      int slide = 0;
      int numClusteredSlide = 0;
      MultiInspiralTable *tmp_slideEvent = NULL;
      MultiInspiralTable *slideClust = NULL;

      if ( vrbflg ) fprintf( stdout, "splitting events by slide\n" );

      for( slide = -numSlides; slide < (numSlides + 1); slide++)
      {
        if ( vrbflg ) fprintf( stdout, "slide number %d; ", slide );
        /* extract the slide */
        tmp_slideEvent = XLALMultiInspiralSlideCut( &inspiralEventList, slide );
        /* run clustering */
        numClusteredSlide = XLALClusterMultiInspiralTable( &tmp_slideEvent,
          cluster_dt, clusterchoice);

        if ( vrbflg ) fprintf( stdout, "%d clustered events \n",
          numClusteredSlide );
        numClusteredEvents += numClusteredSlide;

        /* add clustered triggers */
        if( tmp_slideEvent )
        {
          if( slideClust )
          {
            thisEvent = thisEvent->next = tmp_slideEvent;
          }
          else
          {
            slideClust = thisEvent = tmp_slideEvent;
          }
          /* scroll to end of list */
          for( ; thisEvent->next; thisEvent = thisEvent->next);
        }
      }

      /* free inspiralEventList -- although we expect it to be empty */
      while ( inspiralEventList )
      {
        thisEvent = inspiralEventList;
        inspiralEventList = inspiralEventList->next;
        XLALFreeMultiInspiral( &thisEvent );
      }

      /* move events to coincHead */
      inspiralEventList = slideClust;
      slideClust = NULL;
    }

    if ( vrbflg ) fprintf( stdout, "done\n" );
    if ( vrbflg ) fprintf( stdout, "%d clustered events \n",
        numClusteredEvents );
  }


  /*
   *
   * update search_summary->nevents with an authoritative count of triggers
   *
   */

  searchSummList->nevents = 0;
  thisEvent = inspiralEventList;
  while (thisEvent) {
    searchSummList->nevents += 1;
    thisEvent = thisEvent->next;
  }

  /*
   *
   * write output data
   *
   */


  /* write the main output file containing found injections */
  if ( vrbflg ) fprintf( stdout, "writing output xml files... " );
  memset( &xmlStream, 0, sizeof(LIGOLwXMLStream) );
  LAL_CALL( LALOpenLIGOLwXMLFile( &status, &xmlStream, outputFileName ), &status );

  /* write out the process and process params tables */
  if ( vrbflg ) fprintf( stdout, "process... " );
  XLALGPSTimeNow(&(proctable.processTable->end_time));
  LAL_CALL( LALBeginLIGOLwXMLTable( &status, &xmlStream, process_table ),
      &status );
  LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, proctable,
        process_table ), &status );
  LAL_CALL( LALEndLIGOLwXMLTable ( &status, &xmlStream ), &status );
  free( proctable.processTable );

  /* erase the first empty process params entry */
  {
    ProcessParamsTable *emptyPPtable = procparams.processParamsTable;
    procparams.processParamsTable = procparams.processParamsTable->next;
    free( emptyPPtable );
  }

  /* write the process params table */
  if ( vrbflg ) fprintf( stdout, "process_params... " );
  LAL_CALL( LALBeginLIGOLwXMLTable( &status, &xmlStream,
        process_params_table ), &status );
  LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, procparams,
        process_params_table ), &status );
  LAL_CALL( LALEndLIGOLwXMLTable ( &status, &xmlStream ), &status );

  /* write search_summary table */
  if ( vrbflg ) fprintf( stdout, "search_summary... " );
  outputTable.searchSummaryTable = searchSummList;
  LAL_CALL( LALBeginLIGOLwXMLTable( &status, &xmlStream,
        search_summary_table ), &status );
  LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, outputTable,
        search_summary_table ), &status );
  LAL_CALL( LALEndLIGOLwXMLTable ( &status, &xmlStream ), &status );

  /* write the search_summvars table */
  if ( vrbflg ) fprintf( stdout, "search_summvars... " );
  LAL_CALL( LALBeginLIGOLwXMLTable( &status ,&xmlStream,
        search_summvars_table), &status );
  searchSummvarsTable.searchSummvarsTable = inputFiles;
  LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, searchSummvarsTable,
        search_summvars_table), &status );
  LAL_CALL( LALEndLIGOLwXMLTable( &status, &xmlStream), &status );

  /* write summ_value table */
  if ( summValueList )
  {
    if ( vrbflg ) fprintf( stdout, "search_summary... " );
    outputTable.summValueTable = summValueList;
    LAL_CALL( LALBeginLIGOLwXMLTable( &status, &xmlStream,
          summ_value_table ), &status );
    LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, outputTable,
          summ_value_table ), &status );
    LAL_CALL( LALEndLIGOLwXMLTable ( &status, &xmlStream ), &status );
  }

  /* Write the found injections to the sim table */
  if ( simEventHead )
  {
    if ( vrbflg ) fprintf( stdout, "sim_inspiral... " );
    outputTable.simInspiralTable = simEventHead;
    LAL_CALL( LALBeginLIGOLwXMLTable( &status, &xmlStream,
          sim_inspiral_table ), &status );
    LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, outputTable,
          sim_inspiral_table ), &status );
    LAL_CALL( LALEndLIGOLwXMLTable( &status, &xmlStream ), &status );
  }

  /* Write the results to the inspiral table */
  if ( inspiralEventList )
  {
    if ( vrbflg ) fprintf( stdout, "multi_inspiral... " );
    outputTable.multiInspiralTable = inspiralEventList;
    LAL_CALL( LALBeginLIGOLwXMLTable( &status, &xmlStream,
          multi_inspiral_table ), &status );
    LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, outputTable,
          multi_inspiral_table ), &status );
    LAL_CALL( LALEndLIGOLwXMLTable( &status, &xmlStream ), &status);
  }

  /* close the output file */
  LAL_CALL( LALCloseLIGOLwXMLFile(&status, &xmlStream), &status);
  if ( vrbflg ) fprintf( stdout, "done\n" );


  if ( missedFileName )
  {
    /* open the missed injections file and write the missed injections to it */
    if ( vrbflg ) fprintf( stdout, "writing missed injections... " );
    memset( &xmlStream, 0, sizeof(LIGOLwXMLStream) );
    LAL_CALL( LALOpenLIGOLwXMLFile( &status, &xmlStream, missedFileName ),
        &status );

    if ( missedSimHead )
    {
      outputTable.simInspiralTable = missedSimHead;
      LAL_CALL( LALBeginLIGOLwXMLTable( &status, &xmlStream, sim_inspiral_table ),
          &status );
      LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, outputTable,
            sim_inspiral_table ), &status );
      LAL_CALL( LALEndLIGOLwXMLTable( &status, &xmlStream ), &status );
    }

    LAL_CALL( LALCloseLIGOLwXMLFile( &status, &xmlStream ), &status );
    if ( vrbflg ) fprintf( stdout, "done\n" );
  }

  if ( summFileName )
  {
    LIGOTimeGPS triggerTime;

    /* write out a summary file */
    fp = fopen( summFileName, "w" );

    switch ( dataType )
    {
      case playground_only:
        fprintf( fp, "using data from playground times only\n" );
        break;
      case exclude_play:
        fprintf( fp, "excluding all triggers in playground times\n" );
        break;
      case all_data:
        fprintf( fp, "using all input data\n" );
        break;
      default:
        fprintf( stderr, "data set not defined\n" );
        exit( 1 );
    }

    fprintf( fp, "read triggers from %d files\n", numInFiles );
    fprintf( fp, "number of triggers in input files: %d \n", numEvents );
    fprintf( fp, "number of triggers in input data %d \n", numEventsKept );
    if ( ifoName )
    {
      fprintf( fp, "number of triggers from %s ifo %d \n", ifoName,
          numEventsInIFO );
    }


    if ( snrStar > 0 )
    {
      fprintf( fp, "number of triggers in input data with snr above %f: %d \n",
          snrStar, numEventsAboveSNRThresh );
    }

    if ( rsqVetoThresh > 0 )
    {
      fprintf( fp, "performed R-squared veto on triggers with snr < %f\n",
          rsqMaxSnr);
      fprintf( fp, "with rsqveto_duration below %f\n",
          rsqVetoThresh);
      if ( (rsqAboveSnrCoeff > 0) && (rsqAboveSnrPow > 0) )
      {
        fprintf( fp, "and on triggers with snr > %f\n",
            rsqMaxSnr);
        fprintf( fp, "with rsqveto_duration above %f * snr ^ %f\n",
            rsqAboveSnrCoeff, rsqAboveSnrPow );
      }
      fprintf( fp, "the number of triggers below the R-squared veto are: %d \n",
          numEventsBelowRsqThresh);
    }

    if ( vetoFileName )
    {
      fprintf( fp, "number of triggers not vetoed by %s: %d \n",
          vetoFileName, numEventsSurvivingVeto );
    }

    XLALINT8NSToGPS( &triggerTime, triggerInputTimeNS );
    fprintf( fp, "amount of time analysed for triggers %d sec %d ns\n",
        triggerTime.gpsSeconds, triggerTime.gpsNanoSeconds );

    if ( injectFileName )
    {
      fprintf( fp, "read %d injections from file %s\n",
          numSimEvents, injectFileName );

      fprintf( fp, "number of injections in input data: %d\n", numSimInData );
      fprintf( fp, "number of injections found in input data: %d\n",
          numSimFound );
      fprintf( fp,
          "number of triggers found within %lld msec of injection: %d\n",
          (injectWindowNS / 1000000LL), numMultiFound );

      fprintf( fp, "efficiency: %f \n",
          (REAL4) numSimFound / (REAL4) numSimInData );
    }

    if ( extractSlide )
    {
      fprintf( fp, "kept only triggers from slide %d\n", extractSlide );
    }

    if ( clusterchoice )
    {
      if ( numSlides )
      {
        fprintf( fp, "clustering triggers from %d slides separately\n",
            numSlides );
      }
      fprintf( fp, "number of event clusters with %lld msec window: %d\n",
          cluster_dt/ 1000000LL, numClusteredEvents );
    }

    fclose( fp );
  }


  /*
   *
   * free memory and exit
   *
   */


  /* free the inspiral events we saved */
  while ( inspiralEventList )
  {
    thisEvent = inspiralEventList;
    inspiralEventList = inspiralEventList->next;
    LAL_CALL ( LALFreeMultiInspiral ( &status, &thisEvent ), &status);
  }

  /* free the process params */
  while( procparams.processParamsTable )
  {
    this_proc_param = procparams.processParamsTable;
    procparams.processParamsTable = this_proc_param->next;
    free( this_proc_param );
  }

  /* free the found injections */
  while ( simEventHead )
  {
    thisSimEvent = simEventHead;
    simEventHead = simEventHead->next;
    LALFree( thisSimEvent );
  }

  /* free the temporary memory containing the missed injections */
  while ( missedSimHead )
  {
    tmpSimEvent = missedSimHead;
    missedSimHead = missedSimHead->next;
    LALFree( tmpSimEvent );
  }

  /* free search summaries read in */
  while ( searchSummList )
  {
    thisSearchSumm = searchSummList;
    searchSummList = searchSummList->next;
    LALFree( thisSearchSumm );
  }

  while ( summValueList )
  {
    SummValueTable *thisSummValue;
    thisSummValue = summValueList;
    summValueList = summValueList->next;
    LALFree( thisSummValue );
  }

  if ( vetoFileName )
  {
    XLALSegListClear( &vetoSegs );
  }


  if ( vrbflg ) fprintf( stdout, "checking memory leaks and exiting\n" );
  LALCheckMemoryLeaks();
  exit( 0 );
}