Logo Coherent WaveBurst  
Reference Guide
Logo
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
Toolbox.cc
Go to the documentation of this file.
1 #include "Toolbox.hh"
2 #include "watversion.hh"
3 #include "TTreeFormula.h"
4 #include "GToolbox.hh"
5 #include "TThread.h"
6 #include <Riostream.h>
7 
8 #define CCAST(PAR) const_cast<char*>(PAR) \
9 
10 // Without this macro the THtml doc for CWB::Toolbox can not be generated
11 ClassImp(CWB::Toolbox)
12 
13 int compareSegments(waveSegment a, waveSegment b) {return a.start < b.start;}
14 
15 // definitions used by CWB::Toolbox::mergeCWBTrees with threads
16 
17 #define MAX_THREADS 16
18 
19 #define MAX_TREE_SIZE 100000000000LL
20 
21 struct MergeParms {
22  int threadID;
23  vector<TString> fileList;
24  bool simulation;
25  TString odir;
26  TString label;
27  bool brms;
28  bool bvar;
29  bool bpsm;
30 };
31 
32 void *MergeHandle(void *ptr) {
33 
34  MergeParms mp = *((MergeParms*) ptr);
35 
36  // dump thread file list
37  char ofName[1024];
38  sprintf(ofName,"%s/mergeList.T%d.txt",mp.odir.Data(),mp.threadID);
39 
40  CWB::Toolbox::dumpFileList(mp.fileList, ofName);
41 
42  // exec macro merge
43  char cmd[1024];
44  sprintf(cmd,"root -l -b '%s/cwb_merge_thread.C(\"%s\",%d,\"%s\",\"%s\",%d,%d,%d)'",
45  gSystem->ExpandPathName("$CWB_MACROS"), ofName, mp.simulation,
46  mp.odir.Data(), mp.label.Data(), mp.brms, mp.bvar, mp.bpsm);
47  gSystem->Exec(cmd);
48 
49  // remove thread file list
50  gSystem->Exec(TString::Format("rm %s",ofName));
51 
52  return 0;
53 }
54 
55 //______________________________________________________________________________
56 vector<waveSegment>
58 //
59 // read segment list from file
60 //
61 // Input: ifile - input file name
62 //
63 // Output: return the waveSegment list
64 //
65 
66  // Open file segment list
67  ifstream in;
68  in.open(ifile.Data(),ios::in);
69  if(!in.good()) {
70  cout << "CWB::Toolbox::readSegments - Error Opening File : " << ifile << endl;
71  gSystem->Exit(1);
72  }
73 
74  char str[1024];
75  int fpos=0;
76  int index=0;
77  double start;
78  double stop;
80  vector<waveSegment> iseg;
81  while (1) {
82  fpos=in.tellg();
83  in.getline(str,1024);
84  if(str[0] == '#') continue;
85  in.seekg(fpos, ios::beg);
86  fpos=in.tellg();
87 
88  in >> start >> stop;
89  if (!in.good()) break;
90 
91  seg.index=index++; seg.start=start; seg.stop=stop; iseg.push_back(seg);
92  }
93 
94  in.close();
95 
96  return iseg;
97 }
98 
99 //______________________________________________________________________________
100 vector<waveSegment>
101 CWB::Toolbox::unionSegments(vector<waveSegment>& ilist) {
102 //
103 // Join & sort a waveSegment list
104 //
105 // Input: ilist - waveSegment list
106 //
107 // Output: return the joined waveSegment list
108 //
109 // ilist
110 // xxxxxxxx xxxxx
111 // xxxxxxxx xxx xxx
112 //
113 // output list
114 // xxxxxxxxxxxxx xxxxxxx xxx
115 //
116 
117  vector<waveSegment> vsegs;
118  int n = ilist.size();
119  if(n==0) return vsegs;
120 
121  waveSegment* isegs = new waveSegment[n];
122  waveSegment* osegs = new waveSegment[n+1];
123 
124  for(int i=0;i<n+1;i++) {osegs[i].start=0;osegs[i].stop=0;}
125  for(int i=0;i<n;i++) {
126  if(ilist[i].start>ilist[i].stop) {
127  cout << "CWB::Toolbox::unionSegments - Error : start must be <= stop - start = "
128  << ilist[i].start << " stop = " << ilist[i].stop << endl;
129  exit(1);
130  }
131  if(ilist[i].start<0) {
132  cout << "CWB::Toolbox::unionSegments - Error : start must be positive - start = "
133  << ilist[i].start << endl;
134  exit(1);
135  }
136  isegs[i] = ilist[i];
137  }
138 
139  std::sort(isegs, isegs + n, compareSegments);
140  double right_most = -1;
141  int cnt = 0;
142  for (int i = 0 ; i < n ; i++) {
143  if (isegs[i].start > right_most) {
144  right_most = isegs[i].stop;
145  ++cnt;
146  osegs[cnt].start = isegs[i].start;
147  osegs[cnt].stop = isegs[i].stop;
148  }
149  if (isegs[i].stop > right_most) {
150  right_most = isegs[i].stop;
151  osegs[cnt].stop = isegs[i].stop;
152  }
153  }
154 
155  int vcnt=0;
157  for(int i=0;i<cnt+1;i++) if(osegs[i].stop>0) {seg=osegs[i];seg.index=vcnt++;vsegs.push_back(seg);}
158 
159  delete [] isegs;
160  delete [] osegs;
161 
162  return vsegs;
163 }
164 
165 //______________________________________________________________________________
166 vector<waveSegment>
167 CWB::Toolbox::sortSegments(vector<waveSegment>& ilist) {
168 //
169 // sort a waveSegment list
170 //
171 // Input: ilist - waveSegment list
172 //
173 // Output: return the sorted waveSegment list
174 //
175 
176  int size = ilist.size();
177 
178  double* start = new double[size];
179  double* stop = new double[size];
180  for(int i=0;i<size;i++) {
181  start[i] = ilist[i].start;
182  stop[i] = ilist[i].stop;
183  }
184 
185 // sort list
186 
187  Int_t *id = new Int_t[size];
188  TMath::Sort(size,start,id,false);
189  for(int i=1;i<size;i++) {
190  bool flag=true;
191  if(start[id[i]]<=0) flag=false;
192  if(start[id[i]]>stop[id[i]]) flag=false;
193  if(start[id[i]]<stop[id[i-1]]) flag=false;
194  if(!flag) {
195  cout.precision(14);
196  cout << "CWB::Toolbox::invertSegments - Error in segment list (duplicated veto) : " << endl;
197  cout << id[i-1]+1 << " " << start[id[i-1]] << " " << stop[id[i-1]] << " flag " << flag << endl;
198  cout << id[i]+1 << " " << start[id[i]] << " " << stop[id[i]] << " flag " << flag << endl;
199  gSystem->Exit(1);
200  }
201  }
202 
203 // write list to output vector
204 
205  vector<waveSegment> olist;
206  double ctime=0.;
208  SEG.index = 0;
209  olist.clear();
210 
211  // sort list
212  for(int i=0;i<size;i++) {
213  SEG.index++;
214  SEG.start = start[id[i]];
215  SEG.stop = stop[id[i]];
216  ctime+=stop[id[i]]-start[id[i]];
217  olist.push_back(SEG);
218  }
219 
220  delete [] id;
221  delete [] start;
222  delete [] stop;
223 
224  return olist;
225 }
226 
227 //______________________________________________________________________________
228 vector<waveSegment>
229 CWB::Toolbox::invertSegments(vector<waveSegment>& ilist) {
230 //
231 // invert a waveSegment list
232 //
233 // Input: ilist - waveSegment list
234 //
235 // Output: return the inverted waveSegment list
236 //
237 // ilist
238 // xxxxxxxx xxxxx
239 //
240 // output list
241 // xxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxx
242 //
243 
244  int size = ilist.size();
245 
246  double* start = new double[size];
247  double* stop = new double[size];
248  for(int i=0;i<size;i++) {
249  start[i] = ilist[i].start;
250  stop[i] = ilist[i].stop;
251  }
252 
253 // sort list
254 
255  Int_t *id = new Int_t[size];
256  TMath::Sort(size,start,id,false);
257  for(int i=1;i<size;i++) {
258  bool flag=true;
259  if(start[id[i]]<=0) flag=false;
260  if(start[id[i]]>stop[id[i]]) flag=false;
261  if(start[id[i]]<stop[id[i-1]]) flag=false;
262  if(!flag) {
263  cout.precision(14);
264  cout << "CWB::Toolbox::invertSegments - Error in segment list (duplicated veto) : " << endl;
265  cout << id[i-1]+1 << " " << start[id[i-1]] << " " << stop[id[i-1]] << " flag " << flag << endl;
266  cout << id[i]+1 << " " << start[id[i]] << " " << stop[id[i]] << " flag " << flag << endl;
267  gSystem->Exit(1);
268  }
269  }
270 
271 // write list to output vector
272 
273  vector<waveSegment> olist;
274  double ctime=0.;
276  SEG.index = 0;
277  olist.clear();
278 
279  // invert bad with good periods
280  SEG.index++;
281  SEG.start = 0;
282  SEG.stop = start[id[0]];
283  olist.push_back(SEG);
284  for(int i=0;i<size-1;i++) {
285  SEG.index++;
286  SEG.start = stop[id[i]];
287  SEG.stop = start[id[i+1]];
288  ctime+=SEG.stop-SEG.start;
289  olist.push_back(SEG);
290  }
291  SEG.index++;
292  SEG.start = stop[id[size-1]];
293  SEG.stop = 4000000000;
294  olist.push_back(SEG);
295 
296  delete [] id;
297  delete [] start;
298  delete [] stop;
299 
300  return olist;
301 }
302 
303 //______________________________________________________________________________
304 void
305 CWB::Toolbox::blackmanharris (double* window, int n) {
306 //
307 // blackmanharris window
308 //
309 // Input/Output - window - array of double intialized (must be initialized)
310 // return the window values
311 // Input - n - window length
312 //
313 
314  for (int i = 0; i < n; i++)
315  {
316  double f = 0.0;
317  f = ((double) i) / ((double) (n - 1));
318  window[i] = 0.35875 -
319  0.48829 * cos(2.0 * TMath::Pi() * f) +
320  0.14128 * cos(4.0 * TMath::Pi() * f) -
321  0.01168 * cos(6.0 * TMath::Pi() * f);
322  }
323 
324  double norm = 0;
325  for (int i=0;i<n;i++) norm += pow(window[i],2);
326  norm /= n;
327  for (int i=0;i<n;i++) window[i] /= sqrt(norm);
328 }
329 
330 //______________________________________________________________________________
331 vector<waveSegment>
332 CWB::Toolbox::mergeSegLists(vector<waveSegment>& ilist1, vector<waveSegment>& ilist2) {
333 //
334 // Merge 2 segment lists
335 // NOTE : the input lists must be sorted !!!
336 //
337 // Input: ilist1 - first waveSegment list
338 // ilist2 - second waveSegment list
339 //
340 // Output: return the merged waveSegment list
341 //
342 // ilist1
343 // xxxxxxxx xxxxxxxxxxxx
344 //
345 // ilist2
346 // xxxx xxxxxx xxx
347 //
348 // olist
349 // xxx xxxxx
350 //
351 
352  int i=0;
353  int j=0;
354  int n1=ilist1.size();
355  int n2=ilist2.size();
356  double ctime=0;
357  double start=0;
358  double stop=0;
359 
360  vector<waveSegment> olist;
362  SEG.index = 0;
363 
364  while (i<n1 && j<n2) {
365  if (ilist2[j].stop<=ilist1[i].start) j++;
366  else if (ilist1[i].stop <= ilist2[j].start) i++;
367  else {
368  if (ilist2[j].start < ilist1[i].start) start=ilist1[i].start;
369  else start = ilist2[j].start;
370  if (ilist2[j].stop > ilist1[i].stop) stop=ilist1[i].stop;
371  else stop=ilist2[j].stop;
372  if (ilist2[j].stop >= ilist1[i].stop) i++;
373  else j++;
374  ctime+=stop-start;
375 
376  SEG.index++;
377  SEG.start = start;
378  SEG.stop = stop;
379  olist.push_back(SEG);
380  }
381  }
382 
383  //ilist2=olist;
384  //olist.clear();
385 
386  return olist;
387 }
388 
389 //______________________________________________________________________________
390 vector<waveSegment>
392 //
393 // Read DQ file
394 // Format A : #entry start stop stop-start
395 // Format B : start stop
396 // list is sorted, check if start<stop, check if entries are overlapped
397 //
398 // Input: DQF - DQ structure
399 //
400 // Output: return the list of time ranges
401 //
402 
403  vector<waveSegment> olist;
404 
405 // Open list
406 
407  ifstream in;
408  in.open(DQF.file,ios::in);
409  if (!in.good()) {cout << "CWB::Toolbox::readSegList - Error Opening File : " << DQF.file << endl;gSystem->Exit(1);}
410 
411  int size=0;
412  char str[1024];
413  int fpos=0;
414  while(true) {
415  in.getline(str,1024);
416  if (!in.good()) break;
417  if(str[0] != '#') size++;
418  }
419  //cout << "size " << size << endl;
420  in.clear(ios::goodbit);
421  in.seekg(0, ios::beg);
422  if (size==0) {cout << "CWB::Toolbox::readSegList - Error : File " << DQF.file << " is empty" << endl;gSystem->Exit(1);}
423 
424  int N=0;
425  float dummy;
426  double* start = new double[size];
427  double* stop = new double[size];
428  while (1) {
429  fpos=in.tellg();
430  in.getline(str,1024);
431  if(str[0] == '#') continue;
432  in.seekg(fpos, ios::beg);
433  fpos=in.tellg();
434 
435  if(DQF.c4) in >> dummy >> start[N] >> stop[N] >> dummy;
436  else in >> start[N] >> stop[N];
437  if (!in.good()) break;
438  start[N]+=DQF.shift;
439  stop[N]+=DQF.shift;
440  if(stop[N]<=start[N]) {
441  cout.precision(14);
442  cout << "CWB::Toolbox::readSegList - Error Ranges : " << start[N] << " " << stop[N] << endl;
443  gSystem->Exit(1);
444  }
445  N++;
446  if(N>size) {
447  cout << "CWB::Toolbox::readSegList - Error Max Range : " << N << " " << size << endl;
448  gSystem->Exit(1);
449  }
450  }
451  in.close();
452 
453 // sort list
454 
455  Int_t *id = new Int_t[N];
456  TMath::Sort(N,start,id,false);
457  for(int i=1;i<N;i++) {
458  bool flag=true;
459  if(start[id[i]]<=0) flag=false;
460  if(start[id[i]]>stop[id[i]]) flag=false;
461  if(start[id[i]]<stop[id[i-1]]) flag=false;
462  if(!flag) {
463  cout.precision(14);
464  cout << "CWB::Toolbox::readSegList - Error in segment list file (duplicated veto) : " << DQF.file << endl;
465  cout << id[i-1]+1 << " " << start[id[i-1]] << " " << stop[id[i-1]] << " flag " << flag << endl;
466  cout << id[i]+1 << " " << start[id[i]] << " " << stop[id[i]] << " flag " << flag << endl;
467  gSystem->Exit(1);
468  }
469  }
470 
471 // write list to output vector
472 
473  double ctime=0.;
475  SEG.index = 0;
476  olist.clear();
477  if(DQF.invert) { // invert bad with good periods
478  SEG.index++;
479  SEG.start = 0;
480  SEG.stop = start[id[0]];
481  olist.push_back(SEG);
482  for(int i=0;i<N-1;i++) {
483  SEG.index++;
484  SEG.start = stop[id[i]];
485  SEG.stop = start[id[i+1]];
486  ctime+=SEG.stop-SEG.start;
487  olist.push_back(SEG);
488  }
489  SEG.index++;
490  SEG.start = stop[id[N-1]];
491  SEG.stop = 4000000000;
492  olist.push_back(SEG);
493  } else {
494  for(int i=0;i<N;i++) {
495  SEG.index++;
496  SEG.start = start[id[i]];
497  SEG.stop = stop[id[i]];
498  ctime+=stop[id[i]]-start[id[i]];
499  olist.push_back(SEG);
500  }
501  }
502 
503  delete [] id;
504  delete [] start;
505  delete [] stop;
506 
507  return olist;
508 }
509 
510 //______________________________________________________________________________
511 vector<waveSegment>
513 //
514 // Read & Merge DQ files with DQF.cat<=dqcat
515 //
516 //
517 // Input: nDQF - number of DQ files
518 // dqfile - DQ structure array
519 // dqcat - max DQ cat
520 //
521 // Output: return the list of time ranges which pass the merged max DQ cat conditions
522 //
523 
524  vector<waveSegment> olist;
525 
526  int ndqf=0;
527  dqfile dqf[nDQF];
528  for(int n=0;n<nDQF;n++) { // Read DQ files with DQF.cat<=dqcat
529  if(DQF[n].cat<=dqcat) dqf[ndqf++]=DQF[n];
530  }
531  if(ndqf==0) {
532  cout << "CWB::Toolbox::readSegList - no CWB_CAT=" << dqcat << " files in the list" << endl;
533  gSystem->Exit(1);
534  };
535 
536  vector<waveSegment>* list = new vector<waveSegment>[ndqf];
537 
538  for(int n=0;n<ndqf;n++) list[n]=readSegList(dqf[n]);
539 
540  olist=list[0];
541  for(int n=1;n<ndqf;n++) olist = mergeSegLists(list[n],olist); // Merge DQ files
542 
543  for(int n=0;n<ndqf;n++) list[n].clear();
544 
545  delete [] list;
546 
547  return olist; // return the list of time ranges
548 }
549 
550 //______________________________________________________________________________
551 int
552 CWB::Toolbox::dumpSegList(vector<waveSegment> list, TString fName, bool c4) {
553 //
554 // Dump to file a waveSegment list
555 //
556 // Input: list - waveSegment list
557 // fName - output file name
558 // c4 - output format
559 // false : start stop
560 // true : index start stop (stop-start)
561 //
562 
563  FILE* fP;
564  if((fP = fopen(fName.Data(), "w")) == NULL) {
565  cout << "cannot open output file " << fName.Data() <<". \n";
566  gSystem->Exit(1);
567  };
568  cout << "Write output file : " << fName.Data() << endl;
569 
570  if(c4)
571  fprintf(fP,"# seg start stop duration\n");
572  for(int i=0;i<(int)list.size();i++) {
573  if(c4) {
574  fprintf(fP,"%-d\t%-d\t%-d\t%-d\n",
575  int(list[i].index)-1,
576  int(list[i].start),
577  int(list[i].stop),
578  int(list[i].stop-list[i].start));
579  } else {
580  //fprintf(fP,"%-d\t%-d\n",
581  fprintf(fP,"%d %d\n",
582  int(list[i].start),
583  int(list[i].stop));
584  }
585  }
586  if(fP!=NULL) fclose(fP);
587  return 0;
588 }
589 
590 //______________________________________________________________________________
591 double
592 CWB::Toolbox::getTimeSegList(vector<waveSegment> list) {
593 //
594 // Input: list - segment list
595 //
596 // Return the length in sec of the sum of the segments
597 //
598 
599  double segtime=0;
600  for(int i=0;i<(int)list.size();i++) segtime+=list[i].stop-list[i].start;
601  return segtime;
602 }
603 
604 //______________________________________________________________________________
605 void
606 CWB::Toolbox::dumpJobList(vector<waveSegment> ilist, TString fName, double segLen, double segMLS, double segEdge) {
607 //
608 // dump to file the job segment list
609 //
610 // Input: ilist - waveSegment list
611 // fName - output file name
612 // segLen - Segment length [sec]
613 // segMLS - Minimum Segment Length after DQ_CAT1 [sec]
614 // segEdge - wavelet boundary offset [sec]
615 //
616 
617  vector<waveSegment> olist;
618  olist=getJobList(ilist, segLen, segMLS, segEdge);
619  dumpSegList(olist, fName, false);
620  olist.clear();
621 
622  return;
623 }
624 
625 //______________________________________________________________________________
626 vector<waveSegment>
627 CWB::Toolbox::getJobList(vector<waveSegment> ilist, double segLen, double segMLS, double segEdge) {
628 //
629 // build the job segment list
630 //
631 // the job segments are builded starting from the input ilist
632 // each segment must have a minimum length of segMLS+2segEdge and a maximum length of segLen+2*segEdge
633 // in order to maximize the input live time each segment with lenght<2*(segLen+segEdge) is
634 // divided in 2 segments with length<segLen+2*segEdge
635 // segEdge : xxx
636 // segMLS : -------
637 // segLen : ---------------
638 // input seg : ----------------------------
639 // output segA : xxx---------xxx
640 // output segB : xxx----------xxx
641 //
642 // Input: ilist - number of detectors
643 // segLen - Segment length [sec]
644 // segMLS - Minimum Segment Length after DQ_CAT1 [sec]
645 // segEdge - wavelet boundary offset [sec]
646 //
647 // Output: Return the job segment list
648 //
649 
650  if(segMLS>segLen) {
651  cout << endl << "CWB::Toolbox::getJobList - Error : segMLS must be <= segLen" << endl;
652  cout << "segMLS = " << segMLS << " - segLen = " << segLen << endl << endl;
653  exit(1);
654  }
655 
656  int start,stop,len;
657  int remainder,half;
658  int n;
659  int size = ilist.size();
660  int lostlivetime=0;
661  vector<waveSegment> olist;
662 
664  SEG.index=0;
665  olist.clear();
666 
667  for(int i=0;i<size;i++) {
668  start = fmod(ilist[i].start,1)!=0 ? int(ilist[i].start+1) : ilist[i].start; // 1.x -> 2.0
669  stop = fmod(ilist[i].stop ,1)!=0 ? int(ilist[i].stop) : ilist[i].stop; // 1.x -> 1.0
670  start += segEdge;
671  stop -= segEdge;
672  len=stop-start;
673  if(len<=0) continue;
674 
675  n=len/segLen;
676  if(n==0) {
677  if(len<segMLS) {
678  //printf("too small a segment = %d %d %d %d\n",i,start-8,stop+8,len);
679  lostlivetime+=len;
680  continue;
681  }
682  SEG.index++;
683  SEG.start=start;
684  SEG.stop=stop;
685  olist.push_back(SEG);
686  continue;
687  }
688  if(n==1) {
689  if(len>segLen) {
690  remainder=len;
691  half=int(remainder/2);
692  if(half>=segMLS) {
693  SEG.index++;
694  SEG.start=start;
695  SEG.stop=SEG.start+half;
696  olist.push_back(SEG);
697  SEG.index++;
698  SEG.start=SEG.stop;
699  SEG.stop=stop;
700  olist.push_back(SEG);
701  } else {
702  SEG.index++;
703  SEG.start=start;
704  SEG.stop=SEG.start+segLen;
705  olist.push_back(SEG);
706  }
707  } else {
708  SEG.index++;
709  SEG.start=start;
710  SEG.stop=stop;
711  olist.push_back(SEG);
712  }
713  continue;
714  }
715 
716  for(int j=0;j<n-1;j++) {
717  SEG.index++;
718  SEG.start=segLen*j+start;
719  SEG.stop=SEG.start+segLen;
720  olist.push_back(SEG);
721  }
722  remainder=stop-SEG.stop;
723  half=int(remainder/2);
724  if(half>=segMLS) {
725  SEG.index++;
726  SEG.start=SEG.stop;
727  SEG.stop=SEG.start+half;
728  olist.push_back(SEG);
729  SEG.index++;
730  SEG.start=SEG.stop;
731  SEG.stop=stop;
732  olist.push_back(SEG);
733  } else {
734  SEG.index++;
735  SEG.start=SEG.stop;
736  SEG.stop=SEG.start+segLen;
737  olist.push_back(SEG);
738  }
739  }
740 
741  printf("Toolbox::getJobList : lost livetime after building of the standard job list = %d sec\n",lostlivetime);
742  return olist;
743 }
744 
745 //______________________________________________________________________________
746 vector<waveSegment>
747 CWB::Toolbox::getJobList(vector<waveSegment> cat1List, vector<waveSegment> cat2List,
748  double segLen, double segMLS, double segTHR, double segEdge) {
749 //
750 // build the job segment list
751 //
752 // 1) build job list starting from cat1List
753 // 2) select jobs which have lenght < segTHR after cat2List
754 //
755 // Input: ilist - number of detectors
756 // segLen - Segment length [sec]
757 // segMLS - Minimum Segment Length after DQ_CAT1 [sec]
758 // segTHR - Minimum Segment Length after DQ_CAT2 [sec]
759 // segEdge - wavelet boundary offset [sec]
760 //
761 // Output: Return the job segment list
762 //
763 
764  // build job list starting from cat1
765  vector<waveSegment> jobList1=getJobList(cat1List, segLen, segMLS, segEdge);
766 
767  // select jobs which have after cat2 lenght < segTHR
768  vector<waveSegment> jobList2;
769  for(int i=0;i<jobList1.size();i++) {
770  // check if job segment after cat2 is < segTHR
771  vector<waveSegment> detSegs_dq2;
772  detSegs_dq2.push_back(jobList1[i]);
773  detSegs_dq2 = mergeSegLists(detSegs_dq2,cat2List);
774  double detSegs_ctime = getTimeSegList(detSegs_dq2);
775  if(detSegs_ctime<segTHR) {
776  cout << "CWB::Toolbox::getJobList : job segment=" << i+1
777  << " live time after cat2 : " << detSegs_ctime << endl;
778  cout << " segTHR=" << segTHR
779  << " sec -> job removed !!!" << endl;
780  } else {
781  jobList2.push_back(jobList1[i]);
782  }
783  }
784 
785  return jobList2;
786 }
787 
788 //______________________________________________________________________________
789 vector<slag>
791  size_t slagMin, size_t slagMax, size_t* slagSite, char* slagFile) {
792 //
793 // Get SuperLags list
794 //
795 //
796 // Input: nIFO - number of ifos
797 // slagSize - number of super lags (=1 if simulation>0) - if slagSize=0 -> Standard Segments
798 // slagSegs - number of segments
799 // slagOff - first slag id (slagOff=0 - include zero slag )
800 // slagMin - select the minimum available slag distance (see example) : slagMin must be <= slagMax
801 // slagMax - select the maximum available slag distance (see example)
802 // slagSite - site index starting with 0 (same definition as lagSite)
803 // slagFile - user slag file list (default = NULL)
804 // format : slagID slagID_ifo1 slagID_ifo2 ...
805 // lines starting with # are skipped
806 // Example with 3 ifos :
807 //
808 // # SLAG ifo[0] ifo[1] ifo[2]
809 // 0 0 0 0
810 // 1 0 1 -1
811 // 2 0 -1 1
812 //
813 // Return the slag list
814 //
815 // Built-in slags
816 // The built-in algorithm generates the slag list according the increasing value of the slag distance
817 // The entries with the same distance are randomly reshuffled
818 // The slag distance is defined as the sum over the ifos of the absolute values of the shifts
819 //
820 // Example with 3 ifos :
821 //
822 // SLAG ifo[0] ifo[1] ifo[2]
823 // 0 0 0 0
824 // 1 0 1 -1
825 // 2 0 -1 1
826 // 3 0 2 1
827 // 4 0 2 -1
828 // 5 0 -1 2
829 // 6 0 -2 -1
830 // 7 0 1 2
831 // 8 0 1 -2
832 // 9 0 -1 -2
833 //
834 // the distance is :
835 // 0 for SLAG 0
836 // 2 for SLAG 1,2
837 // 3 for SLAG 3,4,5,6,7,8,9
838 //
839 // slagMin,slagMax select the minimum/maximum available distance
840 // ex: if slagMin=3,slagMax=3 the available slags are 3,4,5,6,7,8,9
841 // slagOff select the slag offset of the available slags
842 // ex: if slagMin=3,slagMax=3,slagOff=2 the available slags are 5,6,7,8,9
843 // slagSize define the number of selected slags
844 // ex: if slagMin=3,slagMax=3,slagOff=2,slagSize=2 then the selected slags are 5,6
845 //
846 
847  if(slagSize<1) slagSize=1;
848 
849  if((int)slagMax>slagSegs) {
850  cout << "CWB::Toolbox::makeSlagList : Error - slagMax must be < slagSegs" << endl;
851  gSystem->Exit(1);
852  }
853 
854  if(slagSegs<=0.) {
855  cout << "CWB::Toolbox::makeSlagList : Error - slagSegs must be positive" << endl;
856  gSystem->Exit(1);
857  }
858 
859  if((slagMax>0)&&(slagMin>slagMax)) {
860  cout << "CWB::Toolbox::getSlagList : Error - slagMin must be < slagMax" << endl;
861  gSystem->Exit(-1);
862  }
863 
864  if(slagSite!=NULL) for(int n=0; n<(int)nIFO; n++) {
865  if(slagSite[n] >= nIFO) {
866  cout << "CWB::Toolbox::getSlagList : Error slagSite - value out of range " << endl;
867  gSystem->Exit(-1);
868  }
869  }
870 
871  vector<slag> slagList;
872  vector<int> id;
873 
874  if(slagFile) { // read list of slags from file
875 
876  cout << endl << "CWB::Toolbox::getSlagList : read slags from file -> " << slagFile << endl;
877 
878  ifstream in;
879  in.open(slagFile, ios::in);
880  if(!in.good()) {
881  cout << "CWB::Toolbox::getSlagList : Error Opening File : " << slagFile << endl;
882  gSystem->Exit(1);
883  }
884 
885  char str[1024];
886  int fpos=0;
887  int id;
888  int size = slagOff+slagSize;
889  while(true) {
890  fpos=in.tellg();
891  in.getline(str,1024);
892  if(str[0] == '#') continue;
893  in.seekg(fpos, ios::beg);
894  fpos=in.tellg();
895  slag SLAG;
896  in >> id;
897  if (!in.good()) break;
898  // check duplicated slag id
899  for(int j=0; j<(int)slagList.size(); j++) {
900  if(id==slagList[j].jobId) {
901  cout << "CWB::Toolbox::getSlagList : duplicated slag id "
902  << " or wrong format in slag file -> " << slagFile << endl;
903  gSystem->Exit(1);
904  }
905  }
906  SLAG.jobId=id;
907  for(int n=0; n<(int)nIFO; n++) {
908  in >> id; SLAG.slagId.push_back(id);
909  }
910  slagList.push_back(SLAG);
911  if (slagList.size()==size) break;
912  if (!in.good()) break;
913  }
914 
915  in.close();
916 
917  if(size>slagList.size()) {
918  cout << "CWB::Toolbox::getSlagList : Error - slagOff+slagSize " << size << " is > entries in slagFile " << slagList.size() << endl;
919  gSystem->Exit(1);
920  }
921 
922  } else { // built-in slag generation
923 
924  cout << endl << "CWB::Toolbox::getSlagList : built-in slags" << endl;
925 
926  // find number of non co-located detectors
927  vector<int> ifo;
928  for(int n=0;n<(int)nIFO;n++) {
929  if(slagSite!=NULL) {
930  bool unique=true;
931  for(int m=0;m<(int)ifo.size();m++) if((int)slagSite[n]==ifo[m]) unique=false;
932  if(unique) ifo.push_back(slagSite[n]);
933  } else {
934  ifo.push_back(n);
935  }
936  }
937  //for(int m=0;m<(int)ifo.size();m++) cout << m << " " << ifo[m] << endl;
938 
939  // add slag 0
940  int jobId=0;
941  if(slagMin==0) {
942  slag SLAG;
943  SLAG.jobId=jobId++;
944  for(int n=0; n<(int)nIFO; n++) SLAG.slagId.push_back(0);
945  slagList.push_back(SLAG);
946  }
947  for(int m=(int)slagMin;m<=(int)slagMax;m++) {
948  //int size = slagSize ? slagOff+slagSize : 0;
949  int size = 0; // get all slags contained in the range
950  int nifo = ifo.size(); // number of non co-located detectors
951  vector<slag> slags;
952  getSlagList(slags,size,m,nifo,id); // get slag list located at range m
953  // add slags to slagList in random mode
954  gRandom->SetSeed(m+1); // random seed is initialized with range
955  while(slags.size()>0) {
956  int k = int(gRandom->Uniform(0,int(slags.size())));
957  slags[k].jobId=jobId++;
958  slagList.push_back(slags[k]);
959  slags.erase(slags.begin()+k); // remove slag from slags list
960  }
961  }
962  // set slags according to slagSite setup
963  if(slagSite!=NULL) {
964  for(int j=0; j<(int)slagList.size(); j++) {
965  slag SLAG = slagList[j];
966  slagList[j].slagId.resize(nIFO);
967  for(int n=0; n<(int)nIFO; n++) {
968  for(int m=0;m<(int)ifo.size();m++)
969  if((int)slagSite[n]==ifo[m]) slagList[j].slagId[n] = SLAG.slagId[m];
970  }
971  }
972  }
973  }
974 
975  if((slagSize>slagList.size()-slagOff)) {
976  cout << "CWB::Toolbox::getSlagList : Error - the number of available slags = "
977  << slagList.size() << " are less than the requested slag (slagSize) = " << slagSize << endl;
978  gSystem->Exit(-1);
979  }
980 
981  // print slag list
982  cout << endl;
983  printf("%14s ","SLAG");
984  for(int n=0; n<nIFO; n++) printf("%8sifo[%d]","",n);
985  printf("\n");
986  for(int i=(int)slagOff; i<int(slagOff+slagSize); i++) {
987  printf("%14d", slagList[i].jobId);
988  for (int n=0; n<nIFO; n++) printf("%14d",slagList[i].slagId[n]);
989  printf("\n");
990  }
991  cout << endl;
992 
993  // fill slag list
994  int jobID=0;
995  slag SLAG;
996  vector<slag> slist;
997  for(int j=(int)slagOff; j<int(slagOff+slagSize); j++){
998  int nseg=0;
999  for(int k=1; k<=slagSegs; k++){
1000  bool check=true;
1001  for (int n=0; n<(int)nIFO; n++) if((k+slagList[j].slagId[n])>slagSegs) check=false;
1002  for (int n=0; n<(int)nIFO; n++) if((k+slagList[j].slagId[n])<0) check=false;
1003  if(check){
1004  SLAG.jobId=++jobID;
1005  SLAG.slagId.clear();
1006  SLAG.segId.clear();
1007  SLAG.slagId.push_back(slagList[j].jobId);
1008  SLAG.slagId.push_back(++nseg); // this number identify the segment number in a slag
1009  for(int n=0; n<(int)nIFO; n++) {
1010  SLAG.slagId.push_back(slagList[j].slagId[n]);
1011  SLAG.segId.push_back(slagList[j].slagId[n]+k);
1012  }
1013  slist.push_back(SLAG);
1014  }
1015  }
1016  }
1017  slagList.clear();
1018 
1019  return slist;
1020 }
1021 
1022 //______________________________________________________________________________
1023 void
1024 CWB::Toolbox::getSlagList(vector<slag>& slagList, int slagSize, int slagRank, int nifo, vector<int>& id) {
1025 //
1026 // Get SuperLags list associate to the slagRank value
1027 //
1028 // Input: slagSize - number of super lags
1029 // slagRank - slag distance
1030 // nifo - number of ifos
1031 // id - temporary auxiliary vector id
1032 //
1033 // Return the slag list for the slagRank value
1034 //
1035 
1036  if(slagSize && ((int)slagList.size()==slagSize)) return;
1037  for(int j=-slagRank;j<=slagRank;j++) {
1038  if(j==0) continue;
1039  bool unique=true;
1040  for(int n=0; n<(int)id.size(); n++) if(j==id[n]) unique=false;
1041  if(!unique) continue;
1042  if(nifo==2) {
1043  id.push_back(j);
1044  int m=0;
1045  for(int n=0; n<(int)id.size(); n++) m+=abs(id[n]);
1046  if(m==slagRank) {
1047  slag SLAG;
1048  SLAG.jobId=slagList.size();
1049  SLAG.slagId.push_back(0); // set first detector with slag shift = 0
1050  for(int n=0; n<(int)id.size(); n++) SLAG.slagId.push_back(id[n]);
1051  slagList.push_back(SLAG);
1052  if(slagSize && ((int)slagList.size()==slagSize)) return;
1053  }
1054  id.resize(id.size()-1);
1055  continue;
1056  } else {
1057  id.push_back(j);
1058  getSlagList(slagList, slagSize, slagRank, nifo-1, id);
1059  id.resize(id.size()-1);
1060  }
1061  }
1062  return;
1063 }
1064 
1065 //______________________________________________________________________________
1066 void
1067 CWB::Toolbox::dumpSlagList(vector<slag> slagList, TString slagFile, bool slagOnly) {
1068 //
1069 // dump slag list to file
1070 //
1071 // Input: slagList - slag list
1072 // slagFile - output file name
1073 // slagOnly - true: write only slagID
1074 // Example with 3 ifos :
1075 //
1076 // # SLAG ifo[0] ifo[1] ifo[2]
1077 // 0 0 0 0
1078 // 1 0 1 -1
1079 // 2 0 -1 1
1080 //
1081 // - false: write slagID + segID
1082 //
1083 
1084  if(((int)slagList.size()>0)&&(slagFile!="")) {
1085 
1086  FILE *fP=NULL;
1087  if((fP = fopen(slagFile.Data(), "w")) == NULL) {
1088  cout << "CWB::Toolbox::makeSlagList : Error - cannot open file " << slagFile.Data() << endl;
1089  gSystem->Exit(1);
1090  }
1091 
1092  int nIFO = slagList[0].segId.size();
1093 
1094  // write header
1095 
1096  fprintf(fP,"#");for (int n=0;n<=nIFO+1;n++) fprintf(fP,"--------------");fprintf(fP,"\n");
1097  fprintf(fP,"# Super Lags List - %d jobs\n",(int)slagList.size());
1098  fprintf(fP,"#");for (int n=0;n<=nIFO+1;n++) fprintf(fP,"--------------");fprintf(fP,"\n");
1099  fprintf(fP,"# nIFO %13d\n",int(nIFO));
1100  fprintf(fP,"#");for (int n=0;n<=nIFO+1;n++) fprintf(fP,"--------------");fprintf(fP,"\n");
1101  if(!slagOnly) fprintf(fP,"#%13s","jobId"); else fprintf(fP,"#");
1102  fprintf(fP,"%14s","slagId");
1103  for(int n=0; n<nIFO; n++) fprintf(fP,"%11s[%1d]","segID",int(n));
1104  fprintf(fP,"\n");
1105  fprintf(fP,"#");for (int n=0;n<=nIFO+1;n++) fprintf(fP,"--------------");fprintf(fP,"\n");
1106 
1107  // write jobs
1108  for(int j=0; j<(int)slagList.size(); j++){
1109  if(slagOnly) {
1110  if(slagList[j].slagId[1]==1) {
1111  fprintf(fP,"%14d", slagList[j].slagId[0]);
1112  for (int n=0; n<nIFO; n++) fprintf(fP,"%14d",slagList[j].slagId[n+2]);
1113  fprintf(fP,"\n");
1114  }
1115  } else {
1116  fprintf(fP,"%14d", slagList[j].jobId); // jobID
1117  fprintf(fP,"%14d", slagList[j].slagId[0]); // slagID
1118  for (int n=0; n<nIFO; n++) fprintf(fP,"%14d",slagList[j].segId[n]); // segID
1119  fprintf(fP,"\n");
1120  }
1121  }
1122 
1123  if(fP!=NULL) fclose(fP);
1124  }
1125 
1126  return;
1127 }
1128 
1129 //______________________________________________________________________________
1130 int
1132  vector<TString> jobFiles, TString stage, int jobmin, int jobmax) {
1133 //
1134 // produce the condor dag file for stages
1135 //
1136 // Input: jobList - list of job ID
1137 // condor_dir - dag,sub condor directory
1138 // label - label used for dag file = 'condor_dir'/'label'.dag
1139 // jobFiles - name of job files created by the previous stage
1140 // stage - analysis stage (Ex : SUPERCLUSTER, LIKELIHOOD)
1141 // jobmin - beg jobList index array
1142 // jobmax - end jobList index array
1143 //
1144 
1145  vector<waveSegment> _jobList(jobList.size());
1146  for(int i=0;i<(int)jobList.size();i++) _jobList[i].index=jobList[i];
1147  return createDagFile(_jobList, condor_dir, label, jobFiles, stage, jobmin, jobmax);
1148 }
1149 
1150 //______________________________________________________________________________
1151 int
1153  int jobmin, int jobmax) {
1154 //
1155 // produce the condor dag file for CWB_STAGE_FULL stage
1156 //
1157 // Input: jobList - list of job : only waveSegment::index is used
1158 // condor_dir - dag,sub condor directory
1159 // label - label used for dag file = 'condor_dir'/'label'.dag
1160 // jobmin - beg jobList index array
1161 // jobmax - end jobList index array
1162 //
1163 
1164  vector<TString> jobFiles;
1165  return createDagFile(jobList, condor_dir, label, jobFiles, "CWB_STAGE_FULL", jobmin, jobmax);
1166 }
1167 
1168 //______________________________________________________________________________
1169 int
1171  vector<TString> jobFiles, TString stage, int jobmin, int jobmax) {
1172 //
1173 // produce the condor dag file for stages
1174 //
1175 // Input: jobList - list of job : only waveSegment::index is used
1176 // condor_dir - dag,sub condor directory
1177 // label - label used for dag file = 'condor_dir'/'label'.dag
1178 // jobFiles - name of job files created by the previous stage
1179 // stage - analysis stage (Ex : SUPERCLUSTER, LIKELIHOOD)
1180 // jobmin - beg jobList index array
1181 // jobmax - end jobList index array
1182 //
1183 
1184  if(jobFiles.size()==0) { // fill jobFile with CWB_UPARAMETERS_FILE env
1186  if(gSystem->Getenv("CWB_UPARAMETERS_FILE")!=NULL) {
1187  cwb_uparameters_file=TString(gSystem->Getenv("CWB_UPARAMETERS_FILE"));
1188  if(cwb_uparameters_file!="") checkFile(cwb_uparameters_file);
1189  jobFiles.resize(jobList.size());
1190  for(int n=0;n<(int)jobFiles.size();n++) jobFiles[n]=cwb_uparameters_file;
1191  } else {
1192  cout << "CWB::Toolbox::createDagFile : Error - CWB_UPARAMETERS_FILE env is not defined" << endl;
1193  gSystem->Exit(1);
1194  }
1195  }
1196  if(jobFiles.size()!=jobList.size()) {
1197  cout << "CWB::Toolbox::createDagFile : Error - jobFiles size " << jobFiles.size() <<
1198  "is != jobList size " << jobList.size() << endl;
1199  gSystem->Exit(1);
1200  }
1201 
1202  int start = jobmin<1 ? 1 : jobmin;
1203  int end = jobmax<1||jobmax>(int)jobList.size() ? jobList.size() : jobmax;
1204 
1205  char ofile[256];
1206  sprintf(ofile,"%s/%s.dag",condor_dir.Data(),label.Data());
1207  ofstream out;
1208  out.open(ofile,ios::out);
1209 
1210  // read jobList
1211  int jID=0;
1212  for(int n=end;n>=start;n--) {
1213  if(jobFiles[n-1]=="") continue;
1214  jID = jobList[n-1].index;
1215  char ostring[256];
1216  sprintf(ostring,"JOB A%i %s/%s.sub",jID,condor_dir.Data(),label.Data());
1217  out << ostring << endl;
1218  sprintf(ostring,"VARS A%i PID=\"%i\" CWB_UFILE=\"%s\" CWB_STAGE=\"%s\"",
1219  jID,jID,jobFiles[n-1].Data(),stage.Data());
1220  out << ostring << endl;
1221  if(gSystem->Getenv("_USE_OSG")!=NULL) {
1222  sprintf(ostring,"SCRIPT POST A%i %s/cwb_net_osg_post.sh %i",jID,gSystem->Getenv("CWB_SCRIPTS"),jID);
1223  out << ostring << endl;
1224  } else {
1225  sprintf(ostring,"RETRY A%i 3000",jID);
1226  out << ostring << endl;
1227  }
1228  }
1229  out.close();
1230  return 0;
1231 }
1232 
1233 //______________________________________________________________________________
1234 int
1236  int jobmin, int jobmax) {
1237 //
1238 // produce the condor dag file for CWB_STAGE_FULL stage
1239 //
1240 // Input: slagList - list of jobId : only slag::index is used
1241 // condor_dir - dag,sub condor directory
1242 // label - label used for dag file = 'condor_dir'/'label'.dag
1243 // jobmin - beg jobList index array
1244 // jobmax - end jobList index array
1245 //
1246 
1247  vector<TString> jobFiles;
1248  return createDagFile(slagList, condor_dir, label, jobFiles, "CWB_STAGE_FULL", jobmin, jobmax);
1249 }
1250 
1251 //______________________________________________________________________________
1252 int
1254  vector<TString> jobFiles, TString stage, int jobmin, int jobmax) {
1255 //
1256 // produce the condor dag file for stages
1257 //
1258 // Input: slagList - list of jobId : only slag::index is used
1259 // condor_dir - dag,sub condor directory
1260 // label - label used for dag file = 'condor_dir'/'label'.dag
1261 // jobFiles - name of job files created by the previous stage
1262 // stage - analysis stage (Ex : SUPERCLUSTER, LIKELIHOOD)
1263 // jobmin - beg jobList index array
1264 // jobmax - end jobList index array
1265 //
1266 
1267  if(jobFiles.size()==0) { // fill jobFile with CWB_UPARAMETERS_FILE env
1269  if(gSystem->Getenv("CWB_UPARAMETERS_FILE")!=NULL) {
1270  cwb_uparameters_file=TString(gSystem->Getenv("CWB_UPARAMETERS_FILE"));
1271  if(cwb_uparameters_file!="") checkFile(cwb_uparameters_file);
1272  jobFiles.resize(slagList.size());
1273  for(int n=0;n<(int)jobFiles.size();n++) jobFiles[n]=cwb_uparameters_file;
1274  } else {
1275  cout << "CWB::Toolbox::createDagFile : Error - CWB_UPARAMETERS_FILE env is not defined" << endl;
1276  gSystem->Exit(1);
1277  }
1278  }
1279  if(jobFiles.size()!=slagList.size()) {
1280  cout << "CWB::Toolbox::createDagFile : Error - jobFiles size " << jobFiles.size() <<
1281  "is != slagList size " << slagList.size() << endl;
1282  gSystem->Exit(1);
1283  }
1284 
1285  int start = jobmin<1 ? 1 : jobmin;
1286  int end = jobmax<1||jobmax>(int)slagList.size() ? slagList.size() : jobmax;
1287 
1288  char ofile[256];
1289  sprintf(ofile,"%s/%s.dag",condor_dir.Data(),label.Data());
1290  ofstream out;
1291  out.open(ofile,ios::out);
1292 
1293  // read slagList // SLAG
1294  int jID=0;
1295  for(int n=end;n>=start;n--) {
1296  if(jobFiles[n-1]=="") continue;
1297  jID = slagList[n-1].jobId;
1298  char ostring[256];
1299  sprintf(ostring,"JOB A%i %s/%s.sub",jID,condor_dir.Data(),label.Data());
1300  out << ostring << endl;
1301  sprintf(ostring,"VARS A%i PID=\"%i\" CWB_UFILE=\"%s\" CWB_STAGE=\"%s\"",
1302  jID,jID,jobFiles[n-1].Data(),stage.Data());
1303  out << ostring << endl;
1304  sprintf(ostring,"RETRY A%i 3000",jID);
1305  out << ostring << endl;
1306  if(gSystem->Getenv("_USE_OSG")!=NULL) {
1307  sprintf(ostring,"SCRIPT POST A%i %s/cwb_net_osg_post.sh",jID,gSystem->Getenv("CWB_SCRIPTS"));
1308  out << ostring << endl;
1309  }
1310  }
1311  out.close();
1312  return 0;
1313 }
1314 
1315 //______________________________________________________________________________
1316 int
1318  TString log_dir, TString ext, TString condor_tag) {
1319 //
1320 // produce the condor sub file
1321 //
1322 // Input: label - label used for dag file = 'condor_dir'/'label'.dag
1323 // condor_dir - dag,sub condor directory
1324 // out_dir - out condor files directory
1325 // err_dir - err condor files directory
1326 // ext - condor directory
1327 // condor_tag - Define a Unique Tag for Condor Jobs
1328 //
1329 
1330  char ofile[256];
1331  if(ext=="")
1332  sprintf(ofile,"%s/%s.sub",condor_dir.Data(),label.Data());
1333  else
1334  sprintf(ofile,"%s/%s.sub.%s",condor_dir.Data(),label.Data(),ext.Data());
1335 
1336  FILE *fP=NULL;
1337  if((fP = fopen(ofile, "w")) == NULL) {
1338  cout << "CWB::Toolbox::createSubFile : Error - cannot open file " << ofile << endl;
1339  gSystem->Exit(1);
1340  }
1341 
1342  fprintf(fP,"universe = vanilla\n");
1343  fprintf(fP,"getenv = true\n");
1344  fprintf(fP,"priority = $(PRI)\n");
1345  fprintf(fP,"on_exit_hold = ( ExitCode != 0 )\n");
1346  fprintf(fP,"request_memory = 3000\n");
1347  fprintf(fP,"executable = cwb.sh\n");
1348  fprintf(fP,"job_machine_attrs = Machine\n");
1349  fprintf(fP,"job_machine_attrs_history_length = 5\n");
1350  fprintf(fP,"requirements = target.machine =!= MachineAttrMachine1 && target.machine =!= MachineAttrMachine2 && target.machine =!= MachineAttrMachine3 && target.machine =!= MachineAttrMachine4 && target.machine =!= MachineAttrMachine5\n");
1351  fprintf(fP,"environment = CWB_JOBID=$(PID);CWB_UFILE=$(CWB_UFILE);CWB_STAGE=$(CWB_STAGE)\n");
1352  if(condor_tag!="") fprintf(fP,"accounting_group = %s\n",condor_tag.Data());
1353  fprintf(fP,"output = %s/$(PID)_%s_$(CWB_STAGE).out\n",out_dir.Data(),label.Data());
1354  fprintf(fP,"error = %s/$(PID)_%s_$(CWB_STAGE).err\n",err_dir.Data(),label.Data());
1355  if(gSystem->Getenv("_USE_OSG")!=NULL) {
1356  TString home_dir= TString(gSystem->Getenv("HOME"));
1357  //cout<<home_dir.Data()<<endl;
1358  fprintf(fP,"log = %s/condor/%s.log\n",home_dir.Data(),label.Data());
1359  fprintf(fP,"should_transfer_files = YES\n");
1360  fprintf(fP,"when_to_transfer_output = ON_EXIT\n");
1361  fprintf(fP,"transfer_input_files = %s/.rootrc, %s/%s.tgz\n",home_dir.Data(), condor_dir.Data(),label.Data());
1362  fprintf(fP,"transfer_output_files = %s/output, %s/log\n", label.Data(), label.Data());
1363  fprintf(fP,"request_memory = 2000\n");
1364  } else {
1365  fprintf(fP,"log = %s/%s.log\n",log_dir.Data(),label.Data());
1366  }
1367  fprintf(fP,"notification = never\n");
1368  fprintf(fP,"rank=memory\n");
1369  fprintf(fP,"queue\n");
1370 
1371  fclose(fP);
1372 
1373  return 0;
1374 }
1375 
1376 //______________________________________________________________________________
1377 vector<int>
1379 //
1380 // get the job list from the dag condor file
1381 //
1382 // Input: condor_dir - dag,sub condor directory
1383 // label - label used for dag file = 'condor_dir'/'label'.dag
1384 //
1385 
1386  char ifile[256];
1387  sprintf(ifile,"%s/%s.dag",condor_dir.Data(),label.Data());
1388  ifstream in;
1389  in.open(ifile);
1390  if(!in.good()) {cout << "Error Opening File : " << ifile << endl;gSystem->Exit(1);}
1391 
1392  vector<int> jobs;
1393 
1394  char istring[1024];
1395  while(1) {
1396  in.getline(istring,1024);
1397  if (!in.good()) break;
1398  TObjArray* token = TString(istring).Tokenize(TString(' '));
1399  TObjString* stoken =(TObjString*)token->At(0);
1400  TString jobLabel = stoken->GetString();
1401  if(jobLabel.CompareTo("JOB")!=0) continue;
1402  stoken =(TObjString*)token->At(1);
1403  int jobID=TString(stoken->GetString()).ReplaceAll("A","").Atoi();
1404  jobs.push_back(jobID);
1405  if(token) delete token;
1406  }
1407 
1408  in.close();
1409 
1410  vector<int> jobList;
1411  Int_t *id = new Int_t[jobs.size()];
1412  Int_t *jd = new Int_t[jobs.size()];
1413  for(int i=0;i<(int)jobs.size();i++) jd[i]=jobs[i];
1414  TMath::Sort((int)jobs.size(),jd,id,false);
1415  for(int i=0;i<(int)jobs.size();i++) jobList.push_back(jd[id[i]]);
1416  jobs.clear();
1417  delete [] id;
1418  delete [] jd;
1419 
1420  return jobList;
1421 }
1422 
1423 //______________________________________________________________________________
1424 vector<float>
1425 CWB::Toolbox::getJobBenchmark(TString ifName, int stageID, TString bench) {
1426 //
1427 // extract benchmark info from bench status history line
1428 // return in vector vbench : vbench[0]=job number - vbench[1]=bench value
1429 //
1430  return getJobBenchmark(ifName, stageID, -1, -1, bench);
1431 }
1432 
1433 //______________________________________________________________________________
1434 vector<float>
1435 CWB::Toolbox::getJobBenchmark(TString ifName, int stageID, int resID, int factorID, TString bench) {
1436 //
1437 // extract benchmark info from bench status history line
1438 // return in vector vbench : vbench[0]=job number - vbench[1]=bench value
1439 //
1440 // These are the format of the bench status history line
1441 // GPS:X1-JOB:X2-STG:X3-FCT:X4-JET:X5-SET:X6-MEM:X7-JFS:X8
1442 // GPS:X1-JOB:X2-STG:X3-FCT:X4-RES:X5-THR:X6
1443 // GPS:X1-JOB:X2-STG:X3-FCT:X4-RES:X5-CSIZE:X6-PSIZE:X7
1444 //
1445 // ifName - root file name containig the history object
1446 // stageID - stage ID (defined in cwb.hh)
1447 // resID - resolution level ID
1448 // factorID - factor ID (defined in user_parameters.C)
1449 //
1450 // bench is :
1451 // GPS : gps time (sec)
1452 // JOB : job number
1453 // STG : stage number (defined in cwb.hh)
1454 // FCT : factors index array
1455 // JET : Job Elapsed Time (sec)
1456 // SET : Stage Elapsed Time (sec)
1457 // MEM : Memory usage (MB)
1458 // JFS : Job File Size - temporary file (bytes)
1459 // THR : Threshold @ Coherence Stage
1460 // CSIZE : cluster size per lag @ coherence stage
1461 // PSIZE : pixels size per lag @ coherence stage
1462 //
1463 
1464  vector<float> vbench(2);
1465  vbench[0]=-1; // job number
1466  vbench[1]=-1; // bench value
1467 
1468  TFile *ifile = TFile::Open(ifName);
1469  if(ifile==NULL) {
1470  cout << "Failed to open " << ifName.Data() << endl;
1471  return vbench;
1472  }
1473 
1474  CWB::History* ihistory = (CWB::History*)ifile->Get("history");
1475  if(ihistory==NULL) {
1476  cout << "Error : history is not present!!!" << endl;
1477  return vbench;
1478  }
1479 
1480  // build stage tag in the bench line status
1481  char stageName[64]; sprintf(stageName,"STG:%d-",stageID);
1482 
1483  // build resolution tag in the bench line status
1484  char resName[64]; sprintf(resName,"RES:%d-",resID);
1485 
1486  // build factor tag in the bench line status
1487  char factorName[64]; sprintf(factorName,"FCT:%d-",factorID);
1488 
1489  int log_size = ihistory->GetLogSize(CCAST("FULL"));
1490  for(int i=0;i<log_size;i++) {
1491  TString log = ihistory->GetLog(CCAST("FULL"),i);
1492  //cout << "log " << log.Data() << endl;
1493  if(!log.Contains(stageName)) continue;
1494  if(resID>=0 && !log.Contains(resName)) continue;
1495  if(factorID>=0 && !log.Contains(factorName)) continue;
1496  if(log.Contains(bench+TString(":"))) {
1497  TObjArray* token = log.Tokenize('\n');
1498  for(int j=0;j<token->GetEntries();j++) {
1499  TString line = ((TObjString*)token->At(j))->GetString();
1500  // extract bench line which contains the "bench:" string
1501  if(line.Contains(bench+TString(":"))) {
1502  //cout << j << " " << (((TObjString*)token->At(j))->GetString()).Data() << endl;
1503  // extract tokens separated by "-"
1504  TObjArray* ltoken = line.Tokenize('-');
1505  for(int k=0;k<ltoken->GetEntries();k++) {
1506  TString stat = ((TObjString*)ltoken->At(k))->GetString();
1507  //cout << k << " " << stat.Data() << endl;
1508  TObjArray* stoken = stat.Tokenize(':');
1509  if(stoken->GetEntries()!=2) continue;
1510  TString stat_name = ((TObjString*)stoken->At(0))->GetString();
1511  TString stat_value = ((TObjString*)stoken->At(1))->GetString();
1512  //cout << stat_name.Data() << " " << stat_value.Data() << endl;
1513  // extract value associated to bench "bench:value"
1514  if(stat_name==bench) {
1515  float value = stat_value.Atof();
1516  if(value>vbench[1]) vbench[1]=value;
1517  //cout << stat_name.Data() << " " << stat_value.Data() << endl;
1518  }
1519  if(stat_name=="JOB") {
1520  vbench[0] = stat_value.Atoi(); // Get JOB ID from bench status line
1521  }
1522  delete stoken;
1523  }
1524  delete ltoken;
1525  }
1526  }
1527  delete token;
1528  }
1529  }
1530 
1531  ifile->Close();
1532 
1533  // if jobID is not present in the bench line then it is extracted from file name
1534  if(vbench[0]==-1) vbench[0] = getJobId(ifName);
1535 
1536  return vbench;
1537 }
1538 
1539 //______________________________________________________________________________
1540 TString
1541 CWB::Toolbox::DAG2LSF(char* dagFile, char* data_label, char* nodedir, char* data_dir,
1542  char* condor_dir, char* log_dir, char* output_dir, char* work_dir) {
1543 //
1544 // Input: dagFile - Dag File
1545 // data_label - data label
1546 // nodedir - temporary dir directory
1547 // data_dir - data directory
1548 // condor_dir - condor directory
1549 // log_dir - log dir
1550 // output_dir - output dir
1551 // work_dir - working dir
1552 //
1553 // Output: input dagFile is used to produce the script LSF file
1554 // if number of jobs>0 return lsf file name otherwise empty string
1555 //
1556 
1557  // get user name
1558  UserGroup_t* uinfo = gSystem->GetUserInfo();
1559  TString uname = uinfo->fUser;
1560 
1561  // get home wat path
1562  TString cwb_home_wat="";
1563  if(gSystem->Getenv("HOME_WAT")!=NULL) {
1564  cwb_home_wat=TString(gSystem->Getenv("HOME_WAT"));
1565  }
1566  if(cwb_home_wat=="") {
1567  cout << "CWB::Toolbox::DAG2LSF : Error : HOME_WAT not defined !!!" << endl;
1568  gSystem->Exit(1);
1569  }
1570 
1571  // get LSF queue name
1572  TString lsf_queue="";
1573  if(gSystem->Getenv("LSF_QUEUE")!=NULL) {
1574  lsf_queue=TString(gSystem->Getenv("LSF_QUEUE"));
1575  }
1576  if(lsf_queue=="") {
1577  cout << "CWB::Toolbox::DAG2LSF : Error : LSF_QUEUE not defined !!!" << endl;
1578  gSystem->Exit(1);
1579  }
1580 
1581  // --------------------------------------------------
1582  // create LSF job script file
1583  // --------------------------------------------------
1584 
1585  // open dag file
1586  ifstream in;
1587  in.open(dagFile);
1588  if(!in.good()) {
1589  cout << "CWB::Toolbox::DAG2LSF - Error Opening File : " << dagFile << endl;
1590  gSystem->Exit(1);
1591  }
1592 
1593  // create LSF file
1594  TString lsfFile = dagFile;
1595  lsfFile.ReplaceAll(".dag",".lsf");
1596  ofstream out;
1597  out.open(lsfFile.Data(),ios::out);
1598  if(!out.good()) {
1599  cout << "CWB::Toolbox::DAG2LSF - Error Opening File : " << lsfFile << endl;
1600  gSystem->Exit(1);
1601  }
1602 
1603  out << "#!/bin/bash" << endl << endl;
1604 
1605  int lsf_job_cnt=0;
1606  char istring[1024];
1607  while(1) {
1608  int PID=0;
1609  TString CWB_UFILE="";
1610  TString CWB_STAGE="";
1611  in.getline(istring,1024);
1612  if (!in.good()) break;
1613  if(!TString(istring).BeginsWith("VARS")) continue;
1614  TObjArray* token = TString(istring).Tokenize(TString(' '));
1615  for(int j=2;j<token->GetEntries();j++) {
1616  TString item = ((TObjString*)token->At(j))->GetString();
1617  if(item.BeginsWith("PID=")) {
1618  item.ReplaceAll("PID=","");
1619  item.ReplaceAll("\"","");
1620  PID = item.Atoi();
1621  continue;
1622  }
1623  if(item.BeginsWith("CWB_UFILE=")) {
1624  item.ReplaceAll("CWB_UFILE=","");
1625  item.ReplaceAll("\"","");
1626  CWB_UFILE=item;;
1627  continue;
1628  }
1629  if(item.BeginsWith("CWB_STAGE=")) {
1630  item.ReplaceAll("CWB_STAGE=","");
1631  item.ReplaceAll("\"","");
1632  CWB_STAGE=item;;
1633  continue;
1634  }
1635  }
1636  //cout << "PID : " << PID << " CWB_UFILE : " << CWB_UFILE << " CWB_STAGE : " << CWB_STAGE << endl;
1637  char lsf_cmd[2048];
1638  char lsf_label[1024]; // label used in the execution node
1639  if(CWB_STAGE=="CWB_STAGE_FULL") {
1640  sprintf(lsf_label,"%s",data_label);
1641  } else {
1642  sprintf(lsf_label,"%s_%s",data_label,CWB_STAGE.Data());
1643  }
1644  sprintf(lsf_cmd,"bsub -q %s -J A%d -g /%s/%s \
1645  \\\n -f \"%s > %s/%d_%s.ufile\" \
1646  \\\n -f \"%s/%s.tgz > %s/%d_%s.tgz\" \
1647  \\\n -o %d_%s.out -f \"%s/%s/%d_%s.out < %d_%s.out\" \
1648  \\\n -e %d_%s.err -f \"%s/%s/%d_%s.err < %d_%s.err\" \
1649  \\\n -f \"%s/%s/%d_%s.tgz < %s/%d_%s.tgz\" \
1650  \\\n -Ep \"rm %d_%s.out\" \
1651  \\\n -Ep \"rm %d_%s.err\" \
1652  \\\n -Ep \"rm %s/%d_%s.tgz\" \
1653  \\\n \"/bin/bash %s/tools/cwb/scripts/cwb_net_lsf.sh %d %s %s %s %s %s\"",
1654  lsf_queue.Data(), PID, uname.Data(), data_label,
1655  CWB_UFILE.Data(), nodedir, PID, lsf_label,
1656  condor_dir, lsf_label, nodedir, PID, lsf_label,
1657  PID, lsf_label, work_dir, log_dir, PID, lsf_label, PID, lsf_label,
1658  PID, lsf_label, work_dir, log_dir, PID, lsf_label, PID, lsf_label,
1659  work_dir, output_dir, PID, lsf_label, nodedir, PID, lsf_label,
1660  PID, lsf_label,
1661  PID, lsf_label,
1662  nodedir, PID, lsf_label,
1663  cwb_home_wat.Data(), PID, CWB_STAGE.Data(), nodedir, data_label, data_dir, CWB_UFILE.Data());
1664  out << lsf_cmd << endl << endl;
1665  //cout << lsf_cmd << endl;
1666  if(token) delete token;
1667  //if(PID%1000==0) cout << PID << endl;
1668  lsf_job_cnt++;
1669  }
1670  out.close();
1671  in.close();
1672 
1673  return lsf_job_cnt>0 ? lsfFile : "";
1674 }
1675 
1676 //______________________________________________________________________________
1677 vector<int>
1679 //
1680 // return vector job numbers extracted from the merged file list
1681 // the job number ID is extracted from the file name : XXX_jobID.root
1682 //
1683 // Input: merge_dir - merge directory
1684 // label - label of the merge name list
1685 // version - version of the merge name list
1686 // - merge name list = 'merge_dir'/merge_'label'.M'version.lst
1687 //
1688 
1689  char ifile[256];
1690  sprintf(ifile,"%s/merge_%s.M%d.lst",merge_dir.Data(),label.Data(),version);
1691  vector<TString> jfname;
1692  return getMergeJobList(ifile,jfname);
1693 }
1694 
1695 //______________________________________________________________________________
1696 vector<int>
1698 //
1699 // return vector job numbers extracted from the ifname file list
1700 // the job number ID is extracted from the file name : XXX_jobID.root
1701 //
1702 // Input: ifname - input file name which contains the list of files
1703 //
1704 
1705  vector<TString> jfname;
1706  return getMergeJobList(ifname,jfname);
1707 }
1708 
1709 //______________________________________________________________________________
1710 vector<int>
1711 CWB::Toolbox::getMergeJobList(TString ifname, vector<TString>& jobFileList) {
1712 //
1713 // return vector job numbers extracted from the ifname file list
1714 // the job number ID is extracted from the file name : XXX_jobID.root
1715 //
1716 // Input: ifname - input file name which contains the list of files
1717 //
1718 // Output: jobFileList - the job file names list
1719 //
1720 
1721  ifstream in;
1722  in.open(ifname.Data());
1723  if(!in.good()) {
1724  cout << "CWB::Toolbox::getMergeJobList : Error Opening File : " << ifname << endl;
1725  gSystem->Exit(1);
1726  }
1727 
1728  vector<int> job;
1729  vector<TString> jfname;
1730 
1731  char istring[1024];
1732  while(1) {
1733  in.getline(istring,1024);
1734  if (!in.good()) break;
1735  TObjArray* token = TString(istring).Tokenize(TString('_'));
1736  TObjString* stoken =(TObjString*)token->At(token->GetEntries()-1);
1737  int jobID=TString(stoken->GetString()).ReplaceAll("job","").ReplaceAll(".root","").Atoi();
1738  if(jobID==0) continue; // file root is a merge file not a job file
1739  job.push_back(jobID);
1740  jfname.push_back(istring);
1741  if(token) delete token;
1742  }
1743 
1744  in.close();
1745 
1746  jobFileList.clear();
1747  vector<int> jobList;
1748  Int_t *id = new Int_t[job.size()];
1749  Int_t *jd = new Int_t[job.size()];
1750  for(int i=0;i<(int)job.size();i++) jd[i]=job[i];
1751  TMath::Sort((int)job.size(),jd,id,false);
1752  for(int i=0;i<(int)job.size();i++) {
1753  jobList.push_back(jd[id[i]]);
1754  jobFileList.push_back(jfname[id[i]]);
1755  }
1756  job.clear();
1757  jfname.clear();
1758  delete [] id;
1759  delete [] jd;
1760 
1761  return jobList;
1762 }
1763 
1764 /*--------------------------------------------------------------------------
1765  return the list of segments with length=segLen contained in the interval
1766  ilist time_max-time_min
1767  the edges of the segments are a multiple of segLen
1768 --------------------------------------------------------------------------*/
1769 //______________________________________________________________________________
1770 vector<waveSegment>
1771 CWB::Toolbox::getSlagJobList(vector<waveSegment> ilist, int seglen) {
1772 //
1773 // Extract Time MIN and MAX from the ilist
1774 // recompute MIN MAX to be a integer multiple of seglen
1775 // Compute the list of segments with length seglen within the MIN-MAX range
1776 //
1777 //
1778 // Input: ilist - list of segments (start,stop)
1779 // seglen - segment length
1780 //
1781 // Output: return the list of segment time ranges
1782 //
1783 
1784  if(ilist.size()==0) {cout << "CWB::Toolbox::getSlagJobList - Error ilist size=0" << endl;gSystem->Exit(1);}
1785  if(seglen<=0) {cout << "CWB::Toolbox::getSlagJobList - Error seglen<=0" << endl;gSystem->Exit(1);}
1786 
1787  waveSegment SEG;
1788  vector<waveSegment> jlist;
1789 
1790  int start=ilist[0].start;
1791  int stop=ilist[ilist.size()-1].stop;
1792  start=seglen*TMath::Nint(double(start/seglen));
1793  stop=seglen*TMath::Nint(double(stop/seglen));
1794 
1795  int njob=(stop-start)/seglen;
1796  for(int n=0;n<njob;n++) {
1797  SEG.start=start+n*seglen;
1798  SEG.stop=SEG.start+seglen;
1799  jlist.push_back(SEG);
1800  }
1801 
1802  return jlist;
1803 }
1804 
1805 //______________________________________________________________________________
1806 waveSegment
1807 CWB::Toolbox::getMaxSeg(vector<waveSegment> list) {
1808 //
1809 //
1810 // Input: list - segment list
1811 //
1812 // Return the segment with the maximum length
1813 //
1814 
1815  waveSegment SEG={0,0,0};
1816  for(int i=0;i<(int)list.size();i++) {
1817  if((list[i].stop-list[i].start)>(SEG.stop-SEG.start)) SEG=list[i];
1818  }
1819  return SEG;
1820 }
1821 
1822 //______________________________________________________________________________
1823 slag
1824 CWB::Toolbox::getSlag(vector<slag> slagList, int jobid) {
1825 //
1826 //
1827 // Input: slagList - slag list
1828 // jobid - job id
1829 //
1830 // Return SLAG structure with slagList.jobId == jobid
1831 //
1832 
1833  slag SLAG;SLAG.jobId=-1;
1834  for(int j=0;j<(int)slagList.size();j++) if(slagList[j].jobId==jobid) {SLAG=slagList[j];break;}
1835  return SLAG;
1836 }
1837 
1838 //______________________________________________________________________________
1839 vector<slag>
1840 CWB::Toolbox::getSlagList(vector<slag> islagList, vector<TString> ifos,
1841  double segLen, double segMin, double segEdge,
1842  int nDQF, dqfile* iDQF, CWB_CAT dqcat) {
1843 //
1844 //
1845 // Input: islagList - vector list of slag structures
1846 // ifos - vector list of ifo names
1847 // segLen - Segment length [sec]
1848 // segMin - Minimum Segment Length after dqcat [sec]
1849 // segEdge - wavelet boundary offset [sec]
1850 // nDQF - size of iDQF array
1851 // iDQF - DQ structure array
1852 // dqcat - dq cat
1853 //
1854 // if dqcat=CWB_CAT1 -> return the list of slags with dq len > segMin+2*segEdge
1855 // if dqcat=CWB_CAT2 -> return the list of slags with dq len > segMin
1856 //
1857 
1858  // dqcat must be CWB_CAT1 or CWB_CAT2
1859  if((dqcat!=CWB_CAT1)&&(dqcat!=CWB_CAT2)) {
1860  cout << "CWB::Toolbox::getSlagList : dqcat must be CWB_CAT1 or CWB_CAT2 !!!" << endl;
1861  gSystem->Exit(1);
1862  }
1863 
1864  int nIFO=0;
1865  slag SLAG;
1866  int lsize=islagList.size();
1867  int nRejected=0;
1868  int livetime1=0;
1869  int livetime2=0;
1870  int segLength=0;
1871  waveSegment SEG,MSEG;
1872  vector<waveSegment> dqList;
1873  vector<waveSegment> dq1List;
1874  vector<waveSegment> jobList;
1875  vector<waveSegment> segList;
1876  vector<slag> oslagList;
1877  int jobID=0;int segID[20];int slagID=0;
1878 
1879  if(lsize>0) nIFO=islagList[0].segId.size();
1880 
1881  dqfile* DQF = new dqfile[nDQF];
1882  for(int i=0;i<nDQF;i++) DQF[i]=iDQF[i];
1883 
1884  // get zero lag merged dq cat 1 list
1885  dq1List=readSegList(nDQF, DQF, CWB_CAT1);
1886  // get number/list of the available super lag jobs
1887  jobList=getSlagJobList(dq1List, segLen);
1888  cout << "input list size " << lsize << endl;
1889  cout << "jobList size " << jobList.size() << endl;
1890  dqList.clear();
1891 
1892  // read dq lists from files and store in ilist
1893  vector<waveSegment>* ilist = new vector<waveSegment>[nDQF];
1894  for(int i=0;i<nDQF;i++) ilist[i]=readSegList(DQF[i]);
1895 
1896  // get range segment for this job intersecting with cat1 list (dqList)
1897  for(int j=0;j<lsize;j++) {
1898  if(j%1000==0) printf("%6d - Rejected slags = %d/%lu\n",j,nRejected,islagList.size());
1899  SLAG = islagList[j]; // slag structure
1900  slagID = SLAG.slagId[0];
1901  jobID = SLAG.jobId;
1902  for(int n=0; n<nIFO; n++) segID[n]=SLAG.segId[n];
1903  cout.precision(2);
1904 
1905  // shift dq files
1906  for(int i=0;i<nDQF;i++) DQF[i].shift=0.;
1907  setSlagShifts(SLAG, ifos, segLen, nDQF, DQF);
1908 
1909  // create shifted merged dq cat file list
1910  dqList.clear();
1911  bool first=true;
1912  for(int i=0;i<nDQF;i++) {
1913  if(DQF[i].cat<=dqcat) {
1914  for(int k=0;k<(int)ilist[i].size();k++) { // apply time shifts
1915  ilist[i][k].start+=DQF[i].shift;
1916  ilist[i][k].stop+=DQF[i].shift;
1917  }
1918  if(first) {dqList=ilist[i];first=false;}
1919  else dqList = mergeSegLists(ilist[i],dqList);
1920  for(int k=0;k<(int)ilist[i].size();k++) { // restore time shifts
1921  ilist[i][k].start-=DQF[i].shift;
1922  ilist[i][k].stop-=DQF[i].shift;
1923  }
1924  }
1925  }
1926 
1927  // create job file list
1928  if(dqList.size()==0) continue;
1929 
1930  segList.clear();
1931  SEG.start = jobList[segID[0]-1].start-segEdge;
1932  SEG.stop = jobList[segID[0]-1].stop+segEdge;
1933 
1934  if(dqcat==CWB_CAT2) {
1935 
1936  // create shifted merged dq cat1 file list
1937  dq1List.clear();
1938  bool first=true;
1939  for(int i=0;i<nDQF;i++) {
1940  if(DQF[i].cat<=CWB_CAT1) {
1941  for(int k=0;k<(int)ilist[i].size();k++) { // apply time shifts
1942  ilist[i][k].start+=DQF[i].shift;
1943  ilist[i][k].stop+=DQF[i].shift;
1944  }
1945  if(first) {dq1List=ilist[i];first=false;}
1946  else dq1List = mergeSegLists(ilist[i],dq1List);
1947  for(int k=0;k<(int)ilist[i].size();k++) { // restore time shifts
1948  ilist[i][k].start-=DQF[i].shift;
1949  ilist[i][k].stop-=DQF[i].shift;
1950  }
1951  }
1952  }
1953 
1954  segList.push_back(SEG);
1955  segList = mergeSegLists(dq1List,segList); // merge detector segments with dq cat 1
1956  SEG = getMaxSeg(segList); // extract max length segment (only this segment is used for analysis)
1957  SEG.start+=segEdge;
1958  SEG.stop-=segEdge;
1959  segList.clear();
1960  }
1961 
1962  segList.push_back(SEG);
1963  segList = mergeSegLists(dqList,segList); // merge detector segments with dq cat
1964  double lenTHR;
1965  if(dqcat==CWB_CAT1) {
1966  MSEG = getMaxSeg(segList); // max length segment
1967  segLength=MSEG.stop-MSEG.start;
1968  lenTHR=segMin+2*segEdge;
1969  }
1970  if(dqcat==CWB_CAT2) {
1971  segLength=getTimeSegList(segList);
1972  lenTHR=segMin;
1973  }
1974  livetime1+=segLength;
1975  if(segLength<lenTHR) {
1976  nRejected++;
1977  } else {
1978  livetime2+=segLength;
1979  oslagList.push_back(SLAG);
1980  }
1981  }
1982  printf("%6lu - Rejected slags = %d/%lu\n\n",islagList.size(),nRejected,islagList.size());
1983  printf("Slag livetime before dq cat%d is approximately %d sec \t= %.2f days\n",dqcat,livetime1,double(livetime1)/86400.);
1984  printf("Slag livetime after dq cat%d is approximately %d sec \t= %.2f days\n",dqcat,livetime2,double(livetime2)/86400.);
1985 
1986  dqList.clear();
1987  dq1List.clear();
1988  for(int i=0;i<nDQF;i++) ilist[i].clear();
1989  delete [] ilist;
1990  delete [] DQF;
1991 
1992  return oslagList;
1993 }
1994 
1995 //______________________________________________________________________________
1996 void
1997 CWB::Toolbox::setSlagShifts(slag SLAG, vector<TString> ifos, double segLen, int nDQF, dqfile* DQF) {
1998 //
1999 // Apply slag shifts into the DQF structures (DQF[].shift)
2000 //
2001 // Input: SLAG - slag structure
2002 // segLen - segment length
2003 // nDQF - size of DQF array
2004 // DQF - array of DQ structures
2005 //
2006 
2007 
2008  // shift dq files
2009  for(int i=0;i<nDQF;i++) {
2010  int ifoID=-1;
2011  for(int j=0;j<(int)ifos.size();j++) if(ifos[j]==DQF[i].ifo) ifoID=j;
2012  if(ifoID==-1) {
2013  cout << "CWB::Toolbox::setSlagShifts - " << DQF[i].ifo << " is not in the contained into ifos vector" << endl;
2014  gSystem->Exit(1);
2015  }
2016  if(ifoID>=(int)SLAG.segId.size()) {
2017  cout << "CWB::Toolbox::setSlagShifts - " << DQF[i].ifo << " index " << ifoID << "is not correct" << endl;
2018  gSystem->Exit(1);
2019  }
2020  DQF[i].shift+=-segLen*(SLAG.segId[ifoID]-SLAG.segId[0]); // apply slag shift to dq
2021  }
2022 
2023  return;
2024 }
2025 
2026 //______________________________________________________________________________
2027 vector<waveSegment>
2028 CWB::Toolbox::getSegList(slag SLAG, vector<waveSegment> jobList,
2029  double segLen, double segMLS, double segEdge,
2030  vector<waveSegment> dqList) {
2031 //
2032 // create merged dq cat 1 file list
2033 //
2034 // Input: SLAG - slag structure
2035 // jobList - list of available super lag segments
2036 // segLen - Segment length [sec]
2037 // segMLS - Minimum Segment Length after DQ_CAT1 [sec]
2038 // segEdge - wavelet boundary offset [sec]
2039 // dqList - dq cat1 list
2040 //
2041 // Return the detector's slag segment ranges associated to SLAG infos & dq cat1 list
2042 //
2043 
2044  waveSegment SEG,MSEG;
2045  vector<waveSegment> segList;
2046 
2047  int nIFO=SLAG.segId.size();
2048 
2049  // get range segment for this job intersecting with cat1 list (dqList)
2050  SEG.start = jobList[SLAG.segId[0]-1].start-segEdge;
2051  SEG.stop = jobList[SLAG.segId[0]-1].stop+segEdge;
2052  segList.push_back(SEG);
2053  segList = mergeSegLists(dqList,segList); // merge detector segments with dq cat 1
2054  MSEG = getMaxSeg(segList); // extract max length segment (only this segment is used for analysis)
2055  int segLength=MSEG.stop-MSEG.start;
2056  if(segLength<segMLS+2*segEdge) {
2057  cout << "CWB::Toolbox::getSegList - Segment length too small : " << segLength << endl;
2058  gSystem->Exit(1);
2059  }
2060 
2061  segList.clear();
2062  for(int n=0; n<nIFO; n++) {
2063  SEG.start = MSEG.start+segLen*(SLAG.segId[n]-SLAG.segId[0])+segEdge;
2064  SEG.stop = MSEG.stop+segLen*(SLAG.segId[n]-SLAG.segId[0])-segEdge;
2065  segList.push_back(SEG);
2066  }
2067  jobList.clear();
2068 
2069  return segList;
2070 }
2071 
2072 //_______________________________________________________________________________________
2073 double
2074 CWB::Toolbox::getLiveTime(vector<waveSegment>& jobList, vector<waveSegment>& dqList) {
2075 
2076  vector<double> dummy;
2077  return getLiveTime(jobList, dqList, dummy);
2078 }
2079 
2080 //_______________________________________________________________________________________
2081 double
2082 CWB::Toolbox::getLiveTime(vector<waveSegment>& jobList, vector<waveSegment>& dqList, vector<double> shiftList) {
2083 //
2084 // return live time in sec
2085 //
2086 // NOTE : this procedure compute the livetime of the jobList after dq=cat2 when lags are applied
2087 // the returned livetime should be with a good approximation consistent
2088 // with the one computed by the cWB algorithm
2089 //
2090 // Input: jobList - job list
2091 // dqList - data quality list
2092 // shiftList - list of time shifts (sec), the size is the detector number
2093 // shift[0]=shift_ifo_1, shift[1]=shift_ifo_2, ... shift[n-1]=shift_ifo_n
2094 // if shift list size is 0 then no shifts are applied
2095 //
2096 // Procedure : for each time shift and for each job the data quality list inside the job interval
2097 // are circulary rotated by a time=shift, the new shifted list is saved into a new segment list
2098 // finaly the new segment list are merged and the total livetime is returned
2099 //
2100 
2101  if(shiftList.size()==0) shiftList.push_back(0.);
2102  int nshift = shiftList.size(); // extract the number of shifts
2103 
2104  waveSegment seg;
2105  vector<waveSegment>* segList = new vector<waveSegment>[nshift];
2106  vector<waveSegment> mergeList=mergeSegLists(jobList,dqList);
2107 
2108  for(int i=0;i<nshift;i++) { // loop over shifts
2109  double shift = shiftList[i];
2110  if(shift==0) {segList[i]=mergeList;continue;} // skip if shift=0
2111  int jsize = jobList.size();
2112  for(int j=0;j<jsize;j++) { // loop over job list
2113  double jstart = jobList[j].start;
2114  double jstop = jobList[j].stop;
2115  double jlen = jstop-jstart;
2116  int ksize = mergeList.size();
2117  for(int k=0;k<ksize;k++) { // loop over dq list
2118  double kstart = mergeList[k].start;
2119  double kstop = mergeList[k].stop;
2120  if((kstop<=jstart)||(kstart>=jstop)) continue; // skip dq outside the job range
2121  // add shift
2122  kstart+=shift;
2123  kstop +=shift;
2124  // circular shift
2125  if(kstop<=jstop) {
2126  seg.start=kstart;seg.stop=kstop;segList[i].push_back(seg);
2127  }
2128  if(kstart>=jstop) {
2129  seg.start=kstart-jlen;seg.stop=kstop-jlen;segList[i].push_back(seg);
2130  }
2131  if((kstart<jstop)&&(kstop>jstop)) {
2132  seg.start=kstart;seg.stop=jstop;segList[i].push_back(seg);
2133  seg.start=jstart;seg.stop=kstop-jlen;segList[i].push_back(seg);
2134  }
2135  }
2136  }
2137  }
2138 
2139  // sort lists (needed by mergeSegLists)
2140  for(int i=0;i<nshift;i++) segList[i]=unionSegments(segList[i]);
2141 
2142  // merge segLists
2143  for(int i=1;i<nshift;i++) segList[0]=mergeSegLists(segList[0],segList[i]);
2144 
2145  double livetime=getTimeSegList(segList[0]);
2146  for(int i=0;i<nshift;i++) segList[i].clear();
2147  delete [] segList;
2148 
2149  return livetime;
2150 }
2151 
2152 //______________________________________________________________________________
2153 int
2154 CWB::Toolbox::shiftBurstMDCLog(std::vector<std::string>& mdcList, vector<TString> ifos, double mdc_shift) {
2155 //
2156 // apply a time shift to the log entries contained in the mdcList
2157 //
2158 // Input: mdcList - list of the log string (one entry for each injected MDC)
2159 // ifos - array of input detector's names
2160 // mdc_shift - time shift
2161 //
2162 
2163  cout.precision(14);
2164  for(int i=0;i<(int)mdcList.size();i++) {
2165  char mdc_string[1024]="";
2166  //cout << "IN-" << mdcList[i] << endl;
2167  TObjArray* token = TString(mdcList[i]).Tokenize(' ');
2168  sprintf(mdc_string,"%s",(((TObjString*)token->At(0))->GetString()).Data());
2169  for(int j=1;j<9;j++)
2170  sprintf(mdc_string,"%s %s",mdc_string,(((TObjString*)token->At(j))->GetString()).Data());
2171  double frTime = (((TObjString*)token->At(9))->GetString()).Atof();
2172  sprintf(mdc_string,"%s %10.6f",mdc_string,frTime+mdc_shift);
2173  //cout << "TIME " << frTime << endl;
2174  double mdcTime = (((TObjString*)token->At(10))->GetString()).Atof();
2175  sprintf(mdc_string,"%s %10.6f",mdc_string,mdcTime+mdc_shift);
2176  //cout << "TIME " << mdcTime << endl;
2177  for(int j=11;j<15;j++)
2178  sprintf(mdc_string,"%s %s",mdc_string,(((TObjString*)token->At(j))->GetString()).Data());
2179  for(int j=15;j<token->GetEntries();j++) {
2180  TString stoken = ((TObjString*)token->At(j))->GetString();
2181  sprintf(mdc_string,"%s %s",mdc_string,stoken.Data());
2182  for(int n=0;n<(int)ifos.size();n++) {
2183  if(ifos[n]==stoken) {
2184  double ifoTime = (((TObjString*)token->At(j+1))->GetString()).Atof();
2185  sprintf(mdc_string,"%s %10.6f",mdc_string,ifoTime+mdc_shift);
2186  //cout << "TIME " << ifos[n].Data() << " " << ifoTime << endl;
2187  j++;
2188  }
2189  }
2190  }
2191  mdcList[i]=mdc_string;
2192  //cout << "OUT-" << mdcList[i] << endl;
2193  if(token) delete token;
2194  }
2195 
2196  return 0;
2197 }
2198 
2199 //______________________________________________________________________________
2200 TString
2202 //
2203 // set entry at position pos contained in the log string
2204 //
2205 // Input: log - log string
2206 // pos - entry position in the log string
2207 // val - string value used to modify the log string
2208 //
2209 // return the modified log string
2210 //
2211 
2212  char sval[32];sprintf(sval,"%e",val);
2213  return SetMDCLog(log, pos, sval);
2214 }
2215 
2216 //______________________________________________________________________________
2217 TString
2219 //
2220 // set entry at position pos contained in the log string
2221 //
2222 // Input: log - log string
2223 // pos - entry position in the log string
2224 // val - string value used to modify the log string
2225 //
2226 // return the modified log string
2227 //
2228 
2229  char log_string[1024]="";
2230 
2231  TObjArray* token = TString(log).Tokenize(' ');
2232  for(int n=0;n<token->GetEntries();n++) {
2233  if(n==pos) sprintf(log_string,"%s %s",log_string, val.Data());
2234  else sprintf(log_string,"%s %s",log_string, (((TObjString*)token->At(n))->GetString()).Data());
2235  }
2236  if(token) delete token;
2237 
2238  return log_string;
2239 }
2240 
2241 //______________________________________________________________________________
2242 int
2244 //
2245 // return the number of entries contained in the log string
2246 //
2247 // Input: log - log string
2248 //
2249 
2250  TObjArray* token = TString(log).Tokenize(' ');
2251  int size = token->GetEntries();
2252  delete token;
2253  return size;
2254 }
2255 
2256 //______________________________________________________________________________
2257 TString
2259 //
2260 // return the entry at position pos contained in the log string
2261 //
2262 // Input: log - log string
2263 // pos - entry position in the log string
2264 //
2265 
2266  TObjArray* token = TString(log).Tokenize(' ');
2267  for(int n=0;n<token->GetEntries();n++) {
2268  if(n==pos) return (((TObjString*)token->At(n))->GetString()).Data();
2269  }
2270  delete token;
2271  return "";
2272 }
2273 
2274 //______________________________________________________________________________
2275 double
2277 //
2278 // compute the MDC time shift to be applied to MDC data
2279 //
2280 // mshift - mdc shift structure
2281 // time - time
2282 //
2283 // the GPS range P=[mshift.startMDC,mshift.stopMDC] defines the MDC period to be used
2284 //
2285 // startMDC stopMDC
2286 // ^ ^
2287 // ................|xxxxxx P xxxxxx|..............
2288 //
2289 // the period P is replicated starting from mshift.offset
2290 //
2291 // mshift.offset time
2292 // ^ ^
2293 // ...|xxxxxx P xxxxxx|xxxxxx P xxxxxx|xxxxxx P xxxxxx|...
2294 // ^
2295 // mshift.offset+mlength*int(time/mlength)
2296 //
2297 // |.. return shift ..|
2298 //
2299 
2300  if(mshift.startMDC<=0.) return 0.;
2301  double mlength = mshift.stopMDC-mshift.startMDC;
2302  if(mlength<=0) return 0.;
2303  return mshift.offset+mlength*int(time/mlength)-mshift.startMDC;
2304 }
2305 
2306 //______________________________________________________________________________
2307 vector<TString>
2309  TString label, bool brms, bool bvar, bool bpsm) {
2310 //
2311 // merge list of tree contained in dir_name using threads
2312 //
2313 // nthreads - number of threads
2314 // simulation - true/false -> simulation/background
2315 // odir - output directory where to store the merged file
2316 // label - label used for the output file name
2317 // brms - true -> merge rms tree
2318 // bvar - true -> merge variability tree
2319 // bpsm - true -> merge probability skymap tree
2320 //
2321 
2322  vector<TString> fileList = getFileListFromDir(dir_name,".root","","wave_");
2323  mergeCWBTrees(nthreads, fileList, simulation, odir, label, brms, bvar, bpsm);
2324  return fileList;
2325 }
2326 
2327 //______________________________________________________________________________
2328 void
2329 CWB::Toolbox::mergeCWBTrees(int nthreads, vector<TString> fileList, bool simulation,
2330  TString odir, TString label, bool brms, bool bvar, bool bpsm) {
2331 //
2332 // merge list of tree contained in the root files listed in fileList using threads
2333 //
2334 // nthreads - number of threads
2335 // ... - see descriptions of parameters in the n the overload methods
2336 //
2337 
2338  if(nthreads>MAX_THREADS) {
2339  cout << "CWB::Toolbox::mergeCWBTrees : Error - nthreads must be <= : " << MAX_THREADS << endl;
2340  exit(1);
2341  }
2342 
2343  TThread *thread[MAX_THREADS];
2344  MergeParms mergeParms[MAX_THREADS];
2345  vector<TString> fList[MAX_THREADS];
2346  int lSize[MAX_THREADS];
2347  TString tLabel[MAX_THREADS];
2348  vector<TString> waveList;
2349  vector<TString> mdcList;
2350  vector<TString> liveList;
2351  vector<TString> rmsList;
2352  vector<TString> varList;
2353 
2354  // compute file lists size
2355  int listSize=1;
2356  if(fileList.size()<=nthreads) {
2357  nthreads=1;
2358  lSize[0]=fileList.size();
2359  } else {
2360  if(fileList.size()%nthreads!=0) {
2361  for(int i=0;i<nthreads;i++) lSize[i]=int(fileList.size()/nthreads);
2362  lSize[0]+=fileList.size()%nthreads;
2363  } else {
2364  for(int i=0;i<nthreads;i++) lSize[i]=int(fileList.size()/nthreads);
2365  }
2366  }
2367 
2368  // fill file lists merged files name
2369  int k=0;
2370  for(int i=0;i<nthreads;i++) {
2371  for(int j=0;j<lSize[i];j++) fList[i].push_back(fileList[k++]);
2372  tLabel[i]=TString::Format("%s.T%d",label.Data(),i);
2373 
2374  waveList.push_back(TString::Format("%s/wave_%s.root",odir.Data(),tLabel[i].Data()));
2375  if(simulation) {
2376  mdcList.push_back(TString::Format("%s/mdc_%s.root",odir.Data(),tLabel[i].Data()));
2377  } else {
2378  liveList.push_back(TString::Format("%s/live_%s.root",odir.Data(),tLabel[i].Data()));
2379  if(brms) rmsList.push_back(TString::Format("%s/rms_%s.root",odir.Data(),tLabel[i].Data()));
2380  if(bvar) varList.push_back(TString::Format("%s/var_%s.root",odir.Data(),tLabel[i].Data()));
2381  }
2382  }
2383 
2384  // fill merge structures
2385  for(int i=0;i<nthreads;i++) {
2386  mergeParms[i].threadID = i;
2387  mergeParms[i].fileList = fList[i];
2388  mergeParms[i].simulation = simulation;
2389  mergeParms[i].odir = odir;
2390  mergeParms[i].label = tLabel[i];
2391  mergeParms[i].brms = brms;
2392  mergeParms[i].bvar = bvar;
2393  mergeParms[i].bpsm = bpsm;
2394  }
2395 
2396  // create & start threads
2397  for(int i=0;i<nthreads;i++) {
2398  char name[128]; sprintf(name,"Merge.T%d",i);
2399  thread[i] = new TThread(name, MergeHandle, (void*) &mergeParms[i]);
2400  thread[i]->Run();
2401  printf("Starting Thread : %s\n",name);
2402  }
2403 
2404  // join threads
2405  for(int i=0;i<nthreads;i++) thread[i]->Join();
2406 
2407  // merge final output merged files
2408  TString fName;
2409 
2410  fName=TString::Format("wave_%s",label.Data());
2411  if(waveList.size()) {
2412  mergeTrees(waveList, "waveburst", odir, fName, true);
2413  for(int i=0;i<waveList.size();i++) gSystem->Exec("rm "+waveList[i]);
2414  }
2415  fName=TString::Format("mdc_%s",label.Data());
2416  if(mdcList.size()) {
2417  mergeTrees(mdcList, "mdc", odir, fName, true);
2418  for(int i=0;i<waveList.size();i++) gSystem->Exec("rm "+mdcList[i]);
2419  }
2420  fName=TString::Format("live_%s",label.Data());
2421  if(liveList.size()) {
2422  mergeTrees(liveList, "liveTime", odir, fName, true);
2423  for(int i=0;i<liveList.size();i++) gSystem->Exec("rm "+liveList[i]);
2424  }
2425  fName=TString::Format("rms_%s",label.Data());
2426  if(rmsList.size()) {
2427  mergeTrees(rmsList, "noise", odir, fName, true);
2428  for(int i=0;i<rmsList.size();i++) gSystem->Exec("rm "+rmsList[i]);
2429  }
2430  fName=TString::Format("var_%s",label.Data());
2431  if(varList.size()) {
2432  mergeTrees(varList, "variability", odir, fName, true);
2433  for(int i=0;i<varList.size();i++) gSystem->Exec("rm "+varList[i]);
2434  }
2435 
2436  // delete threads
2437  for(int i=0;i<nthreads;i++) delete thread[i];
2438 }
2439 
2440 //______________________________________________________________________________
2441 vector<TString>
2443  TString label, bool brms, bool bvar, bool bpsm) {
2444 //
2445 // merge trees contained in dir_name
2446 //
2447 // simulation - true/false -> simulation/background
2448 // odir - output directory where to store the merged file
2449 // label - label used for the output file name
2450 // brms - true -> merge rms tree
2451 // bvar - true -> merge variability tree
2452 // bpsm - true -> merge probability skymap tree
2453 //
2454 
2455  vector<TString> fileList = getFileListFromDir(dir_name,".root","","wave_");
2456  mergeCWBTrees(fileList, simulation, odir, label, brms, bvar, bpsm);
2457  return fileList;
2458 }
2459 
2460 //______________________________________________________________________________
2461 void
2463  TString label, bool brms, bool bvar, bool bpsm) {
2464 //
2465 // merge list of tree contained in the root files listed in fileList
2466 //
2467 // Input: fileList - list of tree root files
2468 // simulation - true/false -> simulation/background
2469 // odir - output directory where to store the merged file
2470 // label - label used for the output file name
2471 // if simulation=true the following files are created
2472 // - 'odir'/wave_'label'.root // detected events
2473 // - 'odir'/mdc_'label'.root // injected events
2474 // - 'odir'/merge_'label'.lst // list of merged files
2475 // if simulation=false the following files are created
2476 // - 'odir'/wave_'label'.root // detected events
2477 // - 'odir'/live_'label'.root // live times
2478 // - 'odir'/merge_'label'.lst // list of merged files
2479 // - 'odir'/rms_'label'.root // if brms=true
2480 // - 'odir'/var_'label'.root // if bvar=true
2481 // brms - true -> merge rms tree
2482 // bvar - true -> merge variability tree
2483 // bpsm - true -> merge probability skymap tree
2484 //
2485 
2486  char s[1024];
2487  char f[1024];
2488  char cmd[4096];
2489 
2490  char c;
2491  if (simulation==1) c = 's';
2492  else c = 'b';
2493  if (simulation)
2494  cout << "CWB::Toolbox::mergeCWBTrees - Start merging "
2495  << fileList.size() << " files (simulation) ..." << endl;
2496  else
2497  cout << "CWB::Toolbox::mergeCWBTrees - Start merging "
2498  << fileList.size() << " files (production) ..." << endl;
2499 
2500  TChain wav("waveburst");
2501  if(!bpsm) wav.SetBranchStatus("Psm",false); // include/exclude from merge the probability skymap
2502  wav.SetMaxTreeSize(MAX_TREE_SIZE);
2503  TChain mdc("mdc");
2504  TChain rms("noise");
2505  TChain var("variability");
2506  TChain liv("liveTime");
2507  int ZombieCnt = 0;
2508 
2509  CWB::History* history = NULL;
2510 
2511  int nfiles=0;
2512  bool bhistory=true;
2513  cout << "CWB::Toolbox::mergeCWBTrees - Add file to chain in progress ..." << endl;
2514  for(int n=0;n<(int)fileList.size();n++) {
2515  sprintf(f,"%s",fileList[n].Data());
2516  //cout << f << endl;
2517 
2518 /* this stuff has been commented out to speed up the merging phase
2519  TFile f1(f,"READ");
2520 
2521  if(f1.IsZombie()) {
2522  ZombieCnt++;
2523  sprintf(cmd,"mv %s %s.zombie",f,f);
2524  cout<<cmd<<endl;
2525  gSystem->Exec(cmd);
2526 
2527  // Check if file txt exist
2528  char txtfile[1024];
2529  sprintf(txtfile,"%s",f);
2530  Long_t id,size,flags,mt;
2531  int estat = gSystem->GetPathInfo(txtfile,&id,&size,&flags,&mt);
2532  if (estat==0) {
2533  TString cmd2 = cmd;
2534  cmd2.ReplaceAll(".root",".txt");
2535  gSystem->Exec(cmd2.Data());
2536  cout<<"Zombie file!!! Renamed root and txt files as :"<<f<<".zombie"<<endl;
2537  }
2538  continue;
2539  }
2540 */
2541 
2542  if(bhistory) {
2543  TFile f1(f,"READ");
2544  history=(CWB::History*)f1.Get("history");
2545  if(history==NULL) history=new CWB::History();
2546  bhistory=false;
2547  }
2548 
2549  wav.Add(f);
2550  if (++nfiles%1000==0) cout << "CWB::Toolbox::mergeCWBTrees - " << nfiles
2551  << "/" << fileList.size() << " files" << endl;
2552  if(c=='s') mdc.Add(f);
2553  else { liv.Add(f); if(brms) rms.Add(f); if(bvar) var.Add(f);}
2554  }
2555 
2556  sprintf(s,"%s/wave_%s.root",odir.Data(),label.Data());
2557  cout << "CWB::Toolbox::mergeCWBTrees - Merging " << s << " in progress ..." << endl;
2558  wav.Merge(s);
2559 
2560  // update history
2561  if(history!=NULL) {
2562  history->SetHistoryModify(true);
2563  const CWB::HistoryStage* stage = history->GetStage(CCAST("MERGE"));
2564  if(stage==NULL) {
2565  history->AddStage(CCAST("MERGE"));
2566  if(!history->TypeAllowed(CCAST("WORKDIR"))) history->AddType(CCAST("WORKDIR"));
2567  char work_dir[512]="";
2568  sprintf(work_dir,"%s",gSystem->WorkingDirectory());
2569  history->AddHistory(CCAST("MERGE"), CCAST("WORKDIR"), work_dir);
2570  }
2571  }
2572  // write history to merge file
2573  if(history!=NULL) {
2574  TFile fwav(s,"UPDATE");
2575  history->Write("history");
2576  fwav.Close();
2577  }
2578 
2579  if(c=='s') {
2580  sprintf(s,"%s/mdc_%s.root",odir.Data(),label.Data());
2581  cout << "CWB::Toolbox::mergeCWBTrees - Merging " << s << " in progress ..." << endl;
2582  mdc.Merge(s);
2583  // write history to merge file
2584  if(history!=NULL) {
2585  TFile fmdc(s,"UPDATE");
2586  history->Write();
2587  fmdc.Close();
2588  }
2589  }
2590  else {
2591  sprintf(s,"%s/live_%s.root",odir.Data(),label.Data());
2592  cout << "CWB::Toolbox::mergeCWBTrees - Merging " << s << " in progress ..." << endl;
2593  liv.Merge(s);
2594  // write history to merge file
2595  if(history!=NULL) {
2596  TFile fliv(s,"UPDATE");
2597  history->Write();
2598  fliv.Close();
2599  }
2600  if(brms) {
2601  sprintf(s,"%s/rms_%s.root",odir.Data(),label.Data());
2602  cout << "CWB::Toolbox::mergeCWBTrees - Merging " << s << " in progress ..." << endl;
2603  rms.Merge(s);
2604  if(history!=NULL) {
2605  TFile frms(s,"UPDATE");
2606  history->Write();
2607  frms.Close();
2608  }
2609  }
2610  if(bvar) {
2611  sprintf(s,"%s/var_%s.root",odir.Data(),label.Data());
2612  cout << "CWB::Toolbox::mergeCWBTrees - Merging " << s << " in progress ..." << endl;
2613  var.Merge(s);
2614  if(history!=NULL) {
2615  TFile fvar(s,"UPDATE");
2616  history->Write();
2617  fvar.Close();
2618  }
2619  }
2620  }
2621  if(history!=NULL) delete history;
2622 
2623  cout << "CWB::Toolbox::mergeCWBTrees - Merged files : " << nfiles<<endl;
2624  //cout << "CWB::Toolbox::mergeCWBTrees - Zombie files : " << ZombieCnt<<endl;
2625  return;
2626 }
2627 
2628 //______________________________________________________________________________
2629 void
2631  TString odir, TString ofName, bool bhistory) {
2632 //
2633 // merge list of tree contained in the root files listed in fileList
2634 //
2635 // Input: fileList - list of tree root files
2636 // treeName - name of tree
2637 // odir - output directory where to store the merged file
2638 // ofName - name used for the output file name
2639 // if ofName not ends with ".root" then ofile_name = 'odir'/'ofName'.root
2640 // else ofile_name = 'odir'/'ofName'
2641 // bhistory - if true then the history is copied into the merged file
2642 //
2643 
2644  char s[1024];
2645  char f[1024];
2646  char cmd[4096];
2647 
2648  cout << "CWB::Toolbox::mergeTrees - Start merging "
2649  << fileList.size() << " files (simulation) ..." << endl;
2650 
2651  TChain tree(treeName);
2652  tree.SetMaxTreeSize(MAX_TREE_SIZE);
2653  int ZombieCnt = 0;
2654 
2655  CWB::History* history = NULL;
2656 
2657  int nfiles=0;
2658  cout << "CWB::Toolbox::mergeTrees - Add file to chain in progress ..." << endl;
2659  for(int n=0;n<(int)fileList.size();n++) {
2660  sprintf(f,"%s",fileList[n].Data());
2661  //cout << f << endl;
2662  TFile f1(f,"READ");
2663 
2664  if(f1.IsZombie()) {
2665  ZombieCnt++;
2666  sprintf(cmd,"mv %s %s.zombie",f,f);
2667  cout<<cmd<<endl;
2668  gSystem->Exec(cmd);
2669 
2670  // Check if file txt exist
2671  char txtfile[1024];
2672  sprintf(txtfile,"%s",f);
2673  Long_t id,size,flags,mt;
2674  int estat = gSystem->GetPathInfo(txtfile,&id,&size,&flags,&mt);
2675  if (estat==0) {
2676  TString cmd2 = cmd;
2677  cmd2.ReplaceAll(".root",".txt");
2678  gSystem->Exec(cmd2.Data());
2679  cout<<"Zombie file!!! Renamed root and txt files as :"<<f<<".zombie"<<endl;
2680  }
2681  continue;
2682  }
2683 
2684  if(bhistory) {
2685  TFile f1(f,"READ");
2686  history=(CWB::History*)f1.Get("history");
2687  if(history==NULL) history=new CWB::History();
2688  bhistory=false;
2689  }
2690 
2691  tree.Add(f);
2692  if (++nfiles%1000==0) cout << "CWB::Toolbox::mergeTrees - " << nfiles
2693  << "/" << fileList.size() << " files" << endl;
2694  }
2695 
2696  if(ofName.EndsWith(".root")) {
2697  sprintf(s,"%s/%s",odir.Data(),ofName.Data());
2698  } else {
2699  sprintf(s,"%s/%s.root",odir.Data(),ofName.Data());
2700  }
2701  cout << "CWB::Toolbox::mergeTrees - Merging " << s << " in progress ..." << endl;
2702  tree.Merge(s);
2703 
2704  // write history to merge file
2705  if(history!=NULL) {
2706  TFile froot(s,"UPDATE");
2707  history->Write("history");
2708  froot.Close();
2709  }
2710  if(history!=NULL) delete history;
2711 
2712  cout << "CWB::Toolbox::mergeTrees - Merged files : " << nfiles<<endl;
2713  cout << "CWB::Toolbox::mergeTrees - Zombie files : " << ZombieCnt<<endl;
2714  return;
2715 }
2716 
2717 //______________________________________________________________________________
2718 vector<TString>
2720 //
2721 // read file from ifName file
2722 //
2723 // Input: ifName - input file name
2724 //
2725 // return a vector of the file names contained in ifName
2726 //
2727 
2728  ifstream in;
2729  in.open(ifName.Data(),ios::in);
2730  if(!in.good()) {
2731  cout << "CWB::Toolbox::readFileList - Error Opening File : " << ifName.Data() << endl;
2732  gSystem->Exit(1);
2733  }
2734 
2735  vector<TString> fileList;
2736 
2737  char istring[8192];
2738  while (1) {
2739  in.getline(istring,8192);
2740  if (!in.good()) break;
2741  fileList.push_back(istring);
2742  }
2743 
2744  return fileList;
2745 }
2746 
2747 //______________________________________________________________________________
2748 void
2750 //
2751 // write file list to ofName file
2752 //
2753 // Input: fileList - input file list
2754 // ofName - output file name
2755 //
2756 
2757  char ofile_name[256];
2758  if(ofName[0]!='/') {
2759  sprintf(ofile_name,"%s/%s",gSystem->WorkingDirectory(),ofName.Data());
2760  } else {
2761  sprintf(ofile_name,"%s",ofName.Data());
2762  }
2763  cout << ofile_name << endl;
2764  ofstream out;
2765  out.open(ofile_name,ios::out);
2766  if (!out.good()) {cout << "CWB::Toolbox::dumpFileList - Error Opening File : " << ofName.Data() << endl;gSystem->Exit(1);}
2767 
2768  for (int i=0;i<(int)fileList.size();i++) {
2769  out << fileList[i] << endl;
2770  }
2771 
2772  out.close();
2773 
2774  return;
2775 }
2776 
2777 //______________________________________________________________________________
2778 vector<waveSegment>
2780  double segLen, double segMLS, double segEdge,
2781  vector<waveSegment> dqList) {
2782 //
2783 // create merged dq cat 1 file list
2784 //
2785 // Input: jobId - job number
2786 // nIfO - detector number
2787 // segLen - Segment length [sec]
2788 // segMLS - Minimum Segment Length after DQ_CAT1 [sec]
2789 // segEdge - wavelet boundary offset [sec]
2790 // dqList - dq cat1 list
2791 //
2792 // Return the detector's slag segment ranges associated to SLAG infos & dq cat1 list
2793 //
2794 
2795 
2796  if (jobId<1) {cout << "CWB::Toolbox::getSegList - Error : jobId must be > 0" << endl;gSystem->Exit(1);}
2797 
2798  vector<waveSegment> jobList = getJobList(dqList, segLen, segMLS, segEdge); // get standard job list
2799 
2800  if (jobId>(int)jobList.size()) {
2801  cout << "CWB::Toolbox::getSegList - Error : jobId is > max jobs " << jobList.size() << endl;
2802  gSystem->Exit(1);
2803  }
2804 
2805  vector<waveSegment> detSegs(nIFO);
2806  for(int i=0;i<nIFO;i++) detSegs[i] = jobList[jobId-1];
2807 
2808  jobList.clear();
2809 
2810  return detSegs;
2811 }
2812 
2813 //______________________________________________________________________________
2814 char*
2816 //
2817 // return the file content in a char buffer
2818 //
2819 // Input: ifName - file name
2820 //
2821 
2822  char* fileBuffer=NULL;
2823 
2824  Long_t id,size,flags,mt;
2825  int estat = gSystem->GetPathInfo(ifName.Data(),&id,&size,&flags,&mt);
2826  if (estat==0) {
2827 
2828  ifstream in;
2829  in.open(ifName.Data(),ios::in);
2830  if(!in.good()) {
2831  cout << "CWB::Toolbox::readFile - Error Opening File : " << ifName.Data() << endl;
2832  gSystem->Exit(1);
2833  }
2834 
2835  fileBuffer = new char[2*size+1];
2836  bzero(fileBuffer,(2*size+1)*sizeof(char));
2837 
2838  char istring[8192];
2839  int fileLength = 0;
2840  while (1) {
2841  in.getline(istring,8192);
2842  if (!in.good()) break;
2843  //cout << istring << endl;
2844  int len = strlen(istring);
2845  istring[len]=0x0a;
2846  strncpy(fileBuffer+fileLength,istring,len+1);
2847  fileLength += len+1;
2848  }
2849  }
2850 
2851  return fileBuffer;
2852 }
2853 
2854 //______________________________________________________________________________
2855 int
2856 CWB::Toolbox::setCuts(TString ifName, TString idir, TString odir, TString trname, TString cuts, TString olabel) {
2857 //
2858 // apply selection cuts to trname tree in ifname root file
2859 // and create an output root file with the selected tree entries
2860 // return selected entries
2861 //
2862 // ifname : input root file name
2863 // idir : input dir
2864 // trname : tree name
2865 // cuts : selection cuts (Ex: netcc[2]>0.5)
2866 // odir : output dir
2867 // olabel : output label used in the output file name (Ex: cc2_gt_0d5)
2868 // ofname.root = ifname.Colabel.root
2869 //
2870 
2871  if(cuts=="") {
2872  cout << "CWB::Toolbox::setCuts - cuts is empty : nothing to do" << endl;
2873  gSystem->Exit(1);
2874  }
2875 
2876  TString ifname = idir+"/"+ifName;
2877 
2878  // open input root file
2879  cout<<"Opening File : " << ifname.Data() << endl;
2880  TFile ifile(ifname);
2881  if (ifile.IsZombie()) {
2882  cout << "CWB::Toolbox::setCuts - Error opening file " << ifname.Data() << endl;
2883  gSystem->Exit(1);
2884  }
2885  TTree *itree = (TTree*)ifile.Get(trname.Data());
2886  if (itree==NULL) {
2887  cout << "CWB::Toolbox::setCuts - tree " << trname
2888  << " is not present in file " << ifname.Data() << endl;
2889  gSystem->Exit(1);
2890  }
2891  Int_t isize = (Int_t)itree->GetEntries();
2892  cout << "tree size : " << isize << endl;
2893  if (isize==0) {
2894  cout << "CWB::Toolbox::setCuts - tree " << trname
2895  << " is empty in file " << ifname.Data() << endl;
2896  gSystem->Exit(1);
2897  }
2898 
2899  // check cuts
2900  TTreeFormula formula("trCuts", cuts.Data(), itree);
2901  int err = formula.Compile(cuts.Data());
2902  if(err) {
2903  cout << "CWB::Toolbox::setCuts - wrong input cuts " << cuts << endl;
2904  return -1;
2905  }
2906 
2907  // get selected entries
2908  itree->SetEstimate(isize);
2909  itree->Draw("Entry$",cuts.Data(),"goff",isize);
2910  int nentries = itree->GetSelectedRows();
2911  cout << "CWB::Toolbox::setCuts - selected entries : "
2912  << nentries << "/" << itree->GetEntries() << endl;
2913 
2914  // create output root file name
2915  TString ofname = odir+"/"+ifName;
2916  ofname.ReplaceAll(".root",TString(".C_")+olabel+".root");
2917  cout << "CWB::Toolbox::setCuts - Create cuts file : " << ofname << endl;
2918  bool overwrite = checkFile(ofname,true);
2919  if(!overwrite) gSystem->Exit(0);
2920 
2921  // create output root file with selection cuts
2922  TFile ofile(ofname,"RECREATE");
2923  TTree* otree = itree->CopyTree(cuts.Data());
2924  otree->SetDirectory(&ofile);
2925  otree->Write();
2926  ofile.Close();
2927 
2928  // create setCuts history
2929  CWB::History* history = (CWB::History*)ifile.Get("history");
2930  if(history==NULL) history=new CWB::History();
2931  if(history!=NULL) {
2932  TList* stageList = history->GetStageNames(); // get stage list
2933  TString pcuts="";
2934  for(int i=0;i<stageList->GetSize();i++) { // get previous cuts
2935  TObjString* stageObjString = (TObjString*)stageList->At(i);
2936  TString stageName = stageObjString->GetString();
2937  char* stage = const_cast<char*>(stageName.Data());
2938  if(stageName=="CUTS") pcuts=history->GetHistory(stage,const_cast<char*>("PARAMETERS"));
2939  }
2940  // update history
2941  history->SetHistoryModify(true);
2942  if(!history->StageAlreadyPresent(CCAST("CUTS"))) history->AddStage(CCAST("CUTS"));
2943  if(!history->TypeAllowed(CCAST("PARAMETERS"))) history->AddType(CCAST("PARAMETERS"));
2944  if(!history->TypeAllowed(CCAST("WORKDIR"))) history->AddType(CCAST("WORKDIR"));
2945  char work_dir[1024]="";
2946  sprintf(work_dir,"%s",gSystem->WorkingDirectory());
2947  history->AddHistory(CCAST("CUTS"), CCAST("WORKDIR"), work_dir);
2948  TString _cuts = (pcuts!="") ? pcuts+" "+cuts : cuts;
2949  history->AddHistory(CCAST("CUTS"), CCAST("PARAMETERS"), CCAST(_cuts.Data()));
2950  char logmsg[2048]; sprintf(logmsg,"Apply Selection Cuts : %s",cuts.Data());
2951  history->AddLog(CCAST("CUTS"), CCAST(logmsg));
2952  }
2953 
2954  // close input root file
2955  ifile.Close();
2956 
2957  // write setCuts history to merge+cuts file
2958  if(history!=NULL) {
2959  TFile ofile(ofname,"UPDATE");
2960  history->Write("history");
2961  ofile.Close();
2962  delete history;
2963  }
2964 
2965  return nentries;
2966 }
2967 
2968 //______________________________________________________________________________
2969 int
2971  TString sels, TString farFile, int irho, TString olabel, bool inclusive) {
2972 //
2973 // add a new ifar (inverse false alarm rate) leaf to the selected entries in the merged wave root file
2974 // for each selected entry a new leaf is created "ifar" which value is obtained from the farFile
2975 // farFile is a text file which contains a corrispondence between rho and far (from background)
2976 // return selected entries
2977 //
2978 // ifname : input root file name
2979 // idir : input dir
2980 // odir : output dir
2981 // trname : tree name
2982 // sels : selection sels (Ex: netcc[2]>0.5)
2983 // farFile : far file (text file with a list entries : rho far)
2984 // irho ; rho index 0/1 : rho[0]/rho[1] to be used for rho to far association
2985 // olabel : output label used in the output file name (Ex: cc2_gt_0d5)
2986 // ofname.root = ifname.Folabel.root
2987 // inclusive : true(def)/false=inclusive/exclusive : used to compute the ifar
2988 //
2989 
2990  if(irho!=0 && irho!=1) {
2991  cout << "CWB::Toolbox::setIFAR - bad irho value : irho must be 0/1" << endl;
2992  gSystem->Exit(1);
2993  }
2994 
2995  if(sels=="") {
2996  cout << "CWB::Toolbox::setIFAR - sels is empty : nothing to do" << endl;
2997  gSystem->Exit(1);
2998  }
2999 
3000  // check if farFile exist
3001  bool exist = checkFile(farFile,false);
3002  if(!exist) gSystem->Exit(0);
3003  // read farFile
3004  vector<double> xrho,xfar;
3005  int xsize = GetStepFunction(farFile, xrho, xfar);
3006  // remove elements with xfar=0
3007  vector<double> trho,tfar;
3008  for(int i=0;i<xsize;i++) {
3009  if(xfar[i]!=0) {
3010  trho.push_back(xrho[i]);
3011  tfar.push_back(xfar[i]);
3012  }
3013  }
3014  xrho=trho; xfar=tfar;
3015  // insert a new element at the beginning with xrho=-DBL_MAX and xfar[xfar[0]]
3016  std::vector<double>::iterator it;
3017  it = xrho.begin(); xrho.insert(it,-DBL_MAX);
3018  it = xfar.begin(); xfar.insert(it,xfar[0]);
3019  // insert a new element at the end with xrho=DBL_MAX/2 and xfar[xfar[xfar.size()-1]]
3020  xrho.push_back(DBL_MAX/2);
3021  xfar.push_back(xfar[xfar.size()-1]);
3022  xsize=xfar.size();
3023  // create step graph used to get far from rho
3024  TGraph gr;
3025  int cnt=0;
3026  for(int i=1;i<xsize;i++) {
3027  double dx = (xrho[i]-xrho[i-1])/100000.;
3028  gr.SetPoint(cnt++,xrho[i]-dx,xfar[i-1]);
3029  gr.SetPoint(cnt++,xrho[i]+dx,xfar[i]);
3030  }
3031 
3032  TString ifname = idir+"/"+ifName;
3033 
3034  // open input root file
3035  cout<<"Opening File : " << ifname.Data() << endl;
3036  TFile ifile(ifname);
3037  if (ifile.IsZombie()) {
3038  cout << "CWB::Toolbox::setIFAR - Error opening file " << ifname.Data() << endl;
3039  gSystem->Exit(1);
3040  }
3041  TTree *itree = (TTree*)ifile.Get(trname.Data());
3042  if (itree==NULL) {
3043  cout << "CWB::Toolbox::setIFAR - tree " << trname
3044  << " is not present in file " << ifname.Data() << endl;
3045  gSystem->Exit(1);
3046  }
3047  Int_t isize = (Int_t)itree->GetEntries();
3048  itree->SetEstimate(isize);
3049  cout << "tree size : " << isize << endl;
3050  if (isize==0) {
3051  cout << "CWB::Toolbox::setIFAR - tree " << trname
3052  << " is empty in file " << ifname.Data() << endl;
3053  gSystem->Exit(1);
3054  }
3055 
3056  // check sels
3057  TTreeFormula fsel("sels", sels.Data(), itree);
3058  int err = fsel.Compile(sels.Data());
3059  if(err) {
3060  cout << "CWB::Toolbox::setIFAR - wrong input sels " << sels << endl;
3061  return -1;
3062  }
3063 
3064  // create output root file name
3065  TString ofname = odir+"/"+ifName;
3066  ofname.ReplaceAll(".root",TString(".S_")+olabel+".root");
3067  cout << "CWB::Toolbox::setIFAR - Create sels file : " << ofname << endl;
3068  bool overwrite = checkFile(ofname,true);
3069  if(!overwrite) gSystem->Exit(0);
3070 
3071  // create output root file with selection sels
3072  TFile ofile(ofname,"RECREATE");
3073  TTree *otree = (TTree*)itree->CloneTree(0);
3074  otree->SetMaxTreeSize(MAX_TREE_SIZE);
3075 
3076  // add ifar,bin leaf to otree
3077  TBranch* branch;
3078  bool ifar_exists=false;
3079  bool bin_exists=false;
3080  TIter next(itree->GetListOfBranches());
3081  while ((branch=(TBranch*)next())) {
3082  if(TString("ifar").CompareTo(branch->GetName())==0) ifar_exists=true;
3083  if(TString("bin").CompareTo(branch->GetName())==0) bin_exists=true;
3084  }
3085  next.Reset();
3086  float ifar=0;
3087  if (ifar_exists) itree->SetBranchAddress("ifar",&ifar);
3088  else otree->Branch("ifar",&ifar,"ifar/F");
3089  string* bin = new string();
3090  if (bin_exists) itree->SetBranchAddress("bin",&bin);
3091  else otree->Branch("bin",bin);
3092 
3093  // get selected entries
3094  itree->Draw("Entry$",sels.Data(),"goff",isize);
3095  double* entry = itree->GetV1();
3096  int nsel = itree->GetSelectedRows();
3097  cout << "CWB::Toolbox::setIFAR - selected entries : "
3098  << nsel << "/" << itree->GetEntries() << endl;
3099  // write ifar for the selected entries
3100  float rho[2];
3101  itree->SetBranchAddress("rho",rho);
3102  for(int i=0;i<nsel;i++) {
3103  ifar=0;
3104  itree->GetEntry(int(entry[i]));
3105  double far = gr.Eval(rho[irho]);
3106  double xifar = far>0 ? 1./far : -1;
3107  if(inclusive) { // inclusive
3108  if(xifar>ifar) {
3109  ifar=xifar;
3110  *bin=olabel.Data();
3111  }
3112  } else { // exclusive
3113  ifar = xifar;
3114  *bin = olabel.Data();
3115  }
3116  otree->Fill();
3117  }
3118  // get not selected entries
3119  itree->Draw("Entry$",TString::Format("!(%s)",sels.Data()).Data(),"goff",isize);
3120  int _nsel = itree->GetSelectedRows();
3121  double* _entry = itree->GetV1();
3122  cout << "CWB::Toolbox::setIFAR - not selected entries : "
3123  << _nsel << "/" << itree->GetEntries() << endl;
3124  // write ifar for the not selected entries
3125  for(int i=0;i<_nsel;i++) {
3126  itree->GetEntry(int(_entry[i]));
3127  if(!ifar_exists) ifar=0; // initialize ifar
3128  if(!bin_exists) *bin=""; // initialize bin
3129  otree->Fill();
3130  }
3131  delete bin;
3132  otree->Write();
3133  ofile.Close();
3134 
3135  // create setIFAR history
3136  CWB::History* history = (CWB::History*)ifile.Get("history");
3137  if(history==NULL) history=new CWB::History();
3138  if(history!=NULL) {
3139  TList* stageList = history->GetStageNames(); // get stage list
3140  TString psels="";
3141  char* pfile=NULL;
3142  for(int i=0;i<stageList->GetSize();i++) { // get previous sels
3143  TObjString* stageObjString = (TObjString*)stageList->At(i);
3144  TString stageName = stageObjString->GetString();
3145  char* stage = const_cast<char*>(stageName.Data());
3146  if(stageName=="IFAR") psels=history->GetHistory(stage,CCAST("PARAMETERS"));
3147  if(stageName=="IFAR") pfile=history->GetHistory(stage,CCAST("FARFILE"));
3148  }
3149  // update history
3150  history->SetHistoryModify(true);
3151  if(!history->StageAlreadyPresent(CCAST("IFAR"))) history->AddStage(CCAST("IFAR"));
3152  if(!history->TypeAllowed(CCAST("PARAMETERS"))) history->AddType(CCAST("PARAMETERS"));
3153  if(!history->TypeAllowed(CCAST("WORKDIR"))) history->AddType(CCAST("WORKDIR"));
3154  if(!history->TypeAllowed(CCAST("FARFILE"))) history->AddType(CCAST("FARFILE"));
3155  char work_dir[1024]="";
3156  sprintf(work_dir,"%s",gSystem->WorkingDirectory());
3157  history->AddHistory(CCAST("IFAR"), CCAST("WORKDIR"), work_dir);
3158  TString _sels = (psels!="") ? psels+"\n"+sels : sels;
3159  history->AddHistory(CCAST("IFAR"), CCAST("PARAMETERS"), CCAST(_sels.Data()));
3160  char logmsg[2048]; sprintf(logmsg,"Created ifar on the bin set (%s) specified by the selection : %s",olabel.Data(),sels.Data());
3161  history->AddLog(CCAST("IFAR"), CCAST(logmsg));
3162  char* buffer = readFile(farFile); // read farFile file
3163  if(buffer!=NULL) {
3164  char* farBuffer=NULL;
3165  if(pfile!=NULL) {
3166  farBuffer = new char[strlen(pfile)+strlen(buffer)+farFile.Sizeof()+10];
3167  sprintf(farBuffer,"%s\n%s\n%s\n",pfile,farFile.Data(),buffer);
3168  } else {
3169  farBuffer = new char[strlen(buffer)+farFile.Sizeof()+10];
3170  sprintf(farBuffer,"%s\n%s\n",farFile.Data(),buffer);
3171  }
3172  history->AddHistory(CCAST("IFAR"), CCAST("FARFILE"), farBuffer);
3173  delete [] buffer;
3174  delete [] farBuffer;
3175  }
3176  }
3177 
3178  // close input root file
3179  ifile.Close();
3180 
3181  // write setIFAR history to merge+sels file
3182  if(history!=NULL) {
3183  TFile ofile(ofname,"UPDATE");
3184  history->Write("history");
3185  ofile.Close();
3186  delete history;
3187  }
3188 
3189  return nsel;
3190 }
3191 
3192 //______________________________________________________________________________
3193 int
3194 CWB::Toolbox::setChunk(TString ifName, TString idir, TString odir, TString trname, int chunk) {
3195 //
3196 // add a new chunk (data chunk id) leaf to the selected entries in the merged wave root file
3197 // return error status
3198 //
3199 // ifname : input root file name
3200 // idir : input dir
3201 // odir : output dir
3202 // trname : tree name
3203 // chunk : chunk id
3204 //
3205 
3206  if(chunk<=0) {
3207  cout << "CWB::Toolbox::setChunk - bad chunk chunk value : chunk must be >0" << endl;
3208  gSystem->Exit(1);
3209  }
3210 
3211  TString ifname = idir+"/"+ifName;
3212 
3213  // open input root file
3214  cout<<"Opening File : " << ifname.Data() << endl;
3215  TFile ifile(ifname);
3216  if (ifile.IsZombie()) {
3217  cout << "CWB::Toolbox::setChunk - Error opening file " << ifname.Data() << endl;
3218  gSystem->Exit(1);
3219  }
3220  TTree *itree = (TTree*)ifile.Get(trname.Data());
3221  if (itree==NULL) {
3222  cout << "CWB::Toolbox::setChunk - tree " << trname
3223  << " is not present in file " << ifname.Data() << endl;
3224  gSystem->Exit(1);
3225  }
3226  Int_t isize = (Int_t)itree->GetEntries();
3227  itree->SetEstimate(isize);
3228  cout << "tree size : " << isize << endl;
3229  if (isize==0) {
3230  cout << "CWB::Toolbox::setChunk - tree " << trname
3231  << " is empty in file " << ifname.Data() << endl;
3232  gSystem->Exit(1);
3233  }
3234 
3235  // create output root file name
3236  TString ofname = odir+"/"+ifName;
3237  char schunk[32];sprintf(schunk,"chunk%d",chunk);
3238  ofname.ReplaceAll(".root",TString(".K_")+schunk+".root");
3239  cout << "CWB::Toolbox::setChunk - Create sels file : " << ofname << endl;
3240  bool overwrite = checkFile(ofname,true);
3241  if(!overwrite) gSystem->Exit(0);
3242 
3243  // create output root file with selection sels
3244  TFile ofile(ofname,"RECREATE");
3245  TTree *otree = (TTree*)itree->CloneTree(0);
3246  otree->SetMaxTreeSize(MAX_TREE_SIZE);
3247 
3248  // add chunk leaf to otree
3249  TBranch* branch;
3250  bool chunk_exists=false;
3251  TIter next(itree->GetListOfBranches());
3252  while ((branch=(TBranch*)next())) {
3253  if(TString("chunk").CompareTo(branch->GetName())==0) chunk_exists=true;
3254  }
3255  next.Reset();
3256  if (chunk_exists) itree->SetBranchAddress("chunk",&chunk);
3257  else otree->Branch("chunk",&chunk,"chunk/I");
3258 
3259  // get selected entries
3260  itree->Draw("Entry$","","goff",isize);
3261  double* entry = itree->GetV1();
3262  int nsel = itree->GetSelectedRows();
3263  cout << "CWB::Toolbox::setChunk - selected entries : "
3264  << nsel << "/" << itree->GetEntries() << endl;
3265  // write chunk for the selected entries
3266  for(int i=0;i<nsel;i++) {
3267  itree->GetEntry(int(entry[i]));
3268  otree->Fill();
3269  }
3270  otree->Write();
3271  ofile.Close();
3272 
3273  // create setChunk history
3274  CWB::History* history = (CWB::History*)ifile.Get("history");
3275  if(history==NULL) history=new CWB::History();
3276  if(history!=NULL) {
3277  TList* stageList = history->GetStageNames(); // get stage list
3278  TString psels="";
3279  char* pfile=NULL;
3280  for(int i=0;i<stageList->GetSize();i++) { // get previous sels
3281  TObjString* stageObjString = (TObjString*)stageList->At(i);
3282  TString stageName = stageObjString->GetString();
3283  char* stage = const_cast<char*>(stageName.Data());
3284  if(stageName=="CHUNK") psels=history->GetHistory(stage,CCAST("PARAMETERS"));
3285  if(stageName=="CHUNK") pfile=history->GetHistory(stage,CCAST("FARFILE"));
3286  }
3287  // update history
3288  history->SetHistoryModify(true);
3289  if(!history->StageAlreadyPresent(CCAST("CHUNK"))) history->AddStage(CCAST("CHUNK"));
3290  if(!history->TypeAllowed(CCAST("PARAMETERS"))) history->AddType(CCAST("PARAMETERS"));
3291  if(!history->TypeAllowed(CCAST("WORKDIR"))) history->AddType(CCAST("WORKDIR"));
3292  char work_dir[1024]="";
3293  sprintf(work_dir,"%s",gSystem->WorkingDirectory());
3294  history->AddHistory(CCAST("CHUNK"), CCAST("WORKDIR"), work_dir);
3295  char logmsg[2048]; sprintf(logmsg,"Created chunk leaf : %d",chunk);
3296  history->AddLog(CCAST("CHUNK"), CCAST(logmsg));
3297  }
3298 
3299  // close input root file
3300  ifile.Close();
3301 
3302  // write setChunk history to merge+sels file
3303  if(history!=NULL) {
3304  TFile ofile(ofname,"UPDATE");
3305  history->Write("history");
3306  ofile.Close();
3307  delete history;
3308  }
3309 
3310  return 0;
3311 }
3312 
3313 //_______________________________________________________________________________________
3314 void
3316 //
3317 // select from the root ifwave file a unique reconstructed event for each injected
3318 // signal. The signal is selected from the reconstructed events which have the same
3319 // injected gps time, the selected one has the maximum rho
3320 //
3321 // ifwave : name of simulation input wave file
3322 // ofwave : name of simulation output wave file (unique reconstructed events)
3323 // nifo : number of detectors
3324 // nfactor : number of simulation factors
3325 // factors : array of simulation factors
3326 // pp_irho : index used for rho = rho[pp_irho]
3327 //
3328 
3329  cout << "CWB::Toolbox::setUniqueEvents - Create unique events file : " << ofwave << endl;
3330  bool overwrite = checkFile(ofwave,true);
3331  if(!overwrite) gSystem->Exit(0);
3332 
3333  TFile* iwroot = TFile::Open(ifwave);
3334  if(iwroot==NULL||!iwroot->IsOpen()) {
3335  cout << "CWB::Toolbox::setUniqueEvents - Error : input file " << ifwave << " not found" << endl;
3336  exit(1);
3337  }
3338 
3339  TTree* iwtree = (TTree*) iwroot->Get("waveburst");
3340  if(iwtree==NULL) {
3341  cout << "CWB::Toolbox::setUniqueEvents - Error : tree waveburst not found in file " << ifwave << endl;
3342  exit(1);
3343  }
3344  cout << endl;
3345  cout << "CWB::Toolbox::setUniqueEvents : number of input events : " << iwtree->GetEntries() << endl;
3346  cout << endl;
3347 
3348  TFile* owroot = new TFile(ofwave,"RECREATE");
3349  if(owroot->IsZombie()) {
3350  cout << "CWB::Toolbox::setUniqueEvents - Error : output file " << ofwave << " not opened" << endl;
3351  exit(1);
3352  }
3353 
3354  TTree *owtree = (TTree*)iwtree->CloneTree(0);
3355  owtree->SetMaxTreeSize(MAX_TREE_SIZE);
3356 
3357  // -------------------------------------------------------------------------
3358  // add new leave to owtree (fsize : number of fragments)
3359  // -------------------------------------------------------------------------
3360  TString leaf_name="fsize";
3361  TBranch* branch;
3362  bool replaceLeaf=false;
3363  TIter next(iwtree->GetListOfBranches());
3364  while ((branch=(TBranch*)next())) {
3365  if (leaf_name.CompareTo(branch->GetName())==0) {
3366  cout << "fragment leaf [" << leaf_name << "] already applied" << endl;
3367  char answer[256];
3368  strcpy(answer,"");
3369  do {
3370  cout << "CWB::Toolbox::setUniqueEvents : Do you want to overwrite the previous leaf ? (y/n) ";
3371  cin >> answer;
3372  } while ((strcmp(answer,"y")!=0)&&(strcmp(answer,"n")!=0));
3373  if (strcmp(answer,"y")==0) {
3374  replaceLeaf=true;
3375  } else {
3376  gSystem->Exit(-1);
3377  }
3378  }
3379  }
3380  next.Reset();
3381  int fsize=1;
3382  if (replaceLeaf) owtree->SetBranchAddress("fsize",&fsize);
3383  else owtree->Branch("fsize",&fsize,"fsize/I");
3384 
3385  char sel[1024];
3386  sprintf(sel,"Entry$:rho[%i]:time[%i]:factor",pp_irho,nIFO);
3387  int iwsize=iwtree->GetEntries();
3388  iwtree->Draw(sel,"","goff",iwsize);
3389  double* entry = iwtree->GetV1();
3390  double* rho = iwtree->GetV2();
3391  double* time = iwtree->GetV3();
3392  double* factor = iwtree->GetV4();
3393 
3394  // extract factors
3395  std::map <float, float> mfactors;
3396  for(int i=0;i<iwsize;i++) { // loop over the tree
3397  iwtree->GetEntry(i);
3398  mfactors[factor[i]]=factor[i];
3399  }
3400  vector<float> factors;
3401  std::map<float, float>::iterator iter;
3402  for (iter=mfactors.begin(); iter!=mfactors.end(); iter++) {
3403  factors.push_back(iter->second);
3404  }
3405  int nfactor=factors.size();
3406 
3407  char cuts[1024];
3408  for(int i=0;i<nfactor;i++) { // loop over the factors
3409  sprintf(cuts,"abs(factor-%g)/%g<0.0001",factors[i],factors[i]);
3410  iwtree->Draw(sel,cuts,"goff",iwsize);
3411  int size=iwtree->GetSelectedRows();
3412  int unique_evt=0; // number of unique events for factor i
3413  if(size==1) {
3414  iwtree->GetEntry(entry[0]);
3415  owtree->Fill();
3416  unique_evt++;
3417  } else if(size>1) {
3418  int* index = new int[size];
3419  TMath::Sort(size,time,index,kFALSE); // sort events in time
3420  int j=index[0];
3421  float rhomax=rho[j];
3422  int imax=j;
3423  double time1=time[j];
3424  double time2=0.;
3425  for(int k=1; k<size; k++) {
3426  j=index[k];
3427  time2=time[j];
3428  if(abs(time1-time2)>0.001 || k==size-1) {
3429  iwtree->GetEntry(entry[imax]);
3430  owtree->Fill(); // store the event with max rho[pp_irho]
3431  imax=j;
3432  rhomax=rho[j];
3433  unique_evt++;
3434  fsize=1;
3435  } else {
3436  if(rho[j]>rhomax) {rhomax=rho[j];imax=j;}
3437  fsize++;
3438  }
3439  time1=time2;
3440  }
3441  delete index;
3442  }
3443  cout << " factor id = " << i << "\t reconstructed events : "
3444  << iwtree->GetSelectedRows() << "\t unique events : "
3445  << unique_evt << "\tfactor = " << factors[i] << endl;
3446  }
3447  cout << endl;
3448  owtree->Write();
3449  owroot->Close();
3450  owroot->Close();
3451 
3452  // create setCuts history
3453  CWB::History* history = (CWB::History*)iwroot->Get("history");
3454  if(history==NULL) history=new CWB::History();
3455  if(history!=NULL) {
3456  TList* stageList = history->GetStageNames(); // get stage list
3457  TString pcuts="";
3458  for(int i=0;i<stageList->GetSize();i++) { // get previous cuts
3459  TObjString* stageObjString = (TObjString*)stageList->At(i);
3460  TString stageName = stageObjString->GetString();
3461  char* stage = const_cast<char*>(stageName.Data());
3462  if(stageName=="CUTS") pcuts=history->GetHistory(stage,const_cast<char*>("PARAMETERS"));
3463  }
3464  // update history
3465  history->SetHistoryModify(true);
3466  if(!history->StageAlreadyPresent(CCAST("CUTS"))) history->AddStage(CCAST("CUTS"));
3467  if(!history->TypeAllowed(CCAST("PARAMETERS"))) history->AddType(CCAST("PARAMETERS"));
3468  if(!history->TypeAllowed(CCAST("WORKDIR"))) history->AddType(CCAST("WORKDIR"));
3469  char work_dir[1024]="";
3470  sprintf(work_dir,"%s",gSystem->WorkingDirectory());
3471  history->AddHistory(CCAST("CUTS"), CCAST("WORKDIR"), work_dir);
3472  TString cuts = (pcuts!="") ? pcuts+" (U)" : "(U)";
3473  history->AddHistory(CCAST("CUTS"), CCAST("PARAMETERS"), CCAST(cuts.Data()));
3474  char logmsg[2048]; sprintf(logmsg,"Apply Selection Cuts : %s","(U)");
3475  history->AddLog(CCAST("CUTS"), CCAST(logmsg));
3476  }
3477 
3478  // close input root file
3479  iwroot->Close();
3480 
3481  // write setCuts history to merge+cuts file
3482  if(history!=NULL) {
3483  TFile ofile(ofwave,"UPDATE");
3484  history->Write("history");
3485  ofile.Close();
3486  delete history;
3487  }
3488 
3489  return;
3490 }
3491 
3492 //______________________________________________________________________________
3493 int
3494 CWB::Toolbox::setVeto(TString ifName, TString idir, TString odir, vector<TString> ifos, int nVDQF, dqfile* VDQF,
3495  int nDQF, dqfile* DQF, double segLen, double segMLS, double segEdge) {
3496 //
3497 // apply Data Quality and veto to waveburst in ifname root file
3498 // and create an output root file adding a flag for each Data Quality
3499 // return selected entries
3500 //
3501 // ifname : input root file name
3502 // idir : input dir
3503 // odir : output dir
3504 // ifos : detector lists
3505 // nVDQF : number of Data Quality files
3506 // VDQF : Data Quality files structures
3507 // nDQF :
3508 // DQF :
3509 // segLen : segment job lenght
3510 // segMLS : minimum segment lenght after DQ2
3511 // segEdge : scratch lenght
3512 //
3513 
3514 
3515  int nIFO = ifos.size();
3516 
3517  CWB::History* history = NULL;
3518  bool bhistory=true;
3519 
3520  // extract from VDQF the set of declared detector's names not included in the ifos list
3521  vector<TString> wifos;
3522  for(int j=0;j<nVDQF;j++) {
3523  if(VDQF[j].cat==CWB_CAT0) continue;
3524  if(VDQF[j].cat==CWB_CAT1) continue;
3525  bool bifo=true;
3526  for(int i=0;i<(int)wifos.size();i++) if(wifos[i].CompareTo(VDQF[j].ifo)==0) bifo=false;
3527  for(int i=0;i<nIFO;i++) if(ifos[i].CompareTo(VDQF[j].ifo)==0) bifo=false;
3528  if(bifo) wifos.push_back(VDQF[j].ifo);
3529  }
3530  for(int i=0;i<(int)wifos.size();i++) cout << wifos[i].Data() << " ";
3531  cout << endl;
3532 //gSystem->Exit(0);
3533 
3534  // build XDQF structure used for internal's computations
3535  int nXDQF=0;
3536  dqfile* XDQF = new dqfile[nVDQF*nIFO];
3537  // netifo contains network with dimension > nIFO (for exclusion vetoes)
3538  int nNET=TMath::Factorial(5);
3539  vector<TString>* xifos = new vector<TString>[nNET];
3540  for(int j=0;j<nVDQF;j++) {
3541  if(VDQF[j].cat==CWB_CAT0) continue;
3542  if(VDQF[j].cat==CWB_CAT1) continue;
3543  bool bifo=false;
3544  for(int i=0;i<nIFO;i++) if(ifos[i].CompareTo(VDQF[j].ifo)==0) bifo=true;
3545  // change CAT if ifo not presents into ifos array
3546  if(!bifo) {
3547  // insert CWB_EXC (WARNING : miss cases with det>3 !!!)
3548  for(int i=0;i<nIFO;i++) {
3549  for(int k=0;k<(int)wifos.size();k++) {
3550  if(wifos[k].CompareTo(VDQF[j].ifo)==0) {
3551  XDQF[nXDQF]=VDQF[j];
3552  strcpy(XDQF[nXDQF].ifo,ifos[i].Data());
3553  XDQF[nXDQF].cat=CWB_EXC;
3554  xifos[nXDQF]=ifos;
3555  xifos[nXDQF].push_back(wifos[k]);
3556  nXDQF++;
3557  }
3558  }
3559  }
3560  } else {
3561  xifos[nXDQF]=ifos;
3562  XDQF[nXDQF]=VDQF[j];
3563  nXDQF++;
3564  }
3565  }
3566  if(nXDQF==0) {
3567  cout << "CWB::Toolbox::setVeto - No veto found : setVeto terminated" << endl;
3568  gSystem->Exit(1);
3569  }
3570  for(int j=0;j<nXDQF;j++) {
3571  cout << "XDQF[" << j << "] " << CWB_CAT_NAME[XDQF[j].cat] << "_" << XDQF[j].ifo << " NETWORK : ";
3572  for(int i=0;i<(int)xifos[j].size();i++) cout << xifos[j][i].Data() << " ";
3573  cout << endl;
3574  }
3575 
3576  // get standard job list
3577  vector<waveSegment> cat1List = readSegList(nDQF, DQF, CWB_CAT1);
3578  vector<waveSegment> jobList = getJobList(cat1List, segLen, segMLS, segEdge);
3579  //vector<waveSegment> cat2List = readSegList(nDQF, DQF, CWB_CAT2);
3580 
3581  // build veto file label
3582  char ifo_label[10][256];
3583  char veto_label[10][256];
3584  int nset=0;
3585  for(int n=0;n<nXDQF;n++) {
3586  TString veto_name = CWB_CAT_NAME[XDQF[n].cat];
3587  bool bnew=true;
3588  for(int m=0;m<nset;m++) if(veto_name.CompareTo(veto_label[m])==0) bnew=false;
3589  if(bnew) strcpy(veto_label[nset++],veto_name.Data());
3590  }
3591  for(int m=0;m<nset;m++) strcpy(ifo_label[m],"");
3592  for(int n=0;n<nXDQF;n++) {
3593  TString veto_name = CWB_CAT_NAME[XDQF[n].cat];
3594  for(int m=0;m<nset;m++) {
3595  if(veto_name.CompareTo(veto_label[m])==0) {
3596  if(!TString(ifo_label[m]).Contains(XDQF[n].ifo)) {
3597  sprintf(ifo_label[m],"%s%s",ifo_label[m],XDQF[n].ifo);
3598  }
3599  }
3600  }
3601  }
3602  char veto_file_label[256]="";
3603  for(int m=0;m<nset;m++) {
3604  if(strlen(veto_file_label)==0) {
3605  sprintf(veto_file_label,".V_%s%s",veto_label[m],ifo_label[m]);
3606  } else {
3607  sprintf(veto_file_label,"%s_%s%s",veto_file_label,veto_label[m],ifo_label[m]);
3608  }
3609  }
3610  strcpy(veto_file_label,TString(veto_file_label).ReplaceAll("veto_","").Data());
3611  strcpy(veto_file_label,TString(veto_file_label).ReplaceAll("1","").Data());
3612  sprintf(veto_file_label,"%s.root",veto_file_label);
3613  cout << "veto file label : " << veto_file_label << endl;
3614 
3615  TString efname = odir+"/"+ifName;
3616  efname.ReplaceAll(".root",veto_file_label);
3617  bool overwrite = checkFile(efname,true);
3618  if(!overwrite) gSystem->Exit(0);
3619 
3620  TString ifname = idir+"/"+ifName;
3621  TString ofname = odir+"/"+ifName;
3622  ofname.ReplaceAll(".root",".root.tmp.1");
3623 
3624 //cout.precision(14);
3625 //for(int k=0;k<jobList.size();k++)
3626 // cout << k << " " << jobList[k].start << " " << jobList[k].stop << endl;
3627 //gSystem->Exit(0);
3628 
3629  vector<waveSegment> vlist;
3630  for(int n=0;n<nXDQF;n++) {
3631  // find ifo index
3632  int iIFO=-1;
3633  for(int i=0;i<nIFO;i++) if(ifos[i].CompareTo(XDQF[n].ifo)==0) iIFO=i;
3634  if (iIFO==-1) continue; // sky ifo not presents into ifos array
3635 
3636 //cout << n << " ifile " << ifname.Data() << endl;
3637 //cout << n << " ofile " << ofname.Data() << endl;
3638 //cout << endl;
3639 
3640  // get veto list
3641  if(XDQF[n].cat==CWB_CAT2) {
3642  // for cat2 is necessary to merge all CAT2 in XDQF
3643  // RDQF contains only ifo which are presents in ifos array
3644  int nRDQF=0;
3645  dqfile* RDQF = new dqfile[nVDQF];
3646  for(int j=0;j<nVDQF;j++) {
3647  for(int k=0;k<nIFO;k++) if(ifos[k].CompareTo(VDQF[j].ifo)==0) RDQF[nRDQF++]=VDQF[j];
3648  }
3649 // for(int j=0;j<nRDQF;j++) cout << "RDQF[" << j << "] " << CWB_CAT_NAME[RDQF[j].cat] << "_" << RDQF[j].ifo.Data() << endl;
3650 //gSystem->Exit(0);
3651  vlist=readSegList(nRDQF, RDQF, CWB_CAT2);
3652  delete [] RDQF;
3653  } else if(XDQF[n].cat==CWB_EXC) {
3654  // extract list (higher net conf) for exclusion veto
3655  // RDQF contains only ifo which are presents in ifos array
3656  int nRDQF=0;
3657  dqfile* RDQF = new dqfile[nVDQF];
3658  for(int j=0;j<nVDQF;j++) {
3659  for(int k=0;k<(int)xifos[n].size();k++) if(xifos[n][k].CompareTo(VDQF[j].ifo)==0) RDQF[nRDQF++]=VDQF[j];
3660  }
3661 // for(int j=0;j<nRDQF;j++) cout << "EXC -> RDQF[" << j << "] " << CWB_CAT_NAME[RDQF[j].cat] << "_" << RDQF[j].ifo.Data() << endl;
3662  vlist=readSegList(nRDQF, RDQF, CWB_CAT2);
3663 //cout.precision(14);
3664 //for(int i=0;i<vlist.size();i++) {
3665 // cout << i << " " << vlist[i].start << " " << vlist[i].stop << endl;
3666 //}
3667 //cout << CWB_CAT_NAME[XDQF[n].cat].Data() << " list size " << vlist.size() << endl;
3668  } else {
3669  vlist=readSegList(XDQF[n]);
3670  }
3671  double vlist_time = getTimeSegList(vlist);
3672 /*
3673 if(XDQF[n].cat==CWB_CAT3) {
3674 cout.precision(14);
3675 for(int i=0;i<vlist.size();i++) {
3676  cout << i << " " << vlist[i].start << " " << vlist[i].stop << endl;
3677 }
3678 cout << CWB_CAT_NAME[XDQF[n].cat].Data() << " list size " << vlist.size() << endl;
3679 gSystem->Exit(1);
3680 }
3681 */
3682  TString veto_name = CWB_CAT_NAME[XDQF[n].cat]+"_"+XDQF[n].ifo;
3683  cout << veto_name << " list duration " << int(vlist_time) << " list size " << vlist.size() << endl;
3684 
3685  // -------------------------------------------------------------------------
3686  // open root file
3687  // -------------------------------------------------------------------------
3688  cout<<"Opening BKG File : " << ifname.Data() << endl;
3689  TFile ifile(ifname);
3690  if (ifile.IsZombie()) {
3691  cout << "CWB::Toolbox::setVeto - Error opening file " << ifname.Data() << endl;
3692  gSystem->Exit(1);
3693  }
3694  TTree *itree = (TTree*)ifile.Get("waveburst");
3695  if (itree==NULL) {
3696  cout << "CWB::Toolbox::setVeto - tree waveburst is not present in file " << ifname.Data() << endl;
3697  gSystem->Exit(1);
3698  }
3699  Int_t isize = (Int_t)itree->GetEntries();
3700  cout << "tree size : " << isize << endl;
3701  if (isize==0) {
3702  cout << "CWB::Toolbox::setVeto - tree waveburst is empty in file " << ifname.Data() << endl;
3703  gSystem->Exit(1);
3704  }
3705  itree->SetEstimate(isize);
3706  char selection[256];sprintf(selection,"time[%d]",iIFO);
3707  itree->Draw(selection,"","goff",isize);
3708  double* time = itree->GetV1();
3709  // check if time is NaN
3710  for(int i=0;i<isize;i++) {
3711  if(TMath::IsNaN(time[i])) {
3712  cout.precision(14);
3713  cout << "CWB::Toolbox::setVeto - tree waveburst file " << ifname.Data() << " contains time NaN in ifo=" << ifos[iIFO] << " time=" << time[i] << endl;
3714  gSystem->Exit(1);
3715  }
3716  }
3717  // sort list
3718  Int_t *id = new Int_t[isize];
3719  bool *bveto = new bool[isize];
3720  TMath::Sort((int)isize,time,id,false);
3721  // add dummy veto to vlist to permit a full trigger loop
3722  waveSegment SEG;
3723  SEG.start=time[id[isize-1]];
3724  SEG.stop=time[id[isize-1]];
3725  vlist.push_back(SEG);
3726  int vsize = vlist.size();
3727 /*
3728 for(int h=0;h<isize;h++) {
3729 cout << h << " " << iIFO << " " << time[id[h]] << endl;
3730 }
3731 gSystem->Exit(1);
3732 */
3733 
3734  if(bhistory) {
3735  history=(CWB::History*)ifile.Get("history");
3736  if(history==NULL) history=new CWB::History();
3737  bhistory=false;
3738  }
3739 
3740  // -------------------------------------------------------------------------
3741  // add new leave to itree
3742  // -------------------------------------------------------------------------
3743  TBranch* branch;
3744  bool replaceVeto=false;
3745  TIter next(itree->GetListOfBranches());
3746  while ((branch=(TBranch*)next())) {
3747  if (veto_name.CompareTo(branch->GetName())==0) {
3748  cout << "Veto [" << veto_name << "] already applied" << endl;
3749  char answer[256];
3750  strcpy(answer,"");
3751  do {
3752  cout << "Do you want to overwrite the previous spurious ? (y/n) ";
3753  cin >> answer;
3754  } while ((strcmp(answer,"y")!=0)&&(strcmp(answer,"n")!=0));
3755  if (strcmp(answer,"y")==0) {
3756  replaceVeto=true;
3757  } else {
3758  gSystem->Exit(-1);
3759  }
3760  }
3761  }
3762  next.Reset();
3763 
3764  // -------------------------------------------------------------------------
3765  // create temporary root file
3766  // -------------------------------------------------------------------------
3767  UChar_t bVeto;
3768  TFile* ftmp = new TFile(ofname,"RECREATE");
3769  if (ftmp->IsZombie()) {
3770  cout << "CWB::Toolbox::setVeto - Error opening file " << ofname.Data() << endl;
3771  gSystem->Exit(1);
3772  }
3773  TTree *trtmp = (TTree*)itree->CloneTree(0);
3774  trtmp->SetMaxTreeSize(MAX_TREE_SIZE);
3775  TString tVeto = veto_name;tVeto+="/b";
3776  if (replaceVeto) {
3777  trtmp->SetBranchAddress(veto_name.Data(),&bVeto);
3778  } else {
3779  trtmp->Branch(veto_name.Data(),&bVeto,tVeto.Data());
3780  }
3781  trtmp->Write();
3782 
3783  // -------------------------------------------------------------------------
3784  // insert flag into event tree
3785  // we add a dummy flag entry to the end of onoff array to avoid to discart good events when
3786  // no flag entries are present
3787  // -------------------------------------------------------------------------
3788  cout << "Start applying flag to time["<<iIFO<<"]..." << endl;
3789 
3790  ftmp->cd();
3791 
3792  int h=0;
3793  int pc = 0;
3794  int ipc = (int)((double)(isize+1)/10.); if(ipc==0) ipc=1;
3795  int count=0;
3796  double ttime=time[id[h]];
3797  for (int h=0;h<isize;h++) bveto[h]=0;
3798  for (int j=0;j<vsize;j++) {
3799  while ((ttime<=vlist[j].stop) && (h<isize)) {
3800  if ((ttime>vlist[j].start)&&(ttime<=vlist[j].stop)) {bveto[id[h]]=1;count++;} else bveto[id[h]]=0;
3801  if(++h<isize) ttime=time[id[h]];
3802  if (h%ipc==0) {cout << pc;if (pc<100) cout << " - ";pc+=10;cout.flush();}
3803  }
3804  }
3805  cout << pc << endl << endl;
3806 
3807  for (int h=0;h<isize;h++) {
3808  itree->GetEntry(h);
3809  bVeto=bveto[h];
3810  trtmp->Fill();
3811  }
3812  trtmp->Write();
3813  delete [] id;
3814  delete [] bveto;
3815 
3816  cout << "Writing new ofile "<< ofname.Data() << endl;
3817  Int_t osize = (Int_t)trtmp->GetEntries();
3818  cout << "osize : " << osize << endl;
3819  cout << "Flagged events: " << count << " Percentage: "<< (double)count/osize << endl;
3820 
3821  if(history!=NULL) {
3822  // update history
3823  history->SetHistoryModify(true);
3824  if(!history->StageAlreadyPresent(CCAST("VETO"))) history->AddStage(CCAST("VETO"));
3825 
3826  // save pp configuration file
3827  if(!history->TypeAllowed(CCAST("PARAMETERS"))) history->AddType(CCAST("PARAMETERS"));
3828  TString ecwb_pparameters_name = TString(gSystem->Getenv("CWB_PPARAMETERS_FILE"));
3829  for(int i=0;i<gApplication->Argc()-1;i++) { // skip last argument (net.C)
3830  if(TString(gApplication->Argv(i)).Contains(".C")) {
3831  char* parametersBuffer = readFile(gApplication->Argv(i));
3832  if(parametersBuffer!=NULL) {
3833  if(TString(gApplication->Argv(i))==ecwb_pparameters_name) {
3834  history->AddHistory(CCAST("VETO"), CCAST("PARAMETERS"), parametersBuffer);
3835  } else {
3836  //history->AddLog(job_stage, parametersBuffer);
3837  }
3838  }
3839  delete [] parametersBuffer;
3840  }
3841  }
3842 
3843  if(!history->TypeAllowed(CCAST("WORKDIR"))) history->AddType(CCAST("WORKDIR"));
3844  char work_dir[1024]="";
3845  sprintf(work_dir,"%s",gSystem->WorkingDirectory());
3846  history->AddHistory(CCAST("VETO"), CCAST("WORKDIR"), work_dir);
3847  //history->AddLog(CCAST("VETO"), CCAST(veto_name.Data()));
3848  char veto_log[256];
3849  sprintf(veto_log,"%s Flagged events: %d/%d - Percentage : %f ",
3850  veto_name.Data(), count, osize, (double)count/osize );
3851  history->AddLog(CCAST("VETO"), CCAST(veto_log));
3852  }
3853 
3854  ftmp->Close();
3855  ifile.Close();
3856  cout << endl;
3857 
3858  ifname=ofname;
3859  if(n%2) ofname.ReplaceAll(".root.tmp.2",".root.tmp.1");
3860  else ofname.ReplaceAll(".root.tmp.1",".root.tmp.2");
3861  }
3862 
3863  delete [] XDQF;
3864  for(int i=0;i<nNET;i++) xifos[i].clear();
3865  delete [] xifos;
3866 
3867  TString rfname = ofname;
3868  ofname = efname;
3869 
3870  TString lfname = ifName; // out live file name
3871  lfname.ReplaceAll(".root",veto_file_label);
3872  lfname.ReplaceAll("wave_","live_");
3873  TString ilfname = idir+"/"+ifName; // in live file name
3874  ilfname.ReplaceAll("wave_","live_");
3875  TString imfname = ilfname; // in mdc file name
3876  imfname.ReplaceAll("live_","mdc_");
3877  TString mfname = lfname; // out mdc file name
3878  mfname.ReplaceAll("live_","mdc_");
3879  TString ilstfname = idir+"/"+ifName; // in list file name
3880  ilstfname.ReplaceAll("wave_","merge_");
3881  ilstfname.ReplaceAll(".root",".lst");
3882  TString lstfname = lfname; // out list file name
3883  lstfname.ReplaceAll("live_","merge_");
3884  lstfname.ReplaceAll(".root",".lst");
3885 
3886  cout << " rfile : " << rfname.Data() << endl;
3887  cout << " ifile : " << ifname.Data() << endl;
3888  cout << " ofile : " << ofname.Data() << endl;
3889  cout << " lfile : " << lfname.Data() << endl;
3890  cout << " mfile : " << mfname.Data() << endl;
3891  cout << " ilstfile : " << ilstfname.Data() << endl;
3892  cout << " lstfile : " << lstfname.Data() << endl;
3893 
3894  char cmd[256];
3895  sprintf(cmd,"mv %s %s",ifname.Data(),ofname.Data());
3896  cout << cmd << endl;
3897  gSystem->Exec(cmd);
3898  int estat;
3899  Long_t id,size,flags,mt;
3900  estat = gSystem->GetPathInfo(ilfname,&id,&size,&flags,&mt);
3901  if (estat==0) {
3902  sprintf(cmd,"cd %s;ln -sf ../%s %s",odir.Data(),ilfname.Data(),lfname.Data());
3903  cout << cmd << endl;
3904  gSystem->Exec(cmd);
3905  }
3906  estat = gSystem->GetPathInfo(imfname,&id,&size,&flags,&mt);
3907  if (estat==0) {
3908  sprintf(cmd,"cd %s;ln -sf ../%s %s",odir.Data(),imfname.Data(),mfname.Data());
3909  cout << cmd << endl;
3910  gSystem->Exec(cmd);
3911  }
3912  estat = gSystem->GetPathInfo(ilstfname,&id,&size,&flags,&mt);
3913  if (estat==0) {
3914  sprintf(cmd,"cd %s;ln -sf ../%s %s",odir.Data(),ilstfname.Data(),lstfname.Data());
3915  cout << cmd << endl;
3916  gSystem->Exec(cmd);
3917  }
3918  sprintf(cmd,"rm %s",rfname.Data());
3919  cout << cmd << endl;
3920  gSystem->Exec(cmd);
3921 
3922  // write history to merge+veto file
3923  if(history!=NULL) {
3924  TFile fhist(ofname,"UPDATE");
3925  history->Write("history");
3926  fhist.Close();
3927  delete history;
3928  }
3929 
3930  vlist.clear();
3931 
3932  return 0;
3933 }
3934 
3935 //______________________________________________________________________________
3936 bool
3938 //
3939 // check if file exists
3940 //
3941 // Input: fName - file name to be checked
3942 //
3943 // Return true if it exists
3944 //
3945 
3946  // ----------------------------------------------------------------
3947  // Check if file exists
3948  // ----------------------------------------------------------------
3949  Long_t id,size=0,flags,mt;
3950  int estat = gSystem->GetPathInfo(fName.Data(),&id,&size,&flags,&mt);
3951  return (estat!=0) ? false : true;
3952 }
3953 
3954 //______________________________________________________________________________
3955 bool
3956 CWB::Toolbox::checkFile(TString fName, bool question, TString message) {
3957 //
3958 // check if file exists
3959 //
3960 // Input: fName - file name to be checked
3961 // question - true -> print question
3962 // message - question message
3963 //
3964 // Return true if answer=y
3965 //
3966 
3967  bool overwrite=true;
3968 
3969  // ----------------------------------------------------------------
3970  // Check if file exists
3971  // ----------------------------------------------------------------
3972  Long_t id,size=0,flags,mt;
3973  int estat = gSystem->GetPathInfo(fName.Data(),&id,&size,&flags,&mt);
3974  if ((estat!=0)&&(!question)) {
3975  cout << "CWB::Toolbox::checkFile - Error - File/Dir \"" << fName.Data() << "\" not exist" << endl;
3976  gSystem->Exit(1);
3977  }
3978 
3979  // -------------------------------------------------------------------------
3980  // Check if output file already exists and asks if you want to overwrite it
3981  // -------------------------------------------------------------------------
3982  if ((estat==0)&&(question)) {
3983  char answer[256];
3984  strcpy(answer,"");
3985  do {
3986  cout << "File/Dir " << fName.Data() << " already exist" << endl;
3987  if(message.Sizeof()>1) cout << message.Data() << endl;
3988  cout << "Do you want to overwrite it ? (y/n) ";
3989  cin >> answer;
3990  cout << endl << endl;
3991  } while ((strcmp(answer,"y")!=0)&&(strcmp(answer,"n")!=0));
3992  if (strcmp(answer,"n")==0) overwrite=false;
3993  }
3994 
3995  return overwrite;
3996 }
3997 
3998 //______________________________________________________________________________
3999 void
4000 CWB::Toolbox::mkDir(TString dir, bool question, bool remove) {
4001 //
4002 // make dir
4003 //
4004 // Input: dir - directory name to be created
4005 // question - true -> ask confirm before creation
4006 // remove - false/true(def) -> not_remove/remove existing files in the dir
4007 //
4008 // Return true if answer=y
4009 //
4010 
4011  char cmd[256];
4012  Long_t id,size=0,flags,mt;
4013  // Check if dir exist
4014  int estat = gSystem->GetPathInfo(dir.Data(),&id,&size,&flags,&mt);
4015  if((estat==0)&&(question==true)) {
4016  char answer[256];
4017  strcpy(answer,"");
4018  do {
4019  cout << endl;
4020  cout << "dir \"" << dir.Data() << "\" already exist" << endl;
4021  cout << "Do you want to remove the files & recreate dir ? (y/n) ";
4022  cin >> answer;
4023  cout << endl;
4024  } while ((strcmp(answer,"y")!=0)&&(strcmp(answer,"n")!=0));
4025  if (strcmp(answer,"y")==0) {
4026  if(remove) sprintf(cmd,"rm %s/*",dir.Data());
4027  cout << cmd << endl;
4028  gSystem->Exec(cmd);
4029  sprintf(cmd,"mkdir -p %s",dir.Data());
4030  cout << cmd << endl;
4031  gSystem->Exec(cmd);
4032  }
4033  } else if((estat==0)&&(question==false)) {
4034  if(remove) sprintf(cmd,"rm %s/*",dir.Data());
4035  cout << cmd << endl;
4036  gSystem->Exec(cmd);
4037  sprintf(cmd,"mkdir -p %s",dir.Data());
4038  cout << cmd << endl;
4039  gSystem->Exec(cmd);
4040  } else {
4041  sprintf(cmd,"mkdir -p %s",dir.Data());
4042  cout << cmd << endl;
4043  gSystem->Exec(cmd);
4044  }
4045 
4046  return;
4047 }
4048 
4049 //______________________________________________________________________________
4050 bool
4051 CWB::Toolbox::rmDir(TString dir, bool question) {
4052 //
4053 // remove dir
4054 //
4055 // Input: dir - directory name to be removed
4056 // question - true -> ask confirm before remove
4057 //
4058 // Return true if answer=y
4059 //
4060 
4061  bool banswer=false;
4062  char cmd[256];
4063  Long_t id,size=0,flags,mt;
4064  int estat = gSystem->GetPathInfo(dir.Data(),&id,&size,&flags,&mt);
4065  // Check if dir exist
4066  if((estat==0)&&(question==true)) {
4067  char answer[256];
4068  strcpy(answer,"");
4069  do {
4070  cout << endl;
4071  sprintf(cmd,"rm -rf %s",dir.Data());
4072  cout << cmd << endl;
4073  cout << "Do you want to remove the dir ? (y/n) ";
4074  cin >> answer;
4075  cout << endl;
4076  } while ((strcmp(answer,"y")!=0)&&(strcmp(answer,"n")!=0));
4077  if (strcmp(answer,"y")==0) {
4078  banswer=true;
4079  gSystem->Exec(cmd);
4080  }
4081  } else if((estat==0)&&(question==false)) {
4082  sprintf(cmd,"rm -rf %s",dir.Data());
4083  cout << cmd << endl;
4084  gSystem->Exec(cmd);
4085  }
4086 
4087  return banswer;
4088 }
4089 
4090 //______________________________________________________________________________
4091 bool
4093 //
4094 // print question and wait for answer y/n
4095 //
4096 // question - question to be printed
4097 //
4098 // Return true/false if answer=y/n
4099 //
4100 
4101  char answer[256];
4102  strcpy(answer,"");
4103  do {
4104  cout << endl;
4105  cout << question << " (y/n) ";
4106  cin >> answer;
4107  cout << endl;
4108  } while ((strcmp(answer,"y")!=0)&&(strcmp(answer,"n")!=0));
4109  return (strcmp(answer,"y")==0) ? true : false;
4110 }
4111 
4112 //______________________________________________________________________________
4113 double
4114 CWB::Toolbox::getZeroLiveTime(int nIFO, TChain& liv, int dummy) {
4115 //
4116 // Calculate live time of zero lag
4117 //
4118 // Input: nIFO : number of detectors
4119 // liv : tree containing live time informatio
4120 // dummy : not used
4121 //
4122 // Output: value of live time
4123 //
4124 
4125  // check if slag is presents in liv tree
4126  TBranch* branch;
4127  bool slagFound=false;
4128  TIter next(liv.GetListOfBranches());
4129  while ((branch=(TBranch*)next())) {
4130  if (TString("slag").CompareTo(branch->GetName())==0) slagFound=true;
4131  }
4132  next.Reset();
4133  if(!slagFound) {
4134  cout << "CWB::Toolbox::getZeroLiveTime : Error - live tree do not contains slag leaf" << endl;
4135  gSystem->Exit(1);
4136  }
4137 
4138  long int ntot = liv.GetEntries();
4139  liv.Draw("live",TString::Format("lag[%d]==0&&slag[%d]==0",nIFO,nIFO).Data(),"goff",ntot);
4140  long int nsel = liv.GetSelectedRows();
4141  double* live = liv.GetV1();
4142 
4143  double liveZero = 0.;
4144  for(long int i=0; i<nsel; i++) liveZero += live[i];
4145 
4146  return liveZero;
4147 }
4148 
4149 //______________________________________________________________________________
4150 double
4154  int lag_number, int slag_number, int dummy) {
4155 //
4156 // Calculate the live time of the total shift performed.
4157 // If defining a lag_number/slag_number, calculate live time referred to this
4158 //
4159 // Input: nIFO : detector number
4160 // liv : tree containing live time information
4161 //
4162 // Output:Trun : wavearray containing live time for each run number
4163 // - the returned size is the maximum run number
4164 // Wlag : wavearray containing lag progressive number
4165 // Wslag : wavearray containing slag progressive number
4166 // TLag : output list of time lag
4167 // TdLag : output list of time index
4168 // lag_number : specific lag number
4169 // slag_number : specific slag number
4170 // dummy : used to increase calculation speed
4171 //
4172 // Examples : (lag_number==-1) && (slag_number==-1) -> all non zero lags : excluded (lag==0&&slag==0)
4173 // (lag_number>=0) && (slag_number>=0) -> select (lag==lag_number) && (slag==slag_number)
4174 // (lag_number>=0) && (slag_number==-1) -> select lag=lag_number : excluded (lag==0&&slag==0)
4175 // (lag_number==-1) && (slag_number>=0) -> select slag=slag_number : excluded (lag==0&&slag==0)
4176 //
4177 // Note: the variable dummy has been introduced to optimize
4178 // speed of the method (the reason is unknown!!!)
4179 
4180 
4181  float xlag[NIFO_MAX+1];
4182  float xslag[NIFO_MAX+1];
4183  Int_t xrun;
4184  double xlive;
4185  double liveTot = 0.;
4186  double Live=0.;
4187  bool save;
4188 
4189  wavearray<double> Qdlag;
4190  wavearray<double>* Qlag = new wavearray<double>[nIFO+1];
4191  wavearray<double>* Qslag = new wavearray<double>[nIFO+1];
4192  wavearray<double> Qtlag;
4193 
4194  std::map <double, std::map <double, int> > QMap;
4195 
4196  // check if slag is presents in liv tree
4197  TBranch* branch;
4198  bool slagFound=false;
4199  TIter next(liv.GetListOfBranches());
4200  while ((branch=(TBranch*)next())) {
4201  if (TString("slag").CompareTo(branch->GetName())==0) slagFound=true;
4202  }
4203  next.Reset();
4204  if(!slagFound) {
4205  cout << "CWB::Toolbox::getLiveTime : Error - live tree do not contains slag leaf" << endl;
4206  gSystem->Exit(1);
4207  }
4208 
4209  int run_max = liv.GetMaximum("run");
4210 
4211  Trun.resize(run_max);
4212  long int ntot = liv.GetEntries();
4213 
4214  // get max lag
4215  TLeaf* leaf = liv.GetLeaf("lag");
4216  if(!leaf) {
4217  cout << "CWB::Toolbox::getLiveTime : Error - lag leaf is not present" << endl;
4218  gSystem->Exit(1);
4219  }
4220  branch = leaf->GetBranch();
4221  int lag_max=0;
4222  for (long int i=0; i<ntot; ++i) {
4223  long int entryNumber = liv.GetEntryNumber(i);
4224  if (entryNumber < 0) break;
4225  branch->GetEntry(entryNumber);
4226  double val = leaf->GetValue(nIFO);
4227  if (val>lag_max) lag_max = (int)val;
4228  }
4229 
4230  liv.SetBranchAddress("slag",xslag);
4231  liv.SetBranchAddress("lag",xlag);
4232  liv.SetBranchAddress("run",&xrun);
4233  liv.SetBranchAddress("live",&xlive);
4234  liv.SetBranchStatus("*",false);
4235  liv.SetBranchStatus("live",true);
4236  liv.SetBranchStatus("lag",true);
4237  liv.SetBranchStatus("slag",true);
4238  liv.SetBranchStatus("run",true);
4239 
4240  int pc = 0;
4241  int ipc = double(ntot)/10.; if(ipc==0) ipc=1;
4242  for(long int i=0; i<ntot; i++) {
4243  liv.GetEntry(i);
4244 
4245  if(i%ipc==0) {if(ntot>100) {cout << pc<<"%";if (pc<100) cout << " - ";pc+=10;cout.flush();}}
4246 
4247  if((lag_number>=0)&&(slag_number>=0)) {
4248  Live = (xlag[nIFO]==lag_number&&xslag[nIFO]==slag_number) ? xlive : 0.; // lag/slag live time
4249  }
4250  if((lag_number>=0)&&(slag_number==-1)) {
4251  Live = ((xlag[nIFO]==lag_number)&&!((xlag[nIFO]==0)&&(xslag[nIFO]==0))) ? xlive : 0.; // lag live time
4252  }
4253  if((lag_number==-1)&&(slag_number>=0)) {
4254  Live = ((xslag[nIFO]==slag_number)&&!((xlag[nIFO]==0)&&(xslag[nIFO]==0))) ? xlive : 0.; // slag live time
4255  }
4256  if((lag_number==-1)&&(slag_number==-1)) {
4257  Live = !((xlag[nIFO]==0)&&(xslag[nIFO]==0)) ? xlive : 0.; // non-zero live time
4258  }
4259 
4260  liveTot += Live;
4261  Trun.data[xrun-1] += Live;
4262 
4263  save = true;
4264 
4265  int K=-1;
4266  if(QMap.find(xlag[nIFO])!=QMap.end()) {
4267  if(QMap[xlag[nIFO]].find(xslag[nIFO])!=QMap[xlag[nIFO]].end()) {
4268  K=QMap[xlag[nIFO]][xslag[nIFO]];
4269  Qtlag.data[K] += xlive;
4270  save=false;
4271  }
4272  }
4273 
4274  if((lag_number>=0)&&(slag_number>=0)) {
4275  save = (xlag[nIFO]==lag_number&&xslag[nIFO]==slag_number) ? save : false;
4276  }
4277  if((lag_number>=0)&&(slag_number==-1)) {
4278  save = ((xlag[nIFO]==lag_number)&&!((xlag[nIFO]==0)&&(xslag[nIFO]==0))) ? save : false;
4279  }
4280  if((lag_number==-1)&&(slag_number>=0)) {
4281  save = ((xslag[nIFO]==slag_number)&&!((xlag[nIFO]==0)&&(xslag[nIFO]==0))) ? save : false;
4282  }
4283  if((lag_number==-1)&&(slag_number==-1)) {
4284  save = !((xlag[nIFO]==0)&&(xslag[nIFO]==0)) ? save : false;
4285  }
4286  if(save) {
4287  for (int j=0; j<nIFO; j++) Qlag[j].append(xlag[j]);
4288  for (int j=0; j<nIFO; j++) Qslag[j].append(xslag[j]);
4289  Qlag[nIFO].append(xlag[nIFO]);
4290  Qslag[nIFO].append(xslag[nIFO]);
4291  Qtlag.append(xlive);
4292  QMap[xlag[nIFO]][xslag[nIFO]] = Qtlag.size()-1;
4293  double dlag=0;
4294  //for (int j=0; j<nIFO; j++) dlag+=(xslag[j]+xlag[j])*(xslag[j]+xlag[j]);
4295  dlag=xslag[nIFO]*lag_max+xlag[nIFO];
4296  Qdlag.append(sqrt(dlag));
4297  }
4298  }
4299  if(pc==100) cout << pc<<"%";;
4300  cout << endl << endl;
4301 
4302  // sort lag using Qdlag (time distance respect to zero lag)
4303  double* dlag = new double[Qdlag.size()];
4304  for(int i=0;i<(int)Qdlag.size();i++) dlag[i]=Qdlag.data[i];
4305  Int_t *id = new Int_t[Qdlag.size()];
4306  TMath::Sort((int)Qdlag.size(),dlag,id,false);
4307  for(int i=0;i<(int)Qdlag.size();i++) {
4308  Tlag.append(Qtlag[id[i]]);
4309  //Tdlag.append(Qdlag[id[i]]);
4310  Tdlag.append(i);
4311  for (int j=0; j<nIFO+1; j++) {
4312  Wlag[j].append(Qlag[j][id[i]]);
4313  Wslag[j].append(Qslag[j][id[i]]);
4314  }
4315  }
4316  delete [] id;
4317  delete [] dlag;
4318 
4319  for (int j=0; j<nIFO+1; j++) {
4320  Qlag[j].resize(0);
4321  Qslag[j].resize(0);
4322  }
4323  delete [] Qlag;
4324  delete [] Qslag;
4325  Qtlag.resize(0);
4326  Qdlag.resize(0);
4327 
4328  return liveTot;
4329 }
4330 
4331 //______________________________________________________________________________
4332 vector<TString>
4333 CWB::Toolbox::getFileListFromDir(TString dir_name, TString endString, TString beginString, TString containString, bool fast) {
4334 //
4335 // get the file list contained in a directory
4336 //
4337 // Input: dir_name - input dir name
4338 // endString - matched end string in file name
4339 // beginString - matched initial string in file name
4340 // containString - matched contained string in file name
4341 // fast - true -> skip check if exist (faster mode)
4342 //
4343 // Output: Return file name list contained in the directory "dir_name"
4344 //
4345 
4346  TString wdir = gSystem->WorkingDirectory();
4347  TSystemDirectory gdir("", dir_name);
4348  TList *dfiles = NULL;
4349  if(fast) { // skip check if are dirs or files, faster when access to remote files
4350  void *dir = gSystem->OpenDirectory(dir_name);
4351  if(dir) {
4352  const char *file = 0;
4353  dfiles = new TList;
4354  dfiles->SetOwner();
4355  while ((file = gSystem->GetDirEntry(dir))) {
4356  dfiles->Add(new TSystemFile(file, dir_name));
4357  }
4358  gSystem->FreeDirectory(dir);
4359  }
4360  } else { // call standard root method (check if are dirs or files)
4361  dfiles = gdir.GetListOfFiles();
4362  }
4363  if(!dfiles) {
4364  cout << "CWB::Toolbox::getFileListFromDir : Error - dir not found !!!" << endl;
4365  gSystem->Exit(1);
4366  }
4367  TIter dnext(dfiles);
4368  TSystemFile *dfile;
4369  TString fname;
4370  vector<TString> fileList;
4371  char path[1024];
4372 
4373  while ((dfile = (TSystemFile*)dnext())) {
4374  fname = dfile->GetName();
4375  sprintf(path,"%s/%s",dir_name.Data(),fname.Data());
4376  bool fsave=true;
4377  if ((endString!="")&&!fname.EndsWith(endString)) fsave=false;
4378  if ((beginString!="")&&!fname.BeginsWith(beginString)) fsave=false;
4379  if ((containString!="")&&!fname.Contains(containString)) fsave=false;
4380  if(fsave) fileList.push_back(path);
4381  }
4382 
4383  gSystem->ChangeDirectory(wdir); // restore original dir
4384 
4385  delete dfiles;
4386 
4387  //cout << "CWB::Toolbox::getDirFileLists - nfiles : " << fileList.size() << endl;
4388 
4389  return fileList;
4390 }
4391 
4392 //______________________________________________________________________________
4393 std::map<int,TString>
4394 CWB::Toolbox::getJobFileMapFromDir(TString dir_name, TString endString, TString beginString, TString containString, bool fast) {
4395 //
4396 // get the job file map (jobId -> file) contained in a directory
4397 //
4398 // Input: dir_name - input dir name
4399 // endString - matched end string in file name
4400 // beginString - matched initial string in file name
4401 // containString - matched contained string in file name
4402 // fast - true -> skip check if exist (faster mode)
4403 //
4404 // Output: Return job file name map (jobId -> file) contained in the directory "dir_name"
4405 //
4406 
4407  vector<TString> fileList = getFileListFromDir(dir_name, endString, beginString, containString, fast);
4408 
4409  std::map<int, TString> fileMap;
4410  for(int i=0;i<fileList.size();i++) {
4411  fileMap[getJobId(fileList[i])]=fileList[i];
4412  }
4413  return fileMap;
4414 }
4415 
4416 //______________________________________________________________________________
4417 void
4420 //
4421 // It produces Poisson Plot on background stage
4422 //
4423 // Input nIFO : detector number
4424 // Wlag : wavearray containing lag progressive number
4425 // Tlag : wavearray containing live time
4426 // Rlag : wavearray containing rate of each lag
4427 // odir : output dir
4428 //
4429 
4430  int NC=0;
4431  double LT=0.,LAMBDA;
4432  double normalization=0;
4433  double enormalization=0;
4434  double mean=0;
4435  double emean=0;
4436  double chi2=0;
4437  int ndf=0;
4438  int myNDF =-1; //one degree of freedom less to account for the mean estimation
4439  double plevel=0;
4440  double ChiSquare=0.0;
4441  double dChiSquare=0.0;
4442  int minCountsPerBin=5;
4443 
4444  // compute min/max false alarms per lag
4445  int min_fa_per_lag=1000000000;
4446  int max_fa_per_lag=0;
4447  for(int j=0; j<(int)Wlag[nIFO].size(); j++){
4448  if(Wlag[nIFO].data[j]>0.) {
4449  int fa_per_lag=Rlag.data[j]*Tlag.data[j];
4450  if(fa_per_lag<min_fa_per_lag) min_fa_per_lag=fa_per_lag;
4451  if(fa_per_lag>max_fa_per_lag) max_fa_per_lag=fa_per_lag;
4452  }
4453  }
4454  int nbin = max_fa_per_lag-min_fa_per_lag;
4455 
4456  //Histogram for the Poisson Test on the background estimation
4457  TH1I *h1 = new TH1I("h1","h1",nbin,min_fa_per_lag,max_fa_per_lag);
4458 
4459  for(int j=0; j<(int)Wlag[nIFO].size(); j++){
4460  if(Wlag[nIFO].data[j]>0.) { //Fill histogram for the Poisson Test on the background estimation
4461  h1->Fill(Rlag.data[j]*Tlag.data[j]);
4462  NC+=Rlag.data[j]*Tlag.data[j];
4463  LT+=Tlag.data[j];
4464  }
4465  }
4466  LAMBDA= LT>0 ? NC/LT : 0;
4467 
4468  cout << "Total Number of bkg coinc.: " << NC << " total Live Time: "
4469  << LT << " nb = " << LAMBDA << endl;
4470 
4471  if(NC==0) return;
4472 
4473  TCanvas *canvas = new TCanvas("BackgroundPoissonFit", "Background Poisson Fit",32,55,750,502);
4474  canvas->Range(-0.75,-1.23433,6.75,8.17182);
4475  canvas->SetBorderSize(1);
4476  canvas->SetFillColor(0);
4477  canvas->SetGridx();
4478  canvas->SetGridy();
4479  canvas->SetFrameFillColor(0);
4480 
4481  //Poisson Integer Function
4482  TF1 poisson("PoissonIFunction",PoissonIFunction,min_fa_per_lag,max_fa_per_lag,2);
4483  poisson.FixParameter(0,h1->GetEntries());
4484  poisson.SetParameter(1,h1->GetMean());
4485 
4486  TH1D* hfit = (TH1D*)h1->Clone("hfit");
4487 
4488  //loop over the populated bins (counts > minCountsPerBin) to calculate the p-level
4489  for (int k=1;k<=hfit->GetNbinsX();k++) {
4490  int n = k-1;
4491  if (poisson.Eval(n)>minCountsPerBin) {
4492  myNDF++; //myNDF starts from -1 !!
4493  dChiSquare=pow((hfit->GetBinContent(k)-poisson.Eval(n)),2)/poisson.Eval(n);
4494  ChiSquare+=dChiSquare;
4495  cout << "NCoinc = " << n << " Found = " << hfit->GetBinContent(k) << " Expected = "
4496  << poisson.Eval(n) << " Chi2_bin" << n << "= " << dChiSquare<<endl;
4497  }
4498  }
4499 
4500  if(myNDF<=0) {
4501  cout << "CWB::Toolbox::doPoissonPlot - Warning !!! - Poisson NDF <=0 " << endl;
4502  return;
4503  }
4504 
4505  // chi2
4506  double myPLevel=TMath::Prob(ChiSquare,myNDF);
4507  cout<<"myChiSquare :"<<ChiSquare<<endl;
4508  cout << "NDF : " << myNDF << endl;
4509  cout<<"myPlevel :"<<myPLevel<<endl;
4510  int XMIN=kMaxInt,XMAX=kMinInt;
4511  int g=0;
4512  while((hfit->GetBinContent(g)==0)&&(g<hfit->GetNbinsX())){XMIN=g;g++;}
4513  g=0;
4514  while((hfit->GetBinContent(hfit->GetNbinsX()-g)==0)&&(g<hfit->GetNbinsX())){XMAX=hfit->GetNbinsX()-g;g++;}
4515  XMIN--;
4516  XMAX++;
4517  cout<<XMIN<<" "<<XMAX<<endl;
4518  hfit->Fit("PoissonIFunction","R");
4519  TF1* fpois = hfit->GetFunction("PoissonIFunction");
4520  fpois->SetFillColor(kGreen);
4521  fpois->SetFillStyle(3002);
4522  fpois->SetLineColor(kGreen);
4523  fpois->SetLineStyle(1);
4524  fpois->SetLineWidth(1);
4525  fpois->SetLineColor(kGreen);
4526  hfit->SetTitle("Poisson Fit (Black : Data - Green : Fit)");
4527  //hfit->SetTitle(name);
4528  hfit->SetLineWidth(4);
4529  hfit->GetXaxis()->SetTitle("#False Alarms/lag");
4530  hfit->GetYaxis()->SetTitle("#Counts");
4531  hfit->GetXaxis()->SetTitleSize(0.04);
4532  hfit->GetYaxis()->SetTitleSize(0.05);
4533  hfit->GetXaxis()->SetLabelSize(0.04);
4534  hfit->GetYaxis()->SetLabelSize(0.04);
4535  hfit->GetXaxis()->SetTitleOffset(0.97);
4536  hfit->GetYaxis()->SetTitleOffset(1.0);
4537  hfit->GetXaxis()->SetRange(XMIN,XMAX);
4538  gStyle->SetOptFit(0);
4539  gStyle->SetOptStat(0);
4540 
4541  hfit->Draw();
4542 
4543  //Standard Chi2 & Probability
4544  chi2 = fpois->GetChisquare();
4545  ndf = fpois->GetNDF()-1;
4546  plevel = TMath::Prob(chi2,ndf);
4547  normalization = fpois->GetParameter(0);
4548  enormalization = fpois->GetParError(0);
4549  mean = fpois->GetParameter(1);
4550  emean = fpois->GetParError(1);
4551 
4552  cout << "Mean : "<<mean<<endl;
4553  cout << "Norm : "<<normalization<<endl;
4554  cout << "ChiSquare : " << chi2 << endl;
4555  cout << "NDF : " << ndf << endl;
4556  cout << "Plevel : " << plevel << endl;
4557 
4558  TLegend *legend = new TLegend(0.597,0.660,0.961,0.921,NULL,"brNDC");
4559  legend->SetLineColor(1);
4560  legend->SetTextSize(0.033);
4561  legend->SetBorderSize(1);
4562  legend->SetLineStyle(1);
4563  legend->SetLineWidth(1);
4564  legend->SetFillColor(10);
4565  legend->SetFillStyle(1001);
4566 
4567  legend->SetTextSize(0.03);
4568  char entry[256];
4569  sprintf(entry,"# lags = %d ",(int)Wlag[nIFO].size());
4570  legend->AddEntry("",entry,"");
4571  //sprintf(entry,"Nc = %d @ rho>%3.1f",NC,T_out);
4572  sprintf(entry,"Nc = %d",NC);
4573  legend->AddEntry("*",entry,"");
4574  sprintf(entry,"Total Live time = %d s",int(LT));
4575  legend->AddEntry("*",entry,"");
4576  sprintf(entry,"Mean = %.3f +/-%.3f FA/lag",mean,emean);
4577  legend->AddEntry("*",entry,"");
4578  sprintf(entry,"Chi2 (counts>%d) = %.3f",minCountsPerBin,ChiSquare);
4579  legend->AddEntry("*",entry,"");
4580  sprintf(entry,"NDF = %d",myNDF);
4581  legend->AddEntry("*",entry,"");
4582  sprintf(entry,"p-level = %.3f",myPLevel);
4583  legend->AddEntry("*",entry,"");
4584  legend->Draw();
4585 
4586  canvas->Update();
4587  char fname[256];
4588  sprintf(fname,"%s/Lag_PoissonFit.png",odir.Data());
4589  canvas->Print(fname);
4590 
4591  delete h1;
4592  delete canvas;
4593 
4594  return;
4595 }
4596 
4597 //______________________________________________________________________________
4598 char*
4600 //
4601 // return a buffer with all environment name variables and their values
4602 //
4603 
4604  const int nCWB = 35;
4605 
4606  TString ecwb_name[nCWB] = {
4607  "SITE_CLUSTER",
4608  "_USE_ICC",
4609  "_USE_CPP11",
4610  "_USE_ROOT6",
4611  "_USE_PEGASUS",
4612  "_USE_HEALPIX",
4613  "_USE_LAL",
4614  "_USE_EBBH",
4615  "HOME_WAT",
4616  "HOME_WAT_FILTERS",
4617  "HOME_WAT_INSTALL",
4618  "HOME_FRLIB",
4619  "HOME_HEALPIX",
4620  "HOME_CFITSIO",
4621  "HOME_CVODE",
4622  "HOME_LAL",
4623  "LAL_INC",
4624  "LALINSPINJ_EXEC",
4625  "CWB_GWAT",
4626  "CWB_HISTORY",
4627  "CWB_MACROS",
4628  "CWB_ROOTLOGON_FILE",
4629  "CWB_PARAMETERS_FILE",
4630  "CWB_UPARAMETERS_FILE",
4631  "CWB_PPARAMETERS_FILE",
4632  "CWB_UPPARAMETERS_FILE",
4633  "CWB_NETS_FILE",
4634  "CWB_NETC_FILE",
4635  "CWB_HTML_INDEX",
4636  "CWB_HTML_HEADER",
4637  "CWB_HTML_BODY_PROD",
4638  "CWB_HTML_BODY_SIM",
4639  "ROOT_VERSION",
4640  "ROOTSYS",
4641  "LD_LIBRARY_PATH"
4642  };
4643 
4644  TString ecwb_value[nCWB];
4645  for(int i=0;i<nCWB;i++) {
4646  if(gSystem->Getenv(ecwb_name[i])==NULL) {
4647  ecwb_value[i]="";
4648  //cout << "Error : environment " << ecwb_name[i].Data() << " is not defined!!!" << endl;gSystem->Exit(1);
4649  } else {
4650  ecwb_value[i]=TString(gSystem->Getenv(ecwb_name[i]));
4651  }
4652 
4653  }
4654 
4655  int ecwb_csize=0;
4656  for(int i=0;i<nCWB;i++) ecwb_csize+=ecwb_name[i].Sizeof();
4657  for(int i=0;i<nCWB;i++) ecwb_csize+=ecwb_value[i].Sizeof();
4658 
4659  char* iBuffer = new char[2*ecwb_csize];
4660  bzero(iBuffer,(2*ecwb_csize)*sizeof(char));
4661 
4662  int len;
4663  int iLength = 0;
4664  for(int i=0;i<nCWB;i++) {
4665  len = ecwb_name[i].Sizeof();
4666  strncpy(iBuffer+iLength,ecwb_name[i].Data(),len);
4667  iLength += len-1;
4668  iBuffer[iLength]='=';
4669  iLength += 1;
4670  len = ecwb_value[i].Sizeof();
4671  strncpy(iBuffer+iLength,ecwb_value[i].Data(),len);
4672  iLength += len-1;
4673  iBuffer[iLength]=0x0a;
4674  iLength += 1;
4675  }
4676 
4677  return iBuffer;
4678 }
4679 
4680 //______________________________________________________________________________
4681 bool
4683 //
4684 // check if leaf is present in the input tree
4685 //
4686 // Input: itree - pointer to the input tree
4687 // leaf - name of the leaf
4688 //
4689 // Return true/false if leaf is present or not present
4690 //
4691 
4692  TBranch* branch;
4693  bool bleaf=false;
4694  TIter next(itree->GetListOfBranches());
4695  while ((branch=(TBranch*)next())) {
4696  if (TString(leaf.Data()).CompareTo(branch->GetName())==0) bleaf=true;
4697  }
4698  next.Reset();
4699  return bleaf;
4700 }
4701 
4702 
4703 //______________________________________________________________________________
4704 void
4705 CWB::Toolbox::makeSpectrum(wavearray<double>& psd, wavearray<double> x, double chuncklen, double scratchlen, bool oneside) {
4706 //
4707 // make PSD
4708 // PSD is computed averaging N=x.size()/chuncklen energy FFT with length=chuncklen
4709 //
4710 // Input: x - input data sample
4711 // chuncklen - FFT length
4712 // scratchlen - input data scratch length
4713 // oneside - true/false = one side/double side PSD
4714 //
4715 // Output : psd - array with the psd values
4716 //
4717 
4718  if(chuncklen<=0) {
4719  cout << "CWB::Toolbox::makeSpectrum : Error - chuncklen<=0" << endl;
4720  exit(1);
4721  }
4722 
4723  if(scratchlen<0) {
4724  cout << "CWB::Toolbox::makeSpectrum : Error - scratchlen<0" << endl;
4725  exit(1);
4726  }
4727 
4728  int scratchsize = scratchlen*x.rate();
4729  int blocksize = chuncklen*x.rate();
4730  scratchsize-=scratchsize%2; // make it even
4731  blocksize-=blocksize%2; // make it even
4732  double df=(double)x.rate()/(double)(blocksize);
4733 
4734  if(x.size()-2*scratchsize<blocksize) {
4735  cout << "CWB::Toolbox::makeSpectrum : Error - data size not enough to produce PSD" << endl;
4736  exit(1);
4737  }
4738 
4739  int loops = (x.size()-2*scratchsize)/blocksize;
4740  cout << "Rate: " << x.rate() << endl;
4741 
4742  double* window = new double[blocksize];
4743  blackmanharris(window, blocksize);
4744 
4745  psd.resize(blocksize/2);
4746  psd=0;
4747 
4748  wavearray<double> y(blocksize);
4749  y.rate(x.rate());
4750 
4751  for (int n=0;n<loops;n++) {
4752 
4753  int shift=n*blocksize;
4754  //cout << "shift: " << shift << endl;
4755  for (int i=0;i<blocksize;i++) y.data[i]=x.data[i+scratchsize+shift];
4756  for (int i=0;i<blocksize;i++) y.data[i]*=window[i];
4757 
4758  y.FFTW(1);
4759  for (int i=0;i<blocksize;i+=2) psd[i/2]+=pow(y.data[i],2)+pow(y.data[i+1],2);
4760  }
4761 
4762  for (int i=0;i<blocksize/2; i++) psd[i]=sqrt(psd[i]/(double)loops);
4763  if(oneside) {
4764  for (int i=0;i<blocksize/2; i++) psd[i]*=sqrt(2/df); // one side psd
4765  } else {
4766  for (int i=0;i<blocksize/2; i++) psd[i]*=sqrt(1/df); // double side psd
4767  }
4768 
4769  psd.start(0.);
4770  psd.stop(df*psd.size());
4771 
4772  delete [] window;
4773  return;
4774 }
4775 
4776 //______________________________________________________________________________
4777 void
4778 CWB::Toolbox::makeSpectrum(TString ofname, wavearray<double> x, double chuncklen, double scratchlen, bool oneside) {
4779 //
4780 // make PSD
4781 // PSD is computed averaging N=x.size()/chuncklen energy FFT with length=chuncklen
4782 // the psd valued are saved to ofname file
4783 //
4784 // Input: ofname - output psd file name (format : freq psd)
4785 // x - input data sample
4786 // chuncklen - FFT length
4787 // scratchlen - input data scratch length
4788 // oneside - true/false = one side/double side PSD
4789 //
4790 
4792  makeSpectrum(psd, x, chuncklen, scratchlen, oneside);
4793  double df = (psd.stop()-psd.start())/psd.size();
4794 
4795  ofstream out;
4796  out.open(ofname.Data(),ios::out);
4797  if (!out.good()) {cout << "CWB::Toolbox::makeSpectrum - Error : Opening File : " << ofname.Data() << endl;gSystem->Exit(1);}
4798  for (int i=0;i<psd.size();i++) {
4799  double freq = i*df+psd.start();
4800  out << freq << " " << psd[i] << endl;
4801  }
4802  out.close();
4803 
4804  return;
4805 }
4806 
4807 //______________________________________________________________________________
4808 void
4810 //
4811 // get colored gaussian noise
4812 //
4813 // Input: fName - input file with PSD values
4814 // format : freq(Hz) singleside-PSD(1/sqrt(Hz))
4815 // seed - base seed for random number generator
4816 // if seed<0 input wavearray is used instead of gaussian random noise
4817 // we pad freq<fabs(seed) with value A = amplitude at freq=fabs(seed)
4818 // 'run' parameter is used as a multiplicative factor for A -> A=A*run
4819 // run - auxiliary seed for random number generator
4820 // SEED = seed+run
4821 // u.size() - input wavearray size
4822 //
4823 // Output: u - wavearray filled with colored gaussian noise @ rate=16384 Hz
4824 //
4825 
4826  #define OTIME_LENGHT 616 // minimum time lenght simulation
4827  #define TIME_SCRATCH 184 // time scratch used by the FFT
4828  #define LOW_CUT_FREQ 2.0 // output noise is 0 for freq<LOW_CUT_FREQ
4829  #define FREQ_RES 0.125 // input PSD is resampled with dF=FREQ_RES
4830  #define SRATE 16384. // output noise is produced @ rate=SRATE
4831 
4832  TRandom3 random;
4833 
4834  // input lenght must be <= OTIME_LENGHT
4835  double ilenght = u.size()/u.rate();
4836  int otime_lenght = (ilenght<OTIME_LENGHT) ? OTIME_LENGHT : int(ilenght);
4837 
4838  // read PSD
4839  ifstream in;
4840  in.open(fName.Data(),ios::in);
4841  if (!in.good()) {
4842  cout << "CWB::Toolbox::getSimNoise - Error Opening File : " << fName.Data() << endl;
4843  gSystem->Exit(1);
4844  }
4845 
4846  int size=0;
4847  char str[1024];
4848  while(true) {
4849  in.getline(str,1024);
4850  if (!in.good()) break;
4851  if(str[0] != '#') size++;
4852  }
4853  //cout << "size " << size << endl;
4854  in.clear(ios::goodbit);
4855  in.seekg(0, ios::beg);
4856 
4857  wavearray<double> ifr(size);
4858  wavearray<double> ish(size);
4859 
4860  int cnt=0;
4861  while (1) {
4862  in >> ifr.data[cnt] >> ish.data[cnt];
4863  if (!in.good()) break;
4864  if(ish.data[cnt]<=0)
4865  {cout << "CWB::Toolbox::getSimNoise - input sensitivity file : " << fName.Data()
4866  << " contains zero at frequency : " << ifr.data[cnt] << " Hz " << endl;gSystem->Exit(1);}
4867  cnt++;
4868  }
4869  in.close();
4870 
4871  // convert frequency sample
4872  size=int((SRATE/2)/FREQ_RES);
4873  wavearray<double> ofr(size);
4874  wavearray<double> osh(size);
4875  for(int i=0;i<(int)ofr.size();i++) ofr[i]=i*FREQ_RES;
4876  convertSampleRate(ifr,ish,ofr,osh);
4877  ifr.resize(0);
4878  ish.resize(0);
4879 
4880  osh*=1./sqrt(osh.size()/(SRATE/2)); // normalization
4881 
4882  int time_factor = (otime_lenght+TIME_SCRATCH)/(2*osh.size()/double(SRATE));
4883 
4884  // change output time lenght
4885  wavearray<double> y; // temporary time series
4886  y.resize(2*osh.size()*time_factor);
4887  y=0.;
4888  for (int i=0;i<(int)osh.size();i++) {
4889  for (int j=0;j<time_factor;j++) {
4890  y.data[i*time_factor+j]=osh.data[i];
4891  }
4892  }
4893  y.rate(SRATE);
4894  y*=1./sqrt(time_factor);
4895  ofr.resize(0);
4896  osh.resize(0);
4897 
4898  wavearray<double> z; // temporary time series
4899  z.rate(y.rate());
4900  z.resize(y.size());
4901  double df=z.rate()/z.size();
4902  for (int i=0;i<(int)z.size()/2;i++) {
4903  double am = y.data[i];
4904  double frequency = df*i;
4905  if (frequency>=LOW_CUT_FREQ) {
4906  z.data[2*i]=am; // (A)
4907  z.data[2*i+1]=am; // (B)
4908  } else {
4909  z.data[2*i]=0;
4910  z.data[2*i+1]=0;
4911  }
4912  }
4913  z*=1./sqrt(2.); // because of (A & B)
4914  y.resize(0);
4915 
4916  int scratch=z.size()/z.rate()-otime_lenght;
4917  cout << "CWB::Toolbox::getSimNoise - scratch : " << scratch << " osize : " << z.size()/z.rate() << endl;
4918  if (scratch<0) {cout << "Error : bad data length -> " << z.size()/z.rate() << endl;gSystem->Exit(1);}
4919 
4920  wavearray<double> x; // temporary time series
4921  x.rate(z.rate());
4922  x.resize(z.size());
4923 
4924  if(seed>=0) {
4925  // generate random gaussian noise -> FFT
4926  random.SetSeed(seed+run);
4927  for (int i=0;i<x.size()-scratch*x.rate();i++) x.data[i]=random.Gaus(0,1);
4928  random.SetSeed(seed+run+1); // to be syncronized with the next frame
4929  for (int i=x.size()-scratch*x.rate();i<(int)x.size();i++) x.data[i]=random.Gaus(0,1);
4930  } else {
4931  // input wavearray is used instead of gaussian random noise
4932  if(u.size()>x.size()) {
4933  cout << "CWB::Toolbox::getSimNoise - Error : whitened data size " << u.size()
4934  << " is greater than temporary datat size " << x.size() << endl;
4935  gSystem->Exit(1);
4936  }
4937  x=0;
4938  int iS = (x.size()-u.size())/2;
4939  for(int i=0;i<u.size();i++) x[i+iS]=u[i];
4940  }
4941  x.FFTW(1);
4942  x*=sqrt(x.size()); // Average x^2 = 1
4943 
4944  // gaussian white noise -> gaussian coloured noise
4945  u=z;
4946  u*=x;
4947  x.resize(0);
4948  z.resize(0);
4949 
4950  if(seed<0) {
4951  // cwb whitened real noise is 0 for freq<16Hz
4952  // we pad freq<fabs(seed) with value = amplitude at freq=fabs(seed)*run
4953  // run parameter is used as a multiplicative factor
4954 
4955  double df=u.rate()/u.size();
4956  int ipad = fabs(seed)/df;
4957  if(ipad>u.size()/2-1) ipad=u.size()/2-1;
4958  double fpad = sqrt(pow(u.data[2*ipad],2)+pow(u.data[2*ipad+1],2))*run;
4959  for(int i=0;i<(int)u.size()/2;i++) {
4960  double frequency = df*i;
4961  if(frequency<=fabs(seed)) {
4962  u.data[2*i] = gRandom->Gaus(0,fpad);
4963  u.data[2*i+1] = gRandom->Gaus(0,fpad);
4964  }
4965  }
4966  }
4967 
4968  // change output frequency SRATE
4969  df=u.rate()/u.size();
4970  int osize = SRATE/df;
4971  u.resize(osize);
4972  u.rate(SRATE);
4973 
4974  u.FFTW(-1);
4975 
4976  scratch=(osize-otime_lenght*u.rate())/2;
4977  for (int i=0;i<otime_lenght*u.rate();i++) u.data[i]=u.data[scratch+i];
4978 
4979  u.resize(otime_lenght*u.rate());
4980 
4981  return;
4982 }
4983 
4984 //______________________________________________________________________________
4987 //
4988 // read PSD from file
4989 //
4990 // input : fName - input file name [freq(Hz) psd]
4991 // fWidth - bandwidth (Hz)
4992 // dFreq - frequency resolution (Hz)
4993 //
4994 // return PSD sampled at df=dFreq up to fWidth Hz
4995 //
4996 
4997  ifstream in;
4998  in.open(fName.Data(),ios::in);
4999  if (!in.good())
5000  {cout << "CWB::Toolbox::ReadDetectorPSD - Error Opening File : "
5001  << fName.Data() << endl;gSystem->Exit(1);}
5002 
5003  cout << "CWB::Toolbox::ReadDetectorPSD - Read File : " << fName.Data() << endl;
5004 
5005  int size=0;
5006  char str[1024];
5007  while(true) {
5008  in.getline(str,1024);
5009  if (!in.good()) break;
5010  if(str[0] != '#') size++;
5011  }
5012  //cout << "size " << size << endl;
5013  in.clear(ios::goodbit);
5014  in.seekg(0, ios::beg);
5015 
5016  wavearray<double> ifr(size);
5017  wavearray<double> ish(size);
5018 
5019  int cnt=0;
5020  while (1) {
5021  in >> ifr.data[cnt] >> ish.data[cnt];
5022  if (!in.good()) break;
5023  if(ish.data[cnt]<=0)
5024  {cout << "CWB::Toolbox::ReadDetectorPSD - input sensitivity file : " << fName.Data()
5025  << " contains zero at frequency : " << ifr.data[cnt] << " Hz " << endl;gSystem->Exit(1);}
5026  cnt++;
5027  }
5028  in.close();
5029 
5030  // convert frequency sample
5031  size=int(fWidth/dFreq);
5032  wavearray<double> ofr(size);
5033  wavearray<double> osh(size);
5034 
5035  for(int i=0;i<(int)ofr.size();i++) ofr[i]=i*dFreq;
5036  convertSampleRate(ifr,ish,ofr,osh);
5037 
5038  osh.rate(size*dFreq);
5039 
5040  return osh;
5041 }
5042 
5043 //______________________________________________________________________________
5044 void
5046 //
5047 // convert sample rate data
5048 // data are resampled using a linear approximation
5049 //
5050 // input : iw - input samples wavearray, sampled @ iw.rate()
5051 // output : ow - output samples wavearray, sampled @ ow.rate()
5052 // ow.rate() is an input parameter
5053 //
5054 
5055  if(iw.size()<=0) {cout << "CWB::Toolbox::convertSampleRate : Error - input size <=0" << endl;gSystem->Exit(1);}
5056  if(iw.rate()<=0) {cout << "CWB::Toolbox::convertSampleRate : Error - input rate <=0" << endl;gSystem->Exit(1);}
5057  if(ow.size()<=0) {cout << "CWB::Toolbox::convertSampleRate : Error - output size <=0" << endl;gSystem->Exit(1);}
5058  if(ow.rate()<=0) {cout << "CWB::Toolbox::convertSampleRate : Error - output rate <=0" << endl;gSystem->Exit(1);}
5059 
5060  // initialize input array
5061  wavearray<double> ix(iw.size());
5062  double idx=1./iw.rate();
5063  for (int i=0;i<(int)ix.size();i++) ix[i]=i*idx;
5064 
5065  // initialize output array
5066  wavearray<double> ox(ow.size());
5067  double odx=1./ow.rate();
5068  for (int i=0;i<(int)ox.size();i++) ox[i]=i*odx;
5069 
5070  // smooth amplitudes
5071  TGraph* grin = new TGraph(ix.size(), ix.data, iw.data);
5072  TGraphSmooth* gs = new TGraphSmooth("normal");
5073  TGraph* grout = gs->Approx(grin,"linear", ox.size(), ox.data);
5074 
5075  // save amplitudes
5076  for (int i=0;i<(int)ox.size();i++) {
5077  grout->GetPoint(i,ox[i],ow[i]);
5078 // cout << i << " " << ox[i] << " " << ow[i] << endl;
5079  }
5080 
5081  delete grin;
5082  delete gs;
5083 
5084  return;
5085 }
5086 
5087 //______________________________________________________________________________
5088 void
5090 //
5091 // convert sample rate data
5092 //
5093 // data are resampled using a linear approximation
5094 // ox are used to resample input amplitudes iy sampled at times ix
5095 //
5096 // input : ix - input times wavearray
5097 // iy - input amplitudes wavearray
5098 // ox - output times wavearray
5099 // output : oy - output amplitutes wavearray
5100 //
5101 
5102  if(ix.size()<=0) {cout << "CWB::Toolbox::convertSampleRate : Error - input size <=0" << endl;gSystem->Exit(1);}
5103  if(ox.size()<=0) {cout << "CWB::Toolbox::convertSampleRate : Error - output size <=0" << endl;gSystem->Exit(1);}
5104 
5105  // smooth amplitudes
5106  TGraph* grin = new TGraph(ix.size(), ix.data, iy.data);
5107  TGraphSmooth* gs = new TGraphSmooth("normal");
5108  TGraph* grout = gs->Approx(grin,"linear", ox.size(), ox.data);
5109 
5110  // save amplitudes
5111  for (int i=0;i<(int)ox.size();i++) {
5112  grout->GetPoint(i,ox[i],oy[i]);
5113  }
5114 
5115  delete grin;
5116  delete gs;
5117 
5118  return;
5119 }
5120 
5121 //______________________________________________________________________________
5122 int
5124 //
5125 // Create Multiplicity plot
5126 //
5127 // Input: ifName : input file name
5128 // idir : input dir
5129 // odir : output dir
5130 // nIFO : detector number
5131 // Tgap : maximum time gap to associate two events as same event
5132 //
5133 
5134  gRandom->SetSeed(1);
5135 
5136  CWB::History* history = NULL;
5137  bool bhistory=true;
5138 
5139  TString efname = odir+"/"+ifName;
5140  efname.ReplaceAll(".root",".N.root");
5141  bool overwrite = checkFile(efname,true);
5142  if(!overwrite) gSystem->Exit(0);
5143 
5144  TString ifname = idir+"/"+ifName;
5145  TString ofname = odir+"/"+ifName;
5146  ofname.ReplaceAll(".root",".root.tmp.1");
5147 
5148  for(int n=0;n<nIFO;n++) {
5149 
5150  // -------------------------------------------------------------------------
5151  // open root file
5152  // -------------------------------------------------------------------------
5153  cout<<"Opening BKG File : " << ifname.Data() << endl;
5154  TFile ifile(ifname);
5155  if (ifile.IsZombie()) {
5156  cout << "CWB::Toolbox::setMultiplicity - Error opening file " << ifname.Data() << endl;
5157  gSystem->Exit(1);
5158  }
5159  TTree *itree = (TTree*)ifile.Get("waveburst");
5160  if (itree==NULL) {
5161  cout << "CWB::Toolbox::setMultiplicity - tree waveburst is not present in file " << ifname.Data() << endl;
5162  gSystem->Exit(1);
5163  }
5164  Int_t tsize = (Int_t)itree->GetEntries();
5165  cout << "tree size : " << tsize << endl;
5166  if (tsize==0) {
5167  cout << "CWB::Toolbox::setMultiplicity - tree waveburst is empty in file " << ifname.Data() << endl;
5168  gSystem->Exit(1);
5169  }
5170  itree->SetEstimate(tsize);
5171  char selection[256];sprintf(selection,"time[%d]:Entry$",n);
5172  char cut[256]="";
5173 // if(n>0) sprintf(cut,"Mm[%d]==1",n-1);
5174  int isize = itree->Draw(selection,cut,"goff",tsize);
5175  double* time = itree->GetV1();
5176  double* entry = itree->GetV2();
5177  // sort list
5178  Int_t *id = new Int_t[isize];
5179  TMath::Sort((int)isize,time,id,false);
5180 
5181  if(bhistory) {
5182  history=(CWB::History*)ifile.Get("CWB::History");
5183  if(history==NULL) history=new CWB::History();
5184  bhistory=false;
5185  }
5186 
5187  // -------------------------------------------------------------------------
5188  // add new leave to itree
5189  // -------------------------------------------------------------------------
5190 
5191  TBranch* branch;
5192  if(n==0) {
5193  TIter next(itree->GetListOfBranches());
5194  while((branch=(TBranch*)next())) {
5195  if(TString("Msize").CompareTo(branch->GetName())==0) {
5196  cout << "Multiplicity already applied" << endl;
5197  char answer[256];
5198  strcpy(answer,"");
5199  do{
5200  cout << "Do you want to overwrite the previous values ? (y/n) ";
5201  cin >> answer;
5202  } while((strcmp(answer,"y")!=0)&&(strcmp(answer,"n")!=0));
5203  if(strcmp(answer,"n")==0) {
5204  gSystem->Exit(-1);
5205  }
5206  }
5207  }
5208  next.Reset();
5209  }
5210 
5211  // -------------------------------------------------------------------------
5212  // create temporary root file
5213  // -------------------------------------------------------------------------
5214 
5215  int* Msize = new int[nIFO];
5216  int* Mid = new int[nIFO];
5217  UChar_t* Mm = new UChar_t[nIFO];
5218 
5219  char cMsize[32];sprintf(cMsize,"Msize[%1d]/I",nIFO);
5220  char cMid[32];sprintf(cMid,"Mid[%1d]/I",nIFO);
5221  char cMm[32];sprintf(cMm,"Mm[%1d]/b",nIFO);
5222 
5223  TFile* ftmp = new TFile(ofname,"RECREATE");
5224  if (ftmp->IsZombie()) {
5225  cout << "CWB::Toolbox::setMultiplicity - Error opening file " << ofname.Data() << endl;
5226  gSystem->Exit(1);
5227  }
5228  TTree *trtmp = (TTree*)itree->CloneTree(0);
5229  trtmp->SetMaxTreeSize(MAX_TREE_SIZE);
5230  if (n>0) {
5231  trtmp->SetBranchAddress("Msize",Msize);
5232  trtmp->SetBranchAddress("Mid",Mid);
5233  trtmp->SetBranchAddress("Mm",Mm);
5234  } else {
5235  trtmp->Branch("Msize",Msize,cMsize);
5236  trtmp->Branch("Mid",Mid,cMid);
5237  trtmp->Branch("Mm",Mm,cMm);
5238  }
5239  trtmp->Write();
5240 
5241  // -------------------------------------------------------------------------
5242  // insert flag into event tree
5243  // we add a dummy flag entry to the end of onoff array to avoid to discart good events when
5244  // no flag entries are present
5245  // -------------------------------------------------------------------------
5246  cout << "Start applying flag to time["<<n<<"]..." << endl;
5247 
5248  ftmp->cd();
5249 
5250  int pc = 0;
5251  int ipc = (int)((double)(isize+1)/10.);
5252  int *oMsize = new int[tsize];
5253  int *oMid = new int[tsize];
5254  bool *oMm = new bool[tsize];
5255  for(int j=0;j<tsize;j++) {
5256  oMsize[j]=1;
5257  oMid[j]=1;
5258  oMm[j]=false;
5259  }
5260  vector<int> mlist;
5261  int xMsize=1;
5262  int xMid=1;
5263  int ientry=int(entry[id[0]]);
5264  oMsize[ientry]=xMsize; oMid[ientry]=xMid; oMm[ientry]=false;
5265  mlist.push_back(id[0]);
5266  for (int j=1;j<isize;j++) {
5267  ientry=int(entry[id[j]]);
5268  oMsize[ientry]=1;
5269  oMm[ientry]=false;
5270  if((time[id[j]]-time[id[j-1]])<Tgap) {
5271  xMsize++;
5272  mlist.push_back(id[j]);
5273  } else {
5274  int xMm=mlist[int(gRandom->Uniform(0,mlist.size()))]; // select random multiplicity event
5275  oMm[int(entry[xMm])]=true; // set master multiplicity event
5276  for(int m=0;m<(int)mlist.size();m++) oMsize[int(entry[mlist[m]])]=xMsize;
5277  mlist.clear();
5278  xMsize=1;xMid++;
5279  mlist.push_back(id[j]);
5280  }
5281  oMid[ientry]=xMid;
5282 
5283  if(ipc!=0) if(j%ipc==0) {cout << pc;if (pc<100) cout << " - ";pc+=10;cout.flush();}
5284  }
5285  cout << pc << endl << endl;
5286 
5287  int* iMsize = new int[nIFO];
5288  int* iMid = new int[nIFO];
5289  UChar_t* iMm = new UChar_t[nIFO];
5290  if(n>0) {
5291  itree->SetBranchAddress("Msize",iMsize);
5292  itree->SetBranchAddress("Mid",iMid);
5293  itree->SetBranchAddress("Mm",iMm);
5294  }
5295  int nevt_master=0;
5296  for (int j=0;j<tsize;j++) {
5297  itree->GetEntry(j);
5298  for(int k=0;k<nIFO;k++) {
5299  Msize[k]=iMsize[k];
5300  Mid[k]=iMid[k];
5301  Mm[k]=iMm[k];
5302  }
5303  Msize[n]=oMsize[j];
5304  Mid[n]=oMid[j];
5305  Mm[n]=oMm[j];
5306  if(Mm[n]) nevt_master++;
5307  trtmp->Fill();
5308 /*
5309 if(n==(nIFO-1)) {
5310  if(Mm[n]) trtmp->Fill();
5311 } else {
5312  trtmp->Fill();
5313 }
5314 */
5315  }
5316  trtmp->Write();
5317  delete [] id;
5318  delete [] oMsize;
5319  delete [] oMid;
5320  delete [] oMm;
5321  delete [] Msize;
5322  delete [] Mid;
5323  delete [] Mm;
5324  delete [] iMsize;
5325  delete [] iMid;
5326  delete [] iMm;
5327 
5328  cout << "Writing new ofile "<< ofname.Data() << endl;
5329  Int_t osize = (Int_t)trtmp->GetEntries();
5330  cout << "osize : " << osize << endl;
5331  cout << "Master events: " << nevt_master << " Percentage: "<< 100.*double(nevt_master)/double(tsize) << endl;
5332 
5333  if((history!=NULL)&&(n==nIFO-1)) {
5334  // update history
5335  history->SetHistoryModify(true);
5336  if(!history->StageAlreadyPresent(CCAST("MULTIPLICITY"))) history->AddStage(CCAST("MULTIPLICITY"));
5337 
5338  if(!history->TypeAllowed(CCAST("WORKDIR"))) history->AddType(CCAST("WORKDIR"));
5339  char work_dir[512]="";
5340  sprintf(work_dir,"%s",gSystem->WorkingDirectory());
5341  history->AddHistory(CCAST("MULTIPLICITY"), CCAST("WORKDIR"), work_dir);
5342  char hTgap[256];sprintf(hTgap,"Tgap = %f",Tgap);
5343  history->AddLog(CCAST("MULTIPLICITY"), CCAST(hTgap));
5344  }
5345 
5346  ftmp->Close();
5347  ifile.Close();
5348  cout << endl;
5349 
5350  ifname=ofname;
5351  if(n%2) ofname.ReplaceAll(".root.tmp.2",".root.tmp.1");
5352  else ofname.ReplaceAll(".root.tmp.1",".root.tmp.2");
5353  }
5354 
5355  TString rfname = ofname;
5356  ofname = efname;
5357 
5358  // define output live merge file
5359  TString lfname = ifName;
5360  lfname.ReplaceAll(".root",".N.root");
5361  lfname.ReplaceAll("wave_","live_");
5362  TString ilfname = idir+"/"+ifName;
5363  ilfname.ReplaceAll("wave_","live_");
5364 
5365  // define output list merge file
5366  TString mfname = ifName;
5367  mfname.ReplaceAll(".root",".N.root");
5368  mfname.ReplaceAll("wave_","merge_");
5369  mfname.ReplaceAll(".root",".lst");
5370  TString imfname = idir+"/"+ifName;
5371  imfname.ReplaceAll("wave_","merge_");
5372  imfname.ReplaceAll(".root",".lst");
5373 
5374  cout << " rfile " << rfname.Data() << endl;
5375  cout << " ifile " << ifname.Data() << endl;
5376  cout << " ofile " << ofname.Data() << endl;
5377  cout << " lfile " << lfname.Data() << endl;
5378  cout << " mfile " << mfname.Data() << endl;
5379 
5380  char cmd[256];
5381  sprintf(cmd,"mv %s %s",ifname.Data(),ofname.Data());
5382  cout << cmd << endl;
5383  gSystem->Exec(cmd);
5384  // create symbolic link to live root file
5385  sprintf(cmd,"cd %s;ln -s ../%s %s",odir.Data(),ilfname.Data(),lfname.Data());
5386  cout << cmd << endl;
5387  gSystem->Exec(cmd);
5388  // create symbolic link to list merge file
5389  sprintf(cmd,"cd %s;ln -s ../%s %s",odir.Data(),imfname.Data(),mfname.Data());
5390  cout << cmd << endl;
5391  gSystem->Exec(cmd);
5392  sprintf(cmd,"rm %s",rfname.Data());
5393  cout << cmd << endl;
5394  gSystem->Exec(cmd);
5395 
5396  // write history to merge+veto file
5397  if(history!=NULL) {
5398  TFile fhist(ofname,"UPDATE");
5399  history->Write();
5400  fhist.Close();
5401  delete history;
5402  }
5403 
5404  return 0;
5405 }
5406 
5407 //______________________________________________________________________________
5409 CWB::Toolbox::getRate(double rho, double Tgap, int nIFO, TChain& wav, wavearray<int>& Wsel,
5411 //
5412 // Calculate FAR rate at a certain rho treshold
5413 //
5414 // Input rho : rho threshold
5415 // Tgap :
5416 // nIFO : detector number
5417 // wav : input tree
5418 // Wsel :
5419 // Wlag : wavearray containing progressive lag number
5420 // Wslag : wavearray containing progressive slag number
5421 // Tlag : wavearray containing live time
5422 //
5423 
5424 // cout << "rhoThr : " << rho << endl;
5425  gRandom->SetSeed(1);
5426  netevent W(&wav,nIFO);
5427  // slag is not defined in the wat-5.4.0
5428  float* iWslag = new float[nIFO+1];
5429  W.fChain->SetBranchAddress("slag",iWslag);
5430 
5431  int size = Wlag[nIFO].size();
5432 
5433  double liveTot=0;
5434  for(int i=0;i<(int)Tlag.size();i++) liveTot+=Tlag[i];
5435 // cout << "liveTot : " << liveTot << endl;
5436 
5437  // compute the number of indipendent slags,lags
5438  int n;
5439  bool save;
5441  wavearray<int> lag;
5442  for(int i=0; i<size; i++) {
5443  int islag=int(Wslag[nIFO].data[i]);
5444  save = true;
5445  n = slag.size();
5446  for(int j=0; j<n; j++) {
5447  if(slag[j]==islag) {save=false; j=n;}
5448  }
5449  if(save) slag.append(islag);
5450 
5451  int ilag=int(Wlag[nIFO].data[i]);
5452  save = true;
5453  n = lag.size();
5454  for(int j=0; j<n; j++) {
5455  if(lag[j]==ilag) {save=false; j=n;}
5456  }
5457  if(save) lag.append(ilag);
5458  }
5459 
5460 // for(int i=0;i<(int)lag.size();i++) cout << i << " LAG " << lag[i] << endl;
5461 // for(int i=0;i<(int)slag.size();i++) cout << i << " SLAG " << slag[i] << endl;
5462 
5463  // construct the array to associate slag,lag to index
5464  int* slag2id = new int[slag.max()+1];
5465  int* lag2id = new int[lag.max()+1];
5466  for(int i=0;i<(int)slag.size();i++) slag2id[slag[i]]=i;
5467  for(int i=0;i<(int)lag.size();i++) lag2id[lag[i]]=i;
5468 
5469  // construct the matrix to associate lag,slag to live times
5470  int** lag2live = (int**)malloc((slag.size())*sizeof(int*));
5471  for (int i=0;i<(int)slag.size();i++) lag2live[i] = new int[lag.size()];
5472 
5473  for(int i=0; i<size; i++) {
5474  int islag=int(Wslag[nIFO].data[i]);
5475  int ilag=int(Wlag[nIFO].data[i]);
5476  lag2live[slag2id[islag]][lag2id[ilag]]=Tlag[i];
5477  }
5478 
5479  // list of rejected lags
5480  bool** lagRej = (bool**)malloc((slag.size())*sizeof(bool*));
5481  for (int i=0;i<(int)slag.size();i++) lagRej[i] = new bool[lag.size()];
5482  for(int i=0;i<(int)slag.size();i++) for(int j=0;j<(int)lag.size();j++) lagRej[i][j]=false;
5483 
5484  int ntrg = wav.GetEntries();
5485 
5486  int *id = new int[ntrg];
5487  int *wslag = new int[ntrg];
5488  int *wlag = new int[ntrg];
5489  int *entry = new int[ntrg];
5490  double** time = (double**)malloc(nIFO*sizeof(double*));
5491  for (int i=0;i<nIFO;i++) time[i] = new double[ntrg];
5492  bool *trgMaster = new bool[ntrg];
5493  for (int i=0;i<ntrg;i++) trgMaster[i] = false;
5494  bool *wrej = new bool[ntrg];
5495  for (int i=0;i<ntrg;i++) wrej[i] = false;
5496 
5497  int isel=0;
5498  for(int i=0; i<ntrg; i++) {
5499  if(!Wsel[i]) continue;
5500  W.GetEntry(i);
5501  if(W.rho[1]>rho) {
5502  bool skip=false;
5503  for(int j=0;j<nIFO;j++) if(!TMath::IsNaN(W.time[j])) time[j][isel]=W.time[j]; else skip=true;
5504  if(skip) continue;
5505  //wslag[isel]=W.slag[nIFO];
5506  wslag[isel]=iWslag[nIFO];
5507  wlag[isel]=W.lag[nIFO];
5508  entry[isel]=i;
5509  isel++;
5510  }
5511  }
5512 // cout << "selTrg : " << isel << endl;
5513 
5514  int rejTrg=0;
5515  double rejLive=0;
5516  vector<double> livlist;
5517  vector<int> idlist;
5518  for(int i=0;i<nIFO;i++) {
5519  if(isel==0) continue;
5520  TMath::Sort((int)isel,time[i],id,false);
5521  int islag = slag2id[wslag[id[0]]];
5522  int ilag = lag2id[wlag[id[0]]];
5523  double live = lag2live[islag][ilag];
5524  livlist.push_back(live);
5525  idlist.push_back(id[0]);
5526  for (int j=1;j<isel;j++) {
5527  if(wrej[id[j]]) continue; // skip trigger if already rejected
5528  if((time[i][id[j]]-time[i][id[j-1]])>Tgap) {
5529 /*
5530  // find minimum live time in the multiplicity list
5531  double liveMin=kMaxInt; int M=0;
5532  for(int m=0;m<(int)livlist.size();m++) {
5533  if(liveMin>livlist[m]) {liveMin=livlist[m];M=m;}
5534  }
5535 */
5536  int M=int(gRandom->Uniform(0,(int)idlist.size())); // select random multiplicity event
5537  trgMaster[idlist[M]]=true;
5538  for(int m=0;m<(int)idlist.size();m++) {
5539  // select only the trigger in the multiplicity list with minimum live time
5540  // check if live time has been already rejected
5541  int islag = slag2id[wslag[idlist[m]]];
5542  int ilag = lag2id[wlag[idlist[m]]];
5543  if(!trgMaster[idlist[m]]) {
5544  if(!lagRej[islag][ilag]) rejLive+=livlist[m];
5545  lagRej[islag][ilag]=true;
5546  wrej[idlist[m]]=true; // Tag the rejected trigger
5547  Wsel[entry[idlist[m]]]=2; // Tag the rejected trigger with 2
5548  rejTrg++;
5549  }
5550  }
5551  livlist.clear();
5552  idlist.clear();
5553  }
5554  int islag = slag2id[wslag[id[j]]];
5555  int ilag = lag2id[wlag[id[j]]];
5556  live = lag2live[islag][ilag];
5557  livlist.push_back(live);
5558  idlist.push_back(id[j]);
5559  }
5560 /*
5561  // find minimum live time in the multiplicity list
5562  double liveMin=kMaxInt; int M=0;
5563  for(int m=0;m<(int)livlist.size();m++) {
5564  if(liveMin>livlist[m]) {liveMin=livlist[m];M=m;}
5565  }
5566 */
5567  int M=int(gRandom->Uniform(0,(int)idlist.size())); // select random multiplicity event
5568  trgMaster[idlist[M]]=true;
5569  for(int m=0;m<(int)idlist.size();m++) {
5570  // select only the trigger in the multiplicity list with minimum live time
5571  // check if live time has been already rejected
5572  int islag = slag2id[wslag[idlist[m]]];
5573  int ilag = lag2id[wlag[idlist[m]]];
5574  if(!trgMaster[idlist[m]]) {
5575  if(!lagRej[islag][ilag]) rejLive+=livlist[m];
5576  lagRej[islag][ilag]=true;
5577  wrej[idlist[m]]=true; // Tag the rejected trigger
5578  Wsel[entry[idlist[m]]]=2; // Tag the rejected trigger with 2
5579  rejTrg++;
5580  }
5581  }
5582  livlist.clear();
5583  idlist.clear();
5584  }
5585 // cout << "rejTrg : " << rejTrg << endl;
5586 
5587  // reject triggers which belong to the rejected lags
5588  for (int j=0;j<isel;j++) {
5589  if(wrej[j]) continue; // only the triggers not already rejected
5590  int islag = slag2id[wslag[j]];
5591  int ilag = lag2id[wlag[j]];
5592  if(lagRej[islag][ilag]) {
5593  Wsel[entry[j]]=2; // Tag the rejected trigger with 2
5594  rejTrg++;
5595  }
5596  }
5597 // cout << "rejTrg final : " << rejTrg << endl;
5598 // cout << "rejLive : " << rejLive << endl;
5599 
5600 /*
5601 int xrejTrg=0;
5602 for (int j=0;j<isel;j++) {
5603  int islag = slag2id[wslag[j]];
5604  int ilag = lag2id[wlag[j]];
5605  if(lagRej[islag][ilag]) {
5606  xrejTrg++;
5607  }
5608 }
5609 cout << "xrejTrg final: " << xrejTrg << endl;
5610 int nlagRej=0;
5611 for(int i=0;i<(int)slag.size();i++) for(int j=0;j<(int)lag.size();j++) if(lagRej[i][j]) nlagRej++;
5612 cout << "nlagRej final: " << nlagRej << endl;
5613 double xlivRej=0;
5614 for(int i=0;i<(int)slag.size();i++) for(int j=0;j<(int)lag.size();j++) if(lagRej[i][j]) xlivRej+=lag2live[i][j];
5615 cout << "xlivRej final: " << xlivRej << endl;
5616 */
5617 /*
5618  for(int j=0; j<size; j++){
5619  printf("slag=%i\t lag=%i\t ",int(Wslag[nIFO].data[j]),int(Wlag[nIFO].data[j]));
5620  //for (int jj=0; jj<nIFO; jj++) printf("%d:slag=%5.2f\tlag=%5.2f\t",jj,Wslag[jj].data[j],Wlag[jj].data[j]);
5621  printf("live=%9.2f\n",Tlag.data[j]);
5622  }
5623 */
5624 
5625  for (int i=0;i<nIFO;i++) delete [] time[i];
5626  delete [] id;
5627  delete [] wslag;
5628  delete [] wlag;
5629  for (int i=0;i<(int)slag.size();i++) delete [] lag2live[i];
5630  delete [] slag2id;
5631  delete [] lag2id;
5632  delete [] iWslag;
5633  delete [] trgMaster;
5634  delete [] wrej;
5635  delete [] entry;
5636 
5637  double rate = (isel-rejTrg)/(liveTot-rejLive);
5638  double erate = sqrt(isel-rejTrg)/(liveTot-rejLive);
5639  return wavecomplex(rate,erate);
5640 }
5641 
5642 
5643 //_______________________________________________________________________________________
5644 int
5645 CWB::Toolbox::GetStepFunction(TString fName, vector<double>& x, vector<double>& y,
5646  vector<double>& ex, vector<double>& ey) {
5647 
5648  GetStepFunction("", fName, 0, x, y, ex, ey);
5649 
5650  // remove the first and the last elements added by the GetStepFunction method
5651  int size=x.size();
5652 
5653  // erase the first element (adde)
5654  x.erase(x.begin()+size-1);
5655  y.erase(y.begin()+size-1);
5656  ex.erase(ex.begin()+size-1);
5657  ey.erase(ey.begin()+size-1);
5658 
5659  // erase the last element
5660  x.erase(x.begin());
5661  y.erase(y.begin());
5662  ex.erase(ex.begin());
5663  ey.erase(ey.begin());
5664 
5665  return x.size();
5666 }
5667 
5668 //_______________________________________________________________________________________
5669 double
5671  vector<double>& x, vector<double>& y, vector<double>& ex, vector<double>& ey) {
5672 //
5673 // read x,y coodinated from fName
5674 // y[x] is approximated with a step function
5675 //
5676 // V : input value
5677 //
5678 // fName : ascii file with the list of x,y coordinateds
5679 // x1 y1
5680 // x2 y2
5681 // .....
5682 // xN yN
5683 //
5684 // option : "xmin" - return minimum x value
5685 // "xmax" - return maximim x value
5686 // "ymin" - return minimum y value
5687 // "ymax" - return maximim y value
5688 // "y" - return the y value corresponding to x=V
5689 //
5690 // ERRORS : the same options can be used for errors : use 'e' in front of the option
5691 // for example to get error of 'x' use 'ex'
5692 // the input file must have 4 columns format : x y ex ey
5693 //
5694 
5695  bool ferror=false; // if true return errors
5696 
5697  // get option
5698  option.ToUpper();
5699  if(option!="") {
5700  if((option!="XMIN")&&(option!="XMAX")&&
5701  (option!="YMIN")&&(option!="YMAX")&&
5702  (option!="Y")&&(option!="EX")&&(option!="EY")) {
5703  cout<<"GetLinearInterpolation : Error : option --value bad value -> "
5704  <<"must be y/xmin/xmax/ymin/ymax"<<endl;
5705  exit(1);
5706  }
5707  if(option.BeginsWith("E")) {ferror=true;option.Remove(0,1);}
5708  }
5709 
5710  double xmin=DBL_MAX;
5711  double ymin=DBL_MAX;
5712  double xmax=-DBL_MAX;
5713  double ymax=-DBL_MAX;
5714 
5715  double exmin=DBL_MAX;
5716  double eymin=DBL_MAX;
5717  double exmax=-DBL_MAX;
5718  double eymax=-DBL_MAX;
5719 
5720  ifstream in;
5721  in.open(fName.Data());
5722  if (!in.good()) {cout << "GetGraphValue : Error Opening File : " << fName << endl;exit(1);}
5723  double ix,iy;
5724  double iex,iey;
5725  char line[1024];
5726  while(1) {
5727  in.getline(line,1024);
5728  if (in.eof()) break;
5729  std::stringstream linestream(line);
5730  if(ferror) { // get error value
5731  if(linestream >> ix >> iy >> iex >> iey) {
5732  ex.push_back(iex);
5733  ey.push_back(iey);
5734  if(iex<exmin) exmin=iex;
5735  if(iey<eymin) eymin=iey;
5736  if(iex>exmax) exmax=iex;
5737  if(iey>eymax) eymax=iey;
5738  } else {
5739  linestream.str(line);
5740  linestream.clear();
5741  if(!(linestream >> ix >> iy)) {
5742  cout << "GetGraphValue : Wrong line format : must be 'x y' " << endl;
5743  exit(1);
5744  }
5745  ex.push_back(0); ey.push_back(0);
5746  exmin=0;eymin=0;exmax=0;eymax=0;
5747  }
5748  } else {
5749  if(!(linestream >> ix >> iy)) {
5750  cout << "GetGraphValue : Wrong line format : must be 'x y' " << endl;
5751  exit(1);
5752  }
5753  ex.push_back(0); ey.push_back(0);
5754  exmin=0;eymin=0;exmax=0;eymax=0;
5755  }
5756  x.push_back(ix);
5757  y.push_back(iy);
5758  if(ix<xmin) xmin=ix;
5759  if(iy<ymin) ymin=iy;
5760  if(ix>xmax) xmax=ix;
5761  if(iy>ymax) ymax=iy;
5762  }
5763  in.close();
5764 
5765  if(option=="XMIN") return ferror ? exmin : xmin;
5766  if(option=="XMAX") return ferror ? exmax : xmax;
5767  if(option=="YMIN") return ferror ? eymin : ymin;
5768  if(option=="YMAX") return ferror ? eymax : ymax;
5769 
5770  if(x.size()==0) cout << "GetGraphValue : Error - input file empty" << endl;
5771 
5772  // Sort respect to x values
5773  int size = x.size();
5774  wavearray<int> I(size);
5775  wavearray<double> X(size);
5776  for(int i=0;i<size;i++) X[i]=x[i];
5777  TMath::Sort(size,X.data,I.data,false);
5778 
5779  // insert a new element at the beginning with x=-DBL_MAX and y[I[0]]
5780  // necessary for TGraph
5781  std::vector<double>::iterator it;
5782  it = x.begin(); x.insert(it,-DBL_MAX);
5783  it = y.begin(); y.insert(it,y[I[0]]);
5784  it = ex.begin(); ex.insert(it,ex[I[0]]);
5785  it = ey.begin(); ey.insert(it,ey[I[0]]);
5786  size = x.size();
5787 
5788  // Re-Sort respect to x values
5789  I.resize(size);
5790  X.resize(size);
5791  for(int i=0;i<size;i++) X[i]=x[i];
5792  TMath::Sort(size,X.data,I.data,false);
5793 
5794  x.push_back(x[I[size-1]]); y.push_back(-DBL_MAX);
5795  ex.push_back(ex[I[size-1]]); ey.push_back(ey[I[size-1]]);
5796  I.resize(size+1); I[size]=I[size-1]; size++;
5797 
5798  if(!ferror) { // return y
5799  if(V<x[I[0]]) return y[I[0]];
5800  if(V>=x[I[size-1]]) return y[I[size-1]];
5801  for(int i=1;i<size;i++) if((V>=x[I[i-1]]) && (V<x[I[i]])) return y[I[i-1]];
5802  } else {
5803  if(option=="X") { // return ex
5804  if(V<x[I[0]]) return ex[I[0]];
5805  if(V>=x[I[size-1]]) return ex[I[size-1]];
5806  for(int i=1;i<size;i++) if((V>=x[I[i-1]]) && (V<x[I[i]])) return ex[I[i-1]];
5807  } else if(option=="Y") { // return ey
5808  if(V<x[I[0]]) return ey[I[0]];
5809  if(V>=x[I[size-1]]) return ey[I[size-1]];
5810  for(int i=1;i<size;i++) if((V>=x[I[i-1]]) && (V<x[I[i]])) return ey[I[i-1]];
5811  }
5812  }
5813 }
5814 
5815 
5816 //______________________________________________________________________________
5817 void
5819 //
5820 // convert to a power of 2 rate > original rate
5821 //
5822 
5823  // compute the new rate
5824  int R=1;while (R < 2*(int)w.rate()) R*=2;
5825 
5826  if(R==2*w.rate()) return;
5827 
5828  Meyer<double> BB(256);
5829  WSeries<double> ww(BB);
5830  wavearray<double> yy(2*w.size());
5831  yy.rate(2*w.rate());
5832  yy.start(w.start());
5833 
5834  ww.Forward(yy,BB,1);
5835  ww=0.;
5836  ww.putLayer(w,0);
5837  ww.Inverse();
5838  yy.resample(ww,R,32);
5839  ww.Forward(yy,BB,1);
5840  ww.getLayer(w,0);
5841 
5842  fprintf(stdout,"--------------------------------\n");
5843  fprintf(stdout,"After resampling: rate=%f, size=%d, start=%f\n", w.rate(),(int)w.size(),w.start());
5844  fprintf(stdout,"--------------------------------\n");
5845 
5846  return;
5847 }
5848 
5849 //______________________________________________________________________________
5850 void
5852 //
5853 // write date and memory usage at a certain point of the analysis
5854 //
5855 
5856  gSystem->Exec("date");
5857  TString s;
5858  FILE *f = fopen(Form("/proc/%d/statm", gSystem->GetPid()), "r");
5859  s.Gets(f);
5860  Long_t total, rss;
5861  sscanf(s.Data(), "%ld %ld", &total, &rss);
5862  cout << str.Data() << " virtual : " << total * 4 / 1024 << " (mb) rss : " << rss * 4 / 1024 << " (mb)" << endl;
5863  fclose(f);
5864  return;
5865 }
5866 
5867 //______________________________________________________________________________
5868 TString
5870 //
5871 // get name of temporary file on the node
5872 //
5873 // Input: label associate to the analysis
5874 // file extension
5875 //
5876 
5877  // create temporary file
5878  gRandom->SetSeed(0);
5879  int rnID = int(gRandom->Rndm(13)*1.e9);
5880  UserGroup_t* uinfo = gSystem->GetUserInfo();
5881  TString uname = uinfo->fUser;
5882  // create temporary dir
5883  gSystem->Exec(TString("mkdir -p /dev/shm/")+uname);
5884 
5885  char fName[256]="";
5886 
5887  sprintf(fName,"/dev/shm/%s/%s_%d.%s",uname.Data(),label.Data(),rnID,extension.Data());
5888 
5889  return fName;
5890 }
5891 
5892 //______________________________________________________________________________
5893 vector<TString>
5894 CWB::Toolbox::sortStrings(vector<TString> ilist) {
5895 //
5896 // sort in alphabetic order the TString list
5897 //
5898 // Input: TString list
5899 // return the sorted TString list
5900 //
5901 
5902  std::vector<std::string> vec(ilist.size());
5903  for(int i=0;i<ilist.size();i++) vec[i]=ilist[i].Data();
5904  std::sort( vec.begin(), vec.end() ) ;
5905  vector<TString> slist(ilist.size());
5906  for(int i=0; i<vec.size(); i++) slist[i]=vec[i];
5907 
5908  return slist;
5909 }
5910 
5911 //______________________________________________________________________________
5912 int
5914 //
5915 // return jobId from the file name
5916 // file must have the following format *_job#id.'fext'
5917 //
5918 
5919  if(!file.EndsWith("."+fext)) {
5920  cout << "CWB::Toolbox::getJobId : input file "
5921  << file.Data() << " must terminate with ." << fext << endl;
5922  gSystem->Exit(1);
5923  }
5924 
5925  file.ReplaceAll("."+fext,"");
5926  TObjArray* token = file.Tokenize('_');
5927  TObjString* sjobId = (TObjString*)token->At(token->GetEntries()-1);
5928  TString check = sjobId->GetString(); check.ReplaceAll("job","");
5929  if(!check.IsDigit()) {
5930  cout << "CWB::Toolbox::getJobId : input file " << file.Data()
5931  << " must terminate with _job#id." << fext << endl;
5932  cout << "#id is not a digit" << endl;
5933  gSystem->Exit(1);
5934  }
5935  int jobId = TString(sjobId->GetString()).ReplaceAll("job","").Atoi();
5936  if(token) delete token;
5937 
5938  return jobId;
5939 }
5940 
5941 //______________________________________________________________________________
5942 TString
5944 // get params from option string
5945 // options format : --par1 val1 --par2 val2 ...
5946 
5947  TObjArray* token;
5948 
5949  // check if input param format is correct
5950  token = param.Tokenize(TString(" "));
5951  if((token->GetEntries())>0) {
5952  TObjString* otoken = (TObjString*)token->At(0);
5953  TString stoken = otoken->GetString();
5954  if(((token->GetEntries())>1) || (!stoken.BeginsWith("--"))) {
5955  cout << "CWB::Toolbox::getParameter : Bad param format \"" << param.Data() << "\"" << endl;
5956  cout << "Correct format is : --par1" << endl;
5957  gSystem->Exit(1);
5958  }
5959  }
5960  if(token) delete token;
5961 
5962  token = options.Tokenize(TString(" "));
5963  // check if input options format is correct
5964  if((token->GetEntries())%2==1) {
5965  cout << "CWB::Toolbox::getParameter : Bad options format \"" << options.Data() << "\"" << endl;
5966  cout << "Correct format is : --par1 val1 --par2 val2 ..." << endl;
5967  gSystem->Exit(1);
5968  }
5969  for(int i=0;i<token->GetEntries();i+=2) {
5970  TObjString* otoken = (TObjString*)token->At(i);
5971  TString stoken = otoken->GetString();
5972  if(!stoken.BeginsWith("--")) {
5973  cout << "CWB::Toolbox::getParameter : Bad options format \"" << stoken.Data() << "\"" << endl;
5974  cout << "Correct format is : --par1 val1 --par2 val2 ..." << endl;
5975  gSystem->Exit(1);
5976  }
5977  }
5978  for(int i=0;i<token->GetEntries();i++) {
5979  TObjString* otoken = (TObjString*)token->At(i);
5980  TString stoken = otoken->GetString();
5981  // exctract value
5982  if(stoken==param) {
5983  if(i<token->GetEntries()-1) {
5984  otoken = (TObjString*)token->At(i+1);
5985  return otoken->GetString();
5986  }
5987  }
5988  }
5989  if(token) delete token;
5990 
5991  return "";
5992 }
5993 
5994 //______________________________________________________________________________
5995 TString
5997 //
5998 // get file name from its pointer fp
5999 //
6000 
6001  int MAXSIZE = 0xFFF;
6002  char proclnk[0xFFF];
6003  char filename[0xFFF];
6004  int fno;
6005  ssize_t r;
6006 
6007  if (fp != NULL)
6008  {
6009  fno = fileno(fp);
6010  sprintf(proclnk, "/proc/self/fd/%d", fno);
6011  r = readlink(proclnk, filename, MAXSIZE);
6012  if (r < 0) return "";
6013  filename[r] = '\0';
6014  return filename;
6015  }
6016  return "";
6017 }
6018 
6019 //______________________________________________________________________________
6020 TString
6022 //
6023 // get file name from its symbolic link
6024 //
6025 
6026  int MAXSIZE = 0xFFF;
6027  char proclnk[0xFFF];
6028  char filename[0xFFF];
6029  ssize_t r;
6030 
6031  if (symlink != NULL)
6032  {
6033  sprintf(proclnk, "%s", symlink);
6034  r = readlink(symlink, filename, MAXSIZE);
6035  if (r < 0) return "";
6036  filename[r] = '\0';
6037  return filename;
6038  }
6039  return "";
6040 }
6041 
6042 //______________________________________________________________________________
6043 void
6045 //
6046 // extract from ifile (contains a list of files) a unique file list and write it to ofile
6047 //
6048 
6049  vector<std::string> ifileList;
6050  vector<std::string> ipathList;
6051  vector<std::string> ofileList;
6052  vector<std::string> opathList;
6053 
6054  ifstream in;
6055  in.open(ifile.Data());
6056  if(!in.good()) {
6057  cout << "CWB::Toolbox::getUniqueFileList : Error Opening Input File : " << ifile.Data() << endl;
6058  gSystem->Exit(1);
6059  }
6060 
6061  // read file list
6062  char istring[1024];
6063  while(1) {
6064  in.getline(istring,1024);
6065  if (!in.good()) break;
6066  TObjArray* token = TString(istring).Tokenize(TString('/'));
6067  // extract last entry -> file name
6068  TObjString* stoken =(TObjString*)token->At(token->GetEntries()-1);
6069  TString fName = stoken->GetString();
6070  //cout << fName.Data() << endl;
6071  ipathList.push_back(istring);
6072  ifileList.push_back(fName.Data());
6073  }
6074  in.close();
6075 
6076  // extract unique file list
6077  for(int i=0;i<(int)ifileList.size();i++) {
6078  bool check=false;
6079  for(int j=0;j<(int)ofileList.size();j++) {
6080  if(TString(ofileList[j])==TString(ifileList[i])) {check=true;break;}
6081  }
6082  if(!check) {
6083  ofileList.push_back(ifileList[i]);
6084  opathList.push_back(ipathList[i]);
6085  }
6086  //cout << i << " " << ipathList[i] << endl;
6087  //cout << i << " " << ifileList[i] << endl;
6088  }
6089 
6090  // write unique file list
6091  ofstream out;
6092  out.open(ofile.Data(),ios::out);
6093  if(!out.good()) {
6094  cout << "CWB::Toolbox::getUniqueFileList : Error Opening Output File : " << ofile.Data() << endl;
6095  gSystem->Exit(1);
6096  }
6097 
6098  for(int i=0;i<(int)ofileList.size();i++) {
6099  out << opathList[i] << endl;
6100  //cout << i << " " << opathList[i] << endl;
6101  //cout << i << " " << ofileList[i] << endl;
6102  }
6103 
6104  out.close();
6105 
6106  return;
6107 }
6108 
6109 //______________________________________________________________________________
6112 //
6113 // return the Hilbert transform
6114 //
6115 
6117 
6118  y.FFTW(1);
6119  for(int i=1;i<(int)y.size()/2;i++) {
6120  double temp=y[2*i+1];
6121  y[2*i+1]=y[2*i];
6122  y[2*i]=-1*temp;
6123  }
6124  y.FFTW(-1);
6125 
6126  return y;
6127 }
6128 
6129 //______________________________________________________________________________
6132 //
6133 // return the envelope from analytic signal analysis
6134 //
6135 
6137 
6138  // compute hilbert transform
6139  wavearray<double> h = getHilbertTransform(y);
6140 
6141  // compute envelope
6142  for(int i=0;i<(int)y.size();i++) {
6143  y[i]=sqrt(y[i]*y[i]+h[i]*h[i]);
6144  }
6145 
6146  return y;
6147 }
6148 
6149 //______________________________________________________________________________
6152 //
6153 // return the instantaneous frequency from analytic signal analysis
6154 //
6155 
6157 
6158  double twopi = TMath::TwoPi();
6159  double dt = 1./x.rate();
6160 
6161  // compute hilbert transform
6162  wavearray<double> h = getHilbertTransform(y);
6163 
6164  // compute phase (use p as temporary array for phase)
6165  wavearray<float> p(h.size());
6166  for(int i=0;i<(int)y.size();i++) {
6167  p[i]=TMath::ATan2(y[i],h[i]);
6168  }
6169 
6170  unWrapPhase(p);
6171  for(int i=1;i<(int)p.size()/2-1;i++) p[2*i]=(p[2*i-1]+p[2*i+1])/2; // cut alias frequency
6172 
6173  // compute frequency
6174  for(int i=1;i<(int)x.size();i++) {
6175  y[i] = (p[i]-p[i-1])/(twopi*dt);
6176  if(y[i]>x.rate()/2) y[i]=0; // cut unphysical frequency
6177  if(y[i]<0) y[i]=0; // cut unphysical frequency
6178  }
6179  if(y.size()>1) y[0]=y[1]; else y[0]=0;
6180  if(y.size()>1) y[y.size()-1]=y[y.size()-2]; else y[y.size()-1]=0;
6181 
6182  return y;
6183 }
6184 
6185 //______________________________________________________________________________
6188 //
6189 // return TF map wavearray NxN : Matrix[i,j]=N*j+i : i=time_index, j=freq_index
6190 //
6191 
6192  int N = x.size();
6193  int dN = 2*N;
6194 
6195  wavearray<double> y = x;
6196  y.FFTW(1);
6197  y.resize(2*y.size());
6198  for(int i=(int)x.size();i<(int)y.size();i++) y[i]=0;
6199  y.FFTW(-1);
6200 
6201  wavearray<double> z(3*dN);
6202  z=0;for(int i=dN; i<2*dN; ++i) z[i] = y[i-dN];
6203 
6204  wavearray<double> wv(N*N);
6205  wv.start(x.start());
6206  wv.rate(x.rate());
6207 
6208  y.resize(dN);
6209  for(int n=1; n<=N; ++n ) {
6210 
6211  for(int i=0; i<N; ++i) y[i] = z[dN+2*n+i]*z[dN+2*n-i];
6212  for(int i=-N; i<0; ++i) y[dN+i] = z[dN+2*n+i]*z[dN+2*n-i];
6213 
6214  y.FFTW(1);
6215 
6216  for(int m=0; m<N; m++) wv[m*N+(n-1)] = y[2*m];
6217  }
6218 
6219  return wv;
6220 }
6221 
6222 //______________________________________________________________________________
6223 void
6225 //
6226 // Phase unwrapping ensures that all appropriate multiples of 2*pi have been included in phase evolution
6227 // p : phase array
6228 // return in p the unwrapped phase
6229 //
6230 
6231  int N = p.size();
6232 
6233  // ported from matlab (Dec 2002)
6234  wavearray<float> dp(N);
6235  wavearray<float> dps(N);
6236  wavearray<float> dp_corr(N);
6237  wavearray<float> cumsum(N);
6238  float cutoff = M_PI; /* default value in matlab */
6239  int j;
6240 
6241  // incremental phase variation
6242  // MATLAB: dp = diff(p, 1, 1);
6243  for (j = 0; j < N-1; j++) dp[j] = p[j+1] - p[j];
6244 
6245  // equivalent phase variation in [-pi, pi]
6246  // MATLAB: dps = mod(dp+dp,2*pi) - pi;
6247  for (j = 0; j < N-1; j++)
6248  dps[j] = (dp[j]+M_PI) - floor((dp[j]+M_PI) / (2*M_PI))*(2*M_PI) - M_PI;
6249 
6250  // preserve variation sign for +pi vs. -pi
6251  // MATLAB: dps(dps==pi & dp>0,:) = pi;
6252  for (j = 0; j < N-1; j++)
6253  if ((dps[j] == -M_PI) && (dp[j] > 0))
6254  dps[j] = M_PI;
6255 
6256  // incremental phase correction
6257  // MATLAB: dp_corr = dps - dp;
6258  for (j = 0; j < N-1; j++)
6259  dp_corr[j] = dps[j] - dp[j];
6260 
6261  // Ignore correction when incremental variation is smaller than cutoff
6262  // MATLAB: dp_corr(abs(dp)<cutoff,:) = 0;
6263  for (j = 0; j < N-1; j++)
6264  if (fabs(dp[j]) < cutoff)
6265  dp_corr[j] = 0;
6266 
6267  // Find cumulative sum of deltas
6268  // MATLAB: cumsum = cumsum(dp_corr, 1);
6269  cumsum[0] = dp_corr[0];
6270  for (j = 1; j < N-1; j++)
6271  cumsum[j] = cumsum[j-1] + dp_corr[j];
6272 
6273  // Integrate corrections and add to P to produce smoothed phase values
6274  // MATLAB: p(2:m,:) = p(2:m,:) + cumsum(dp_corr,1);
6275  for (j = 1; j < N; j++) p[j] += cumsum[j-1];
6276 
6277 }
6278 
6279 //______________________________________________________________________________
6280 void
6281 CWB::Toolbox::getSineFittingParams(double a, double b, double c, double rate,
6282  double& amplitude, double& omega, double& phase) {
6283 //
6284 // return the amplitude,phase,omega of the 3 numbers Sine fitting
6285 // a,b,c are 3 consecutive discrete values sampled at rate='rate'
6286 // return != 0 only if (b>a && b>c) or (b<a && b<c)
6287 //
6288 
6289  double dt = 1./rate;
6290 
6291  // The time of maximum is the time of b - cp.phase/cp.omega
6292 
6293  if(((a<b && b>=c && b>0)||(a>b && b<=c && b<0)) && (fabs((a+c)/(2*b))<1)){
6294 
6295  omega = acos((a+c)/(2*b))/dt;
6296  phase = atan2(a*a+c*a-2*b*b, 2*a*b*sin(omega*dt));
6297  amplitude = (a!=0)?(a/cos(phase)):(b/sin(omega*dt));
6298 
6299  return;
6300  } else {
6301  amplitude = 0;
6302  return;
6303  }
6304 }
6305 
6306 //______________________________________________________________________________
6307 TString
6309 //
6310 // Write x array to frame file
6311 //
6312 // Input: x - wavearray data
6313 // chName - channel name
6314 // frName - frame name
6315 // frLabel - label used for output file name
6316 // file name path = frDir/frLabel-gps-length.gwf
6317 // frDir - output directory
6318 //
6319 // return file name
6320 //
6321 
6322  // check input wavearray data
6323  if(x.size()==0 || x.rate()==0) {
6324  cout << "CWB::Toolbox::WriteFrameFile - Error : wavearray size=0 or rate=0 " << endl;
6325  exit(1);
6326  }
6327 
6328  double gps = x.start();
6329  double length = (x.size()/x.rate());
6330 
6331  // check gps integer
6332  if(fmod(gps,1)!=0) {
6333  cout << "CWB::Toolbox::WriteFrameFile - Error : start gps time is not integer" << endl;
6334  exit(1);
6335  }
6336  // check length integer
6337  if(fmod(length,1)!=0) {
6338  cout << "CWB::Toolbox::WriteFrameFile - Error : length is not integer" << endl;
6339  exit(1);
6340  }
6341 
6342  if(frDir=="") frDir=".";
6343 
6344  char frFile[1024];
6345  sprintf(frFile,"%s/%s-%lu-%lu.gwf",frDir.Data(),frLabel.Data(),(int)gps,(int)length);
6346  cout << frFile << endl;
6347  FrFile *ofp = FrFileONew(frFile,1); // gzip compression
6348 
6349  /*----------------------- Create a new frame ---------*/
6350 
6351  FrameH* simFrame = FrameNew(const_cast<char*>(frLabel.Data()));
6352  simFrame->frame = 0;
6353  simFrame->run = -1;
6354  simFrame->dt = length;
6355  simFrame->GTimeS = gps;
6356  simFrame->GTimeN = 0;
6357 
6358  cout << "Size (sec) " << x.size()/x.rate() << endl;
6359  FrProcData* proc = FrProcDataNew(simFrame,const_cast<char*>(chName.Data()),x.rate(),x.size(),-64);
6360  if(proc == NULL) {cout << "CWB::Toolbox::WriteFrameFile - Cannot create FrProcData" << endl; exit(-1);}
6361  proc->timeOffset = 0;
6362  proc->tRange = simFrame->dt;
6363  proc->type = 1; // Time Serie
6364 
6365  for (int i=0;i<(int)proc->data->nData;i++) proc->data->dataD[i] = x[i];
6366 
6367  int err=FrameWrite(simFrame,ofp);
6368  if (err) {cout << "CWB::Toolbox::WriteFrameFile - Error writing frame" << endl;exit(1);}
6369  FrameFree(simFrame);
6370 
6371  if (ofp!=NULL) FrFileOEnd(ofp);
6372 
6373  return frFile;
6374 }
6375 
TTree * tree
Definition: TimeSortTree.C:20
static void setUniqueEvents(TString ifwave, TString ofwave, int nIFO, int pp_irho)
Definition: Toolbox.cc:3315
size_t append(const wavearray< DataType_t > &)
Definition: wavearray.cc:775
double pc
Definition: DrawEBHH.C:15
double rho
double segMLS
Definition: test_config1.C:47
char cut[512]
int slagSize
Definition: test_config1.C:65
virtual size_t size() const
Definition: wavearray.hh:127
static void unWrapPhase(wavearray< float > &p)
Definition: Toolbox.cc:6224
char val[20]
double startMDC
Definition: Toolbox.hh:88
static void PrintProcInfo(TString str="")
Definition: Toolbox.cc:5851
Double_t PoissonIFunction(Double_t *x, Double_t *par)
Definition: Toolfun.hh:11
Float_t * rho
biased null statistics
Definition: netevent.hh:93
double start
Definition: network.hh:37
TString ofName
static waveSegment getMaxSeg(vector< waveSegment > list)
Definition: Toolbox.cc:1807
#define TIME_SCRATCH
static double g(double e)
Definition: GNGen.cc:98
static vector< TString > getFileListFromDir(TString dir_name, TString endString="", TString beginString="", TString containString="", bool fast=false)
Definition: Toolbox.cc:4333
static wavearray< double > getWignerVilleTransform(wavearray< double > x)
Definition: Toolbox.cc:6187
size_t * slagSite
Definition: test_config1.C:69
int slagOff
Definition: test_config1.C:68
int nfiles
par[0] value
mdcshift mdc_shift
Definition: test_config1.C:93
tuple f
Definition: cwb_online.py:91
printf("total live time: non-zero lags = %10.1f \n", liveTot)
double time1
TString live
char cmd[1024]
TB createDagFile(rslagList, full_condor_dir, data_label, jobFiles, cwb_stage_name)
fprintf(stdout,"start=%f duration=%f rate=%f\n", x.start(), x.size()/x.rate(), x.rate())
virtual void rate(double r)
Definition: wavearray.hh:123
static int setMultiplicity(TString ifName, TString idir, TString odir, int nIFO, double dTime)
Definition: Toolbox.cc:5123
double Live
CWB run(runID)
Int_t nentries
Definition: TimeSortTree.C:24
wavearray< double > a(hp.size())
wavearray< double > Trun(500000)
cout<< "slagList size : "<< slagList.size()<< endl;cout<< endl<< "Start segments selection from dq cat1 list ..."<< endl<< endl;rslagList=TB.getSlagList(slagList, ifos, segLen, segMLS, segEdge, nDQF, DQF, CWB_CAT1);cout<< "Number of selected jobs after cat1 : "<< rslagList.size()<< endl;cout<< endl<< "Start segments selection from dq cat2 list ..."<< endl<< endl;rslagList=TB.getSlagList(rslagList, ifos, segLen, segTHR, segEdge, nDQF, DQF, CWB_CAT2);cout<< "Number of selected jobs after cat2 : "<< rslagList.size()<< endl;vector< TString > jobFiles
static TString WriteFrameFile(wavearray< double > x, TString chName, TString frName, TString frLabel, TString frDir="")
Definition: Toolbox.cc:6308
#define XMAX
static int setIFAR(TString ifName, TString idir, TString odir, TString trname, TString sels, TString farFile, int irho, TString olabel, bool inclusive=true)
Definition: Toolbox.cc:2970
par[0] name
int n
Definition: cwb_net.C:10
vector< slag > slist
wavearray< double > z
Definition: Test10.C:32
dqfile VDQF[100]
bool invert
Definition: Toolbox.hh:70
cout<< "skymap size : "<< L<< endl;for(int l=0;l< L;l++) sm.set(l, l);sm > const_cast< char * >("skymap.dat")
TString("c")
int nset
Definition: cwb_mkeff.C:57
char ifo[32]
Definition: Toolbox.hh:66
bool TypeAllowed(char *Name)
Definition: History.cc:109
double stopMDC
Definition: Toolbox.hh:89
int count
Definition: compare_bkg.C:373
static void doPoissonPlot(int nIFO, wavearray< double > *Wlag, wavearray< double > Tlag, wavearray< double > Rlag, TString odir)
Definition: Toolbox.cc:4418
cout<< endl;cout<< "ts size = "<< ts.size()<< " ts rate = "<< ts.rate()<< endl;tf.Forward(ts, wdm);int levels=tf.getLevel();cout<< "tf size = "<< tf.size()<< endl;double dF=tf.resolution();double dT=1./(2 *dF);cout<< "rate(hz) : "<< RATE<< "\t layers : "<< nLAYERS<< "\t dF(hz) : "<< dF<< "\t dT(ms) : "<< dT *1000.<< endl;int itime=TIME_PIXEL_INDEX;int ifreq=FREQ_PIXEL_INDEX;int index=(levels+1)*itime+ifreq;double time=itime *dT;double freq=(ifreq >0)?ifreq *dF:dF/4;cout<< endl;cout<< "PIXEL TIME = "<< time<< " sec "<< endl;cout<< "PIXEL FREQ = "<< freq<< " Hz "<< endl;cout<< endl;wavearray< double > x
double frequency
double phase
bool c4
Definition: Toolbox.hh:71
Int_t GetEntry(Int_t)
Definition: netevent.cc:387
CWB_CAT dqcat
char odir[1024]
double amplitude
float xslag[6]
wavearray< double > psd(33)
TString mdc[4]
int slagMax
Definition: test_config1.C:67
dqfile * XDQF
vector< int > segId
Definition: Toolbox.hh:84
std::vector< waveSegment > olist
return wmap canvas
CWB_CAT
Definition: Toolbox.hh:54
static std::map< int, TString > getJobFileMapFromDir(TString dir_name, TString endString="", TString beginString="", TString containString="", bool fast=false)
Definition: Toolbox.cc:4394
Long_t flags
float xlag
CWB::History * history
TTree * fChain
root input file cointainig the analyzed TTree
Definition: netevent.hh:45
static wavearray< double > getHilbertIFrequency(wavearray< double > x)
Definition: Toolbox.cc:6151
cout<< "baudline_FFL : "<< baudline_FFL<< endl;ofstream out;out.open(baudline_FFL, ios::out);if(!out.good()){cout<< "Error Opening File : "<< baudline_FFL<< endl;exit(1);}ifstream in;in.open(frFiles[ifoID], ios::in);if(!in.good()){cout<< "Error Opening File : "<< frFiles[ifoID]<< endl;exit(1);}TString pfile_path="";char istring[1024];while(1){in > istring
Definition: cwb_frdisplay.C:94
Long_t size
NET segList
Definition: cwb_net.C:276
static double getLiveTime(vector< waveSegment > &jobList, vector< waveSegment > &dqList)
Definition: Toolbox.cc:2074
#define M
Definition: UniqSLagsList.C:3
int m
Definition: cwb_net.C:10
static double getTimeSegList(vector< waveSegment > list)
Definition: Toolbox.cc:592
virtual void start(double s)
Definition: wavearray.hh:119
char ofile[512]
vector< waveSegment > detSegs_dq2
Definition: cwb_net.C:279
double segEdge
Definition: test_config1.C:49
static TString CWB_CAT_NAME[14]
Definition: GToolbox.hh:4
int nVDQF
int j
Definition: cwb_net.C:10
wavearray< int > Wsel(ntrg)
i drho i
static vector< waveSegment > invertSegments(vector< waveSegment > &ilist)
Definition: Toolbox.cc:229
TList * list
static bool checkFile(TString fName, bool question=false, TString message="")
Definition: Toolbox.cc:3956
int isize
static vector< int > getMergeJobList(TString merge_dir, TString label, int version)
Definition: Toolbox.cc:1678
TB mergeTrees(fileList, TREE_NAME, OUTPUT_MERGE_DIR, OFILE_NAME, false)
#define MAX_TREE_SIZE
Definition: Toolbox.cc:19
wc clear()
int jobID
Definition: cwb_net.C:177
#define N
std::vector< waveSegment > mlist
int jobId
Definition: Toolbox.hh:82
double fWidth
Definition: DrawPSD.C:16
cout<< "ctime : "<< int(ctime)<< " sec "<< ctime/3600.<< " h "<< ctime/86400.<< " day"<< endl;std::vector< waveSegment > jlist
char ifo[NIFO_MAX][8]
double Tgap
Definition: test_config1.C:23
static char * getEnvCWB()
Definition: Toolbox.cc:4599
#define SRATE
static wavecomplex getRate(double rho, double Tgap, int nIFO, TChain &wav, wavearray< int > &Wsel, wavearray< double > *Wlag, wavearray< double > *Wslag, wavearray< double > Tlag)
Definition: Toolbox.cc:5409
TString symlink
nDQF
Definition: cwb_eced.C:92
int compareSegments(waveSegment a, waveSegment b)
Definition: Toolbox.cc:13
iseg push_back(seg)
static double getZeroLiveTime(int nIFO, TChain &liv, int dummy=0)
Definition: Toolbox.cc:4114
static vector< waveSegment > unionSegments(vector< waveSegment > &ilist)
Definition: Toolbox.cc:101
double segTHR
Definition: test_config1.C:48
void * MergeHandle(void *ptr)
Definition: Toolbox.cc:32
static void mergeTrees(vector< TString > fileList, TString treeName, TString odir, TString ofName, bool bhistory)
Definition: Toolbox.cc:2630
wavearray< double > w
Definition: Test1.C:27
static vector< float > getJobBenchmark(TString ifName, int stageID, TString bench)
Definition: Toolbox.cc:1425
virtual DataType_t max() const
Definition: wavearray.cc:1316
cout<< endl;sprintf(dq1ListFile,"%s/%s.dq1", dump_dir, data_label);vector< waveSegment > dq1List
Definition: cwb_dump_dq.C:13
nc append(pix)
#define nIFO
ofstream out
Definition: cwb_merge.C:196
CWB_CAT cat
Definition: Toolbox.hh:68
static int setCuts(TString ifName, TString idir, TString odir, TString trname, TString cuts, TString olabel)
Definition: Toolbox.cc:2856
char data_label[512]
Definition: test_config1.C:160
TString chName[NIFO_MAX]
int nXDQF
double factor
double time2
char str[1024]
char file[1024]
Definition: Toolbox.hh:67
double time[6]
Definition: cbc_plots.C:435
static char * readFile(TString ifName)
Definition: Toolbox.cc:2815
static vector< TString > mergeCWBTrees(TString dir_name, bool simulation, TString odir, TString label, bool brms=false, bool bvar=false, bool bpsm=false)
Definition: Toolbox.cc:2442
TString uname
static void getSimNoise(wavearray< double > &u, TString fName, int seed, int run)
Definition: Toolbox.cc:4809
wavearray< double > Rlag
static TString GetMDCLog(TString log, int pos)
Definition: Toolbox.cc:2258
static int createSubFile(TString label, TString condor_dir, TString out_dir, TString err_dir, TString log_dir, TString ext="", TString condor_tag="")
Definition: Toolbox.cc:1317
waveSegment SEG
TGraph * gr
int jobmax
wavearray< double > h
Definition: Regression_H1.C:25
vector< int > jobList
static void convertSampleRate(wavearray< double > iw, wavearray< double > ow)
Definition: Toolbox.cc:5045
static bool isLeafInTree(TTree *itree, TString leaf)
Definition: Toolbox.cc:4682
static void resampleToPowerOfTwo(wavearray< double > &w)
Definition: Toolbox.cc:5818
vector< slag > slagList
float islag
char * GetLog(char *Stage, int index)
Definition: History.cc:286
i() int(T_cor *100))
int GetLogSize(char *Stage)
Definition: History.cc:280
static vector< TString > readFileList(TString ifName)
Definition: Toolbox.cc:2719
static void dumpFileList(vector< TString > fileList, TString ofName)
Definition: Toolbox.cc:2749
TString label
Definition: MergeTrees.C:21
double Pi
const int NIFO_MAX
Definition: wat.hh:4
bool log
Definition: WaveMDC.C:41
dqfile DQF[12]
Definition: test_config1.C:171
TTree * otree
static int dumpSegList(vector< waveSegment > list, TString fName, bool c4=false)
Definition: Toolbox.cc:552
TString frDir[NIFO_MAX]
TB dumpSegList(dq1List, dq1ListFile, false)
wavearray< double > Tlag
int getLayer(wavearray< DataType_t > &w, double n)
param: n - layer number
Definition: wseries.cc:175
static vector< waveSegment > getSlagJobList(vector< waveSegment > ilist, int seglen=600)
Definition: Toolbox.cc:1771
static int setChunk(TString ifName, TString idir, TString odir, TString trname, int chunk)
Definition: Toolbox.cc:3194
TIter next(twave->GetListOfBranches())
Float_t * lag
time between consecutive events
Definition: netevent.hh:65
char fname[1024]
segLen
Definition: cwb_eced.C:7
double shift
Definition: Toolbox.hh:69
static int GetMDCLogSize(TString log)
Definition: Toolbox.cc:2243
char merge_dir[512]
Definition: test_config1.C:147
TList * GetStageNames()
Definition: History.cc:409
static bool rmDir(TString dir, bool question=true)
Definition: Toolbox.cc:4051
double liveTot
double xlive
int k
wavearray< double > Tdlag
char data_dir[512]
Definition: test_config1.C:152
char schunk[32]
Definition: cwb_setchunk.C:56
double offset
Definition: Toolbox.hh:90
UserGroup_t * uinfo
Definition: cwb_frdisplay.C:73
bool StageAlreadyPresent(char *Name)
Definition: History.cc:89
vector< TString > getFileListFromDir(TString dir_name, TString endString="", TString beginString="")
Definition: cwb_csh2sh.C:148
float chi2
Definition: cbc_plots.C:603
vector< waveSegment > cat1List
TObjArray * token
char log_dir[512]
Definition: test_config1.C:151
static vector< TString > sortStrings(vector< TString > ilist)
Definition: Toolbox.cc:5894
double * entry
Definition: cwb_setcuts.C:206
static void getUniqueFileList(TString ifile, TString ofile)
Definition: Toolbox.cc:6044
TFile * ifile
static int createDagFile(vector< waveSegment > jobList, TString condor_dir, TString label, int jobmin=0, int jobmax=0)
Definition: Toolbox.cc:1152
static int getJobId(TString file, TString fext="root")
Definition: Toolbox.cc:5913
bool slagFound
static vector< waveSegment > getJobList(vector< waveSegment > ilist, double segLen=600., double segMLS=300., double segEdge=8.)
Definition: Toolbox.cc:627
static bool question(TString question)
Definition: Toolbox.cc:4092
wavearray< double > yy
Definition: TestFrame5.C:12
WSeries< double > ww
Definition: Regression_H1.C:33
waveSegment seg
TFile * froot
TString GetString(TTree *tree, int run, int lag, TString psfix)
Definition: Toolfun.hh:261
bool SetHistoryModify(bool Replace=true)
Definition: History.cc:435
static vector< waveSegment > sortSegments(vector< waveSegment > &ilist)
Definition: Toolbox.cc:167
static double getMDCShift(mdcshift mshift, double time)
Definition: Toolbox.cc:2276
static wavearray< double > getHilbertTransform(wavearray< double > x)
Definition: Toolbox.cc:6111
double factors[100]
Definition: test_config1.C:84
double dt
virtual void FFTW(int=1)
Definition: wavearray.cc:878
#define OTIME_LENGHT
FILE * fP
static slag getSlag(vector< slag > slagList, int jobid)
Definition: Toolbox.cc:1824
regression r
Definition: Regression_H1.C:44
static int shiftBurstMDCLog(std::vector< std::string > &mdcList, vector< TString > ifos, double mdc_shift)
Definition: Toolbox.cc:2154
vector< waveSegment > detSegs
Definition: cwb_net.C:175
static void dumpJobList(vector< waveSegment > ilist, TString fName, double segLen=600., double segMLS=300., double segEdge=8.)
Definition: Toolbox.cc:606
s s
Definition: cwb_net.C:137
static void setSlagShifts(slag SLAG, vector< TString > ifos, double segLen, int nDQF, dqfile *DQF)
Definition: Toolbox.cc:1997
float irho
int index
Definition: network.hh:36
char options[256]
TString frName[NIFO_MAX]
double liveZero
int nifo
static vector< slag > getSlagList(size_t nIFO, size_t slagSize, int slagSegs, int slagOff, size_t slagMin, size_t slagMax, size_t *slagSite, char *slagFile=NULL)
Definition: Toolbox.cc:790
static void dumpSlagList(vector< slag > slagList, TString slagFile, bool slagOnly=false)
Definition: Toolbox.cc:1067
static vector< waveSegment > readSegList(dqfile DQF)
Definition: Toolbox.cc:391
dqfile dqf[nDQF]
static wavearray< double > GetDetectorPSD(TString fName, double fWidth=8192., double dFreq=1.)
Definition: Toolbox.cc:4986
static int setVeto(TString ifName, TString idir, TString odir, vector< TString > ifos, int nVDQF, dqfile *VDQF, int nDQF, dqfile *DQF, double segLen, double segMLS, double segEdge)
Definition: Toolbox.cc:3494
vector< waveSegment > iseg
double gps
Double_t * time
beam pattern coefficients for hx
Definition: netevent.hh:75
char answer[256]
TLine * line
Definition: compare_bkg.C:482
static vector< int > getCondorJobList(TString condor_dir, TString label)
Definition: Toolbox.cc:1378
static TString getParameter(TString options, TString param="")
Definition: Toolbox.cc:5943
condor_log_dir ReplaceAll("X_HOME", uhome.Data())
ifstream in
bool inclusive
Definition: cwb_setifar.C:139
cout<< "Starting reading output directory ..."<< endl;vector< TString > fileList
static int GetStepFunction(TString fName, vector< double > &x, vector< double > &y, vector< double > &ex=DEFAULT_DOUBLE_VECTOR, vector< double > &ey=DEFAULT_DOUBLE_VECTOR)
Definition: Toolbox.cc:5645
wavearray< int > index
Definition: Meyer.hh:18
int jobmin
virtual void stop(double s)
Definition: wavearray.hh:121
vector< int > slagId
Definition: Toolbox.hh:83
#define MAX_THREADS
Definition: Toolbox.cc:17
double fabs(const Complex &x)
Definition: numpy.cc:37
TString dir_name[NDIR]
Definition: cwb_mkdir.C:52
string file
Definition: cwb_online.py:385
TString sel("slag[1]:rho[1]")
static TString DAG2LSF(char *dagFile, char *data_label, char *nodedir, char *data_dir, char *condor_dir, char *log_dir, char *output_dir, char *work_dir)
Definition: Toolbox.cc:1541
static TString SetMDCLog(TString log, int pos, TString val)
Definition: Toolbox.cc:2218
static void mkDir(TString dir, bool question=false, bool remove=true)
Definition: Toolbox.cc:4000
TBranch * branch
void resample(const wavearray< DataType_t > &, double, int=6)
Definition: wavearray.cc:485
int slagID
Definition: cwb_net.C:177
vector< TString > fList
Definition: LoopChirpMass.C:30
static vector< waveSegment > getSegList(int jobId, int nIFO, double segLen, double segMLS, double segEdge, vector< waveSegment > dqList)
Definition: Toolbox.cc:2779
int estat
void AddLog(char *Stage, char *Log, TDatime *Time=NULL)
Definition: History.cc:169
void Forward(int n=-1)
param: wavelet - n is number of steps (-1 means full decomposition)
Definition: wseries.cc:228
strcpy(RunLabel, RUN_LABEL)
int cnt
Definition: Toolbox.hh:81
cout<< "total cat1 livetime : "<< int(cat1_time)<< " sec "<< cat1_time/3600.<< " h "<< cat1_time/86400.<< " day"<< endl;cout<< endl;vector< waveSegment > cat2List
Definition: cwb_dump_job.C:22
char ilstfname[1024]
double df
double omega
Definition: testWDM_4.C:12
static vector< waveSegment > readSegments(TString ifile)
Definition: Toolbox.cc:57
static void makeSpectrum(wavearray< double > &psd, wavearray< double > x, double chuncklen=8, double scratchlen=0, bool oneside=true)
Definition: Toolbox.cc:4705
sprintf(tfres,"(1/%g)x(%g) (sec)x(Hz)", 2 *df, df)
nfactor[0]
Definition: cwb_eced.C:10
Long_t mt
TTree * itree
static TString getFileName(FILE *fp)
Definition: Toolbox.cc:5996
bool overwrite
Definition: cwb_dump_inj.C:82
static void getSineFittingParams(double a, double b, double c, double rate, double &amplitude, double &omega, double &phase)
Definition: Toolbox.cc:6281
static vector< waveSegment > mergeSegLists(vector< waveSegment > &ilist1, vector< waveSegment > &ilist2)
Definition: Toolbox.cc:332
char * AddType(char *TypeName)
Definition: History.cc:487
TString cwb_uparameters_file
wavearray< double > Wlag[NIFO_MAX+1]
slagFile
Definition: cwb_tune_slag.C:7
DataType_t * data
Definition: wavearray.hh:301
static TString getTemporaryFileName(TString label="temporary", TString extension="tmp")
Definition: Toolbox.cc:5869
int jobId
char nodedir[1024]
Definition: test_config1.C:187
Long_t id
double detSegs_ctime
Definition: cwb_net.C:285
char condor_dir[512]
Definition: test_config1.C:148
double dFreq
Definition: DrawPSD.C:17
char work_dir[512]
Definition: test_config1.C:143
int cat
int segID[20]
Definition: cwb_net.C:177
static wavearray< double > getHilbertEnvelope(wavearray< double > x)
Definition: Toolbox.cc:6131
char formula[256]
static bool isFileExisting(TString fName)
Definition: Toolbox.cc:3937
int slagMin
Definition: test_config1.C:66
int rnID
bool save
double ctime
char * GetHistory(char *StageName, char *Type)
Definition: History.cc:255
string version
Definition: cWB_conf.py:136
const CWB::HistoryStage * GetStage(char *Name)
Definition: History.cc:676
simulation
Definition: cwb_eced.C:9
fclose(ftrig)
#define LOW_CUT_FREQ
double shift[NIFO_MAX]
char fName[256]
for(int i=0;i< 101;++i) Cos2[2][i]=0
virtual void resize(unsigned int)
Definition: wavearray.cc:445
int check
char output_dir[512]
Definition: test_config1.C:146
double length
Definition: TestBandPass.C:18
void Inverse(int n=-1)
param: n - number of steps (-1 means full reconstruction)
Definition: wseries.cc:273
wavearray< double > y
Definition: Test10.C:31
double stop
Definition: network.hh:38
void putLayer(wavearray< DataType_t > &, double n)
param: n - layer number
Definition: wseries.cc:201
CWB::History * ihistory
TString frLabel[NIFO_MAX]
float ilag
i drho pp_irho
static void blackmanharris(double *window, int n)
Definition: Toolbox.cc:305
int nsel
Definition: cwb_setcuts.C:219
void AddHistory(char *Stage, char *Type, char *History, TDatime *Time=NULL)
Definition: History.cc:207
TB checkFile(gSystem->Getenv("CWB_ROOTLOGON_FILE"))
CWB_STAGE
Definition: cwb.hh:102
char * AddStage(char *StageName)
Definition: History.cc:446
TString ifos[60]
#define FREQ_RES
exit(0)
#define CCAST(PAR)
Definition: Toolbox.cc:8
wavearray< double > Wslag[NIFO_MAX+1]
TString treeName
Definition: MergeTrees.C:15