source: BAORadio/AmasNancay/analyse.cc@ 523

Last change on this file since 523 was 523, checked in by campagne, 14 years ago

add dump; sort input file list; correct input opts treatment bug (jec)

File size: 48.4 KB
RevLine 
[507]1//
2// Analyse of Amas@Nancay runs by J.E Campagne (LAL)
3// Version 0: 1/6/2011
4//-----------------------------
5
6// Utilisation de SOPHYA pour faciliter les tests ...
7#include "sopnamsp.h"
8#include "machdefs.h"
9
10#include <stdlib.h>
11#include <dirent.h>
12
13
14// include standard c/c++
15#include <iostream>
16#include <fstream>
17#include <string>
18#include <vector>
19#include <map>
20#include <functional>
21#include <algorithm>
22#include <numeric>
23#include <list>
24#include <exception>
25
26// include sophya mesure ressource CPU/memoire ...
27#include "resusage.h"
28#include "ctimer.h"
29#include "timing.h"
30#include "timestamp.h"
31#include "strutilxx.h"
32#include "ntuple.h"
33#include "fioarr.h"
34#include "tarrinit.h"
35#include "histinit.h"
36#include "fitsioserver.h"
37#include "fiosinit.h"
38#include "ppersist.h"
39
40
41const sa_size_t NUMBER_OF_CHANNELS = 2;
42const sa_size_t NUMBER_OF_FREQ = 8192;
43const r_4 LOWER_FREQUENCY = 1250.0; //MHz
44const r_4 TOTAL_BANDWIDTH = 250.0; //MHz
45
46//decalration of non class members functions
47extern "C" {
48 int Usage(bool);
49}
50
51
52//----------------------------------------------------------
53//Utility fonctions
54// Function for deleting pointers in map.
55template<class A, class B>
56struct DeleteMapFntor
57{
58 // Overloaded () operator.
59 // This will be called by for_each() function.
60 bool operator()(pair<A,B> x) const
61 {
62 // Assuming the second item of map is to be
63 // deleted. Change as you wish.
64 delete x.second;
65 return true;
66 }
67};
68//-----
69bool compare(const pair<string,r_4>& i, const pair<string,r_4>& j) {
70 return i.second < j.second;
71}
72//-----
73sa_size_t round_sa(r_4 r) {
74 return static_cast<sa_size_t>((r > 0.0) ? (r + 0.5) : (r - 0.5));
75}
76//-----
77string StringToLower(string strToConvert){
78 //change each element of the string to lower case
79 for(unsigned int i=0;i<strToConvert.length();i++) {
80 strToConvert[i] = tolower(strToConvert[i]);
81 }
82 return strToConvert;//return the converted string
83}
84//-----
[523]85//JEC 22/9/11 comparison, not case sensitive to sort File liste START
86bool stringCompare( const string &left, const string &right ){
87 if( left.size() < right.size() )
88 return true;
89 return false;
90 for( string::const_iterator lit = left.begin(), rit = right.begin(); lit != left.end() && rit != right.end(); ++lit, ++rit )
91 if( tolower( *lit ) < tolower( *rit ) )
92 return true;
93 else if( tolower( *lit ) > tolower( *rit ) )
94 return false;
95}//JEC 22/9/11 comparison, not case sensitive to sort File liste END
96//-----
[507]97list<string> ListOfFileInDir(string dir, string filePettern) throw(string) {
98 list<string> theList;
99
100
101 DIR *dip;
102 struct dirent *dit;
[523]103 string msg; string fileName;
[507]104 string fullFileName;
105 size_t found;
106
107 if ((dip=opendir(dir.c_str())) == NULL ) {
108 msg = "opendir failed on directory "+dir;
109 throw msg;
110 }
111 while ( (dit = readdir(dip)) != NULL ) {
112 fileName = dit->d_name;
113 found=fileName.find(filePettern);
114 if (found != string::npos) {
115 fullFileName = dir + "/";
116 fullFileName += fileName;
117 theList.push_back(fullFileName);
118 }
119 }//eo while
120 if (closedir(dip) == -1) {
121 msg = "closedir failed on directory "+dir;
122 throw msg;
123 }
[523]124
125 //JEC 22/9/11 START
126 theList.sort(stringCompare);
127 //JEC 22/9/11 END
128
[507]129 return theList;
130}
131
132
133//Declaration of local classes
134//----------------------------------------------
135//Process Interface
136class IProcess {
137public:
138 IProcess() {}
139 virtual ~IProcess() {}
140 virtual int processCmd() throw(string) =0;
141};
142//------------
143//Common Process
144class ProcessBase : public IProcess {
145public:
146 ProcessBase();
147 virtual ~ProcessBase();
148 void SetInputPath(const string& inputPath) {inputPath_ = inputPath;}
149 void SetOutputPath(const string& outputPath) {outputPath_ = outputPath;}
150 void SetSourceName(const string& sourceName) {sourceName_ = sourceName;}
151 void SetDateOfRun(const string& dateOfRun) {dateOfRun_ = dateOfRun;}
152 void SetSpectraDirectory(const string& spectraDirectory) {spectraDirectory_ = spectraDirectory;}
153 void SetTypeOfFile(const string& typeOfFile) { typeOfFile_ = typeOfFile; }
154 void SetNumCycle(const string& numcycle) {numcycle_ = numcycle; }
155 void SetScaFileName(const string& scaFileName) { scaFileName_ =scaFileName; }
156
157 void SetDebugLevel(const string& debuglev) {
158 debuglev_ = atoi(debuglev.c_str());
159 }
160
161 virtual int processCmd() throw(string);
162
163protected:
164 string inputPath_;
165 string outputPath_;
166 string sourceName_;
167 string dateOfRun_;
168 string spectraDirectory_;
169 string typeOfFile_;
170
171 string numcycle_; //cycle numbers format="first,last"
172 sa_size_t ifirstCycle_;
173 sa_size_t ilastCycle_;
174
175
176 uint_4 debuglev_;
177 string scaFileName_;
178 NTuple* scaTuple_;
179 map<sa_size_t,sa_size_t> idCycleInTuple_;
180};
181ProcessBase::ProcessBase() {
182 scaTuple_ = 0;
183}
184ProcessBase::~ProcessBase() {
185 if (scaTuple_) delete scaTuple_;
186 scaTuple_ = 0;
187}
188//------------
189//Process ON/OFF data
190//------------
191class ProcessONOFFData : public ProcessBase {
192protected:
193 string freqBAOCalibration_;//string MHz
194public:
195 ProcessONOFFData(){}
196 virtual ~ProcessONOFFData(){}
197
198 void SetFreqBAOCalibration(const string& freqBAOCalibration) {
199 freqBAOCalibration_ = freqBAOCalibration;
200 }
201
202 virtual int processCmd() throw(string);
203};
204//------------
205//Process Gain
206//------------
207class ProcessGain : public ProcessBase {
208protected:
209 string mode_; //mode of data taken for gain computation On || Off
210public:
211 ProcessGain(){}
212 virtual ~ProcessGain(){}
213
214 void SetMode(const string& mode) {mode_ = mode;}
215
216 virtual int processCmd() throw(string);
217};
218//------------
219//Process Calibration
220//------------
221class ProcessCalibration : public ProcessBase {
222protected:
223 string option_; //option of calibration procedure
224 string freqBAOCalibration_;//string MHz
225 r_4 valfreqBAOCalibration_; //value MHz
226 string bandWidthBAOCalibration_;//string MHz
227 r_4 valbandWidthBAOCalibration_;//value MHz
228
229 sa_size_t lowerFreqBin_;
230 sa_size_t upperFreqBin_;
231
232public:
233 ProcessCalibration() {}
234 virtual ~ProcessCalibration(){}
235
236 void SetOption(const string& option) {option_ = option;}
237 void SetFreqBAOCalibration(const string& freqBAOCalibration) {
238 freqBAOCalibration_ = freqBAOCalibration;
239 valfreqBAOCalibration_ = atof(freqBAOCalibration_.c_str());
240 }
241 void SetBandWidthBAOCalibration(const string& bandWidthBAOCalibration) {
242 bandWidthBAOCalibration_ = bandWidthBAOCalibration;
243 valbandWidthBAOCalibration_ = atof(bandWidthBAOCalibration_.c_str());
244 }
245
246 void ComputeLowerUpperFreqBin();
247
248 virtual int processCmd() throw(string);
249};
250void ProcessCalibration::ComputeLowerUpperFreqBin() {
251 sa_size_t c0 = round_sa(NUMBER_OF_FREQ*(valfreqBAOCalibration_-LOWER_FREQUENCY)/TOTAL_BANDWIDTH);
252 sa_size_t dc = round_sa(NUMBER_OF_FREQ*valbandWidthBAOCalibration_/TOTAL_BANDWIDTH);
253 lowerFreqBin_ = c0-dc/2;
254 upperFreqBin_ = c0+dc/2;
255}
256
257
258//----------------------------------------------------
259//----------------------------------------------------
260int main(int narg, char* arg[])
261{
262
263 //Init process types
264 map<string,IProcess*> process;
265 process["dataOnOff"] = new ProcessONOFFData();
266 process["gain"] = new ProcessGain();
267 process["calib"] = new ProcessCalibration();
268
269 //Init Sophya related modules
270 // SophyaInit();
271 TArrayInitiator _inia; //nneded for TArray persistancy
272 FitsIOServerInit(); //needed for input file
273
274 //message used in Exceptions
275 string msg;
276
277 //Return code
278 int rc = 0;
279
280 //Arguments managements
281 if ((narg>1)&&(strcmp(arg[1],"-h")==0)) return Usage(false);
282 if (narg<11) return Usage(true);
283
284 string action;
285 string inputPath = ".";
286 string outputPath = ".";
287 string sourceName;
288 string scaFile;
289 string dateOfRun;
290 string spectraDirectory;
291 string freqBAOCalib = "";
292 string bandWidthBAOCalib = "";
293 string debuglev = "0";
294 string mode = "";
295 string numcycle;
296 string calibrationOpt = "";
297
298 string typeOfFile="medfiltmtx";
299
300
301 // bool okarg=false;
302 int ka=1;
303 while (ka<(narg-1)) {
304 if (strcmp(arg[ka],"-debug")==0) {
305 debuglev=arg[ka+1];
306 ka+=2;
307 }
[523]308 else if (strcmp(arg[ka],"-act")==0) {
[507]309 action=arg[ka+1];
310 ka+=2;
311 }
[523]312 else if (strcmp(arg[ka],"-inPath")==0) {
[507]313 inputPath=arg[ka+1];
314 ka+=2;
315 }
[523]316 else if (strcmp(arg[ka],"-outPath")==0) {
[507]317 outputPath=arg[ka+1];
318 ka+=2;
319 }
320 else if (strcmp(arg[ka],"-source")==0) {
321 sourceName=arg[ka+1];
322 ka+=2;
323 }
324 else if (strcmp(arg[ka],"-sca")==0) {
325 scaFile=arg[ka+1];
326 ka+=2;
327 }
328 else if (strcmp(arg[ka],"-date")==0) {
329 dateOfRun=arg[ka+1];
330 ka+=2;
331 }
332 else if (strcmp(arg[ka],"-specdir")==0) {
333 spectraDirectory=arg[ka+1];
334 ka+=2;
335 }
336 else if (strcmp(arg[ka],"-specname")==0) {
337 typeOfFile=arg[ka+1];
338 ka+=2;
339 }
340 else if (strcmp(arg[ka],"-freqBAOCalib")==0) {
341 freqBAOCalib = arg[ka+1];
342 ka+=2;
343 }
344 else if (strcmp(arg[ka],"-bwBAOCalib")==0) {
345 bandWidthBAOCalib = arg[ka+1];
346 ka+=2;
347 }
348 else if (strcmp(arg[ka],"-mode")==0) {
349 mode =arg[ka+1];
350 ka+=2;
351 }
352 else if (strcmp(arg[ka],"-numcycle")==0) {
353 numcycle =arg[ka+1];
354 ka+=2;
355 }
356 else if (strcmp(arg[ka],"-calibopt")==0) {
357 calibrationOpt =arg[ka+1];
358 ka+=2;
359 }
360 else ka++;
361 }//eo while
362
363
[523]364 //JEC 21/9/11 Give the input parameters START
365 cout << " action " << action << "\n"
366 << " inputPath = " << inputPath << "\n"
367 << " outputPath = " << outputPath << "\n"
368 << " sourceName = " << sourceName << "\n"
369 << " scaFile = " << scaFile << "\n"
370 << " dateOfRun = " << dateOfRun << "\n"
371 << " spectraDirectory = " << spectraDirectory << "\n"
372 << " freqBAOCalib = " << freqBAOCalib << "\n"
373 << " bandWidthBAOCalib = " << bandWidthBAOCalib << "\n"
374 << " debuglev = " << debuglev << "\n"
375 << " mode = " << mode << "\n"
376 << " numcycle = " << numcycle << "\n"
377 << " calibrationOpt = " << calibrationOpt << endl;
378 //JEC 21/9/11 Give the input parameters END
[507]379
[523]380
[507]381 try {
382 //verification of action
383 if(process.find(action) == process.end()) {
384 msg = "action ";
385 msg += action + " not valid... FATAL";
386 rc = 999;
387 throw msg;
388 }
389
390
[523]391
392
393
[507]394 //
395 //Process initialisation...
396 //
397 try {
398 ProcessBase* procbase = dynamic_cast<ProcessBase*>(process[action]);
399 if (procbase == 0) {
400 msg= "action ";
401 msg += action + "Not a <process base> type...FATAL";
402 rc = 999;
403 throw msg;
404 }
405 procbase->SetInputPath(inputPath);
406 procbase->SetOutputPath(outputPath);
407
408 if ("" == sourceName) {
409 msg = "(FATAL) missingsourceName for action " + action;
410 Usage(true);
411 throw msg;
412 }
413 procbase->SetSourceName(sourceName);
414
415 if ("" == dateOfRun) {
416 msg = "(FATAL) missing dateOfRun for action " + action;
417 Usage(true);
418 throw msg;
419 }
420 procbase->SetDateOfRun(dateOfRun);
421
422
423 if ("" == spectraDirectory) {
424 msg = "(FATAL) missing spectraDirectory for action " + action;
425 Usage(true);
426 throw msg;
427 }
428 procbase->SetSpectraDirectory(spectraDirectory);
429
430 if ("" == scaFile) {
431 msg = "(FATAL) missing scaFile for action " + action;
432 Usage(true);
433 throw msg;
434 }
435 procbase->SetScaFileName(scaFile);
436
437 if ("" == numcycle) {
438 msg = "(FATAL) missing cycle number for action " + action;
439 Usage(true);
440 throw msg;
441 }
442 procbase->SetNumCycle(numcycle);
443
444
445 procbase->SetTypeOfFile(typeOfFile);
446
447 procbase->SetDebugLevel(debuglev);
448 }
449 catch(exception& e){
450 throw e.what();
451 }
452
453 try {
454 ProcessONOFFData* procdata = dynamic_cast<ProcessONOFFData*>(process[action]);
455 if (procdata) {
456 if (freqBAOCalib == "") {
457 msg = "(FATAL) missing calibration BAO frequency for action " + action;
458 Usage(true);
459 throw msg;
460 }
461 procdata->SetFreqBAOCalibration(freqBAOCalib);
462 }
463 }
464 catch(exception& e){
465 throw e.what();
466 }
467
468
469 try {
470 ProcessGain* procgain = dynamic_cast<ProcessGain*>(process[action]);
471 if(procgain) {
472 if (mode == "") {
473 msg = "(FATAL) missing mode-type for action " + action;
474 Usage(true);
475 throw msg;
476 }
477 procgain->SetMode(mode);
478 }
479 }
480 catch(exception& e){
481 throw e.what();
482 }
483
484 try {
485 ProcessCalibration* proccalib = dynamic_cast<ProcessCalibration*>(process[action]);
486 if(proccalib) {
487 if (calibrationOpt == "") {
488 msg = "(FATAL) missing calibration option";
489 Usage(true);
490 throw msg;
491 }
492 if (freqBAOCalib == "") {
493 msg = "(FATAL) missing calibration BAO frequency for action " + action;
494 Usage(true);
495 throw msg;
496 }
497 if (bandWidthBAOCalib == "") {
498 msg = "(FATAL) missing calibration BAO frequency band width for action " + action;
499 Usage(true);
500 throw msg;
501 }
502 proccalib->SetOption(calibrationOpt);
503 proccalib->SetFreqBAOCalibration(freqBAOCalib);
504 proccalib->SetBandWidthBAOCalibration(bandWidthBAOCalib);
505 proccalib->ComputeLowerUpperFreqBin();
506 }
507 }
508 catch(exception& e){
509 throw e.what();
510 }
511
512 //
513 //execute command
514 //
515 rc = process[action]->processCmd();
516
517 }
518 catch (std::exception& sex) {
519 cerr << "\n analyse.cc std::exception :" << (string)typeid(sex).name()
520 << "\n msg= " << sex.what() << endl;
521 rc = 78;
522 }
523 catch ( string str ) {
524 cerr << "analyse.cc Exception raised: " << str << endl;
525 }
526 catch (...) {
527 cerr << " analyse.cc catched unknown (...) exception " << endl;
528 rc = 79;
529 }
530
531
532
533
534 cout << ">>>> analyse.cc ------- END ----------- RC=" << rc << endl;
535
536 //Delete processes
537 for_each(process.begin(),process.end(), DeleteMapFntor<string,IProcess*>());
538
539 return rc;
540}
541
542//---------------------------------------------------
543int Usage(bool flag) {
544 cout << "Analyse.cc usage...." << endl;
[514]545 cout << "analyse -act <action_type>: dataOnOff, gain, calib\n"
[507]546 << " -inPath <path for input files: default='.'>\n"
547 << " -outPath <path for output files: default='.'>\n"
548 << " -source <source name> \n"
549 << " -date <YYYYMMDD>\n"
550 << " -sca <file name scaXYZ.sum.trans>\n"
551 << " -specdir <generic directory name of spectra fits files>\n"
552 << " -specname <generic name of spectra fits files>\n"
553 << " -freqBAOCalib <freq in MHZ> freq. of calibration BAO\n"
[514]554 << " valid for act=dataOnOff\n"
[507]555 << " -bwBAOCalib <band width MHz> band width arround central freq. for calibration BAO\n"
556 << " valid for act=calib\n"
557 << " -mode <mode_type>:\n"
558 << " valid for act=gain, mode_type: On, Off\n"
559 << " -numcycle <number>,<number>:\n"
560 << " valid for all actions"
561 << " -calibopt <option>:\n"
562 << " valid for act=calib: indiv OR mean (NOT USED)"
563 << " -debuglev <number> [0=default]\n"
564 << " 1: normal print\n"
565 << " 2: save intermediate spectra\n"
566 << endl;
567 if (flag) {
568 cout << "use <path>/analyse -h for detailed instructions" << endl;
569 return 5;
570 }
571 return 1;
572}
573
574int ProcessBase::processCmd() throw(string) {
575 int rc =0;
576 string msg;
577 if(debuglev_>0)cout << "Process Base" << endl;
578 //------------------------
579 //Use the sca file informations
580 //------------------------
581 // string scaFullPathName = "./";
582 //TOBE FIXED scaFullPathName += sourceName_+"/"+dateOfRun_ + StringToLower(sourceName_)+"/";
583 string scaFullPathName = inputPath_ + "/"
584 + sourceName_+ "/" +dateOfRun_ + StringToLower(sourceName_)+ "/" + scaFileName_;
585 char* scaTupleColumnName[9] = {"cycle","stcalOn","spcalOn","stOn","spOn","stcalOff","spcalOff","stOff","spOff"};
586 scaTuple_ = new NTuple(9,scaTupleColumnName);
587 int n = scaTuple_->FillFromASCIIFile(scaFullPathName);
588 if(n<0){ //Error
589 msg = "(FATAL) NTuple error loading "+ scaFullPathName;
590 rc = 999;
591 throw msg;
592 }
593
594 if(debuglev_>1){
595 cout << "ProcessBase::processCmd: dump tuple in " << scaFullPathName << endl;
596 scaTuple_->Show(cout);
597 }
598
599
600 //Get the cycles (here consider consecutive cycles)
601 //The SCA file cannot be used as the DAQ can miss some cycles...
602 // r_8 firstCycle, lastCycle;
603 // scaTuple_->GetMinMax("cycle",firstCycle,lastCycle);
604 // ifirstCycle_ = (sa_size_t)firstCycle;
605 // ilastCycle_ = (sa_size_t)lastCycle;
606 //Analyse the string given by -numcycle command line
607 int ai1=0,ai2=0;
608 sscanf(numcycle_.c_str(),"%d,%d",&ai1,&ai2);
609 ifirstCycle_ = (sa_size_t)ai1;
610 ilastCycle_ = (sa_size_t)ai2;
611
612
613 //associate cycle number to index line in tuple
614 sa_size_t nLines = scaTuple_->NbLines();
615 for(sa_size_t iL=0; iL<nLines; ++iL){
616 idCycleInTuple_[(sa_size_t)scaTuple_->GetCell(iL,"cycle")]=iL;
617 }
618
619
620 return rc;
621}
622//----------------------------------------------
623int ProcessONOFFData::processCmd() throw(string) {
624 int rc = 0;
625 try {
626 rc = ProcessBase::processCmd();
627 }
628 catch (string s) {
629 throw s;
630 }
631 if(debuglev_>0)cout << "Process Data" << endl;
632 vector<string> modeList;
633 modeList.push_back("On");
634 modeList.push_back("Off");
635 vector<string>::const_iterator iMode;
636
637 uint_4 id;
638 string tag;
639
640 //
641 //Process to get sucessively
642 //Raw Spectra,
643 //BAO Calibrated Spectra
644 //and RT Calibrated Spectra
645 //The pocesses are separated to allow intermediate save of results
646
647 map< pair<string, sa_size_t>, TMatrix<r_4> > spectreCollect;
648 map< pair<string, sa_size_t>, TMatrix<r_4> >::iterator iSpectre, iSpectreEnd;
649
650 for (iMode = modeList.begin(); iMode != modeList.end(); ++iMode) {
651 string mode = *iMode;
652 if(debuglev_>0)cout << "Process RAW Mode " << mode << endl;
653
654 //------------------------------------------
655 //Produce Raw spectra per cycle
656 //------------------------------------------
657
658 string directoryName;
659 list<string> listOfSpecFiles;
660 list<string>::const_iterator iFile, iFileEnd;
661
662
663 //
664 //loop on cycles
665 //
666 for (sa_size_t icycle = ifirstCycle_; icycle <= ilastCycle_; icycle++) {
667 //TOBE FIXED directoryName = "./" + sourceName_ + "/"+ dateOfRun_ + StringToLower(sourceName_) + "/" +mode + "/";
668 directoryName = "./" + mode + "/";
669 stringstream sicycle;
670 sicycle << icycle;
671 directoryName += spectraDirectory_ + sicycle.str() + "/";
672
673 //read directory
674 listOfSpecFiles = ListOfFileInDir(directoryName,typeOfFile_);
675
676
677 //compute mean of spectra created in a cycle
678 if(debuglev_>0)cout << "compute mean for cycle " << icycle << endl;
679 TMatrix<r_4> spectreMean(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ); //implicit init to 0
680 iFileEnd = listOfSpecFiles.end();
681 r_4 nSpectres = 0;
682 for (iFile = listOfSpecFiles.begin(); iFile != iFileEnd; ++iFile) {
683 FitsInOutFile aSpectrum(*iFile,FitsInOutFile::Fits_RO);
684 TMatrix<r_4> spectre(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ);
685 aSpectrum >> spectre;
686 spectreMean += spectre;
687 nSpectres++;
688 }// end of for files
689 if(nSpectres>0) spectreMean /= nSpectres;
690
691 //save mean spectrum
692 spectreCollect.insert( pair< pair<string,sa_size_t>, TMatrix<r_4> >(make_pair(mode,icycle),TMatrix<r_4>(spectreMean,false) ));
693 }//end of for cycles
694 }//end loop on mode for raw preocess
695
696 if(debuglev_>1) {//save mean spectra on file
697 cout << "Save mean raw spectra" << endl;
698 string fileName;
699 //TOBE FIXED fileName = "./" + sourceName_ + "/" + dateOfRun_ + "_" + StringToLower(sourceName_) + "_" + "dataRaw" + ".ppf";
700 fileName = "./dataRaw_" + dateOfRun_ + "_" + StringToLower(sourceName_) + ".ppf";
701
702 POutPersist fos(fileName);
703 id=0;
704 iSpectreEnd = spectreCollect.end();
705 for (iSpectre = spectreCollect.begin();
706 iSpectre != iSpectreEnd ; ++iSpectre, ++id) {
707 tag = "specRaw";
[523]708
709 //JEC 20/9/11 modif tag to take into account Mode and Cycle number START
710// stringstream sid;
711// sid << id;
712// tag += sid.str();
713 tag += (iSpectre->first).first;
[507]714 stringstream sid;
[523]715 sid << (iSpectre->first).second;
[507]716 tag += sid.str();
[523]717 if(debuglev_>9) {
718 cout << "save tag<" << tag << ">" << endl;
719 }
720 //JEC 20/9/11 modif tag to take into account Mode and Cycle number END
721
[507]722 fos << PPFNameTag(tag) << iSpectre->second;
723 }
724 }//end of save fits
725
726
727
728 for (iMode = modeList.begin(); iMode != modeList.end(); ++iMode) {
729 string mode = *iMode;
730 if(debuglev_>0)cout << "Process CALIB BAO Mode " << mode << endl;
731 //------------------------------------------
732 // Correct Raw spectra for BAO calibration
733 //------------------------------------------
734 //Read BAO calibration files
735 sa_size_t nr,nc; //values read
[523]736//JEC 20/9/11 use mean calibration coeff upon all cycles START
737// bool first = true;
738// TMatrix<r_4> calibBAOfactors;
739// for (sa_size_t iCh=0;iCh<NUMBER_OF_CHANNELS;++iCh){
740// string calibFileName = inputPath_+ "/"
741// + sourceName_ + "/" + dateOfRun_ + StringToLower(sourceName_)
742// + "/calib_" + dateOfRun_ + "_" + StringToLower(sourceName_) + "_"
743// + mode + "_" + freqBAOCalibration_ + "MHz";
744// stringstream channel;
745// channel << iCh;
746// calibFileName += "-Ch" + channel.str() + "Cycles.txt";
747// if(debuglev_>0) cout << "Read file " << calibFileName << endl;
748// ifstream ifs(calibFileName.c_str());
749// if ( ! ifs.is_open() ) {
750// rc = 999;
751// throw calibFileName + " cannot be opened...";
752// }
753// TVector<r_4> aCalib;
754// if(debuglev_>9) cout << "Debug 1" << endl;
755// aCalib.ReadASCII(ifs,nr,nc);
756// if(debuglev_>9) cout << "Debug 2" << endl;
757// if(first){
758// first = false;
759// if(debuglev_>9) cout << "Debug 3" << endl;
760// calibBAOfactors.SetSize(NUMBER_OF_CHANNELS,nr);
761// if(debuglev_>9) cout << "Debug 4" << endl;
762// }
763// calibBAOfactors( Range(iCh), Range::all() ) = aCalib.Transpose();
764// if(debuglev_>9) cout << "Debug 5" << endl;
765// ifs.close();
766// }//end of loop on channels
[507]767
[523]768
769 string calibFileName = inputPath_+ "/"
770 + sourceName_ + "/" + dateOfRun_ + StringToLower(sourceName_)
771 + "/calib_" + dateOfRun_ + "_" + StringToLower(sourceName_) + "_"
772 + mode + "_" + freqBAOCalibration_ + "MHz-All.txt";
[507]773
[523]774 if(debuglev_>0) cout << "Read file " << calibFileName << endl;
775 ifstream ifs(calibFileName.c_str());
776 if ( ! ifs.is_open() ) {
777 rc = 999;
778 throw calibFileName + " cannot be opened...";
779 }
780 TVector<r_4> calibBAOfactors;
781 if(debuglev_>9) cout << "Debug 1" << endl;
782 calibBAOfactors.ReadASCII(ifs,nr,nc);
783 if(debuglev_>9){
784 cout << "Debug 2: (nr,nc): "<< nr << "," << nc << endl;
785 calibBAOfactors.Print(cout);
786 }
[507]787
[523]788//JEC 20/9/11 use mean calibration coeff upon all cycles END
789
[507]790 //
791 //spectra corrected by BAO calibration factor
[523]792 //-----make it different on Channels and Cycles (1/06/2011) OBSOLETE
793 //use mean calibration coeff upon all cycles (20/6/11)
[507]794 //warning cycles are numbered from 1,...,N
795 //
796 if(debuglev_>0)cout << "do calibration..." << endl;
797 for (sa_size_t icycle = ifirstCycle_; icycle <= ilastCycle_; icycle++) {
798 TMatrix<r_4> specmtx(spectreCollect[make_pair(mode,icycle)],true); //share the memory
799
800 for (sa_size_t iCh=0;iCh<NUMBER_OF_CHANNELS;++iCh){
[523]801 //JEC 20/9/11 use mean calibration coeff upon all cycles START
802
803 // specmtx( Range(iCh), Range::all() ) /= calibBAOfactors(iCh,icycle-1);
804 specmtx( Range(iCh), Range::all() ) /= calibBAOfactors(iCh);
805 //JEC 20/9/11 use mean calibration coeff upon all cycles END
[507]806 }
807 }
808 } //end loop mode for BAO calib
809
810 if(debuglev_>1){ //save mean spectra BAO calibrated on file
811 cout << "save calibrated BAO spectra" << endl;
812 string fileName;
[514]813 //TO BE FIXED fileName = "./" + sourceName_ + "/" + dateOfRun_ + "_" + StringToLower(sourceName_) + "_" + "dataBAOCalib" + ".ppf";
814 fileName = "./dataBAOCalib_" + dateOfRun_ + "_" + StringToLower(sourceName_) + ".ppf";
815
[507]816 POutPersist fos(fileName);
817 iSpectreEnd = spectreCollect.end();
818 id=0;
819 for (iSpectre = spectreCollect.begin();iSpectre != iSpectreEnd ; ++iSpectre, ++id) {
[523]820
[507]821 tag = "specBAOCalib";
[523]822 //JEC 20/9/11 modif tag to take into account Mode and Cycle number START
823// stringstream sid;
824// sid << id;
825// tag += sid.str();
826 tag += (iSpectre->first).first;
[507]827 stringstream sid;
[523]828 sid << (iSpectre->first).second;
[507]829 tag += sid.str();
[523]830 if(debuglev_>9) {
831 cout << "save tag<" << tag << ">" << endl;
832 }
833 //JEC 20/9/11 modif tag to take into account Mode and Cycle number END
834
835 fos << PPFNameTag(tag) << iSpectre->second;
[507]836 }
837 }//end of save fits
838
839
840 for (iMode = modeList.begin(); iMode != modeList.end(); ++iMode) {
841 string mode = *iMode;
842 if(debuglev_>0)cout << "Process CALIB RT Mode " << mode << endl;
843 //------------------------------------------
844 // Correct BAO calib spectra for RT calibration
845 //------------------------------------------
846 //Very Preliminary May-June 11
847 //coef RT @ 1346MHz Ouest - Est associees a Ch 0 et 1
848 r_4 calibRT[NUMBER_OF_CHANNELS] = {27.724, 22.543};
849 for (sa_size_t icycle = ifirstCycle_; icycle <= ilastCycle_; icycle++) {
850 TMatrix<r_4> specmtx(spectreCollect[make_pair(mode,icycle)],true); //share the memory
851 for (sa_size_t iCh=0;iCh<NUMBER_OF_CHANNELS;++iCh){
852 specmtx( Range(iCh), Range::all() ) *= calibRT[iCh];
853 }
854 }
855 }//end loop on mode RT calib
856
857 {//save mean spectra BAO & RT calibrated on file
858 if(debuglev_>0)cout << "save calibrated BAO & RT spectra" << endl;
859 string fileName;
[514]860 //TO BE FIXED fileName = "./" + sourceName_ + "/" + dateOfRun_ + "_" + StringToLower(sourceName_) + "_" + "dataBAORTCalib" + ".ppf";
861 fileName = "./dataBAORTCalib_" + dateOfRun_ + "_" + StringToLower(sourceName_) + ".ppf";
[507]862 POutPersist fos(fileName);
863 iSpectreEnd = spectreCollect.end();
864 id = 0;
865 for (iSpectre = spectreCollect.begin();iSpectre != iSpectreEnd ; ++iSpectre, ++id) {
866 tag = "specBAORTCalib";
[523]867 //JEC 20/9/11 modif tag to take into account Mode and Cycle number START
868// stringstream sid;
869// sid << id;
870// tag += sid.str();
871 tag += (iSpectre->first).first;
[507]872 stringstream sid;
[523]873 sid << (iSpectre->first).second;
[507]874 tag += sid.str();
[523]875 if(debuglev_>9) {
876 cout << "save tag<" << tag << ">" << endl;
877 }
878 //JEC 20/9/11 modif tag to take into account Mode and Cycle number END
879 fos << PPFNameTag(tag) << iSpectre->second;
[507]880 }
881 }//end of save fits
882
883 //------------------------------------------
884 // Perform ON-OFF
885 //------------------------------------------
886
887 map< sa_size_t, TMatrix<r_4> > diffCollect;
888 map< sa_size_t, TMatrix<r_4> >::iterator iDiff, iDiffEnd;
889
890 TMatrix<r_4> diffMeanOnOff(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ); //init zero
891 r_4 nCycles = 0;
892 for (sa_size_t icycle = ifirstCycle_; icycle <= ilastCycle_; icycle++) {
893 nCycles++;
894 TMatrix<r_4> specmtxOn(spectreCollect[make_pair(modeList[0],icycle)],false); //clone the memory
895 TMatrix<r_4> specmtxOff(spectreCollect[make_pair(modeList[1],icycle)],false); //clone the memory
896 TMatrix<r_4> diffOnOff = specmtxOn - specmtxOff;
897 diffCollect.insert(pair< sa_size_t,TMatrix<r_4> >(icycle,TMatrix<r_4>(diffOnOff,false) ));
898 diffMeanOnOff += diffOnOff;
899 }//end loop on cycle
900 if(nCycles>0) diffMeanOnOff/=nCycles;
901
902 //exctract channels and do the mean
903 TVector<r_4> meanOfChan(NUMBER_OF_FREQ); //implicitly init to 0
904 for (sa_size_t iCh=0; iCh<NUMBER_OF_CHANNELS; ++iCh) {
905 meanOfChan += diffMeanOnOff.Row(iCh).Transpose();
906 }
907 meanOfChan /= (r_4)NUMBER_OF_CHANNELS;
908
909
910
911 {//save diff ON-OFF BAO & RT calibrated
912 if(debuglev_>0)cout << "save ON-OFF spectra" << endl;
913 string fileName;
[514]914 //TO BE FIXED fileName = "./" + sourceName_ + "/" + dateOfRun_ + "_" + StringToLower(sourceName_) + "_" + "diffOnOff" + ".ppf";
915 fileName = "./diffOnOff_" + dateOfRun_ + "_" + StringToLower(sourceName_) + ".ppf";
[507]916 POutPersist fos(fileName);
917 iDiffEnd = diffCollect.end();
918 id = 0;
919 for (iDiff = diffCollect.begin();iDiff != iDiffEnd ; ++iDiff, id++) {
920 tag = "specONOFF";
921 stringstream sid;
[523]922 //JEC 20/9/11 sid << id;
923 sid << iDiff->first;
[507]924 tag += sid.str();
[523]925 if(debuglev_>9) {
926 cout << "save tag<" << tag << ">" << endl;
927 }
928 fos << PPFNameTag(tag) << iDiff->second;
[507]929 }
930 //save the mean also
931 fos << PPFNameTag("specONOFFMean") << diffMeanOnOff;
932 fos << PPFNameTag("specONOFF2ChanMean") << meanOfChan;
933 }//end of save fits
934
935 return rc;
936} //ProcessONOFFData::processCmd
937//
938//----------------------------------------------
939//
940int ProcessGain::processCmd() throw(string) {
941 int rc = 0;
942 string msg = "";
943
944 try {
945 rc = ProcessBase::processCmd();
946 }
947 catch (string s) {
948 throw s;
949 }
950 if(debuglev_>0)cout << "Process Gain" << endl;
951
952 string directoryName;
953 //TOBE FIXED directoryName = "./" + sourceName_ + "/"+ dateOfRun_ + StringToLower(sourceName_) + "/" +mode_ + "/";
954 //JEC 6/09/2011 numcycle_ repalced by ifirstCycle_ according to definition of numcycle_ and the fact that for GAIN 1 cycle is involved
955 stringstream thegaincycle;
956 thegaincycle << ifirstCycle_;
957 directoryName = inputPath_ + "/"
958 + sourceName_ + "/" + dateOfRun_ + StringToLower(sourceName_) + "/"
959 + mode_ + "/" + spectraDirectory_ + thegaincycle.str() + "/";
960
961 list<string> listOfSpecFiles;
962 list<string>::const_iterator iFile, iFileEnd;
963 //read directory
964
965 listOfSpecFiles = ListOfFileInDir(directoryName,typeOfFile_);
966
967 //Mean power computed over the N channels to select the spectra for gain computation
968 //The threshold is computed "on-line" as 1% of the difference (max power -min power) over the
969 // the min power.
970 //A possible alternative is to set an absolute value...
971 if(debuglev_>0)cout << "compute mean poser spectra for files in " << directoryName << endl;
972 iFileEnd = listOfSpecFiles.end();
973 map<string, r_4> meanpowerCollect;
[523]974 //JEC 21/9/11 add meanpower for each Channels START
975 map<string, r_4> meanPowerPerChanCollect;
976 //JEC 21/9/11 add meanpower for each Channels END
977
[507]978 map<string, r_4>::const_iterator iMeanPow, iMeanPowEnd;
979
980 for (iFile = listOfSpecFiles.begin(); iFile != iFileEnd; ++iFile) {
981 FitsInOutFile aSpectrum(*iFile,FitsInOutFile::Fits_RO);
982 TMatrix<r_4> spectre(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ);
983 aSpectrum >> spectre;
984 meanpowerCollect[*iFile] = spectre.Sum()/spectre.Size();
[523]985 //JEC 21/9/11 add meanpower for each Channels START
986 for (sa_size_t iCh=0; iCh<NUMBER_OF_CHANNELS; ++iCh) {
987 TVector<r_4> specChan(NUMBER_OF_FREQ);
988 specChan = spectre.Row(iCh).Transpose();
989 stringstream tmp;
990 tmp << iCh;
991 string tag = *iFile + "_" + tmp.str();
992 meanPowerPerChanCollect[tag] = specChan.Sum()/specChan.Size();
993 }
994 //JEC 21/9/11 add meanpower for each Channels END
[507]995 }//end of for files
996 pair<string, r_4> minelement = *min_element(meanpowerCollect.begin(),meanpowerCollect.end(),compare);
997 pair<string, r_4> maxelement = *max_element(meanpowerCollect.begin(),meanpowerCollect.end(),compare);
998 if(debuglev_>1){
999 cout << "meanpowerCollect has " << meanpowerCollect.size() << " spectra registered" << endl;
1000 cout << "find min mean power "<<minelement.second << " for " << minelement.first << endl;
1001 cout << "find max mean power "<<maxelement.second << " for " << maxelement.first << endl;
1002 }
1003 r_4 threshold = minelement.second + 0.01*(maxelement.second-minelement.second);
1004 if(debuglev_>1){
1005 cout << "threshold found at " << threshold <<endl;
1006 }
1007
1008 TMatrix<r_4> spectreMean(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ); //implicit init to 0
1009 r_4 nSpectres = 0;
1010 iMeanPowEnd = meanpowerCollect.end();
1011 for (iMeanPow = meanpowerCollect.begin(); iMeanPow != iMeanPowEnd; ++iMeanPow) {
1012 if ( iMeanPow->second <= threshold ) {
1013 //TODO avoid the reloading of the file may speed up
1014 FitsInOutFile aSpectrum(iMeanPow->first,FitsInOutFile::Fits_RO);
1015 TMatrix<r_4> spectre(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ);
1016 aSpectrum >> spectre;
1017 spectreMean += spectre;
1018 nSpectres++;
1019 }
1020 }
1021 if(debuglev_>1){
1022 cout << "Number of files selected for gain " << nSpectres <<endl;
1023 }
1024 if(nSpectres>0) {
1025 spectreMean /= nSpectres;
1026 } else {
1027 stringstream tmp;
1028 tmp << threshold;
1029 msg = "Gain: cannot find a spectra above threshold value =" + tmp.str() + " ... FATAL";
1030 throw msg;
1031 }
1032
1033 //Save gain spectra
1034 {
1035 //use ! to override the file: special features of cfitsio library
1036 string fileName;
1037 //TOBE FIXED fileName = "!./" + sourceName_ + "/gain_" + dateOfRun_ + "_" + StringToLower(sourceName_) + ".fits";
1038 fileName = "!"+ outputPath_ + "/gain_" + dateOfRun_ + "_" + StringToLower(sourceName_) + ".fits";
1039 if(debuglev_>1){
1040 cout << "save gains in " << fileName << endl;
1041 }
1042 FitsInOutFile fos(fileName, FitsInOutFile::Fits_Create);
1043 fos << spectreMean;
1044 }
1045 //save mean power values
1046 {
1047 vector<r_4> tmp;
[523]1048 //JEC 21/9/11 add meanpower for each Channels START
1049 vector<r_4> tmpCh0; //for Chan 0
1050 vector<r_4> tmpCh1; //for Chan 1
1051 //JEC 21/9/11 add meanpower for each Channels END
[507]1052 for (iFile = listOfSpecFiles.begin(); iFile != iFileEnd; ++iFile) {
[523]1053 if (debuglev_>9) {
1054 cout << "Gain: save mean power of file: " << *iFile << endl;
1055 }
[507]1056 tmp.push_back(meanpowerCollect[*iFile]);
[523]1057 //JEC 21/9/11 add meanpower for each Channels START
1058 stringstream tmp0;
1059 tmp0 << (sa_size_t)0;
1060 string tag0 = *iFile + "_" + tmp0.str();
1061 tmpCh0.push_back(meanPowerPerChanCollect[tag0]);
1062 if (NUMBER_OF_CHANNELS>1){
1063 stringstream tmp1;
1064 tmp1 << (sa_size_t)1;
1065 string tag1 = *iFile + "_" + tmp1.str();
1066 tmpCh1.push_back(meanPowerPerChanCollect[tag1]);
1067 }
1068 //JEC 21/9/11 add meanpower for each Channels END
[507]1069 }
1070 string fileName;
1071 //TOBE FIXED fileName = "./" + sourceName_ + "/gain_monitor_" + dateOfRun_
1072 fileName = outputPath_ + "/gain_monitor_" + dateOfRun_ + "_" + StringToLower(sourceName_) + ".ppf";
1073 POutPersist fos(fileName);
1074 TVector<r_4> tvtmp(tmp);
[523]1075 fos.PutObject(tvtmp,"gainmoni"); //Attention initialement le tag etait "monitor"...
1076 //JEC 21/9/11 add meanpower for each Channels START
1077 TVector<r_4> tvtmp0(tmpCh0);
1078 fos.PutObject(tvtmp0,"gainmoni0");
1079 if (NUMBER_OF_CHANNELS>1){
1080 TVector<r_4> tvtmp1(tmpCh1);
1081 fos.PutObject(tvtmp1,"gainmoni1");
1082 }
1083 //JEC 21/9/11 add meanpower for each Channels END
[507]1084 }
1085
1086 cout << "OK gain finished" <<endl;
1087 return rc;
1088}//ProcessGain::processCmd
1089//
1090//----------------------------------------------
1091//
1092int ProcessCalibration::processCmd() throw(string) {
1093 int rc = 0;
1094 string msg = "";
1095
1096 try {
1097 rc = ProcessBase::processCmd();
1098 }
1099 catch (string s) {
1100 throw s;
1101 }
1102 if(debuglev_>0)cout << "Process Calibration with option "<< option_ << endl;
1103
1104 vector<string> modeList;
1105 modeList.push_back("On");
1106 modeList.push_back("Off");
1107
1108 r_8 t0absolute = -1; //TIMEWIN of the first spectra used
1109 r_8 timeTag0 = -1; //MEANTT, mean TIME TAG of the first paquet window
1110 bool first = true; // for initialisation
1111
1112 // Power Tuple
1113 // mode, cycle, time, {Ch0, ... ,ChN} mean poser in the range [f0-Bw/2, f0+Bw/2]
1114 vector<string> varPowerTupleName; //ntuple variable naming
1115 varPowerTupleName.push_back("mode");
1116 varPowerTupleName.push_back("cycle");
1117 varPowerTupleName.push_back("time");
1118 for (sa_size_t iCh=0; iCh<NUMBER_OF_CHANNELS;++iCh){
1119 stringstream tmp;
1120 tmp << iCh;
1121 varPowerTupleName.push_back("Ch"+tmp.str());
1122 }
1123 r_4 valPowerTuple[varPowerTupleName.size()];
1124 NTuple powerEvolution(varPowerTupleName);
1125
1126
1127 //-----------------
1128 //Start real process
1129 //------------------
1130 for (size_t iMode = 0; iMode < modeList.size(); ++iMode) {
1131 string mode = modeList[iMode];
1132 if(debuglev_>0)cout << "Process Calibration for Mode " << mode << endl;
1133
1134 //initialize the start of each calibration procedure given by the RT SCA file
1135 //see ProcessBase::processCmd for the structure of the sca file
1136 string scaStartCalibName = "stcal"+mode;
1137 sa_size_t idStartCalib = scaTuple_->ColumnIndex(scaStartCalibName);
1138
1139 string directoryName;
1140 list<string> listOfSpecFiles;
1141 list<string>::const_iterator iFile, iFileEnd;
1142 //
1143 //loop on cycles
1144 //
1145 for (sa_size_t icycle = ifirstCycle_; icycle <= ilastCycle_; icycle++) {
1146
1147 directoryName = inputPath_ + "/"
1148 + sourceName_ + "/"+ dateOfRun_ + StringToLower(sourceName_) + "/" +mode + "/";
1149 stringstream sicycle;
1150 sicycle << icycle;
1151 directoryName += spectraDirectory_ + sicycle.str() + "/";
1152
1153 //read directory
1154 listOfSpecFiles = ListOfFileInDir(directoryName,typeOfFile_);
1155
1156 iFileEnd = listOfSpecFiles.end();
1157 DVList header;
1158 TMatrix<r_4> spectre(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ); //implicit init to 0
1159
1160 for (iFile = listOfSpecFiles.begin(); iFile != iFileEnd; ++iFile) {
1161 FitsInOutFile aSpectrum(*iFile,FitsInOutFile::Fits_RO);
1162 aSpectrum.GetHeaderRecords(header);
1163 aSpectrum >> spectre;
1164
1165 if(first){//initialise the timer
1166 first = false;
1167 t0absolute = header.GetD("TIMEWIN")/1000.;
1168 timeTag0 = header.GetD("MEANTT");
1169 if (debuglev_>1){
1170 cout << "debug Header of " << *iFile << endl;
1171 cout << "TIMEWIN = " << setprecision(12) << t0absolute << " "
1172 << "MEANTT = " << setprecision(12) << timeTag0 << endl;
1173 }
1174 }//end init timer
1175
1176 //Set time of current file
1177 //Add to the non-precise absolute origin an precise increment
1178 r_4 timeTag = t0absolute + (header.GetD("MEANTT") - timeTag0);
1179 int index=0;
1180 valPowerTuple[index++] = iMode;
1181 valPowerTuple[index++] = icycle;
1182 valPowerTuple[index++] = timeTag-scaTuple_->GetCell(idCycleInTuple_[icycle],idStartCalib); //take the RT time start as refernce
1183
1184 //Compute the mean power of the two channel (separatly) in the range [f-bw/2, f+bw/2]
1185 for (sa_size_t iCh=0; iCh<NUMBER_OF_CHANNELS;++iCh){
1186 TMatrix<r_4> tmp(spectre(Range(iCh),Range(lowerFreqBin_,upperFreqBin_)),false);
1187 r_4 mean = tmp.Sum()/(r_4)tmp.Size();
1188 valPowerTuple[index++] = mean;
1189 }//end of channel loop
1190
1191 //Fill Tuple
1192 powerEvolution.Fill(valPowerTuple);
1193 }//end of files loop
1194 }//end of cycles loop
1195 }//end of mode loop
1196
1197 //store power evolution Tuple
1198 if(debuglev_>0){
1199 cout << "ProcessCalibration::processCmd: dump powerEvolution tuple" << endl;
1200 powerEvolution.Show(cout);
1201 }
1202 //
1203 //Compute Calibration Coefficients as function of mode/cycle/channels
1204 //
1205
1206 //Tsys,Incremant Intensity... Tuple
1207 //mode mode cycle [(tsys0,dint0),...,(tsysN,dintN)]
1208 vector<string> varCalibTupleName;
1209 varCalibTupleName.push_back("mode");
1210 varCalibTupleName.push_back("cycle");
1211 for (sa_size_t iCh=0; iCh<NUMBER_OF_CHANNELS;++iCh){
1212 stringstream tmp;
1213 tmp << iCh;
1214 varCalibTupleName.push_back("tsys"+tmp.str());
1215 varCalibTupleName.push_back("dint"+tmp.str());
1216 }
1217 r_4 valCalibTuple[varCalibTupleName.size()];
1218 NTuple calibEvolution(varCalibTupleName);
1219
1220 // select time E [twin0,twin1] U [twin2,twin3] for Tsys
1221 // time unit = second
1222 const r_4 twin0 = -3.;
1223 const r_4 twin1 = -1.;
1224 const r_4 twin2 = 6.;
1225 const r_4 twin3 = 8;
1226 const r_4 thresholdFactor = 0.80; //80% of the diff. Max-Min intensity
1227
1228 sa_size_t inModeIdx = powerEvolution.ColumnIndex("mode");
1229 sa_size_t inCycleIdx= powerEvolution.ColumnIndex("cycle");
1230 sa_size_t inTimeIdx = powerEvolution.ColumnIndex("time");
1231 sa_size_t inOffsetCh0 = powerEvolution.ColumnIndex("Ch0"); //nb Ch0 position in the powerEvolution tuple
1232 if(debuglev_>1) cout << "DEBUG: in Idx: ("
1233 << inModeIdx << ", "
1234 << inCycleIdx << ", "
1235 << inTimeIdx << ", "
1236 << inOffsetCh0 << ")"
1237 << endl;
1238
1239
1240 size_t outModeIdx = calibEvolution.ColumnIndex("mode");
1241 size_t outCycleIdx= calibEvolution.ColumnIndex("cycle");
1242 size_t outOffsetCh0 = calibEvolution.ColumnIndex("tsys0"); //nb Ch0 position in the monitor tuple
1243 size_t outNDataPerCh= 2;
1244 if(debuglev_>1) cout << "DEBUG: out Idx: ("
1245 << outModeIdx << ", "
1246 << outCycleIdx << ", "
1247 << outOffsetCh0 << ")"
1248 << endl;
1249
1250 sa_size_t nPowerEvolEntry = powerEvolution.NEntry();
1251 double minMode;
1252 double maxMode;
1253 powerEvolution.GetMinMax("mode",minMode,maxMode);
1254 double minCycleNum;
1255 double maxCycleNum;
1256 powerEvolution.GetMinMax("cycle",minCycleNum,maxCycleNum);
1257 if(debuglev_>1) cout << "DEBUG mode ("<<minMode<<","<<maxMode<<")\n"
1258 << "cycle ("<<minCycleNum<<","<<maxCycleNum<<")"
1259 << endl;
1260
1261 r_4* aPowerEvolEntry; // a ligne of the powerEvolution tuple
1262// r_4* aPowerEvolEntry = new r_4[powerEvolution.NbColumns()]; // a ligne of the powerEvolution tuple
1263
1264 r_4 minMean;
1265 r_4 maxMean;
1266
1267 for (size_t iMode = (size_t)minMode; iMode <= (size_t)maxMode; iMode++){
1268 for (size_t iCycle = (size_t)minCycleNum; iCycle <= (size_t)maxCycleNum; iCycle++ ){
1269 if(debuglev_>1) cout<<"DEBUG >>>>>>> mode/cycle: " << iMode << "/" << iCycle << endl;
1270
1271 valCalibTuple[outModeIdx]=iMode;
1272 valCalibTuple[outCycleIdx]=iCycle;
1273 //
1274 //Compute the Min && Max value of each Ch<i> data
1275 if(debuglev_>1) cout<<"DEBUG compute Min and Max for each channels" << endl;
1276 //
1277 TVector<r_4> chMean[NUMBER_OF_CHANNELS];
1278 for (sa_size_t iCh=0;iCh<NUMBER_OF_CHANNELS;iCh++){
1279 chMean[iCh].SetSize(nPowerEvolEntry);
1280 }
1281 for (sa_size_t ie=0; ie<nPowerEvolEntry; ie++){
1282 aPowerEvolEntry = powerEvolution.GetVec(ie);
1283 if ( (size_t)aPowerEvolEntry[inModeIdx] == iMode && (size_t)aPowerEvolEntry[inCycleIdx] == iCycle ){
1284 for (sa_size_t iCh=0;iCh<NUMBER_OF_CHANNELS;iCh++){
1285 chMean[iCh](ie) = aPowerEvolEntry[iCh+inOffsetCh0];
1286 }//end cut
1287 }
1288 }//eo loop on tuple entries
1289 for (sa_size_t iCh=0;iCh<NUMBER_OF_CHANNELS;iCh++){
1290 //
1291 //select values to compute background Tsys
1292 if(debuglev_>1) {
1293 cout<< "DEBUG >>>> Ch[" << iCh << "]" << endl;
1294 cout<< "DEBUG select values to compute background Tsys " << endl;
1295 }
1296 //
1297
1298 std::vector<r_4> lowerInt;
1299 for (sa_size_t ie=0; ie<nPowerEvolEntry; ie++){
1300 aPowerEvolEntry = powerEvolution.GetVec(ie);
1301 if ( (size_t)aPowerEvolEntry[inModeIdx] == iMode && (size_t)aPowerEvolEntry[inCycleIdx] == iCycle ){
1302 r_4 time = aPowerEvolEntry[inTimeIdx];
1303 if ( (time >= twin0 && time <= twin1) ||
1304 (time >= twin2 && time <= twin3)
1305 ) lowerInt.push_back(aPowerEvolEntry[iCh+inOffsetCh0]);
1306 }//end cut
1307 } //end loop entries
1308 //
1309 //compute the Tsys
1310 if(debuglev_>1) cout <<"DEBUG compute Tsys" << endl;
1311 //
1312 std::nth_element(lowerInt.begin(),
1313 lowerInt.begin()+lowerInt.size()/2,
1314 lowerInt.end());
1315 r_4 tsys = *(lowerInt.begin()+lowerInt.size()/2);
1316 if(debuglev_>1) cout << "DEBUG tsys["<<iCh<<"] : " << tsys <<endl;
1317 //
1318 //set the threshold for DAB detection
1319 //
1320 chMean[iCh].MinMax(minMean,maxMean);
1321 minMean = (tsys > minMean) ? tsys : minMean; //pb of empty vector
1322 if(debuglev_>1) cout << "DEBUG min["<<iCh<<"] : " << minMean
1323 << " max["<<iCh<<"] : " << maxMean
1324 <<endl;
1325 r_4 deltathres = thresholdFactor * (maxMean-minMean);
1326 r_4 thres = tsys + deltathres;
1327 if(debuglev_>1) cout << "DEBUG thres["<<iCh<<"] : " << thres <<endl;
1328 //
1329 //collect upper part of the DAB
1330 if(debuglev_>1) cout <<"DEBUG collect upper part of the DAB" << endl;
1331 //
1332 std::vector<r_4> upperInt;
1333 for (sa_size_t ie=0; ie<nPowerEvolEntry; ie++){
1334 aPowerEvolEntry = powerEvolution.GetVec(ie);
1335 if ( (size_t)aPowerEvolEntry[inModeIdx] == iMode && (size_t)aPowerEvolEntry[inCycleIdx] == iCycle ){
1336 r_4 mean = aPowerEvolEntry[iCh+inOffsetCh0];
1337 if (mean >= thres) upperInt.push_back(mean);
1338 }//end cut
1339 }//eo loop on channels
1340 //
1341 //compute adjacent differences to detect the 2 DAB levels
1342 //
1343 if(debuglev_>1) cout << "(DEBUG )size upper [" << iCh << "]: " << upperInt.size() <<endl;
1344 std::vector<r_4> upperIntAdjDiff(upperInt.size());
1345 std::adjacent_difference(upperInt.begin(),
1346 upperInt.end(),
1347 upperIntAdjDiff.begin());
1348 //
1349 //Search the 2 DAB states
1350 if(debuglev_>1) cout<<"DEBUG Search the 2 DAB states" << endl;
1351 //
1352 std::vector<r_4> upIntState[2];
1353 int state=-1;
1354 for (size_t i=1;i<upperInt.size();i++) {//skip first value
1355 if (fabs(upperIntAdjDiff[i])<upperInt[i]*0.010) {
1356 if(state == -1) state=0;
1357 if(state == -2) state=1;
1358 upIntState[state].push_back(upperInt[i]);
1359 } else {
1360 if (state == 0) state=-2;
1361 }
1362 }
1363 //
1364 //Take the mean of the median values of each levels
1365 if(debuglev_>1)cout << "DEBUG mean of the median values of each levels" << endl;
1366 //
1367 r_4 meanUpper = 0;
1368 r_4 nval = 0;
1369 for (int i=0;i<2;i++) {
1370 if (!upIntState[i].empty()) {
1371 std::nth_element(upIntState[i].begin(),
1372 upIntState[i].begin()+upIntState[i].size()/2,
1373 upIntState[i].end());
1374 meanUpper += *(upIntState[i].begin()+upIntState[i].size()/2);
1375 nval++;
1376 }
1377 }
1378 meanUpper /= nval;
1379 //
1380 //Finaly the increase of power due to the DAB is:
1381 //
1382 r_4 deltaInt = meanUpper - tsys;
1383 if(debuglev_>1) cout << "DEBUG deltaInt["<<iCh<<"] : " << deltaInt <<endl;
1384 //
1385 //Save for monitoring and final calibration operations
1386 //
1387 valCalibTuple[outOffsetCh0+outNDataPerCh*iCh] = tsys;
1388 valCalibTuple[outOffsetCh0+outNDataPerCh*iCh+1] = deltaInt;
1389 }//end loop on channels
1390 if(debuglev_>1) cout<<"DEBUG Fill the calibEvolution tuple" << endl;
1391 calibEvolution.Fill(valCalibTuple);
1392 }//eo loop on Cycles
1393 }//eo loop on Modes
1394 //
1395 //store calibration evolution Tuple
1396 //
1397 if(debuglev_>0){
1398 cout << "ProcessCalibration::processCmd: dump calibEvolution tuple" << endl;
1399 calibEvolution.Show(cout);
1400 }
1401 //
1402 //Compute the means per channel of the calibration coefficients (deltaInt)
1403 //and save cycle based Calibration Ctes in file named as
1404 // <source>-<date>-<mode>-<fcalib>MHz-Ch<channel>Cycles.txt
1405 // format <cycle> <coef>
1406 //the means are stored in files
1407 // <source>-<date>-<mode>-<fcalib>MHz-All.txt
1408 // format <channel> <coef>
1409 //
1410 sa_size_t nModes = (sa_size_t)(maxMode - minMode) + 1;
1411 string calibCoefFileName;
1412 ofstream calibMeanCoefFile[nModes]; //Mean over cycles
1413 ofstream calibCoefFile[nModes][NUMBER_OF_CHANNELS]; //cycle per cycle
1414 for (sa_size_t iMode=0; iMode<nModes; iMode++){
1415 //The file for the Means Coeff.
1416 calibCoefFileName = outputPath_ + "/calib_"
1417 + dateOfRun_ + "_" + StringToLower(sourceName_) + "_"
1418 + modeList[iMode] + "_"
1419 + freqBAOCalibration_ + "MHz-All.txt";
1420 calibMeanCoefFile[iMode].open(calibCoefFileName.c_str());
1421 //The file for the cycle per cycle Coeff.
1422 for (sa_size_t iCh=0; iCh<NUMBER_OF_CHANNELS; iCh++){
1423 stringstream chString;
1424 chString << iCh;
1425 calibCoefFileName = outputPath_ + "/calib_"
1426 + dateOfRun_ + "_" + StringToLower(sourceName_) + "_"
1427 + modeList[iMode] + "_"
1428 + freqBAOCalibration_ + "MHz-Ch" + chString.str() + "Cycles.txt";
1429 calibCoefFile[iMode][iCh].open(calibCoefFileName.c_str());
1430 }
1431 }
1432
1433 r_4* aCalibEvolEntry;
1434 sa_size_t nCalibEvolEntry = calibEvolution.NEntry();
1435
1436 TMatrix<r_4> meanCalibCoef(nModes,NUMBER_OF_CHANNELS); //by default init to 0
1437 TMatrix<r_4> nData4Mean(nModes,NUMBER_OF_CHANNELS);
1438
1439 //READ the calibration tuple, fill the array for mean and write to ascii file
1440 for (sa_size_t ie=0; ie<nCalibEvolEntry; ie++){
1441 aCalibEvolEntry = calibEvolution.GetVec(ie);
1442 if(debuglev_>1){
1443 cout << "DEBUG mode/cycle/Coef "
1444 << aCalibEvolEntry[outModeIdx] << " "
1445 << aCalibEvolEntry[outCycleIdx] << " ";
1446 }
1447 for (sa_size_t iCh=0; iCh<NUMBER_OF_CHANNELS; iCh++){
1448 if(debuglev_>1) cout << aCalibEvolEntry[outOffsetCh0+outNDataPerCh*iCh+1] << " "; // for debug
1449 sa_size_t currentMode = (sa_size_t)(aCalibEvolEntry[outModeIdx] - minMode); //ok even if minMode <> 0
1450 nData4Mean(currentMode,iCh)++;
1451 meanCalibCoef(currentMode,iCh) += aCalibEvolEntry[outOffsetCh0+outNDataPerCh*iCh+1];
1452
1453 calibCoefFile[currentMode][iCh] << aCalibEvolEntry[outCycleIdx] << " "
1454 << setprecision(12)
1455 << aCalibEvolEntry[outOffsetCh0+outNDataPerCh*iCh+1]
1456 << endl;
1457 }
1458 if(debuglev_>1) cout << endl; //for debug
1459 }
1460
1461 //Perform means: true means that div per 0 is treated (slower but safer)
1462 meanCalibCoef.Div(nData4Mean,true);
1463
1464 if(debuglev_>0){
1465 cout << "DEBUG nData4Mean" << endl;
1466 nData4Mean.Print(cout);
1467 cout << "DEBUG meanCalibCoef (averaged)" << endl;
1468 meanCalibCoef.Print(cout);
1469 }
1470
1471 //Save means Coef
1472 for (sa_size_t iMode=0; iMode<nModes; iMode++){
1473 for (sa_size_t iCh=0; iCh<NUMBER_OF_CHANNELS; iCh++){
1474 calibMeanCoefFile[iMode] << setprecision(12)
1475 << meanCalibCoef(iMode,iCh)
1476 << endl;
1477 }
1478 }
1479
1480 //Save Monitor File
1481 {
1482 string fileName = outputPath_ + "/calib_monitor_" + dateOfRun_ + "_" + StringToLower(sourceName_) + ".ppf";
1483 POutPersist calibMonitorFile(fileName);
1484 calibMonitorFile << PPFNameTag("powermoni") << powerEvolution;
1485 calibMonitorFile << PPFNameTag("calibmoni") << calibEvolution;
1486 }
1487
1488 //Clean & Return
1489 for (sa_size_t iMode=0; iMode<nModes; iMode++){
1490 calibMeanCoefFile[iMode].close();
1491 for (sa_size_t iCh=0; iCh<NUMBER_OF_CHANNELS; iCh++){
1492 calibCoefFile[iMode][iCh].close();
1493 }
1494 }
1495
1496 cout << "Ok calibration finished" << endl;
1497 return rc;
1498}//ProcessCalibration::processCmd
1499
Note: See TracBrowser for help on using the repository browser.