/[PAMELA software]/DarthVader/S4Level2/src/S4Core.cpp
ViewVC logotype

Contents of /DarthVader/S4Level2/src/S4Core.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.32 - (show annotations) (download)
Tue Oct 14 14:07:27 2014 UTC (10 years, 3 months ago) by mocchiut
Branch: MAIN
CVS Tags: v10RED, v10REDr01, HEAD
Changes since 1.31: +2 -1 lines
10RED: lost sync bug fixed

1 //
2 // Given a calibration and a data file this program create an ntuple with LEVEL2 S4 variables
3 //
4 //
5 // C/C++ headers
6 //
7 #include <fstream>
8 #include <string.h>
9 #include <iostream>
10 #include <cstring>
11 #include <stdio.h>
12 //
13 // ROOT headers
14 //
15 #include <TGraph.h>
16 #include <TF1.h>
17 #include <TTree.h>
18 #include <TClassEdit.h>
19 #include <TObject.h>
20 #include <TList.h>
21 #include <TArrayI.h>
22 #include <TArrayD.h>
23 #include <TSystem.h>
24 #include <TSystemDirectory.h>
25 #include <TString.h>
26 #include <TFile.h>
27 #include <TClass.h>
28 #include <TSQLServer.h>
29 #include <TSQLRow.h>
30 #include <TSQLResult.h>
31 #include <TClonesArray.h>
32 #include <stdlib.h>
33 #include <math.h>
34 //
35 // RunInfo header
36 //
37 #include <RunInfo.h>
38 #include <GLTables.h>
39 //
40 // YODA headers
41 //
42 #include <PamelaRun.h>
43 #include <PscuHeader.h>
44 #include <PscuEvent.h>
45 #include <EventHeader.h>
46 #include <CalibS4Event.h>
47 #include <physics/S4/S4Event.h>
48 //
49 // This program headers
50 //
51 #include <S4Level2.h>
52 #include <S4Core.h>
53 #include <S4Verl2.h>
54 //
55 using namespace std;
56 //
57 /*
58 * Fit function Received from Valeria Malvezzi 06/02/2006
59 */
60 Double_t fitf(Double_t *x, Double_t *par){
61 Double_t fitval =(par[0]*x[0])+par[1];
62 return fitval;
63 }
64
65 /*
66 * Fit the S4 calibration with a straight line - Received from Valeria Malvezzi 06/02/2006
67 */
68 TArrayD *S4_paramfit(UInt_t atime, TSQLServer *dbc){
69 //
70 TArrayD *parametri = new TArrayD(2);
71 //
72 GL_S4_CALIB *glS4calib = new GL_S4_CALIB();
73 //
74 // if ( !dbc->IsConnected() ) throw -504;
75 Int_t s4sig = glS4calib->Query_GL_S4_CALIB(atime, dbc);
76 if ( s4sig != -57 && s4sig < 0 ){
77 parametri->AddAt(0.,0);
78 parametri->AddAt(0.,1);
79 return parametri;
80 };
81 if ( s4sig < 0 ) throw s4sig;
82 //
83 GL_ROOT *glroot = new GL_ROOT();
84 // if ( !dbc->IsConnected() ) throw -504;
85 glroot->Query_GL_ROOT(glS4calib->ID_ROOT_L0,dbc);
86 //
87 stringstream ftmpname;
88 ftmpname.str("");
89 ftmpname << glroot->PATH.Data() << "/";
90 ftmpname << glroot->NAME.Data();
91 //
92 TFile *file = 0;
93 file = new TFile(ftmpname.str().c_str());
94 //
95 if ( !file ) return(NULL);
96 //
97 TTree *tr = 0;
98 tr = (TTree*)file->Get("CalibS4");
99 if ( !tr ){
100 file->Close();
101 return(NULL);
102 };
103 //
104 pamela::CalibS4Event *S4CalibEvent = 0;
105 tr->SetBranchAddress("CalibS4", &S4CalibEvent);
106 if ( tr->GetEntries() < glS4calib->EV_ROOT ) return(NULL);
107 //
108 if ( tr->GetEntry(glS4calib->EV_ROOT) <= 0 ) throw -36;
109 //
110 // Variables initialization
111 //
112 Double_t mip[3]={1, 30, 300};
113 Double_t adc[3] = {0.,0.,0.};
114 //
115 // Fit calibrations and find parameters to calibrate data
116 //
117 pamela::S4::S4Event *s4Record = 0;
118 //
119 for (Int_t j = 0; j < 4; j++){
120 for (Int_t i = 0; i < 128; i++){
121 s4Record = (pamela::S4::S4Event*)S4CalibEvent->Records->At((j*128 + i));
122 switch (j) {
123 case 0 :{
124 adc[0]=adc[0]+((s4Record->S4_DATA)-32);
125 break;
126 };
127 case 1 :{
128 adc[1]=adc[1]+((s4Record->S4_DATA)-32);
129 break;
130 };
131 case 3 :{
132 adc[2]=adc[2]+((s4Record->S4_DATA)-32);
133 break;
134 };
135 };
136 };
137 };
138 //
139 adc[0]=adc[0]/128;
140 adc[1]=adc[1]/128;
141 adc[2]=adc[2]/128;
142 // if ( IsDebug() ) printf(" adc1 = %g adc2 = %g adc3 = %g\n",adc[0],adc[1],adc[2]);
143 TGraph *fitpar = new TGraph (3, adc, mip);
144 TF1 *func = new TF1("fitf", fitf, -1., 400., 2); // function definition with 2 parameters
145 //
146 func->SetParameters(0.3,1.); // parameters initialization to 1
147 func->SetParNames("m","q"); //parameter's name
148 fitpar->Fit(func,"qr"); //function fit
149 parametri->AddAt(func->GetParameter(0),0);
150 parametri->AddAt(func->GetParameter(1),1);
151 // if ( parametri[0] < 0. || parametri[0] > 0.5 || parametri[1] < 0.7 || parametri[1] > 1.1 ) valid = 0;
152 //
153 delete glroot;
154 delete glS4calib;
155 delete fitpar;
156 delete func;
157 file->Close();
158 //
159 return parametri;
160 };
161
162 //
163 // CORE ROUTINE
164 //
165 //
166 int S4Core(UInt_t run, TFile *file,GL_TABLES *glt, Int_t S4argc, char *S4argv[]){
167 //
168 // Set these to true to have a verbose output.
169 //
170 Bool_t debug = false;
171 Bool_t verbose = false;
172 //
173 //
174 // Output directory is the working directoy.
175 //
176 const char* outDir = gSystem->DirName(gSystem->DirName(file->GetPath()));
177 //
178 Int_t i = 0;
179 TString processFolder = Form("S4Folder_%u",run);
180 if ( S4argc > 0 ){
181 i = 0;
182 while ( i < S4argc ){
183 if ( !strcmp(S4argv[i],"-processFolder") ) {
184 if ( S4argc < i+1 ){
185 throw -3;
186 };
187 processFolder = (TString)S4argv[i+1];
188 i++;
189 };
190 if ( (!strcmp(S4argv[i],"--debug")) || (!strcmp(S4argv[i],"-g"))) {
191 verbose = true;
192 debug = true;
193 };
194 if ( (!strcmp(S4argv[i],"--verbose")) || (!strcmp(S4argv[i],"-v"))) {
195 verbose = true;
196 };
197 i++;
198 };
199 };
200 // Variables for level2
201 //
202 TTree *S4tr = 0;
203 UInt_t nevents = 0;
204 //
205 // Variables needed to reprocess data
206 //
207 Long64_t maxsize = 10000000000LL;
208 TTree::SetMaxTreeSize(maxsize);
209 //
210 TString S4version;
211 ItoRunInfo *runinfo = 0;
212 TArrayI *runlist = 0;
213 TTree *S4trclone = 0;
214 Bool_t reproc = false;
215 Bool_t reprocall = false;
216 UInt_t nobefrun = 0;
217 UInt_t noaftrun = 0;
218 UInt_t numbofrun = 0;
219 stringstream ftmpname;
220 TString fname;
221 UInt_t totfileentries = 0;
222 UInt_t idRun = 0;
223 Double_t ParamFit0 = 0.;
224 Double_t ParamFit1 = 0.;
225 //
226 // variables needed to handle error signals
227 //
228 Int_t code = 0;
229 Int_t sgnl;
230 //
231 // S4 level2 classes
232 //
233 S4Level2 *s4 = new S4Level2();
234 S4Level2 *s4clone = new S4Level2();
235 //
236 // define variables for opening and reading level0 file
237 //
238 TFile *l0File = 0;
239 TTree *l0tr = 0;
240 TBranch *l0head = 0;
241 TBranch *l0S4 =0;
242 pamela::S4::S4Event *l0s4e = 0;
243 pamela::EventHeader *eh = 0;
244 pamela::PscuHeader *ph = 0;
245 //
246 // Define other basic variables
247 //
248 UInt_t procev = 0;
249 stringstream file2;
250 stringstream file3;
251 stringstream qy;
252 Int_t totevent = 0;
253 UInt_t atime = 0;
254 // Int_t ei = 0;
255 UInt_t re = 0;
256 //
257 // Working filename
258 //
259 TString outputfile;
260 stringstream name;
261 name.str("");
262 name << outDir << "/";
263 //
264 // temporary file and folder
265 //
266 TFile *tempfile = 0;
267 TTree *tempS4 = 0;
268 stringstream tempname;
269 stringstream S4folder;
270 Bool_t myfold = false;
271 tempname.str("");
272 tempname << outDir;
273 tempname << "/" << processFolder.Data();
274 S4folder.str("");
275 S4folder << tempname.str().c_str();
276 tempname << "/S4tree_run";
277 tempname << run << ".root";
278 UInt_t totnorun = 0;
279 //
280 // DB classes
281 //
282 GL_ROOT *glroot = new GL_ROOT();
283 GL_TIMESYNC *dbtime = 0;
284 //
285 // Let's start!
286 //
287 // As a first thing we must check what we have to do: if run = 0 we must process all events in the file has been passed
288 // if run != 0 we must process only that run but first we have to check if the tree MyDetector2 already exist in the file
289 // if it exists we are reprocessing data and we must delete that entries, if not we must create it.
290 //
291 if ( run == 0 ) reproc = true;
292 //
293 //
294 // Output file is "outputfile"
295 //
296 if ( !file->IsOpen() ){
297 //printf(" S4 - ERROR: cannot open file for writing\n");
298 throw -501;
299 };
300 //
301 // Retrieve GL_RUN variables from the level2 file
302 //
303 S4version = S4Info(false); // we should decide how to handle versioning system
304 //
305 // create an interface to RunInfo called "runinfo"
306 //
307 runinfo = new ItoRunInfo(file);
308 //
309 // open "Run" tree in level2 file, if not existing return an error (sngl != 0)
310 //
311 sgnl = 0;
312 sgnl = runinfo->Update(run,"S4",S4version);
313 if ( sgnl ){
314 //printf(" S4 - ERROR: RunInfo exited with non-zero status\n");
315 code = sgnl;
316 goto closeandexit;
317 } else {
318 sgnl = 0;
319 };
320 //
321 // number of events in the file BEFORE the first event of our run
322 //
323 nobefrun = runinfo->GetFirstEntry();
324 //
325 // total number of events in the file
326 //
327 totfileentries = runinfo->GetFileEntries();
328 //
329 // first file entry AFTER the last event of our run
330 //
331 noaftrun = runinfo->GetLastEntry() + 1;
332 //
333 // number of run to be processed
334 //
335 numbofrun = runinfo->GetNoRun();
336 totnorun = runinfo->GetRunEntries();
337 //
338 // Try to access the S4 tree in the file, if it exists we are reprocessing data if not we are processing a new run
339 //
340 S4trclone = (TTree*)file->Get("S4");
341 //
342 if ( !S4trclone ){
343 //
344 // tree does not exist, we are not reprocessing
345 //
346 reproc = false;
347 if ( run == 0 ){
348 if (verbose) printf(" S4 - WARNING: you are reprocessing data but S4 tree does not exist!\n");
349 }
350 if ( runinfo->IsReprocessing() && run != 0 ) {
351 if (verbose) printf(" S4 - WARNING: it seems you are not reprocessing data but S4\n versioning information already exists in RunInfo.\n");
352 }
353 } else {
354 //
355 // tree exists, we are reprocessing data. Are we reprocessing a single run or all the file?
356 //
357 S4trclone->SetAutoSave(900000000000000LL);
358 reproc = true;
359 //
360 // update versioning information
361 //
362 if (verbose) printf("\n Preparing the pre-processing...\n");
363 //
364 if ( run == 0 || totnorun == 1 ){
365 //
366 // we are reprocessing all the file
367 // if we are reprocessing everything we don't need to copy any old event and we can just work with the new tree and delete the old one immediately
368 //
369 reprocall = true;
370 //
371 if (verbose) printf("\n S4 - WARNING: Reprocessing all runs\n");
372 //
373 } else {
374 //
375 // we are reprocessing a single run, we must copy to the new tree the events in the file which preceed the first event of the run
376 //
377 reprocall = false;
378 //
379 if (verbose) printf("\n S4 - WARNING: Reprocessing run number %u \n",run);
380 //
381 // copying old tree to a new file
382 //
383 gSystem->MakeDirectory(S4folder.str().c_str());
384 myfold = true;
385 tempfile = new TFile(tempname.str().c_str(),"RECREATE");
386 tempS4 = S4trclone->CloneTree(-1,"fast");
387 tempS4->SetName("S4-old");
388 tempfile->Write();
389 tempfile->Close();
390 }
391 //
392 // Delete the old tree from old file and memory
393 //
394 S4trclone->Delete("all");
395 //
396 if (verbose) printf(" ...done!\n");
397 //
398 };
399 //
400 // create mydetector tree mydect
401 //
402 file->cd();
403 S4tr = new TTree("S4-new","PAMELA Level2 S4 data");
404 S4tr->SetAutoSave(900000000000000LL);
405 S4tr->Branch("S4Level2","S4Level2",&s4);
406 //
407 if ( reproc && !reprocall ){
408 //
409 // open new file and retrieve also tree informations
410 //
411 tempfile = new TFile(tempname.str().c_str(),"READ");
412 S4trclone = (TTree*)tempfile->Get("S4-old");
413 S4trclone->SetAutoSave(900000000000000LL);
414 S4trclone->SetBranchAddress("S4Level2",&s4clone);
415 //
416 if ( nobefrun > 0 ){
417 if (verbose){
418 printf("\n Pre-processing: copying events from the old tree before the processed run\n");
419 printf(" Copying %u events in the file which are before the beginning of the run %u \n",nobefrun,run);
420 printf(" Start copying at event number 0, end copying at event number %u \n",nobefrun);
421 }
422 for (UInt_t j = 0; j < nobefrun; j++){
423 //
424 if ( S4trclone->GetEntry(j) <= 0 ) throw -36;
425 //
426 // copy s4clone to mydec
427 //
428 // s4->Clear();
429 //
430 memcpy(&s4,&s4clone,sizeof(s4clone));
431 //
432 // Fill entry in the new tree
433 //
434 S4tr->Fill();
435 //
436 };
437 if (verbose) printf(" Finished successful copying!\n");
438 };
439 };
440 //
441 // Get the list of run to be processed, if only one run has to be processed the list will contain one entry only.
442 //
443 runlist = runinfo->GetRunList();
444 //
445 // Loop over the run to be processed
446 //
447 for (UInt_t irun=0; irun < numbofrun; irun++){
448 //
449 // retrieve the first run ID to be processed using the RunInfo list
450 //
451 idRun = runlist->At(irun);
452 if (verbose){
453 printf("\n\n\n ####################################################################### \n");
454 printf(" PROCESSING RUN NUMBER %u \n",idRun);
455 printf(" ####################################################################### \n\n\n");
456 }
457 //
458 runinfo->ID_ROOT_L0 = 0;
459 //
460 // store in the runinfo class the GL_RUN variables for our run
461 //
462 sgnl = 0;
463 sgnl = runinfo->GetRunInfo(idRun);
464 if ( sgnl ){
465 if ( debug ) printf(" S4 - ERROR: RunInfo exited with non-zero status\n");
466 code = sgnl;
467 goto closeandexit;
468 } else {
469 sgnl = 0;
470 };
471 //
472 // now you can access that variables using the RunInfo class this way runinfo->ID_ROOT_L0
473 //
474 if ( runinfo->ID_ROOT_L0 == 0 ){
475 if ( debug ) printf("\n S4 - ERROR: no run with ID_RUN = %u \n\n Exiting... \n\n",idRun);
476 code = -5;
477 goto closeandexit;
478 };
479 //
480 // prepare the timesync for the db
481 //
482 TString host = glt->CGetHost();
483 TString user = glt->CGetUser();
484 TString psw = glt->CGetPsw();
485 TSQLServer *dbc = TSQLServer::Connect(host.Data(),user.Data(),psw.Data());
486 if ( !dbc->IsConnected() ) throw -504;
487 stringstream myquery;
488 myquery.str("");
489 myquery << "SET time_zone='+0:00';";
490 delete dbc->Query(myquery.str().c_str());
491 delete dbc->Query("SET sql_mode = 'NO_UNSIGNED_SUBTRACTION';");
492 dbtime = new GL_TIMESYNC(runinfo->ID_ROOT_L0,"ID",dbc);
493 //
494 // Search in the DB the path and name of the LEVEL0 file to be processed.
495 //
496 // if ( !dbc->IsConnected() ) throw -504;
497 glroot->Query_GL_ROOT(runinfo->ID_ROOT_L0,dbc);
498 //
499 ftmpname.str("");
500 ftmpname << glroot->PATH.Data() << "/";
501 ftmpname << glroot->NAME.Data();
502 fname = ftmpname.str().c_str();
503 //
504 // print out informations
505 //
506 totevent = runinfo->NEVENTS;
507 if (verbose){
508 printf("\n LEVEL0 data file: %s \n",fname.Data());
509 printf(" RUN HEADER absolute time is: %u \n",runinfo->RUNHEADER_TIME);
510 printf(" RUN TRAILER absolute time is: %u \n",runinfo->RUNTRAILER_TIME);
511 printf(" %i events to be processed for run %u: from %u to %u \n\n",totevent,idRun,runinfo->EV_FROM,(runinfo->EV_FROM+totevent));
512 }
513 //
514 // if ( !totevent ) goto closeandexit;
515 //
516 // Open Level0 file
517 //
518 if ( l0File ) l0File->Close();
519 l0File = new TFile(fname.Data());
520 if ( !l0File ) {
521 if ( debug ) printf(" S4 - ERROR: problems opening Level0 file\n");
522 code = -6;
523 goto closeandexit;
524 };
525 //
526 l0tr = (TTree*)l0File->Get("Physics");
527 if ( !l0tr ) {
528 if ( debug ) printf(" S4 - ERROR: no Physics tree in Level0 file\n");
529 l0File->Close();
530 code = -7;
531 goto closeandexit;
532 };
533 l0head = l0tr->GetBranch("Header");
534 if ( !l0head ) {
535 if ( debug ) printf(" S4 - ERROR: no Header branch in Level0 tree\n");
536 l0File->Close();
537 code = -8;
538 goto closeandexit;
539 };
540 l0S4 = l0tr->GetBranch("S4");
541 if ( !l0S4 ) {
542 if ( debug ) printf(" S4 - ERROR: no S4 branch in Level0 tree\n");
543 l0File->Close();
544 code = -503;
545 goto closeandexit;
546 };
547 //
548 l0tr->SetBranchAddress("S4", &l0s4e);
549 l0tr->SetBranchAddress("Header", &eh);
550 //
551 nevents = l0S4->GetEntries();
552 //
553 if ( nevents < 1 && totevent ) {
554 if ( debug ) printf(" S4 - ERROR: Level0 file is empty\n\n");
555 l0File->Close();
556 code = -11;
557 goto closeandexit;
558 };
559 //
560 if ( runinfo->EV_TO > nevents-1 && totevent ) {
561 if ( debug ) printf(" S4 - ERROR: too few entries in the S4 tree\n");
562 l0File->Close();
563 code = -12;
564 goto closeandexit;
565 };
566 //
567 // Check if we have to load parameter files (or calibration associated to runs and not to events)
568 // second query: which is the value of paramfit relative to the calibration?
569 //
570 TArrayD *params = 0;
571 params = S4_paramfit(runinfo->RUNHEADER_TIME, dbc);
572 if ( !params ){
573 code = -13;
574 goto closeandexit;
575 };
576 //
577 ParamFit0 = params->At(0);
578 ParamFit1 = params->At(1);
579 //
580 // run over all the events of the run
581 //
582 if (verbose) printf("\n Ready to start! \n\n Processed events: \n\n");
583 //
584 if ( dbc ){
585 dbc->Close();
586 delete dbc;
587 dbc = 0;
588 };
589 //
590 for ( re = runinfo->EV_FROM; re < (runinfo->EV_FROM+runinfo->NEVENTS); re++){
591 //
592 if ( procev%1000 == 0 && procev > 0 && verbose ) printf(" %iK \n",procev/1000);
593 //
594 if ( l0head->GetEntry(re) <= 0 ) throw -36;
595 //
596 // absolute time of this event
597 //
598 ph = eh->GetPscuHeader();
599 atime = dbtime->DBabsTime(ph->GetOrbitalTime());
600 //
601 // paranoid check
602 //
603 if ( (atime > (runinfo->RUNTRAILER_TIME+1)) || (atime < (runinfo->RUNHEADER_TIME-1)) ) {
604 if (verbose) printf(" S4 - WARNING: event at time outside the run time window, skipping it\n");
605 goto jumpev;
606 };
607 //
608 procev++;
609 //
610 // start processing
611 //
612 s4->Clear();
613 if ( l0S4->GetEntry(re) <= 0 ) throw -36;
614 if (l0s4e->unpackError == 0){
615 s4->S4adc = l0s4e->S4_DATA;
616 //
617 if ((l0s4e->S4_DATA) > 31 ){
618 s4->S4calibrated = ParamFit0*((l0s4e->S4_DATA)-32)+ParamFit1;
619 }else{
620 s4->S4calibrated = 0;
621 }
622 };
623 //
624 s4->unpackError = l0s4e->unpackError;
625 //
626 S4tr->Fill();
627 //
628 //
629 jumpev:
630 debug = false;
631 //
632 };
633 //
634 // Here you may want to clear some variables before processing another run
635 //
636 delete dbtime;
637 if ( params ) delete params;
638 //
639 }; // process all the runs
640 //
641 if (verbose) printf("\n Finished processing data \n");
642 //
643 closeandexit:
644 //
645 // we have finished processing the run(s). If we processed a single run now we must copy all the events after our run from the old tree to the new one and delete the old tree.
646 //
647 if ( !reprocall && reproc && code >= 0 ){
648 if ( totfileentries > noaftrun ){
649 if (verbose){
650 printf("\n Post-processing: copying events from the old tree after the processed run\n");
651 printf(" Copying %i events in the file which are after the end of the run %i \n",(int)(totfileentries-noaftrun),(int)run);
652 printf(" Start copying at event number %i end copying at event number %i \n",(int)noaftrun,(int)totfileentries);
653 }
654 for (UInt_t j = noaftrun; j < totfileentries; j++ ){
655 //
656 // Get entry from old tree
657 //
658 if ( S4trclone->GetEntry(j) <= 0 ) throw -36;
659 //
660 // copy s4clone to s4
661 //
662 // s4 = new S4Level2();
663 // s4->Clear();
664 memcpy(&s4,&s4clone,sizeof(s4clone));
665 //
666 // Fill entry in the new tree
667 //
668 S4tr->Fill();
669 };
670 if (verbose) printf(" Finished successful copying!\n");
671 };
672 };
673 //
674 // Close files, delete old tree(s), write and close level2 file
675 //
676 if ( l0File ) l0File->Close();
677 if ( tempfile ) tempfile->Close();
678 if ( myfold) gSystem->Unlink(tempname.str().c_str());
679 //
680 //runinfo->Write();
681 if ( S4tr ) S4tr->SetName("S4");
682 if ( file ){
683 file->cd();
684 if ( S4tr ) S4tr->Write("S4", TObject::kOverwrite); // 10RED bug fixed
685 //file->Write();
686 };
687 //
688 if ( myfold ) gSystem->Unlink(S4folder.str().c_str());
689 //
690 // the end
691 //
692 if (verbose) printf("\n Exiting...\n");
693 //
694 if ( glroot ) delete glroot;
695 if ( runinfo ) runinfo->Close();
696 if ( runinfo ) delete runinfo;
697 //
698 if(code < 0) throw code;
699 return(code);
700 }
701
702

  ViewVC Help
Powered by ViewVC 1.1.23