BayesWavePost.c 110 KB
Newer Older
1

2 3 4 5 6 7 8 9

/***************************  REQUIRED LIBRARIES  ***************************/

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <math.h>
Tyson Littenberg's avatar
Tyson Littenberg committed
10
#include <fftw3.h>
11
#include <sys/stat.h>
12 13
#include <gsl/gsl_cdf.h>

14

15
#include <lal/LALInferenceTemplate.h>
16 17 18
#include <lal/LALSimIMR.h>
#include <lal/LALSimulation.h>
#include <lal/RingUtils.h>
19

20 21 22 23 24 25 26 27 28 29 30 31
#include "BayesLine.h"
#include "BayesWave.h"
#include "BayesWaveIO.h"
#include "BayesWaveMCMC.h"
#include "BayesWaveMath.h"
#include "BayesWavePrior.h"
#include "BayesWaveModel.h"
#include "BayesWaveWavelet.h"
#include "BayesWaveProposal.h"
#include "BayesWaveEvidence.h"
#include "BayesWaveLikelihood.h"

32 33
/*************  PROTOTYPE DECLARATIONS FOR INTERNAL FUNCTIONS  **************/

34 35
#define GLOBAL_F_RESOLUTION 8.0 // Frequency resolution for Qscans (Hz)

36 37 38 39 40 41 42 43
struct Moments
{
  double *overlap;
  double *energy;
  double *frequency;
  double *time;
  double *bandwidth;
  double *duration;
44
  double *snr;
45
  double networkOverlap;
46 47
  double *hmax;
  double *t_at_hmax;
48
  double *f_at_max_amp;
49 50 51 52 53 54
  double *medianfrequency;
  double *mediantime;
  double *bandwidth90percentinterval;
  double *duration90percentinterval;
  double *tl;
  double *th;
55 56
};

57
void print_help_message(void);
58
void ComputeWaveformOverlap(struct Data *data, double **hinj, double **hrec, double **psd, struct Moments *m);
59
void PrintRhof(struct Data *data, double deltaF, double **h, double **psd, struct Moments *m);
60
void ComputeWaveformMoments(struct Data *data, double **h, double **psd, struct Moments *m);
61 62
void ComputeGeocenterMoments(struct Data *data, double deltaF, double deltaT, double *h, double *psd, struct Moments *m);

63
void free_moments(struct Moments *m);
64
void initialize_moments(struct Moments *m, int NI);
65
void setup_output_files(int NI, int injectionFlag, char *outdir, char *model, char *weighting, FILE **momentsOut, struct Data *data);
66 67
void discard_burnin_samples(FILE *params, int *COUNT, int *BURNIN);
void print_moments(int NI, int injectionFlag, FILE **outfile, struct Moments *m);
68
void print_waveforms(struct Data *data, double **h, double **psd, FILE **ofile);
69
void print_spectrum(struct Data *data, double **h, FILE **ofile);
70
void print_hdot(struct Data *data, double **h, double **psd, FILE **ofile, double deltaF);
71
void print_spectrograms(struct Data *data, char outdir[], char type[], char *ifo, double *h, double *psd);
72

73
void get_time_domain_hdot(double *hdot, double *h, int N, int imin, int imax, double deltaF);
74

75
void print_stats(struct Data *data, LIGOTimeGPS GPS, int injectionFlag, char *outdir, char model[], int **dimension);
76 77 78

double get_energy(int imin, int imax, double *a, double deltaF);
double get_rhof(int imin, int imax, double *a, double deltaF, double *arg);
Tyson Littenberg's avatar
Tyson Littenberg committed
79
double get_rhof_net(int imin, int imax, double **a, double deltaF, double *arg, int NI);
80 81
double rhonorm(int imax, double *a, double deltaF);
double get_f0(int imax, double *a, double deltaF);
82 83 84 85 86

void get_f_quantiles(int imin, int imax, double *rhof, double deltaF, double *fm, double *bw);
void get_t_quantiles(int N, double *rhot, double deltaT, double *tm, double *dur);
double get_rhof_f2weighted(int imin, int imax, double *a, double deltaF, double *arg);

87
double get_band(int imax, double *a, double deltaF, double f0);
88
void get_hmax_and_t(int imax, double *a, double deltaT, double *hmax, double *t_at_hmax);
Tyson Littenberg's avatar
Tyson Littenberg committed
89
void get_time_domain_waveforms(double *hoft, double *h, int N, int imin, int imax);
90
double get_rhot(int N, double *a, double deltaT, double *arg);
Tyson Littenberg's avatar
Tyson Littenberg committed
91
double get_rhot_net(int N, double **a, double deltaT, double *arg, int NI);
92
void whiten_data(int imin, int imax, double *a, double *Snf);
93

94
void write_time_freq_samples(struct Data *data);
95

96 97
void print_single_waveform(struct Data *data, double **h, double **psd, FILE *ofile);

98
void tf_tracks(double *hoft, double *frequency_out, double deltaT, int N);
Meg Millhouse's avatar
Meg Millhouse committed
99
void interp_tf(double **tf, double **pts, int tlength, int Nsample);
100
void median_and_CIs(double **waveforminfo, int N, int Nwaveforms, double deltaT, FILE *outfile, double *median_waveform);
101
void median_and_CIs_fourierdom(double **waveforminfo, int N, int Nwaveforms, double deltaT, FILE *outfile, double *median_waveform);
102 103
void Q_scan(struct Data *data, double *median_waveform, double Q, double *invPSD, FILE *outfile);
void Transform(double *hoff, double Q, double dt, double fmin, double *invPSD, int n, int m, FILE *outfile);
Meg Millhouse's avatar
Meg Millhouse committed
104

105
void print_anderson_darling_p_values(char *outDir, int Nsamp);
106
void anderson_darling_test(char *outdir, int ifo, double fmin, double Tobs, char *model, char **ifos);
107

Meg Millhouse's avatar
Meg Millhouse committed
108

109
int post_process_model(char model_name[], char model_type[], struct Data *data, struct Model *model, struct Chain *chain, double **hdata, double **hoft, double **psd, double **one, double **hinj, int **dimension, int injectionFlag, LIGOTimeGPS GPStrig, bool lite);
110

111 112 113
void get_time_domain_envelope(double *envelope, double *hdata_sample, int N, int imin, int imax);
double get_time_at_max(double *hdata_sample, int N, int imin, int imax, double deltaT);
void get_freq_at_max(double *hdata_sample, int N, int imin, int imax, double deltaT, double *f_at_max_amp);
114

115 116 117 118 119
/* ============================  MAIN PROGRAM  ============================ */

int main(int argc, char *argv[])
{

120
  /*   Variable declaration   */
121
  int i, ifo, imin, ii;//, imax;
122

Tyson Littenberg's avatar
Tyson Littenberg committed
123
  char filename[MAXSTRINGSIZE];
124 125 126 127 128 129

  /* LAL data structure that will contain all of the data from the frame files */
  LALInferenceRunState *runState = XLALCalloc(1,sizeof(LALInferenceRunState));

  runState->commandLine = LALInferenceParseCommandLine(argc,argv);

130 131
  print_version(stdout);

132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
  /******************************************************************************/
  /*                                                                            */
  /*  Usage statment if --help                                                  */
  /*                                                                            */
  /******************************************************************************/

  if(LALInferenceGetProcParamVal(runState->commandLine, "--help") || argc==1)
  {
    print_help_message();
    return 0;
  }

  /******************************************************************************/
  /*                                                                            */
  /*  Read/store  data                                                          */
  /*                                                                            */
  /******************************************************************************/

  /*
151 152
   Unlike in BayesWaveBurst, we DO NOT want to read and store the IFO data,
   but we have to use LALInferenceReadData to properly setup the runState
153
   structure and use the injection software.
154 155

   This is a hack to fill the runState detector with zeros so that all we store
156
   in runState is the injected waveform.
157
   */
158 159

  if( LALInferenceGetProcParamVal(runState->commandLine, "--0noise") )
160
  {
161
    fprintf(stdout,"Found --0noise in the command line\n");
162
  } else {
163 164 165 166 167 168 169 170 171 172
    fprintf(stdout," \n");
    fprintf(stdout,"Error:  You must include --0noise in the command line\n");
    return 0;
  }

  fprintf(stdout, "\n");
  fprintf(stdout, " ======= LALInferenceReadData() ======\n");
  runState->data = LALInferenceReadData(runState->commandLine);
  fprintf(stdout, "\n");

173 174 175 176 177
  // Check if this is a "lite" version (less ouput)                                                                                                    
  bool lite = False;
  if (LALInferenceGetProcParamVal(runState->commandLine, "--lite")) {
    lite = True;
  }
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201

  /******************************************************************************/
  /*                                                                            */
  /*  read/store data                                                           */
  /*                                                                            */
  /******************************************************************************/
  LALInferenceIFOData *dataPtr = NULL;

  dataPtr = runState->data;

  double *SNRinj = NULL;

  int NI;
  int N = dataPtr->timeData->data->length;
  double Tobs = (double)N*dataPtr->timeData->deltaT;

  ifo=0;
  while(dataPtr!=NULL)
  {
    dataPtr = dataPtr->next;
    ifo++;
  }
  NI=ifo;

Tyson Littenberg's avatar
Tyson Littenberg committed
202 203 204
  double **freqData = double_matrix(NI-1,N-1);
  double **psd      = double_matrix(NI-1,N/2-1);
  double **one      = double_matrix(NI-1,N/2-1);
205 206 207 208 209

  struct Data *data = malloc(sizeof(struct Data));

  /*
   Unused, but needed for command line and initialization functions
210
   */
211 212 213
  struct Prior *prior = malloc(sizeof(struct Prior));
  struct Chain *chain = malloc(sizeof(struct Chain));

Tyson Littenberg's avatar
Tyson Littenberg committed
214 215 216 217
  const gsl_rng_type *T = gsl_rng_default;
  chain->seed = gsl_rng_alloc(T);
  gsl_rng_env_setup();
  
218
  parse_command_line(data, chain, prior, runState->commandLine);
219 220
    
    
221 222
  // Median stuff
  double norm;
223

224 225 226 227 228 229 230
  /*
   Move to the directory specified by the user, or stay in ./
   */
  chdir(data->outputDirectory);
  fprintf(stdout,"\nOutputting all data to: %s \n\n", data->outputDirectory);

  /*
231
   OUTPUT DIRECTORY
232
   */
Tyson Littenberg's avatar
Tyson Littenberg committed
233
  char outdir[MAXSTRINGSIZE];
234 235 236
  sprintf(outdir,"%spost",data->runName);
  mkdir(outdir,S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);

Tyson Littenberg's avatar
Tyson Littenberg committed
237
  char wavedir[MAXSTRINGSIZE];
Tyson Littenberg's avatar
Tyson Littenberg committed
238 239 240
  sprintf(wavedir,"%s/waveforms",outdir);
  mkdir(wavedir,S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);

241 242
  /*
   Get trigger time in GPS seconds
243
   */
244 245 246 247 248 249 250 251 252 253
  LALStatus status;
  char *chartmp=NULL;
  LIGOTimeGPS GPStrig;
  ProcessParamsTable *ppt = NULL;

  memset(&status,0,sizeof(status));
  ppt = LALInferenceGetProcParamVal(runState->commandLine,"--trigtime");
  LALStringToGPS(&status,&GPStrig,ppt->value,&chartmp);


254
  // burstMDC injection
255
  int injectionFlag = 0;
256
  int xmlInjectionFlag = 0;
257 258 259 260 261 262 263
  if(LALInferenceGetProcParamVal(runState->commandLine, "--MDC-cache"))
  {
    SNRinj = malloc((NI+1)*sizeof(double));
    fprintf(stdout, " ==== LALInferenceInjectFromMDC(): started. ====\n");
    InjectFromMDC(runState->commandLine, runState->data, SNRinj);
    fprintf(stdout, " ==== LALInferenceInjectFromMDC(): finished. ====\n\n");
    free(SNRinj);
264 265

    injectionFlag = 1;
266 267
  }

268
  //CBC injection
269 270 271 272 273
  if(LALInferenceGetProcParamVal(runState->commandLine, "--inj"))
  {
    fprintf(stdout, " ==== LALInferenceInjectInspiralSignal(): started. ====\n");
    LALInferenceInjectInspiralSignal(runState->data,runState->commandLine);
    fprintf(stdout, " ==== LALInferenceInjectInspiralSignal(): finished. ====\n\n");
274 275

    injectionFlag = 1;
276
    //if(!LALInferenceGetProcParamVal(runState->commandLine, "--lalinspiralinjection"))xmlInjectionFlag = 1;
277 278
  }

279 280 281 282 283 284 285 286
  
  // Check chirplet flag
  int chirpletFlag = 0;
  if (LALInferenceGetProcParamVal(runState->commandLine, "--chirplets")) {
    chirpletFlag = 1;
  }
  
  
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
  //Output Fourier domain data for BayesLine
  dataPtr = runState->data;

  double fmin   = dataPtr->fLow;
  double fmax   = dataPtr->fHigh;
  double deltaT = dataPtr->timeData->deltaT;

  int tsize = dataPtr->timeData->data->length/4;

  //Copy Fourier domain data & PSD from LAL data types into simple arrays
  ifo=0;
  imin = (int)(fmin*Tobs);
  while(dataPtr!=NULL)
  {
    for(i=0; i<N/2; i++)
    {
      if(i<imin)
      {
        freqData[ifo][2*i]   = 0.0;
        freqData[ifo][2*i+1] = 0.0;
Tyson Littenberg's avatar
Tyson Littenberg committed
307
        psd[ifo][i] = 1.0;
Meg Millhouse's avatar
Meg Millhouse committed
308
        one[ifo][i] = 1.0;
309 310 311
      }
      else
      {
Tyson Littenberg's avatar
Tyson Littenberg committed
312 313 314 315 316 317 318 319 320
        freqData[ifo][2*i]   = creal(dataPtr->freqData->data->data[i]);
        freqData[ifo][2*i+1] = cimag(dataPtr->freqData->data->data[i]);

        /*
         Innerproducts are expecting <n_i^2> instead of Sn(f):
         So psd arrays == <n_i^2> = T/2 * Sn(f)
         */
        psd[ifo][i] = dataPtr->oneSidedNoisePowerSpectrum->data->data[i]*Tobs/2.0;
        one[ifo][i] = 1.0;
321 322 323 324 325 326
      }
    }
    dataPtr = dataPtr->next;
    ifo++;
  }

327
  //Storage for h+(f) and hx(f) of all IFOs
Tyson Littenberg's avatar
Tyson Littenberg committed
328 329
  double **freqDataPlus  = double_matrix(NI-1,N-1);
  double **freqDataCross = double_matrix(NI-1,N-1);
330

331

332 333 334 335 336 337 338 339 340
  /******************************************************************************/
  /*                                                                            */
  /*  Setup DATA, CHAIN, PRIOR, MODEL structures                                */
  /*                                                                            */
  /******************************************************************************/

  /*
   DATA
   */
341
  initialize_data(data,freqData,N,tsize,Tobs,NI,fmin,fmax);
342 343 344 345 346
  
  // Check chirplet flag
  if (chirpletFlag) data->NW = 6;
  else data->NW = 5;
  
347 348 349
  //Write out time and freq. samples
  write_time_freq_samples(data);

350 351 352 353 354 355 356
  data->detector  = malloc(NI*sizeof(LALDetector*));
  data->epoch     = runState->data->epoch;

  ifo=0;
  dataPtr = runState->data;
  while(dataPtr!=NULL)
  {
357
    sprintf(data->ifos[ifo],"%s",dataPtr->name);
358 359 360 361 362
    data->detector[ifo] = dataPtr->detector;
    ifo++;
    dataPtr = dataPtr->next;
  }

363 364 365
  /*
   CHAIN
   */
Tyson Littenberg's avatar
Tyson Littenberg committed
366
  //chain->NC = chain->NCmin;
367
  allocate_chain(chain,NI,data->Npol);
368 369 370 371 372 373 374 375 376

  /*
   PRIOR
   */
  data->Dmax = 200;

  int omax = 10;
  if(data->Dmax < omax) omax = data->Dmax;

377
  //Maximum number of sineGaussians
Tyson Littenberg's avatar
Tyson Littenberg committed
378 379
  prior->gmin = int_vector(data->NI-1);
  prior->gmax = int_vector(data->NI-1);
380
  //Wavelet parameters
Tyson Littenberg's avatar
Tyson Littenberg committed
381
  prior->range = double_matrix(4,1);
382 383

  initialize_priors(data, prior, omax);
384 385 386 387 388

  /*
   MODEL
   */
  struct Model *model = malloc(sizeof(struct Model));
Tyson Littenberg's avatar
Tyson Littenberg committed
389
  initialize_model(model, data, prior, psd, chain->seed);
390 391 392 393 394 395

  //Use Welch averaged PSD from LALInferenceReadData
  for(ifo=0; ifo<data->NI; ifo++)
  {
    for(i=0; i<N/2; i++)
    {
396 397
      model->SnS[ifo][i] = psd[ifo][i];
      model->Snf[ifo][i] = psd[ifo][i];
398 399 400
    }
  }

Tyson Littenberg's avatar
Tyson Littenberg committed
401 402 403
  // BayesWave internal injection
  if(LALInferenceGetProcParamVal(runState->commandLine,"--BW-inject"))
  {
404
    fprintf(stdout, " ==== BayesWaveInjection(): started. ====\n");
405
    BayesWaveInjection(runState->commandLine, data, chain, prior, psd, &chain->NC);
406
    fprintf(stdout, " ==== BayesWaveInjection(): finished. ====\n\n");
Tyson Littenberg's avatar
Tyson Littenberg committed
407 408 409 410
    injectionFlag = 1;
  }


411 412 413
  /*
   BAYESLINE PSD
   */
414 415
  int PSDimin = 0;
  int PSDimax = data->N/2;
416

Tyson Littenberg's avatar
Tyson Littenberg committed
417

418 419
  /******************************************************************************/
  /*                                                                            */
420 421
  /*  Declare the list of metrics to compute as part                            */
  /*  of the post-processing step.                                              */
422 423 424
  /*                                                                            */
  /******************************************************************************/

425 426
  fprintf(stdout, "\n");
  fprintf(stdout, " ===== BayesWave Post Processing =====\n");
427

428 429 430
  //print p-values for reference
  print_anderson_darling_p_values(outdir,N);

431
  //User-friendly arrays for PSD, signal, and injected waveform
Tyson Littenberg's avatar
Tyson Littenberg committed
432 433
  double **hinj      = malloc(NI*sizeof(double*));
  double **hinjPlus  = malloc(NI*sizeof(double*));
434
  double **hinjCross = malloc(NI*sizeof(double*));
Tyson Littenberg's avatar
Tyson Littenberg committed
435
  double **hoft      = malloc(NI*sizeof(double*));
436
  double **roft      = malloc(NI*sizeof(double*));
437
  double **hinj_white= malloc(NI*sizeof(double*));
438

439 440
  for(ifo=0; ifo<NI; ifo++)
  {
Tyson Littenberg's avatar
Tyson Littenberg committed
441 442
    hinj[ifo]      = malloc(N*sizeof(double));
    hinjPlus[ifo]  = malloc(N*sizeof(double));
443
    hinjCross[ifo] = malloc(N*sizeof(double));
Tyson Littenberg's avatar
Tyson Littenberg committed
444
    hoft[ifo]      = malloc(N*sizeof(double));
445
    roft[ifo]      = malloc(N*sizeof(double));
446
    hinj_white[ifo]= malloc(N*sizeof(double));
447 448
  }
  
449
  //Fill hinj, hinjPlus, and hCrossPlus with the injected waveform (held in data because did a 0-noise simulation) and its + and x polarizations
450
  for(ifo=0; ifo<NI; ifo++) for(i=0; i<N; i++) hinj[ifo][i] = data->s[ifo][i];
451 452
  if(xmlInjectionFlag)
  {
453
    for(ifo=0; ifo<NI; ifo++) for(i=0; i<N; i++) hinjPlus[ifo][i]  = freqDataPlus[ifo][i];
454 455
    for(ifo=0; ifo<NI; ifo++) for(i=0; i<N; i++) hinjCross[ifo][i] = freqDataCross[ifo][i];
  }
456

457
  // Different structures for whitened and "colored" moments
Tyson Littenberg's avatar
Tyson Littenberg committed
458 459
  struct Moments *whitenedInjectionMoments      = malloc(sizeof(struct Moments));
  struct Moments *whitenedPlusInjectionMoments  = malloc(sizeof(struct Moments));
460
  struct Moments *whitenedCrossInjectionMoments = malloc(sizeof(struct Moments));
Tyson Littenberg's avatar
Tyson Littenberg committed
461
  struct Moments *whitenedPlusSignalMoments     = malloc(sizeof(struct Moments));
462
  struct Moments *whitenedCrossSignalMoments    = malloc(sizeof(struct Moments));
463
  struct Moments *geoInjectionMoments           = malloc(sizeof(struct Moments));
464 465

  initialize_moments(whitenedInjectionMoments, NI);
466 467
  if(xmlInjectionFlag)
  {
468
    initialize_moments(whitenedPlusInjectionMoments,  NI);
469 470
    initialize_moments(whitenedCrossInjectionMoments, NI);
  }
471
  initialize_moments(whitenedPlusSignalMoments,  NI);
Tyson Littenberg's avatar
Tyson Littenberg committed
472
  initialize_moments(whitenedCrossSignalMoments, NI);
473
  initialize_moments(geoInjectionMoments,        NI);
474

Tyson Littenberg's avatar
Tyson Littenberg committed
475 476
  struct Moments *coloredInjectionMoments      = malloc(sizeof(struct Moments));
  struct Moments *coloredPlusInjectionMoments  = malloc(sizeof(struct Moments));
477
  struct Moments *coloredCrossInjectionMoments = malloc(sizeof(struct Moments));
478 479

  initialize_moments(coloredInjectionMoments, NI);
480 481
  if(xmlInjectionFlag)
  {
482
    initialize_moments(coloredPlusInjectionMoments,  NI);
483 484
    initialize_moments(coloredCrossInjectionMoments, NI);
  }
Tyson Littenberg's avatar
Tyson Littenberg committed
485

486 487 488 489
  // Keep track of dimension distribution for output stats
  int **dimension = malloc(NI*sizeof(int *));
  for(ifo=0; ifo<NI; ifo++) dimension[ifo] = malloc(data->Dmax*sizeof(int));

490
  // Output injected moments separately
Tyson Littenberg's avatar
Tyson Littenberg committed
491 492 493 494 495 496
  FILE **whitenedInjFile      = malloc((NI+1)*sizeof(FILE*));
  FILE **coloredInjFile       = malloc((NI+1)*sizeof(FILE*));
  FILE **whitenedPlusInjFile  = malloc((NI+1)*sizeof(FILE*));
  FILE **coloredPlusInjFile   = malloc((NI+1)*sizeof(FILE*));
  FILE **whitenedCrossInjFile = malloc((NI+1)*sizeof(FILE*));
  FILE **coloredCrossInjFile  = malloc((NI+1)*sizeof(FILE*));
497
  FILE **geoInjFile           = malloc(1*sizeof(FILE*));
498 499


500
  // Output a subsample of all whitened waveforms to a single (gigantic) file
501

502
  FILE **injWhitenedSpectrumFile      = malloc(NI*sizeof(FILE*));
Tyson Littenberg's avatar
Tyson Littenberg committed
503 504
  FILE **injWhitenedWaveformFile      = malloc(NI*sizeof(FILE*));
  FILE **injPlusWhitenedWaveformFile  = malloc(NI*sizeof(FILE*));
505
  FILE **injCrossWhitenedWaveformFile = malloc(NI*sizeof(FILE*));
Tyson Littenberg's avatar
Tyson Littenberg committed
506 507
  FILE **injColoredWaveformFile       = malloc(NI*sizeof(FILE*));
  FILE **injPlusColoredWaveformFile   = malloc(NI*sizeof(FILE*));
508
  FILE **injCrossColoredWaveformFile  = malloc(NI*sizeof(FILE*));
509 510
  FILE **whitenedInjQscanFile         = malloc(NI*sizeof(FILE*));
  FILE **injectedTfFile               = malloc(NI*sizeof(FILE*));
511
  
512 513 514 515 516 517 518 519 520 521
  /********************************/
  /*                              */
  /*  Post process data           */
  /*                              */
  /********************************/

  // read data from file made by BayesWaveBurst
  FILE *FDdata = NULL;

  // Output a subsample of all whitened waveforms to a single (gigantic) file
Meg Millhouse's avatar
Meg Millhouse committed
522 523 524
  FILE **whitenedDataFile      = malloc(NI*sizeof(FILE*));
  FILE **coloredDataFile       = malloc(NI*sizeof(FILE*));
  FILE **whitenedDataQscanFile = malloc(NI*sizeof(FILE*));
525

526
  double junk;
527
  
528 529
  for(ifo=0; ifo<NI; ifo++)
  {
530
    sprintf(filename,"waveforms/%sfourier_domain_data_%s.dat",data->runName,data->ifos[ifo]);
531 532 533

    if( (FDdata = fopen(filename,"r")) == NULL)
    {
534
      fprintf(stdout,"Could not find %s.  Filling data array with 0's\n",filename);
535
      for(i=0; i<data->N; i++) hoft[ifo][i] = 0.0;
536 537

      fclose(FDdata);
538 539 540
    }
    else
    {
541 542 543
      for(i=0; i<data->N/2; i++) fscanf(FDdata,"%lg %lg %lg",&junk,&hoft[ifo][2*i],&hoft[ifo][2*i+1]);
      fclose(FDdata);

544
      sprintf(filename,"waveforms/%sfourier_domain_residual_%s.dat",data->runName,data->ifos[ifo]);
545 546 547 548 549 550 551 552 553 554 555 556 557
      if( (FDdata = fopen(filename,"r")) == NULL)
      {
        for(i=0; i<data->N/2; i++)
        {
          roft[ifo][2*i]   = hoft[ifo][2*i];
          roft[ifo][2*i+1] = hoft[ifo][2*i+1];
        }
      }
      else
      {
        for(i=0; i<data->N/2; i++) fscanf(FDdata,"%lg %lg %lg",&junk,&roft[ifo][2*i],&roft[ifo][2*i+1]);
        fclose(FDdata);
      }
558
      fprintf(stdout, "Getting data into same format as waveforms\n");
559

560 561
    }
  }
562
  
563 564
  //print fourier-domain data and model PSD
  FILE *PSDfile=NULL;
565 566
  double dpower;
  double rpower;
567 568
  for(ifo=0; ifo<NI; ifo++)
  {
569
    sprintf(filename,"%s/gaussian_noise_model_%s.dat",outdir,data->ifos[ifo]);
570
    PSDfile = fopen(filename,"w");
571 572 573 574 575 576
    for(i=PSDimin; i<PSDimax; i++)
    {
      dpower = hoft[ifo][2*i]*hoft[ifo][2*i]+hoft[ifo][2*i+1]*hoft[ifo][2*i+1];
      rpower = roft[ifo][2*i]*roft[ifo][2*i]+roft[ifo][2*i+1]*roft[ifo][2*i+1];
      fprintf(PSDfile,"%g %g %g %g\n",(double)i/data->Tobs,dpower,rpower,psd[ifo][i]);
    }
577
    fclose(PSDfile);
578

579
    sprintf(filename,"%s/colored_data_%s.dat",outdir,data->ifos[ifo]);
580 581
    coloredDataFile[ifo] = fopen(filename,"w");

582
    sprintf(filename,"%s/whitened_data_%s.dat",outdir,data->ifos[ifo]);
583
    whitenedDataFile[ifo] = fopen(filename,"w");
Meg Millhouse's avatar
Meg Millhouse committed
584
      
585

586
  }
587
  
588
  //print time-domain data
589 590
  print_waveforms(data, hoft, psd, whitenedDataFile);
  print_waveforms(data, hoft, one, coloredDataFile);
591 592 593 594 595 596
  
  double **hdata = double_matrix(NI-1,data->N-1);
  double **htemp = double_matrix(NI-1,data->N-1);
  double **invPSD = double_matrix(NI-1,data->N/2-1);
  
  
Tyson Littenberg's avatar
Tyson Littenberg committed
597
  char datadir[MAXSTRINGSIZE];
598 599 600 601 602 603 604 605
  sprintf(datadir,"%spost/data",data->runName);
  mkdir(datadir,S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);

  for(ifo=0; ifo<NI; ifo++)
  {
    whiten_data(data->imin, data->imax, hoft[ifo], psd[ifo]);
   
    get_time_domain_waveforms(hdata[ifo], hoft[ifo], data->N, data->imin, data->imax);
Meg Millhouse's avatar
Meg Millhouse committed
606
    
607 608
    norm = sqrt((double)data->N);
    for (ii = 0; ii < data->N; ii++)  hdata[ifo][ii] /= norm;
609
    
610 611 612
    if (!lite){
      print_spectrograms(data,datadir,"data",data->ifos[ifo], hdata[ifo], one[ifo]);
    }
613 614 615 616 617 618 619
    for (ii = 0; ii < data->N/2; ii++) invPSD[ifo][ii] = 1.0/psd[ifo][ii];
    
    //recolor h(t)-- need hoft to check fourier domain residuals
    whiten_data(data->imin, data->imax, hoft[ifo], invPSD[ifo]);
  }
  
  
620 621
  for(ifo=0; ifo<NI; ifo++)
  {
622 623
    fclose(whitenedDataFile[ifo]);
    fclose(coloredDataFile[ifo]);
624
  }
625
  
626 627
  free(whitenedDataFile);
  free(coloredDataFile);
628 629 630
  free(whitenedDataQscanFile);
  
  
631

632 633 634 635 636 637 638
  /********************************/
  /*                              */
  /*  Post process injection      */
  /*                              */
  /********************************/
  if(injectionFlag)
  {
639
    
640
    fprintf(stdout, "Computing moments for injected waveform\n");
641

642
    for(ifo=0; ifo<NI; ifo++)
643
    {
644
      sprintf(filename,"%s/injected_whitened_waveform_%s.dat",outdir,data->ifos[ifo]);
645
      injWhitenedWaveformFile[ifo] = fopen(filename,"w");
646
      sprintf(filename,"%s/injected_whitened_spectrum_%s.dat",outdir,data->ifos[ifo]);
647
      injWhitenedSpectrumFile[ifo] = fopen(filename,"w");
648 649
      if(xmlInjectionFlag)
      {
650
        sprintf(filename,"%s/injected_plus_whitened_waveform_%s.dat",outdir,data->ifos[ifo]);
651
        injPlusWhitenedWaveformFile[ifo] = fopen(filename,"w");
652
        sprintf(filename,"%s/injected_cross_whitened_waveform_%s.dat",outdir,data->ifos[ifo]);
653 654
        injCrossWhitenedWaveformFile[ifo] = fopen(filename,"w");
      }
655
      
656
      sprintf(filename,"%s/injected_colored_waveform_%s.dat",outdir,data->ifos[ifo]);
657
      injColoredWaveformFile[ifo] = fopen(filename,"w");
658 659
      if(xmlInjectionFlag)
      {
660
        sprintf(filename,"%s/injected_plus_colored_waveform_%s.dat",outdir,data->ifos[ifo]);
661
        injPlusColoredWaveformFile[ifo] = fopen(filename,"w");
662
        sprintf(filename,"%s/injected_cross_colored_waveform_%s.dat",outdir,data->ifos[ifo]);
663 664
        injCrossColoredWaveformFile[ifo] = fopen(filename,"w");
      }
665 666 667
      
      sprintf(filename,"%s/injected_tf_%s.dat",outdir,data->ifos[ifo]);
      injectedTfFile[ifo] = fopen(filename,"w");
668
    }
669

670 671
    setup_output_files(NI, injectionFlag, outdir, "injection", "whitened", whitenedInjFile, data);
    setup_output_files(NI, injectionFlag, outdir, "injection", "colored", coloredInjFile, data);
672

673
    setup_output_files(-1, injectionFlag, outdir, "injection", "geocenter", geoInjFile, data);
674

675 676
    if(xmlInjectionFlag)
    {
677 678 679 680
      setup_output_files(NI, injectionFlag, outdir, "injectionPlus", "whitened", whitenedPlusInjFile,data);
      setup_output_files(NI, injectionFlag, outdir, "injectionPlus", "colored", coloredPlusInjFile, data);
      setup_output_files(NI, injectionFlag, outdir, "injectionCross", "whitened", whitenedCrossInjFile, data);
      setup_output_files(NI, injectionFlag, outdir, "injectionCross", "colored", coloredCrossInjFile,data);
681
    }
682

683 684
    for(ifo=0; ifo<NI; ifo++)
    {
685 686
      whitenedInjectionMoments->overlap[ifo] = 1.0;
      coloredInjectionMoments->overlap[ifo]  = 1.0;
687 688
      if(xmlInjectionFlag)
      {
Tyson Littenberg's avatar
Tyson Littenberg committed
689 690
        whitenedPlusInjectionMoments->overlap[ifo]  = 1.0;
        coloredPlusInjectionMoments->overlap[ifo]   = 1.0;
691 692 693
        whitenedCrossInjectionMoments->overlap[ifo] = 1.0;
        coloredCrossInjectionMoments->overlap[ifo]  = 1.0;
      }
694
    }
Tyson Littenberg's avatar
Tyson Littenberg committed
695 696
    whitenedInjectionMoments->networkOverlap = 1.0;
    coloredInjectionMoments->networkOverlap  = 1.0;
697
    geoInjectionMoments->networkOverlap = 1.0;
698

699 700
    ComputeWaveformMoments(data, hinj, psd, whitenedInjectionMoments); // INJECTION
    ComputeWaveformMoments(data, hinj, one, coloredInjectionMoments);
701 702

    /* Calculate "geocenter" */
703 704
    //ComputeGeocenterMoments(data, deltaF, deltaT, hinj[0], one[0], geoInjectionMoments);
    //print_moments(0, injectionFlag, geoInjFile, geoInjectionMoments);
Tyson Littenberg's avatar
Tyson Littenberg committed
705

706 707
    if(xmlInjectionFlag)
    {
708 709 710 711
      ComputeWaveformMoments(data, hinjPlus, psd, whitenedPlusInjectionMoments);
      ComputeWaveformMoments(data, hinjPlus, one, coloredPlusInjectionMoments);
      ComputeWaveformMoments(data, hinjCross, psd, whitenedCrossInjectionMoments);
      ComputeWaveformMoments(data, hinjCross, one, coloredCrossInjectionMoments);
712
    }
713

714 715 716
    
    // Whitened hrss is meaningless and colored SNR are meaningless
     //Swap their values in the structures so the moments files are self-contained
717 718 719 720 721 722

     for(ifo=0; ifo<NI; ifo++)
     {
     whitenedInjectionMoments->energy[ifo] = coloredInjectionMoments->energy[ifo];
     coloredInjectionMoments->snr[ifo]     = whitenedInjectionMoments->snr[ifo];
     }
723
     
Tyson Littenberg's avatar
Tyson Littenberg committed
724 725

    //Detector-by-detector moments
726 727 728 729
    for(ifo=0; ifo<NI; ifo++)
    {
      print_moments(ifo, injectionFlag, whitenedInjFile, whitenedInjectionMoments);
      print_moments(ifo, injectionFlag, coloredInjFile, coloredInjectionMoments);
730 731 732 733 734 735 736
      if(xmlInjectionFlag)
      {
        print_moments(ifo, injectionFlag, whitenedPlusInjFile, whitenedPlusInjectionMoments);
        print_moments(ifo, injectionFlag, coloredPlusInjFile, coloredPlusInjectionMoments);
        print_moments(ifo, injectionFlag, whitenedCrossInjFile, whitenedCrossInjectionMoments);
        print_moments(ifo, injectionFlag, coloredCrossInjFile, coloredCrossInjectionMoments);
      }
737
    }
738

739
    //Print injected time-domain waveforms (and their + and x polarizations if possible)
740 741
    if(xmlInjectionFlag)
    {
742
      
743 744 745 746 747 748
      //LALinference injections are windowed to improve FFTs to the time domain
      double **windowed_injection = malloc(NI*sizeof(double*));
      for(ifo=0; ifo<NI; ifo++) windowed_injection[ifo] = malloc(N*sizeof(double));
      //Window and output hinj in the time domain
      print_waveforms(data, windowed_injection, psd, injWhitenedWaveformFile);
      print_waveforms(data, windowed_injection, one, injColoredWaveformFile);
749
      print_spectrum(data, windowed_injection, injWhitenedSpectrumFile);
750 751 752 753 754 755
      //Window and output hinjPlus in the time domain
      print_waveforms(data, windowed_injection, psd, injPlusWhitenedWaveformFile);
      print_waveforms(data, windowed_injection, one, injPlusColoredWaveformFile);
      //Window and output hinjCross in the time domain
      print_waveforms(data, windowed_injection, psd, injCrossWhitenedWaveformFile);
      print_waveforms(data, windowed_injection, one, injCrossColoredWaveformFile);
756
        
757 758 759
      for (ifo = 0; ifo < NI; ifo++)
      {
        for (i = 0; i<data->N; i++)  hinj_white[ifo][i] = hinj[ifo][i];
760
        
761 762 763 764 765 766
        whiten_data(data->imin, data->imax, hinj_white[ifo], psd[ifo]);
        
        get_time_domain_waveforms(htemp[ifo], hinj_white[ifo], data->N, data->imin, data->imax);
        
        print_spectrograms(data,outdir,"injected",data->ifos[ifo], htemp[ifo], one[ifo]);
       }
767 768 769 770 771
    }
    else
    {
      print_waveforms(data, hinj, psd, injWhitenedWaveformFile);
      print_waveforms(data, hinj, one, injColoredWaveformFile);
772
      
773
      print_spectrum(data, hinj, injWhitenedSpectrumFile);
774 775 776 777
      
      
      for (ifo = 0; ifo < NI; ifo++)
      {
778
        
779
        for (i = 0; i<data->N; i++) hinj_white[ifo][i] = hinj[ifo][i];
780
        
781 782 783
        whiten_data(data->imin, data->imax, hinj_white[ifo], psd[ifo]);
        
        get_time_domain_waveforms(htemp[ifo], hinj_white[ifo], data->N, data->imin, data->imax);
784
        
785
        print_spectrograms(data,outdir,"injected",data->ifos[ifo], htemp[ifo], one[ifo]);
786

787 788 789
        // injected tf
        tf_tracks(htemp[ifo], hinj_white[ifo], deltaT, data->N);
        for (i = 0; i < data->N; i++)   fprintf(injectedTfFile[ifo],"%g %g\n",i*deltaT,hinj_white[ifo][i]);
790
        
791
      }
792
    }
793 794 795

    for(ifo=0; ifo<NI; ifo++)
    {
796 797
      fclose(injWhitenedWaveformFile[ifo]);
      fclose(injColoredWaveformFile[ifo]);
798 799
      fclose(whitenedInjFile[ifo]);
      fclose(coloredInjFile[ifo]);
800 801 802 803 804 805 806 807 808 809
      if(xmlInjectionFlag)
      {
        fclose(injPlusWhitenedWaveformFile[ifo]);
        fclose(injCrossWhitenedWaveformFile[ifo]);
        fclose(injPlusColoredWaveformFile[ifo]);
        fclose(injCrossColoredWaveformFile[ifo]);
        fclose(whitenedPlusInjFile[ifo]);
        fclose(whitenedCrossInjFile[ifo]);
        fclose(coloredPlusInjFile[ifo]);
        fclose(coloredCrossInjFile[ifo]);
Meg Millhouse's avatar
Meg Millhouse committed
810
          fclose(injectedTfFile[ifo]);
811
      }
812
    }
813 814 815

    fclose(geoInjFile[0]);
    free(geoInjFile);
816

817 818
    free(injWhitenedWaveformFile);
    free(injColoredWaveformFile);
819 820
    free(whitenedInjFile);
    free(coloredInjFile);
821 822 823 824 825 826 827 828 829 830
    if(xmlInjectionFlag)
    {
      free(injPlusWhitenedWaveformFile);
      free(injCrossWhitenedWaveformFile);
      free(injPlusColoredWaveformFile);
      free(injCrossColoredWaveformFile);
      free(whitenedPlusInjFile);
      free(whitenedCrossInjFile);
      free(coloredPlusInjFile);
      free(coloredCrossInjFile);
Meg Millhouse's avatar
Meg Millhouse committed
831
        free(injectedTfFile);
832 833
        
        
834
    }
835
      free(whitenedInjQscanFile);
Tyson Littenberg's avatar
Tyson Littenberg committed
836
      free_double_matrix(htemp,NI-1);
837
      
838 839 840

  }

841 842 843 844
  /***************************************/
  /*                                     */
  /*  Post process signal+glitch model   */
  /*                                     */
845 846 847 848 849 850 851
  /***************************************/
  if(data->fullModelFlag)
  {
    post_process_model("full", "signal", data, model, chain, hdata, hoft, psd, one, hinj, dimension, injectionFlag, GPStrig, lite);
    post_process_model("full", "glitch", data, model, chain, hdata, hoft, psd, one, hinj, dimension, injectionFlag, GPStrig, lite);
    post_process_model("full", "full",   data, model, chain, hdata, hoft, psd, one, hinj, dimension, injectionFlag, GPStrig, lite);
  }
852 853 854 855 856 857
  
  /***************************************/
  /*                                     */
  /*  Post process signal model          */
  /*                                     */
  /***************************************/
858
  if(data->signalModelFlag) post_process_model("signal", "signal", data, model, chain, hdata, hoft, psd, one, hinj, dimension, injectionFlag, GPStrig, lite);
859 860
 

861 862 863 864 865
  /***************************************/
  /*                                     */
  /*  Post process glitch model          */
  /*                                     */
  /***************************************/
866
  if(data->glitchModelFlag) post_process_model("glitch", "glitch", data, model, chain, hdata, hoft, psd, one, hinj, dimension, injectionFlag, GPStrig, lite);
867 868

  
869 870 871 872 873
  /*****************************************/
  /*                                       */
  /*  Post process cleaning phase          */
  /*                                       */
  /*****************************************/
874
  if(data->cleanModelFlag) post_process_model("clean", "glitch", data, model, chain, hdata, hoft, psd, one, hinj, dimension, injectionFlag, GPStrig, lite);
875

876
  
877 878 879 880 881
  /*****************************************/
  /*                                       */
  /*  Post process noise phase             */
  /*                                       */
  /*****************************************/
882
  if(data->noiseModelFlag) post_process_model("noise", "noise", data, model, chain, hdata, hoft, psd, one, hinj, dimension, injectionFlag, GPStrig, lite);
883 884
  
  
885 886 887 888 889
  /*****************************************/
  /*                                       */
  /*  Free memory, exit cleanly            */
  /*                                       */
  /*****************************************/
890 891 892 893
  
  free_double_matrix(hdata,NI-1);
  
  if(data->nukeFlag)
894
  {
895
    fprintf(stdout, " ======= rm'ing chains/ and checkpoint/ ======\n");
Tyson Littenberg's avatar
Tyson Littenberg committed
896
    char command[MAXSTRINGSIZE];
897 898
    sprintf(command,"rm -rvf chains checkpoint");
    system(command);
899
  }
900 901 902 903 904 905
  
  fprintf(stdout, " ======= DONE! ======\n");
  
  return 0;
  
}
906

907

908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
void print_help_message(void)
{
  fprintf(stdout,"\n ======== BayesWavePost USAGE: =======\n\n");
  fprintf(stdout,"REQUIRED:\n");
  fprintf(stdout,"  --ifo IFO              interferometer (H1,L1,V1)\n");
  fprintf(stdout,"  --IFO-flow             minimum frequency (Hz)\n");
  fprintf(stdout,"  --IFO-cache LALAdLIGO  lie about the PSD\n");
  fprintf(stdout,"  --trigtime             GPS trigger time\n");
  fprintf(stdout,"  --srate                sampling rate (Hz)\n");
  fprintf(stdout,"  --seglen               duration of data (s)\n");
  fprintf(stdout,"  --PSDstart             GPS start time for PSD estimation\n");
  fprintf(stdout,"  --PSDlength            duration of PSD estimation length\n");
  fprintf(stdout,"  --dataseed 1234        Lie about random seed for data\n");
  fprintf(stdout,"  --0noise               no noise realization\n");
  fprintf(stdout,"\n");
  fprintf(stdout,"OPTIONAL:\n");
  fprintf(stdout,"  ----------------------------------------------------------------------------------\n");
  fprintf(stdout,"  --- Run parameters   -------------------------------------------------------------\n");
  fprintf(stdout,"  ----------------------------------------------------------------------------------\n");
  fprintf(stdout,"  --runName              run name for output files\n");
  fprintf(stdout,"  --nuke                 delete chains/ and checkpoint/ when done [NOT RECOMMENDED]\n");
  fprintf(stdout,"\n");
  fprintf(stdout,"  ----------------------------------------------------------------------------------\n");
  fprintf(stdout,"  --- Model parameters   -----------------------------------------------------------\n");
  fprintf(stdout,"  ----------------------------------------------------------------------------------\n");
  fprintf(stdout,"  --bayesLine            use BayesLine for PSD model\n");
  fprintf(stdout,"\n");
  fprintf(stdout,"  ----------------------------------------------------------------------------------\n");
  fprintf(stdout,"  --- LALInference injection  options  ---------------------------------------------\n");
  fprintf(stdout,"  ----------------------------------------------------------------------------------\n");
  fprintf(stdout,"  --inj injfile.xml      Injection XML file to use\n");
  fprintf(stdout,"  --event N              Event number from Injection XML file to use\n");
  fprintf(stdout,"\n");
  fprintf(stdout,"  ----------------------------------------------------------------------------------\n");
  fprintf(stdout,"  --- Burst MDC injection  options  ------------------------------------------------\n");
  fprintf(stdout,"  ----------------------------------------------------------------------------------\n");
  fprintf(stdout,"  --MDC-channel          IFO1-chan, IFO2-chan, etc\n");
  fprintf(stdout,"  --MDC-cache            IFO1-mdcframe, IFO2-mdcframe, etc\n");
  fprintf(stdout,"  --MDC-prefactor        Rescale injection amplitude (1.0)\n");
  fprintf(stdout,"\n");
  fprintf(stdout,"  ----------------------------------------------------------------------------------\n");
  fprintf(stdout,"  --- BayesWave internal injection options  ----------------------------------------\n");
  fprintf(stdout,"  ----------------------------------------------------------------------------------\n");
  fprintf(stdout,"  --BW-inject            (signal/glitch)\n");
  fprintf(stdout,"  --BW-injName           runName that produced the chain file \n");
  fprintf(stdout,"  --BW-path              Path to BW chain file for injection (./chains) \n");
  fprintf(stdout,"  --BW-event             Which sample from BayesWave chain (200000)\n");
  fprintf(stdout,"\n");
  fprintf(stdout,"EXAMPLE:\n");
  fprintf(stdout,"./bayeswave_post --ifo H1 --H1-flow 32 --H1-cache LALSimAdLIGO --H1-channel LALSimAdLIGO --trigtime 900000000.00 --srate 512 --seglen 4 --PSDstart 900000000 --PSDlength 1024 --dataseed 1234 --0noise\n");
  fprintf(stdout,"\n");
}
960 961


962

963 964 965 966 967
void ComputeWaveformOverlap(struct Data *data, double **hinj, double **hrec, double **psd, struct Moments *m)
{
  int N = data->N;
  int NI = data->NI;
  int imin = data->imin;
968

969
  int ifo,n;
970

971 972
  double **invpsd = malloc(NI*sizeof(double *));
  for(ifo=0; ifo<NI; ifo++) invpsd[ifo] = malloc(N/2*sizeof(double));
973

974 975 976 977
  //get input waveform into right format (either colored or whitened)
  for(ifo=0; ifo<NI; ifo++)
  {
    for(n=0; n<N/2; n++)
Tyson Littenberg's avatar
Tyson Littenberg committed
978 979 980 981
    {
      invpsd[ifo][n] = 1/psd[ifo][n];
    }
  }
982

983 984 985 986 987 988
  double hihi; //Detector (hinj|hinj)
  double hrhr; //Detector (hrec|hrec)
  double hrhi; //Detector (hrec|hinj)
  double ii=0; //Network (hinj|hinj)
  double rr=0; //Network (hrec|hrec)
  double ri=0; //Network (hrec|hinj)
989 990 991

  for(ifo=0; ifo<NI; ifo++)
  {
992 993 994
    hihi = fourier_nwip(imin, N/2, hinj[ifo], hinj[ifo], invpsd[ifo]);
    hrhr = fourier_nwip(imin, N/2, hrec[ifo], hrec[ifo], invpsd[ifo]);
    hrhi = fourier_nwip(imin, N/2, hrec[ifo], hinj[ifo], invpsd[ifo]);
995

996 997 998 999
    ii += hihi;
    rr += hrhr;
    ri += hrhi;

1000
    //Store inj-rec overlap of each detector to file
1001
    m->overlap[ifo] =  hrhi/sqrt(hihi*hrhr); // (hrec|hinj)/sqrt((hrec|hrec)(hinj|hinj))
1002
  }
1003 1004

  //Store inj-rec networ overlap to file
1005
  m->networkOverlap = ri/sqrt(ii*rr); // (hrec|hinj)/sqrt((hrec|hrec)(hinj|hinj))
Tyson Littenberg's avatar
Tyson Littenberg committed
1006 1007 1008 1009

  for(ifo=0; ifo<NI; ifo++) free(invpsd[ifo]);
  free(invpsd);

1010 1011
}

1012
void PrintRhof(struct Data *data, double deltaF, double **h, double **psd, struct Moments *m){
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
  int N = data->N;
  int NI = data->NI;
  int imin = data->imin;
  int imax = data->imax;
  int i;

  int ifo,n;
  double *rho = malloc(N*sizeof(double));
  double **wf = malloc(NI*sizeof(double *));

  double **invPSD = malloc(NI*sizeof(double *));

  for(ifo=0; ifo<NI; ifo++)
  {
    wf[ifo]=malloc(N*sizeof(double));

    invPSD[ifo] = malloc(N/2*sizeof(double));
  }

  //get input waveform into right format (either colored or whitened)
  for(ifo=0; ifo<NI; ifo++)
  {
    for(n=0; n<N/2; n++)
1036
    {
1037 1038 1039
      invPSD[ifo][n] = 1/psd[ifo][n];
      wf[ifo][2*n]   = h[ifo][2*n]/sqrt(psd[ifo][n]);
      wf[ifo][2*n+1] = h[ifo][2*n+1]/sqrt(psd[ifo][n]);
1040
    }
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
  }

  for(ifo=0; ifo<=NI; ifo++)
  {
    /*
     RECOVERED SIGNAL ENERGY
     */
    if(ifo<NI) m->energy[ifo] = get_rhof(imin, imax, wf[ifo], deltaF, rho);
    else m->energy[ifo] = get_rhof_net(imin, imax, wf, deltaF, rho, NI);

    // *********** print rho **************** //


    if(ifo==0){ // do only for H1
      printf("\n\n\n");
      for (i=0; i<imax; i+=10) {
        printf("%g %g\n",(double)i*deltaF,rho[i]);
      }
      printf("\n\n\n");
1060
    }
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074

  }

  for(ifo=0; ifo<NI; ifo++)
  {
    free(wf[ifo]);

    free(invPSD[ifo]);
  }
  free(rho);
  free(wf);

  free(invPSD);

1075 1076
}

1077

1078
void ComputeWaveformMoments(struct Data *data, double **h, double **psd, struct Moments *m)
1079 1080 1081 1082 1083 1084
{
  int N = data->N;
  int NI = data->NI;
  int imin = data->imin;
  int imax = data->imax;

1085 1086 1087
  double deltaT = data->Tobs/(double)N;
  double deltaF = 1./data->Tobs;
  
1088 1089
  int ifo,n;
  double *rho = malloc(N*sizeof(double));
Tyson Littenberg's avatar
Tyson Littenberg committed
1090
  double **wt = malloc(NI*sizeof(double *));
1091
  double **wf = malloc(NI*sizeof(double *));
1092

1093 1094
  double **invPSD = malloc(NI*sizeof(double *));

Tyson Littenberg's avatar
Tyson Littenberg committed
1095 1096 1097 1098
  for(ifo=0; ifo<NI; ifo++)
  {
    wt[ifo]=malloc(N*sizeof(double));
    wf[ifo]=malloc(N*sizeof(double));
1099 1100

    invPSD[ifo] = malloc(N/2*sizeof(double));
Tyson Littenberg's avatar
Tyson Littenberg committed
1101
  }
1102 1103 1104 1105 1106 1107

  //get input waveform into right format (either colored or whitened)
  for(ifo=0; ifo<NI; ifo++)
  {
    for(n=0; n<N/2; n++)
    {
1108
      invPSD[ifo][n] = 1/psd[ifo][n];
1109 1110
      wf[ifo][2*n]   = h[ifo][2*n]/sqrt(psd[ifo][n]);
      wf[ifo][2*n+1] = h[ifo][2*n+1]/sqrt(psd[ifo][n]);
1111
        
1112
    }
1113

Tyson Littenberg's avatar
Tyson Littenberg committed
1114 1115
    //transform waveform into time-domain
    get_time_domain_waveforms(wt[ifo], wf[ifo], N, imin, imax);
1116 1117
  }

1118
  //SNR
1119
  for(ifo=0; ifo<NI; ifo++) m->snr[ifo] = detector_snr(imin, imax, h[ifo], invPSD[ifo], 1.0);
1120 1121 1122 1123 1124 1125 1126

  /******************************/
  /*                            */
  /*  Frequency domain moments  */
  /*                            */
  /******************************/

Tyson Littenberg's avatar
Tyson Littenberg committed
1127
  for(ifo=0; ifo<=NI; ifo++)
1128 1129 1130 1131
  {
    /*
     RECOVERED SIGNAL ENERGY
     */
Tyson Littenberg's avatar
Tyson Littenberg committed
1132 1133 1134 1135
    if(ifo<NI)
      m->energy[ifo] = get_rhof(imin, imax, wf[ifo], deltaF, rho);
    else
      m->energy[ifo] = get_rhof_net(imin, imax, wf, deltaF, rho, NI);
1136

1137 1138 1139
      
      
      
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
    /*
     RECOVERED CENTRAL FREQUENCY
     */
    m->frequency[ifo] = get_f0(imax, rho, deltaF);


    /*
     RECOVERED BANDWIDTH
     */
    m->bandwidth[ifo] = get_band(imax, rho, deltaF, m->frequency[ifo]);
1150

1151
    /* Median f and 90% interval bw */
1152
    //get_f_quantiles(imin, imax, rho, deltaF, &fmedtemp, &bwtemp);
1153

1154 1155
    //m->medianfrequency[ifo] = fmedtemp;
    //m->bandwidth90percentinterval[ifo] = bwtemp;
1156 1157


1158 1159 1160
  }


Tyson Littenberg's avatar
Tyson Littenberg committed
1161

1162 1163 1164 1165 1166 1167
  /******************************/
  /*                            */
  /*     Time domain moments    */
  /*                            */
  /******************************/

Tyson Littenberg's avatar
Tyson Littenberg committed
1168
  for(ifo=0; ifo<=NI; ifo++)
1169 1170 1171 1172
  {
    /*
     RECOVERED SIGNAL ENERGY
     */
Tyson Littenberg's avatar
Tyson Littenberg committed
1173 1174 1175 1176
    if(ifo<NI)
      m->energy[ifo] = get_rhot(N, wt[ifo], deltaT, rho);
    else
      m->energy[ifo] = get_rhot_net(N, wt, deltaT, rho, NI);
1177 1178
      
      
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188

    /*
     RECOVERED CENTRAL TIME
     */
    m->time[ifo] = get_f0(N, rho, deltaT);

    /*
     RECOVERED WAVEFORM DURATION
     */
    m->duration[ifo] = get_band(N, rho, deltaT, m->time[ifo]);
1189

1190 1191 1192 1193
    /*
     Median t and quantiles
     */

1194 1195 1196
    //get_t_quantiles(N, rho, deltaT, &tmedtemp, &durtemp);
    //m->mediantime[ifo] = tmedtemp;
    //m->duration90percentinterval[ifo] = durtemp;
1197 1198


1199 1200 1201 1202 1203 1204 1205 1206 1207

    /*
     WAVEFORM MAXIMUM AND TIME AT MAXIMUM
     */
    if(ifo<NI)
    {
      get_hmax_and_t(N, wt[ifo], deltaT, &m->hmax[ifo], &m->t_at_hmax[ifo]);
    }

1208 1209 1210 1211 1212 1213 1214 1215 1216
    /*
      Frquency at maximum amplitude                                                                                                                                    
    */
    if(ifo<NI)
    {
      get_freq_at_max(wf[ifo], N, imin, imax, deltaT, &m->f_at_max_amp[ifo]);
    }


1217 1218 1219
  }


Tyson Littenberg's avatar
Tyson Littenberg committed
1220 1221 1222 1223
  for(ifo=0; ifo<NI; ifo++)
  {
    free(wf[ifo]);
    free(wt[ifo]);
1224 1225

    free(invPSD[ifo]);
Tyson Littenberg's avatar
Tyson Littenberg committed
1226
  }
1227 1228 1229 1230
  free(rho);
  free(wt);
  free(wf);

1231 1232 1233 1234 1235 1236 1237 1238 1239
  free(invPSD);

}

void ComputeGeocenterMoments(struct Data *data, double deltaF, double deltaT, double *h, double *psd, struct Moments *m)
{
  int N = data->N;
  int imin = data->imin;
  int imax = data->imax;
Tyson Littenberg's avatar
Tyson Littenberg committed
1240
  double tmedtemp, durtemp, fmedtemp, bwtemp;