/[PAMELA software]/chewbacca/YodaProfiler/src/PamelaDBOperations.cpp
ViewVC logotype

Annotation of /chewbacca/YodaProfiler/src/PamelaDBOperations.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.4 - (hide annotations) (download)
Fri Oct 31 11:21:44 2008 UTC (16 years, 1 month ago) by pam-fi
Branch: MAIN
Changes since 1.3: +1543 -514 lines
added tracker calibration recovery from chewbacca ROOT_TABLE

1 mocchiut 1.1 //
2     #include <iomanip>
3     #include <sstream>
4     //
5     #include <iostream>
6     #include <string>
7     #include <fstream>
8     #include <list>
9     #include <errno.h>
10     //
11     #include <TFile.h>
12     #include <TSystem.h>
13     #include <TSQLResult.h>
14     #include <TSQLRow.h>
15     #include <TTree.h>
16     #include <TGraph.h>
17     #include <TTimeStamp.h>
18     #include <TF1.h>
19     //
20     #include <EventHeader.h>
21     #include <PscuHeader.h>
22     #include <mcmd/McmdEvent.h>
23     #include <mcmd/McmdRecord.h>
24     #include <RunHeaderEvent.h>
25     #include <RunTrailerEvent.h>
26     #include <CalibCalPedEvent.h>
27     #include <CalibCalPulse1Event.h>
28     #include <CalibCalPulse2Event.h>
29     #include <CalibS4Event.h>
30     #include <CalibTrk1Event.h>
31     #include <CalibTrk2Event.h>
32     #include <varDump/VarDumpEvent.h>
33     #include <varDump/VarDumpRecord.h>
34     #include <physics/S4/S4Event.h>
35     //
36     #include <sgp4.h>
37    
38     #include <PamelaDBOperations.h>
39     //
40     using namespace std;
41     using namespace pamela;
42    
43     // Some function to work with cTle stuff.
44     bool compTLE(cTle* tle1, cTle *tle2);
45     float getTleJulian(cTle *);
46     string getTleDatetime(cTle*);
47    
48     /**
49     * Constructor.
50     * @param host hostname for the SQL connection.
51     * @param user username for the SQL connection.
52     * @param password password for the SQL connection.
53     * @param filerawname The path and name to the raw file.
54     * @param filerootname The path and name of the raw file.
55     * @param boot file BOOT number.
56     * @param obt0 file obt0.
57     * @param tsync file timesync.
58     * @param debug debug flag.
59     * @param tlefilename ascii file with TLE 3 line elements.
60     */
61     PamelaDBOperations::PamelaDBOperations(TString host, TString user, TString password, TString filerawname, TString filerootname, UInt_t boot, UInt_t tsync, UInt_t obt0, Bool_t debug, TString tlefilename, UInt_t dwinput, Bool_t staticp, Bool_t gpamela){
62     //
63     chewbacca = false;
64     chminentry = 0;
65     chID = 0;
66     if ( filerootname.IsDigit() ){
67     if ( debug ) printf(" => using database to process the file \n");
68     chewbacca = true;
69     chID = (UInt_t)filerootname.Atoll();
70     //
71     // are these really necessary?
72     //
73     staticp = false;
74     INSERT_RAW = false;
75     dwinput = 1;
76     //
77     };
78     //
79     STATIC=false;
80     if ( staticp ) STATIC=true;
81     //
82     SetConnection(host,user,password);
83     //
84     SetDebugFlag(debug);
85     //
86     glrun = new GL_RUN();
87     //
88     if ( !chewbacca ){
89     if ( !boot ) SetNOBOOT(false);
90     SetTsync(tsync,gpamela);
91     SetBOOTnumber(boot,gpamela);
92     SetObt0(obt0);
93     };
94     //
95     SetTLEPath(tlefilename);
96     //
97     //
98     if ( !chewbacca ) INSERT_RAW =!filerawname.IsNull();
99     if (INSERT_RAW) SetRawName(filerawname);
100     //
101     INSERT_ROOT = !filerootname.IsNull();
102     this->SetOrbitNo(dwinput);
103     //
104     this->SetID_RAW(0);
105     this->SetID_ROOT(0);
106    
107     VALIDATE = false;
108    
109     //
110     };
111    
112     /**
113     * Destructor
114     */
115     void PamelaDBOperations::Close(){
116     if( conn && conn->IsConnected() ) conn->Close();
117     delete clean_time;
118     delete glrun;
119     delete this;
120     };
121    
122     //
123     // SETTERS
124     //
125    
126     void PamelaDBOperations::OpenL0File(TString filerootname){
127     if( INSERT_ROOT ){
128     if ( chewbacca ){
129     //
130     // retrieve from the ROOT_TABLE the chewbacca path and filename
131     //
132     stringstream qu;
133     TSQLResult *result = 0;
134     TSQLResult *result2 = 0;
135     TSQLRow *row = 0;
136     TSQLRow *row2 = 0;
137     TString chpath;
138     TString chfile;
139     UInt_t ridn = 0;
140     qu.str("");
141     qu << "SELECT ROOT_ID_N,PKT_NUMBER_INIT,PKT_NUMBER_FINAL,PKT_OBT_INIT,PKT_OBT_FINAL from ROOT_TABLE_MERGING where ID_N=" << chID << ";";
142     if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());
143     result = conn->Query(qu.str().c_str());
144     if ( result ){
145     row = result->Next();
146     if ( row ){
147     ridn = (UInt_t)atoll(row->GetField(0));
148     chpktmin = (UInt_t)atoll(row->GetField(1));
149     chpktmax = (UInt_t)atoll(row->GetField(2));
150     chobtmin = (UInt_t)atoll(row->GetField(3));
151     chobtmax = (UInt_t)atoll(row->GetField(4));
152     } else {
153     throw -84;
154     };
155     } else {
156     throw -84;
157     };
158     delete result;
159     qu.str("");
160     qu << "SELECT FOLDER_NAME,FILE_NAME,OBT_TIME_SYNC,LAST_TIME_SYNC_INFO,TIME_OFFSET,BOOT_NUMBER,PKT_NUMBER_INIT,PKT_NUMBER_FINAL,PKT_OBT_INIT,PKT_OBT_FINAL from ROOT_TABLE where ID_N=" << ridn << ";";
161     if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());
162     result2 = conn->Query(qu.str().c_str());
163     if ( result2 ){
164     row2 = result2->Next();
165     if ( row2 ){
166     chpath = (TString)gSystem->ExpandPathName(row2->GetField(0))+'/';
167     chfile = (TString)(row2->GetField(1));
168     chobtts = (UInt_t)atoll(row2->GetField(2));
169     chlastts = (UInt_t)atoll(row2->GetField(3));
170     chresursts = (UInt_t)atoll(row2->GetField(4));
171     chboot = (UInt_t)atoll(row2->GetField(5));
172     //
173     chpktinit = (UInt_t)atoll(row2->GetField(6));
174     chpktfinal = (UInt_t)atoll(row2->GetField(7));
175     chobtinit = (UInt_t)atoll(row2->GetField(8));
176     chobtfinal = (UInt_t)atoll(row2->GetField(9));
177     //
178     } else {
179     throw -85;
180     };
181     } else {
182     throw -85;
183     };
184     filerootname = chpath + chfile;// + ".root";
185     if ( debug ) printf(" chewbacca: filename is %s \n",filerootname.Data());
186     };
187     this->SetRootName(filerootname);
188     file = TFile::Open(this->GetRootName().Data());
189     } else {
190     this->SetRootName("");
191     };
192     }
193    
194     //
195     // must be out of the constructor in order to FORCE the validation of the latest runs in case you run the validation together with the latest file
196     //
197     void PamelaDBOperations::CheckValidate(Long64_t olderthan){
198     clean_time = new TDatime();
199     //
200     if(olderthan >= 0){
201     VALIDATE = true;
202     UInt_t timelim = 0;
203     timelim = (UInt_t)clean_time->Convert(true) - olderthan;
204     clean_time->Set(timelim,false);
205     };
206     };
207    
208     /**
209     * Open the DB connection
210     * @param host hostname for the SQL connection.
211     * @param user username for the SQL connection.
212     * @param password password for the SQL connection.
213     */
214     void PamelaDBOperations::SetConnection(TString host, TString user, TString password){
215     if ( IsDebug() ) printf(" Connecting using host = %s user = %s password = %s \n",host.Data(),user.Data(),password.Data());
216     conn = TSQLServer::Connect(host.Data(),user.Data(),password.Data());
217     };
218    
219     /**
220     * Store the ID of the ROOT file.
221     * @param idr ID of the ROOT file
222     */
223     void PamelaDBOperations::SetID_ROOT(UInt_t idr){
224     idroot=idr;
225     };
226    
227     /**
228     * Store the ID of the RAW file.
229     * @param idr ID of the RAW file
230     */
231     void PamelaDBOperations::SetID_RAW(UInt_t idr){
232     id=idr;
233     };
234    
235     /**
236     * Set the debug flag
237     *
238     */
239     void PamelaDBOperations::SetDebugFlag(Bool_t dbg){
240     debug = dbg;
241     };
242    
243     /**
244     * Set the autoboot flag
245     *
246     */
247     void PamelaDBOperations::SetAutoBoot(Bool_t dbg){
248     AUTOBOOT = dbg;
249     };
250    
251     /**
252     * Set the pedantic flag
253     *
254     */
255     void PamelaDBOperations::SetPedantic(Bool_t dbg){
256     PEDANTIC = dbg;
257     };
258    
259     /**
260     * Set the nofrag flag
261     *
262     */
263     void PamelaDBOperations::SetNoFrag(Bool_t nf){
264     NOFRAG = nf;
265     };
266    
267     /**
268     * Store the BOOT number of the RAW file.
269     * @param boot BOOT number of the RAW file
270     */
271     void PamelaDBOperations::SetBOOTnumber(UInt_t boot){
272     this->SetBOOTnumber(boot,false);
273     };
274    
275     /**
276     * Store the BOOT number of the RAW file.
277     * @param boot BOOT number of the RAW file
278     */
279     void PamelaDBOperations::SetBOOTnumber(UInt_t boot, Bool_t gpamela){
280     BOOTNO=boot;
281     if ( gpamela ){
282     stringstream oss;
283     TSQLResult *result = 0;
284     TSQLRow *row = 0;
285     if ( !boot ){
286     //
287     BOOTNO = 1;
288     //
289     // look in the DB for the last timesync and the last run
290     //
291     oss.str("");
292     oss << "SELECT BOOT_NUMBER FROM GL_RUN order by RUNHEADER_TIME desc limit 1;";
293     result = conn->Query(oss.str().c_str());
294     if ( result ){
295     row = result->Next();
296     if ( row ){
297     BOOTNO = (UInt_t)atoll(row->GetField(0)) + 1;
298     };
299     };
300     };
301     };
302     };
303    
304     /**
305     * Store the time sync of the RAW file.
306     * @param boot time sync
307     */
308     void PamelaDBOperations::SetTsync(UInt_t ts){
309     this->SetTsync(ts,false);
310     };
311    
312     /**
313     * Store the time sync of the RAW file.
314     * @param boot time sync
315     */
316     void PamelaDBOperations::SetTsync(UInt_t ts, Bool_t gpamela){
317     //
318     // if not gpamela or given tsync file set ts
319     //
320     tsync=ts;
321     if ( gpamela ){
322     stringstream oss;
323     TSQLResult *result = 0;
324     TSQLRow *row = 0;
325     TSQLResult *result2 = 0;
326     TSQLRow *row2 = 0;
327     if ( !ts ){
328     //
329     tsync = 1;
330     //
331     // look in the DB for the last timesync and the last run
332     //
333     oss.str("");
334     oss << "SELECT TIMESYNC FROM GL_TIMESYNC order by TIMESYNC desc limit 1;";
335     result = conn->Query(oss.str().c_str());
336     if ( result ){
337     row = result->Next();
338     if ( row ){
339     tsync = (UInt_t)atoll(row->GetField(0)) + 1;
340     oss.str("");
341     oss << "SELECT (RUNTRAILER_TIME-RUNHEADER_TIME) FROM GL_RUN order by RUNHEADER_TIME desc limit 1;";
342     result2 = conn->Query(oss.str().c_str());
343     if ( result2 ){
344     row2 = result2->Next();
345     if ( row2 ){
346     tsync += (UInt_t)atoll(row2->GetField(0));
347     };
348     }
349     };
350     };
351     };
352     };
353     };
354    
355     /**
356     * Store the time sync of the RAW file.
357     * @param boot time sync
358     */
359     void PamelaDBOperations::SetObt0(UInt_t ts){
360     obt0=ts;
361     };
362    
363     /**
364     * Store the RAW filename.
365     * @param str the RAW filename.
366     */
367     void PamelaDBOperations::SetRawName(TString str){
368     filerawname=str;
369     };
370    
371     /**
372     * Store the ROOT filename.
373     * @param str the ROOT filename.
374     */
375     void PamelaDBOperations::SetRootName(TString str){
376     filerootname=str;
377     };
378    
379     /**
380     * Store the downlink orbit number from filename.
381     */
382     void PamelaDBOperations::SetOrbitNo(UInt_t dwinput){
383     dworbit = 0;
384     //
385     if ( dwinput ){
386     dworbit = dwinput;
387     if ( IsDebug() && !chewbacca ) printf(" Downlink orbit given by hand: %i \n",dworbit);
388     return;
389     };
390     //
391     TString name = this->GetRootFile();
392     Int_t nlength = name.Length();
393     if ( nlength < 5 ) return;
394     TString dwo = 0;
395     for (Int_t i = 0; i<5; i++){
396     dwo.Append(name[i],1);
397     };
398     if ( dwo.IsDigit() ){
399     dworbit = (UInt_t)dwo.Atoi();
400     } else {
401     dwo="";
402     for (Int_t i = 8; i<13; i++){
403     dwo.Append(name[i],1);
404     };
405     if ( dwo.IsDigit() ) dworbit = (UInt_t)dwo.Atoi();
406     };
407     if ( IsDebug() ) printf(" Downlink orbit is %i (dwo = %s) \n",dworbit,dwo.Data());
408     return;
409     };
410    
411    
412    
413     /**
414     * Store the NOBOOT flag.
415     * @param noboot true/false.
416     */
417     void PamelaDBOperations::SetNOBOOT(Bool_t noboot){
418     NOBOOT = noboot;
419     };
420    
421     /**
422     * Store path to the TLE file.
423     */
424     void PamelaDBOperations::SetTLEPath(TString str){
425     tlefilename = str;
426     };
427    
428     TString PamelaDBOperations::GetRawPath(){
429     if ( STATIC ){
430     return((TString)gSystem->DirName(filerawname.Data())+'/');
431     } else {
432     return((TString)gSystem->ExpandPathName("$PAM_RAW")+'/');
433     };
434     };
435    
436     TString PamelaDBOperations::GetRootPath(){
437     if ( STATIC ){
438     return((TString)gSystem->DirName(filerootname.Data())+'/');
439     } else {
440     return((TString)gSystem->ExpandPathName("$PAM_L0")+'/');
441     };
442     };
443    
444     /**
445     * Store the olderthan variable
446     * @param olderthan
447     */
448     // void PamelaDBOperations::SetOlderThan(Long64_t oldthan){
449     // olderthan = oldthan;
450     // };
451    
452     /**
453     * Retrieve the ID_RAW, if exists, returns NULL if does not exist.
454     */
455     Bool_t PamelaDBOperations::SetID_RAW(){
456     stringstream oss;
457     TSQLResult *result = 0;
458     TSQLRow *row = 0;
459     oss.str("");
460     if ( STATIC ){
461     oss << "SELECT ID FROM GL_RAW WHERE "
462     << " PATH = '" << this->GetRawPath().Data() << "' AND "
463     << " NAME = '" << this->GetRawFile().Data() << "' ";
464     } else {
465     oss << "SELECT ID FROM GL_RAW WHERE "
466     << " PATH = '$PAM_RAW' AND "
467     << " NAME = '" << this->GetRawFile().Data() << "' ";
468     }
469     result = conn->Query(oss.str().c_str());
470     if ( result == NULL ) throw -4;
471     row = result->Next();
472     if ( !row ) return(false);
473     id = (UInt_t)atoll(row->GetField(0));
474     delete result;
475     return(true);
476     }
477    
478     /**
479     *
480     * Set the variables which have to be stored in the GL_RUN table and that do not depend on the RUN
481     *
482     */
483     void PamelaDBOperations::SetCommonGLRUN(UInt_t absth, UInt_t abstt){
484     glrun->SetBOOTNUMBER(BOOTNO);
485     glrun->SetRUNHEADER_TIME(absth);
486     glrun->SetRUNTRAILER_TIME(abstt);
487     glrun->SetID_ROOT_L2(0);
488     glrun->SetID_ROOT_L0(idroot);
489     glrun->SetVALIDATION(0);
490     };
491    
492     /**
493 mocchiut 1.2 *
494     * Set the variables which belogns to physendrun tree
495     *
496     */
497     void PamelaDBOperations::SetPhysEndRunVariables(){
498     //
499     //
500     //
501     TTree *T = 0;
502     T = (TTree*)file->Get("PhysEndRun");
503     if ( !T || T->IsZombie() ) throw -90;
504     //
505     PhysEndRunEvent *pher= 0;
506     EventHeader *eh = 0;
507     T->SetBranchAddress("PhysEndRun", &pher);
508     T->SetBranchAddress("Header", &eh);
509     //
510     UInt_t phobt = 0;
511     UInt_t phpkt = 0;
512     //
513     glrun->SetPHYSENDRUN_MASK_S3S2S12(0);
514     glrun->SetPHYSENDRUN_MASK_S11CRC(0);
515     //
516     for (Int_t p=0; p<T->GetEntries(); p++){
517     //
518     T->GetEntry(p);
519     //
520     phobt = (UInt_t)eh->GetPscuHeader()->GetOrbitalTime();
521     phpkt = (UInt_t)eh->GetPscuHeader()->GetCounter();
522     //
523     if ( this->PKT(phpkt) >= this->PKT(glrun->GetRUNHEADER_PKT()) && this->PKT(phpkt) <= this->PKT(glrun->GetRUNTRAILER_PKT()) && this->OBT(phobt) >= this->OBT(glrun->GetRUNHEADER_OBT()) && this->OBT(phobt) <= this->OBT(glrun->GetRUNTRAILER_OBT()) ){
524     if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() || glrun->GetPHYSENDRUN_MASK_S11CRC() ){
525     if ( IsDebug() ) printf(" WARNING while looping in physendrun: found two PhysEndRun packet for the same RUN! \n");
526     if ( IsDebug() ) printf(" Actual values: %X %X New values %X %X \n ",glrun->GetPHYSENDRUN_MASK_S3S2S12(),glrun->GetPHYSENDRUN_MASK_S11CRC(),(UInt_t)pher->TB_ENDRUN.TB_PMT_MASK_S3S2S12,(UInt_t)pher->TB_ENDRUN.TB_PMT_MASK_S11CRC);
527     if ( PEDANTIC && IsDebug() ) printf(" ERROR while looping in physendrun: found two PhysEndRun packet for the same RUN!\n ");
528     if ( PEDANTIC ) throw -91;
529     } else {
530     glrun->SetPHYSENDRUN_MASK_S3S2S12((UInt_t)pher->TB_ENDRUN.TB_PMT_MASK_S3S2S12);
531     glrun->SetPHYSENDRUN_MASK_S11CRC((UInt_t)pher->TB_ENDRUN.TB_PMT_MASK_S11CRC);
532     };
533     };
534     };
535     //
536     };
537    
538     /**
539 mocchiut 1.1 * Patch, look for upper limits to avoid processing retransmitted data
540     */
541     Int_t PamelaDBOperations::SetUpperLimits(){
542     UInt_t nevent = 0;
543     UInt_t pktlast = 0;
544     UInt_t obtlast = 0;
545     Long64_t t_pktlast = 0LL;
546     // UInt_t t_obtlast = 0;
547     Long64_t t_obtlast = 0LL;
548     Long64_t upperpkt2 = 0LL;
549     Long64_t upperobt2 = 0LL;
550     UInt_t zomp = 0;
551     UInt_t jump = 50000; // was 5000
552     EventCounter *code=0;
553     //
554     Long64_t deltapkt = 5000LL;
555     Long64_t deltaobt = 50000LL;
556     //
557     pcksList packetsNames;
558     pcksList::iterator Iter;
559     getPacketsNames(packetsNames);
560     //
561     pktfirst = 0;
562     obtfirst = 0;
563     ppktfirst = 0;
564     pobtfirst = 0;
565     //
566     //
567     //
568     TTree *T = 0;
569     T = (TTree*)file->Get("Physics");
570     if ( !T || T->IsZombie() ) throw -16;
571     EventHeader *eh = 0;
572     PscuHeader *ph = 0;
573     T->SetBranchAddress("Header", &eh);
574     nevent = T->GetEntries();
575     //
576     T->GetEntry(0);
577     ph = eh->GetPscuHeader();
578    
579     if ( chewbacca ){
580     if ( IsDebug() ) printf(" FROM CHEWBACCA: upperpkt %u upperobt %u lowerpkt %u lowerobt %u \n",chpktmax,chobtmax,chpktmin,chobtmin);
581     ppktfirst = chpktmin;
582     pobtfirst = chobtts*1000;
583     } else {
584     //
585     pktfirst = ph->GetCounter();
586     obtfirst = ph->GetOrbitalTime();
587     ppktfirst = pktfirst;
588     pobtfirst = obtfirst; // to be changed AFTER time sync determination this is a profiler bug!
589     };
590     //
591     code = eh->GetCounter();
592     UInt_t en = 0;
593     // if ( !chewbacca ){
594     for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
595     en = code->Get(GetPacketType(*Iter));
596     if ( !strcmp("CalibCalPed",*Iter) || !strcmp("CalibTrk1",*Iter) || !strcmp("CalibTrk2",*Iter) || !strcmp("CalibS4",*Iter) ){
597     if ( IsDebug() ) printf(" We have a calibration before the first physic packet: packet type is %s, entries: %i \n",*Iter,en);
598     //
599     TTree *TC = 0;
600     TC = (TTree*)file->Get("CalibCalPed");
601     if ( !TC || TC->IsZombie() ) throw -16;
602     EventHeader *ehc = 0;
603     PscuHeader *phc = 0;
604     TC->SetBranchAddress("Header", &ehc);
605     TC->GetEntry(0);
606     phc = ehc->GetPscuHeader();
607     pktfirst = phc->GetCounter();
608     obtfirst = phc->GetOrbitalTime();
609     //
610     };
611     };
612     //
613     T->GetEntry(nevent-1);
614     ph = eh->GetPscuHeader();
615     pktlast = ph->GetCounter();
616     obtlast = ph->GetOrbitalTime();
617     //
618     // paranoid check
619     //
620     if ( chewbacca ) {
621     //
622     // query the ROOT_TABLE to find upper and lower limits of the file and compare them to the given interval
623     //
624     if ( IsDebug() ) printf(" Is good if \n");
625     if ( IsDebug() ) printf("PKT(chpktfinal) >= PKT(chpktmax) && PKT(chpktinit) <= PKT(chpktmin) && OBT(chobtfinal) >= OBT(chobtmax) && OBT(chobtinit) <= OBT(chobtmin) \n");
626     if ( IsDebug() ) printf(" %llu >= %llu && %llu <= %llu && %llu >= %llu && %llu <= %llu \n",PKT(chpktfinal),PKT(chpktmax),PKT(chpktinit),PKT(chpktmin),OBT(chobtfinal),OBT(chobtmax),OBT(chobtinit),OBT(chobtmin));
627     if ( PKT(chpktfinal) >= PKT(chpktmax) && PKT(chpktinit) <= PKT(chpktmin) && OBT(chobtfinal) >= OBT(chobtmax) && OBT(chobtinit) <= OBT(chobtmin) ){
628     if ( IsDebug() ) printf(" OK, the file contains the chewbacca interval\n");
629     } else {
630     if ( IsDebug() ) printf(" Bah, the file seems to be the wrong one, the chewbacca interval is not contained in the file... is the DB correctly filled??\n");
631     if ( PEDANTIC ) throw -89;
632     };
633     };
634     //
635     nrtbef = 0;
636     nrtaf = 0;
637     nrtbef = 0;
638     nrtaf = 0;
639     //
640     if ( chewbacca ){
641     pktfirst = chpktmin;
642     obtfirst = chobtmin;
643     pktlast = chpktmax;
644     obtlast = chobtmax;
645     upperpkt = PKT(chpktmax);
646     upperobt = OBT(chobtmax);
647     pktlast = numeric_limits<UInt_t>::max();
648     Int_t it = 0;
649     UInt_t tjump = 50000;
650     //UInt_t tjump = 100;
651     while ( tjump > 0 ){
652     pktlast = numeric_limits<UInt_t>::max();
653     while ( pktlast > chpktmax && (Int_t)(nevent-1-it) >= 0 ){
654     if ( (Int_t)(nevent-1-it) >= 0 ){
655     T->GetEntry(nevent-1-it);
656     ph = eh->GetPscuHeader();
657     pktlast = ph->GetCounter();
658     } else {
659     pktlast = chpktmax + 1;
660     };
661     if ( (!(it%1000) || abs((int)pktlast - (int)chpktmax)<1000 ) && debug ) printf(" look for up %i %i %i nevent %u (nevent-1-it) %i \n",it,pktlast,chpktmax,nevent,(Int_t)(nevent-1-it));
662     it += tjump;
663     };
664     if ( tjump > 1 ) it -= 2*tjump;
665     if ( it < 0 ) it = 0;
666     //
667     if ( debug ) printf(" - look for up %i %i %i nevent %u (nevent-1-it) %i \n",it,pktlast,chpktmax,nevent,(Int_t)(nevent-1-it));
668     if ( debug ) printf(" - up , tjump was %u it was %u \n",tjump,it);
669     if ( tjump == 1 ) tjump = 0;
670     if ( tjump == 10 ) tjump = 1;
671     if ( tjump == 100 ) tjump = 10;
672     if ( tjump == 1000 ) tjump = 100;
673     if ( tjump == 5000 ) tjump = 1000;
674     if ( tjump == 50000 ) tjump = 5000;
675     //
676     };
677     Int_t tupperentry = (Int_t)nevent-1-(Int_t)it+1;//+1+1;
678     if ( tupperentry < 0 ) tupperentry = 0;
679     upperentry = tupperentry;
680     it = 0;
681     pktlast = 0;
682     tjump = 50000;
683     //tjump = 100;
684     while ( tjump > 0 ){
685     pktlast = 0;
686     while ( pktlast < chpktmin && it < (Int_t)nevent ){
687     if ( it < (Int_t)nevent ){
688     T->GetEntry(it);
689     ph = eh->GetPscuHeader();
690     pktlast = ph->GetCounter();
691     } else {
692     // pktlast = chpktmax - 1;
693     pktlast = chpktmin - 1;
694     };
695     if ( !(it%1000) && debug ) printf("look for down %i %i %i \n",it,pktlast,chpktmin);
696     it += tjump;
697     };
698     if ( tjump > 1 ) it -= 2*tjump;
699     if ( it < 0 ) it = 0;
700     //
701     if ( debug ) printf(" down , tjump was %u it was %u \n",tjump,it);
702     if ( tjump == 1 ) tjump = 0;
703     if ( tjump == 10 ) tjump = 1;
704     if ( tjump == 100 ) tjump = 10;
705     if ( tjump == 1000 ) tjump = 100;
706     if ( tjump == 5000 ) tjump = 1000;
707     if ( tjump == 50000 ) tjump = 5000;
708     //
709     };
710     Int_t tchminentry = (Int_t)it-1;//-1+1;
711     if ( tchminentry < 0 ) tchminentry = 0;
712     chminentry = tchminentry;
713     //
714     if ( debug ) printf(" Chewbacca: chminentry %i chmaxentry %i delta %i nevent %i \n",chminentry,upperentry,upperentry-chminentry,nevent);
715     //
716     //
717     //
718     TTree *rh=(TTree*)file->Get("RunHeader");
719     if ( !rh || rh->IsZombie() ) throw -17;
720     TTree *rt=(TTree*)file->Get("RunTrailer");
721     if ( !rt || rt->IsZombie() ) throw -18;
722     //
723     rh->SetBranchAddress("RunHeader", &runh);
724     rh->SetBranchAddress("Header", &ehh);
725     //
726     rt->SetBranchAddress("RunTrailer", &runt);
727     rt->SetBranchAddress("Header", &eht);
728     //
729     rhev = rh->GetEntries();
730     rtev = rt->GetEntries();
731     //
732     if ( IsDebug() ){
733     for (Int_t rr=0; rr<rh->GetEntries(); rr++){
734     rh->GetEntry(rr);
735     phh = ehh->GetPscuHeader();
736     printf(" RUNHEADER %i OBT %u PKT %u \n",rr,phh->GetOrbitalTime(),phh->GetCounter());
737     };
738     for (Int_t rr=0; rr<rt->GetEntries(); rr++){
739     rt->GetEntry(rr);
740     pht = eht->GetPscuHeader();
741     printf(" RUNTRAILER %i OBT %u PKT %u \n",rr,pht->GetOrbitalTime(),pht->GetCounter());
742     };
743     };
744     //
745     nrhev = 0;
746     nrhbef = 0;
747     nrhaf = 0;
748     for (Int_t rr=0; rr<rh->GetEntries(); rr++){
749     rh->GetEntry(rr);
750     phh = ehh->GetPscuHeader();
751     if ( debug ) printf(" RRRRRRR %llu %llu %llu %llu %llu %llu \n",PKT(phh->GetCounter()),PKT(pktfirst),upperpkt,OBT(obtfirst),OBT(phh->GetOrbitalTime()),upperobt);
752     if ( PKT(phh->GetCounter()) >= PKT(pktfirst) && PKT(phh->GetCounter()) <= upperpkt && OBT(phh->GetOrbitalTime()) >= OBT(obtfirst) && OBT(phh->GetOrbitalTime()) <= upperobt ){
753     nrhev++;
754     if ( debug ) printf(" ++++ RH %i \n",nrhev);
755     };
756     if ( !nrhev ) nrhbef++;
757     if ( (nrhev && (nrhev+1+nrhbef+1) == rr) || nrhaf ) nrhaf++;
758     };
759     nrtev = 0;
760     nrtbef = 0;
761     nrtaf = 0;
762     for (Int_t rr=0; rr<rt->GetEntries(); rr++){
763     rt->GetEntry(rr);
764     pht = eht->GetPscuHeader();
765     if ( debug ) printf(" TTTTTTT %llu %llu %llu %llu %llu %llu \n",PKT(pht->GetCounter()),PKT(pktfirst),upperpkt,OBT(obtfirst),OBT(pht->GetOrbitalTime()),upperobt);
766     if ( PKT(pht->GetCounter()) >= PKT(pktfirst) && PKT(pht->GetCounter()) <= upperpkt && OBT(pht->GetOrbitalTime()) >= OBT(obtfirst) && OBT(pht->GetOrbitalTime()) <= upperobt ){
767     nrtev++;
768     if ( debug ) printf(" ++++ RT %i \n",nrtev);
769     };
770     if ( !nrtev ) nrtbef++;
771     if ( (nrtev && (nrtev+1+nrtbef+1) == rr) || nrtaf ) nrtaf++;
772     };
773     if ( debug ) printf(" NUMBER OF RH %i RT %i IN THE INTERVAL, NUMBER OF TOTAL RH %i RT %i \n",nrhev,nrtev,rhev,rtev);
774     if ( debug ) printf(" RH before %i RH after %i -- RT before %i RT after %i \n",nrhbef,nrhaf,nrtbef,nrtaf);
775     //
776     T->GetEntry(upperentry);
777     ph = eh->GetPscuHeader();
778     pktlast = ph->GetCounter();
779     nevent = upperentry - chminentry;
780     //
781     } else {
782     upperpkt = PKT(pktlast);
783     upperobt = OBT(obtlast);
784     upperentry = nevent-1;
785     };
786     //
787     if ( chewbacca && nevent < 1 ) {
788 mocchiut 1.2 pktfirst = chpktmin;
789     upperpkt = PKT(chpktmax);
790     pktlast = chpktmax;
791     obtfirst = chobtmin;
792     obtlast = chobtmax;
793     upperobt = OBT(chobtmax);
794 mocchiut 1.1 };
795     //
796     if ( IsDebug() ) printf(" First entries are: OBT %u pkt_num %u entry %i\n",obtfirst,pktfirst,chminentry);
797     //
798     if ( IsDebug() ) printf(" Last entries are: OBT %lld pkt_num %lld entry %i\n",upperobt,upperpkt,upperentry);
799     //
800     if ( (PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) > OBT(obtfirst)) || (PKT(pktlast) > PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) ){
801 mocchiut 1.2 if ( IsDebug() ) printf(" Inconsistent PKT/OBT sequence: \n (PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) > OBT(obtfirst)) %llu < %llu && %llu > %llu \n OR \n (PKT(pktlast) > PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) %llu > %llu && %llu < %llu \n",PKT(pktlast),PKT(pktfirst),OBT(obtlast),OBT(obtfirst),PKT(pktlast),PKT(pktfirst),OBT(obtlast),OBT(obtfirst));
802     if ( PEDANTIC ) throw -88;
803     return(32);
804 mocchiut 1.1 };
805     //
806     if ( !nevent ) return(64);
807     //
808     if ( nevent < 2 ) return(128);
809     if ( nevent < jump ) jump = 1;
810     // if ( nevent < jump ) jump = int(nevent/10);
811     // if ( !jump ) jump = 1;
812     //
813     if ( (PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) || (labs(PKT(pktlast)-PKT(pktfirst))<deltapkt && labs(OBT(obtlast)-OBT(obtfirst))<deltaobt) && nevent > deltapkt ){
814     //
815     if ( IsDebug() ) printf(" starting jump %i \n",jump);
816     // if ( IsDebug() ) printf(" (PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) > OBT(obtfirst)) %llu < %llu && %llu > %llu \n OR \n (PKT(pktlast) > PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) %llu > %llu && %llu < %llu \n",PKT(pktlast),PKT(pktfirst),OBT(obtlast),OBT(obtfirst),PKT(pktlast),PKT(pktfirst),OBT(obtlast),OBT(obtfirst));
817     if ( IsDebug() ) printf(" labs(PKT(pktlast)-PKT(pktfirst) %lu < deltapkt %lld && labs(OBT(obtlast)-OBT(obtfirst)) %lu <deltaobt %lld && nevent %u > deltapkt %lld \n",(labs(PKT(pktlast)-PKT(pktfirst))),deltapkt, labs(OBT(obtlast)-OBT(obtfirst)),deltaobt, nevent, deltapkt);
818     if ( PEDANTIC ) throw -66;
819     // go back
820     zomp = nevent - 2;
821     //
822     while ( jump > 0 ){
823     //
824     t_pktlast = PKT(pktlast);
825     t_obtlast = OBT(obtlast);
826     //
827     for (UInt_t i = zomp; i>1; i-=jump){
828     //
829     if ( i >= 0 ) T->GetEntry(i);
830     ph = eh->GetPscuHeader();
831     upperpkt = PKT(ph->GetCounter());
832     upperobt = OBT(ph->GetOrbitalTime());
833     upperentry = i;
834     //
835     if ( (i-1) >= 0 ) T->GetEntry(i-1);
836     ph = eh->GetPscuHeader();
837     upperpkt2 = PKT(ph->GetCounter());
838     upperobt2 = OBT(ph->GetOrbitalTime());
839     //
840     if ( (t_pktlast < upperpkt && t_obtlast > upperobt) || (t_pktlast < upperpkt2 && t_obtlast > upperobt2) ){
841     if ( IsDebug() ) printf(" .-. upperpkt2 %lld upperobt2 %lld \n",upperpkt2,upperobt2);
842     if ( IsDebug() ) printf(" .-. upperpkt %lld t_pktlast %lld upperobt %lld t_obtlast %lld \n",upperpkt,t_pktlast,upperobt,t_obtlast);
843     if ( IsDebug() ) printf(" .-. jump %i zomp %i upperpkt %lld pktlast %u upperobt %lld obtlast %u last entry is %i \n",jump,zomp,upperpkt,pktlast,upperobt,obtlast,i);
844     throw -13;
845     };
846     //
847     if ( t_pktlast < upperpkt && t_obtlast < upperobt && t_pktlast < upperpkt2 && t_obtlast < upperobt2 ){
848     zomp = i + jump + 1;
849     if ( zomp > nevent-2 ) zomp = nevent - 2;
850     if ( IsDebug() ) printf(" .-. jump %i zomp %i upperpkt %lld pktlast %u upperobt %lld obtlast %u last entry is %i \n",jump,zomp,upperpkt,pktlast,upperobt,obtlast,i);
851     break;
852     };
853     //
854     t_pktlast = upperpkt;
855     t_obtlast = upperobt;
856     };
857     //
858     if ( jump == 1 ) jump = 0;
859     if ( jump == 10 ) jump = 1;
860     if ( jump == 100 ) jump = 10;
861     if ( jump == 1000 ) jump = 100;
862     if ( jump == 5000 ) jump = 1000;
863     if ( jump == 50000 ) jump = 5000;
864     //
865     };
866     //
867     };
868     //
869     // check if last runtrailer is within limits, if not extend limits (one should check for all packets but we need only runtrailer)
870     //
871     if ( !chewbacca ){
872     PacketType *pctp=0;
873     TTree *rh=(TTree*)file->Get("RunHeader");
874     if ( !rh || rh->IsZombie() ) throw -17;
875     TTree *rt=(TTree*)file->Get("RunTrailer");
876     if ( !rt || rt->IsZombie() ) throw -18;
877     //
878     rh->SetBranchAddress("RunHeader", &runh);
879     rh->SetBranchAddress("Header", &ehh);
880     //
881     rt->SetBranchAddress("RunTrailer", &runt);
882     rt->SetBranchAddress("Header", &eht);
883     //
884     rhev = rh->GetEntries();
885     rtev = rt->GetEntries();
886     Long64_t sobtt = 0LL;
887     Long64_t sobth = 0LL;
888     Long64_t spktt = 0LL;
889     Long64_t spkth = 0LL;
890     Long64_t pktt = 0LL;
891     Long64_t obtt = 0LL;
892     Long64_t pkth = 0LL;
893     Long64_t obth = 0LL;
894     //
895     if ( rhev || rtev ){
896    
897     T->GetEntry(upperentry);
898     code = eh->GetCounter();
899     Int_t lasttrail = code->Get(pctp->RunTrailer);
900     Int_t lasthead = code->Get(pctp->RunHeader);
901     if ( lasttrail < rtev ){
902     rt->GetEntry(lasttrail);
903     pht = eht->GetPscuHeader();
904     pktt = PKT(pht->GetCounter());
905     obtt = OBT(pht->GetOrbitalTime());
906     };
907     //
908     if ( lasthead < rhev ){
909     rh->GetEntry(lasthead);
910     phh = ehh->GetPscuHeader();
911     pkth = PKT(phh->GetCounter());
912     obth = OBT(phh->GetOrbitalTime());
913     };
914     //
915     if ( IsDebug() ) printf(" rhev before %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
916     if ( pkth > upperpkt && obth > upperobt ){
917     if ( IsDebug() ) printf(" Upper limits extended to include last header: ph %lld upperp %lld oh %lld uppero %lld \n",pkth,upperpkt,obth,upperobt);
918     upperpkt = pkth;
919     upperobt = obth;
920     rhev = lasthead+1;
921     } else {
922     rhev = lasthead;
923     };
924     if ( IsDebug() ) printf(" rhev after %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
925     //
926     if ( IsDebug() ) printf(" rtev beforev %i pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
927     if ( pktt > upperpkt && obtt > upperobt ){
928     if ( IsDebug() ) printf(" Upper limits extended to include last trailer: pt %lld upperp %lld ot %lld uppero %lld \n",pktt,upperpkt,obtt,upperobt);
929     upperpkt = pktt;
930     upperobt = obtt;
931     rtev = lasttrail+1;
932     } else {
933     rtev = lasttrail;
934     };
935     if ( IsDebug() ) printf(" rtev after %i pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
936     // goto kikko;
937     //
938     //
939     // Check if runtrailer/runheader are within lower limits
940     //
941     //
942     pkth = 0LL;
943     obth = 0LL;
944     spkth = 0LL;
945     sobth = 0LL;
946     for (Int_t k=0; k<rhev; k++){
947     if ( k > 0 ){
948     spkth = pkth;
949     sobth = obth;
950     };
951     rh->GetEntry(k);
952     phh = ehh->GetPscuHeader();
953     pkth = PKT(phh->GetCounter());
954     obth = OBT(phh->GetOrbitalTime());
955     //
956     // if ( IsDebug() ) printf(" k %i rhev before %i ph %u upperp %u oh %u uppero %u \n",k,rhev,pkth,spkth,obth,sobth);
957     //
958     if ( pkth < spkth && obth < sobth ){
959     if ( IsDebug() ) printf(" RH PROBLEMS determining the event repetition at the end of the file lasthead %i \n",rhev);
960     if ( PEDANTIC ) throw -66;
961     //
962     rhev = k-1;
963     rh->GetEntry(rhev);
964     pkth = spkth;
965     obth = sobth;
966     //
967     UInt_t evbefh = 0;
968     code = ehh->GetCounter();
969     evbefh = code->Get(pctp->Physics);
970     if ( evbefh >= 0 ){
971     T->GetEntry(evbefh);
972     ph = eh->GetPscuHeader();
973     t_pktlast = PKT(ph->GetCounter());
974     t_obtlast = OBT(ph->GetOrbitalTime());
975     if ( t_pktlast <= spkth && t_obtlast <= sobth ){ // jump
976     upperpkt = pkth;
977     upperobt = obth;
978     upperentry = evbefh-1;
979     } else {
980     while ( t_pktlast > spkth && t_obtlast > sobth && evbefh < nevent ){
981     evbefh++;
982     T->GetEntry(evbefh);
983     ph = eh->GetPscuHeader();
984     t_pktlast = PKT(ph->GetCounter());
985     t_obtlast = OBT(ph->GetOrbitalTime());
986     };
987     T->GetEntry(evbefh-1);
988     ph = eh->GetPscuHeader();
989     upperpkt = PKT(ph->GetCounter());
990     upperobt = OBT(ph->GetOrbitalTime());
991     upperentry = evbefh-1;
992     };
993     };
994     if ( IsDebug() ) printf(" rhev after %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
995     goto kikko0;
996     };
997     };
998     kikko0:
999     //
1000     //
1001     //
1002     pktt = 0LL;
1003     obtt = 0LL;
1004     spktt = 0LL;
1005     sobtt = 0LL;
1006     for (Int_t k=0; k<rtev; k++){
1007     if ( k > 0 ){
1008     spktt = pktt;
1009     sobtt = obtt;
1010     };
1011     rt->GetEntry(k);
1012     pht = eht->GetPscuHeader();
1013     pktt = PKT(pht->GetCounter());
1014     obtt = OBT(pht->GetOrbitalTime());
1015     //
1016     // if ( IsDebug() ) printf(" k %i rtev beforev %i pt %i upperp %i ot %llu uppero %llu \n",k,rtev,pktt,spktt,obtt,sobtt);
1017     //
1018     if ( pktt < spktt && obtt < sobtt ){
1019     if ( IsDebug() ) printf(" RT PROBLEMS determining the event repetition at the end of the file lasttrail %i \n",rtev);
1020     if ( PEDANTIC ) throw -66;
1021     //
1022     rtev = k-1;
1023     rt->GetEntry(rtev);
1024     pktt = spktt;
1025     obtt = sobtt;
1026     if ( IsDebug() ) printf(" lasttrail %i pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
1027     //
1028     UInt_t evbeft = 0;
1029     code = eht->GetCounter();
1030     evbeft = code->Get(pctp->Physics);
1031     if ( evbeft >= 0 ){
1032     T->GetEntry(evbeft);
1033     ph = eh->GetPscuHeader();
1034     t_pktlast = PKT(ph->GetCounter());
1035     t_obtlast = OBT(ph->GetOrbitalTime());
1036     if ( t_pktlast <= spktt && t_obtlast <= sobtt ){ // jump
1037     upperpkt = pktt;
1038     upperobt = obtt;
1039     upperentry = evbeft-1;
1040     } else {
1041     while ( t_pktlast > spktt && t_obtlast > sobtt && evbeft < nevent ){
1042     evbeft++;
1043     T->GetEntry(evbeft);
1044     ph = eh->GetPscuHeader();
1045     t_pktlast = PKT(ph->GetCounter());
1046     t_obtlast = OBT(ph->GetOrbitalTime());
1047     };
1048     T->GetEntry(evbeft-1);
1049     ph = eh->GetPscuHeader();
1050     upperpkt = PKT(ph->GetCounter());
1051     upperobt = OBT(ph->GetOrbitalTime());
1052     upperentry = evbeft-1;
1053     };
1054     };
1055     if ( IsDebug() ) printf(" rtev after %i pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
1056     goto kikko;
1057     // break;
1058     //
1059     };
1060     //
1061     };
1062     //
1063     kikko:
1064     //
1065     T->GetEntry(upperentry);
1066     code = eh->GetCounter();
1067     lasttrail = code->Get(pctp->RunTrailer);
1068     lasthead = code->Get(pctp->RunHeader);
1069     if ( lasttrail < rtev ){
1070     rt->GetEntry(lasttrail);
1071     pht = eht->GetPscuHeader();
1072     pktt = PKT(pht->GetCounter());
1073     obtt = OBT(pht->GetOrbitalTime());
1074     };
1075     //
1076     if ( lasthead < rhev ){
1077     rh->GetEntry(lasthead);
1078     phh = ehh->GetPscuHeader();
1079     pkth = PKT(phh->GetCounter());
1080     obth = OBT(phh->GetOrbitalTime());
1081     };
1082     //
1083     if ( IsDebug() ) printf(" rhev before %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
1084     if ( pkth > upperpkt && obth > upperobt ){
1085     if ( IsDebug() ) printf(" Upper limits extended to include last header: ph %lld upperp %lld oh %lld uppero %lld \n",pkth,upperpkt,obth,upperobt);
1086     upperpkt = pkth;
1087     upperobt = obth;
1088     rhev = lasthead+1;
1089 mocchiut 1.2 } else {
1090 mocchiut 1.1 rhev = lasthead;
1091     };
1092     if ( IsDebug() ) printf(" rhev after %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
1093     //
1094     if ( IsDebug() ) printf(" rtev beforev %i pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
1095     if ( pktt > upperpkt && obtt > upperobt ){
1096     if ( IsDebug() ) printf(" Upper limits extended to include last trailer: pt %lld upperp %lld ot %lld uppero %lld \n",pktt,upperpkt,obtt,upperobt);
1097     upperpkt = pktt;
1098     upperobt = obtt;
1099     rtev = lasttrail+1;
1100     } else {
1101     rtev = lasttrail;
1102     };
1103     if ( IsDebug() ) printf(" rtev after %i pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
1104     //
1105     };
1106     };
1107     //
1108     if ( IsDebug() ) printf(" Upper limits are: OBT %lld pkt_num %lld upper entry %i \n",upperobt,upperpkt,upperentry);
1109     //
1110     return(0);
1111     }
1112    
1113     /**
1114     *
1115     * Trick to have unique RUN ID numbers even when runs are deleted and mysql deamon restarted.
1116     * Entries in the _RUNID_GEN table are never deleted.
1117     *
1118     **/
1119     UInt_t PamelaDBOperations::AssignRunID(){
1120     //
1121     TSQLResult *result = 0;
1122     TSQLRow *row = 0;
1123     UInt_t runid = 0;
1124     //
1125     stringstream oss;
1126     //
1127     oss.str("");
1128     oss << "INSERT INTO _RUNID_GEN VALUES (NULL);";
1129     result = conn->Query(oss.str().c_str());
1130     if ( !result ) throw -10;
1131     oss.str("");
1132     oss << "SELECT ID FROM _RUNID_GEN ORDER BY ID DESC LIMIT 1;";
1133     result = conn->Query(oss.str().c_str());
1134     if ( !result ) throw -10;
1135     //
1136     row = result->Next();
1137     //
1138     if ( !row ) throw -28;
1139     //
1140     runid = (UInt_t)atoll(row->GetField(0));
1141     //
1142     return(runid);
1143     };
1144    
1145     //
1146     // GETTERS
1147     //
1148    
1149     /**
1150     *
1151     * Returns the DB absolute time needed to associate calibrations to data
1152     *
1153     */
1154     UInt_t PamelaDBOperations::GetAbsTime(UInt_t obt){
1155     //
1156     return(((UInt_t)(OBT(obt)/1000)+toffset));
1157     //
1158     };
1159    
1160     /**
1161     *
1162     * List of packet types (just to make easily the loops)
1163     *
1164     */
1165     const PacketType* PamelaDBOperations::GetPacketType(const char* type){
1166     if ( !strcmp(type,"Pscu") ) return(PacketType::Pscu);
1167     if ( !strcmp(type,"PhysEndRun") ) return(PacketType::PhysEndRun);
1168     if ( !strcmp(type,"CalibCalPulse1") ) return(PacketType::CalibCalPulse1);
1169     if ( !strcmp(type,"CalibCalPulse2") ) return(PacketType::CalibCalPulse2);
1170     if ( !strcmp(type,"Physics") ) return(PacketType::Physics);
1171     if ( !strcmp(type,"CalibTrkBoth") ) return(PacketType::CalibTrkBoth);
1172     if ( !strcmp(type,"CalibTrk1") ) return(PacketType::CalibTrk1);
1173     if ( !strcmp(type,"CalibTrk2") ) return(PacketType::CalibTrk2);
1174     if ( !strcmp(type,"CalibTof") ) return(PacketType::CalibTof);
1175     if ( !strcmp(type,"CalibS4") ) return(PacketType::CalibS4);
1176     if ( !strcmp(type,"CalibCalPed") ) return(PacketType::CalibCalPed);
1177     if ( !strcmp(type,"Calib1_Ac1") ) return(PacketType::Calib1_Ac1);
1178     if ( !strcmp(type,"Calib2_Ac1") ) return(PacketType::Calib2_Ac1);
1179     if ( !strcmp(type,"Calib1_Ac2") ) return(PacketType::Calib1_Ac2);
1180     if ( !strcmp(type,"Calib2_Ac2") ) return(PacketType::Calib2_Ac2);
1181     if ( !strcmp(type,"CalibCal") ) return(PacketType::CalibCal);
1182     if ( !strcmp(type,"RunHeader") ) return(PacketType::RunHeader);
1183     if ( !strcmp(type,"RunTrailer") ) return(PacketType::RunTrailer);
1184     if ( !strcmp(type,"CalibHeader") ) return(PacketType::CalibHeader);
1185     if ( !strcmp(type,"CalibTrailer") ) return(PacketType::CalibTrailer);
1186     if ( !strcmp(type,"InitHeader") ) return(PacketType::InitHeader);
1187     if ( !strcmp(type,"InitTrailer") ) return(PacketType::InitTrailer);
1188     if ( !strcmp(type,"EventTrk") ) return(PacketType::EventTrk);
1189     if ( !strcmp(type,"Log") ) return(PacketType::Log);
1190     if ( !strcmp(type,"VarDump") ) return(PacketType::VarDump);
1191     if ( !strcmp(type,"ArrDump") ) return(PacketType::ArrDump);
1192     if ( !strcmp(type,"TabDump") ) return(PacketType::TabDump);
1193     if ( !strcmp(type,"Tmtc") ) return(PacketType::Tmtc);
1194     if ( !strcmp(type,"Mcmd") ) return(PacketType::Mcmd);
1195     if ( !strcmp(type,"ForcedFECmd") ) return(PacketType::ForcedFECmd);
1196     if ( !strcmp(type,"Ac1Init") ) return(PacketType::Ac1Init);
1197     if ( !strcmp(type,"CalInit") ) return(PacketType::CalInit);
1198     if ( !strcmp(type,"TrkInit") ) return(PacketType::TrkInit);
1199     if ( !strcmp(type,"TofInit") ) return(PacketType::TofInit);
1200     if ( !strcmp(type,"TrgInit") ) return(PacketType::TrgInit);
1201     if ( !strcmp(type,"NdInit") ) return(PacketType::NdInit);
1202     if ( !strcmp(type,"S4Init") ) return(PacketType::S4Init);
1203     if ( !strcmp(type,"Ac2Init") ) return(PacketType::Ac2Init);
1204     if ( !strcmp(type,"CalAlarm") ) return(PacketType::CalAlarm);
1205     if ( !strcmp(type,"Ac1Alarm") ) return(PacketType::Ac1Alarm);
1206     if ( !strcmp(type,"TrkAlarm") ) return(PacketType::TrkAlarm);
1207     if ( !strcmp(type,"TrgAlarm") ) return(PacketType::TrgAlarm);
1208     if ( !strcmp(type,"TofAlarm") ) return(PacketType::TofAlarm);
1209     if ( !strcmp(type,"S4Alarm") ) return(PacketType::S4Alarm);
1210     if ( !strcmp(type,"Ac2Alarm") ) return(PacketType::Ac2Alarm);
1211     if ( !strcmp(type,"TsbT") ) return(PacketType::TsbT);
1212     if ( !strcmp(type,"TsbB") ) return(PacketType::TsbB);
1213     return(PacketType::Invalid);
1214     };
1215    
1216     //
1217     // PRIVATE FUNCTIONS
1218     //
1219    
1220     // /**
1221     // * Open the ROOT filename for reading
1222     // */
1223     // void PamelaDBOperations::OpenFile(){
1224     // file = TFile::Open(this->GetRootName().Data());
1225     // //
1226    
1227     void PamelaDBOperations::CheckFile(){
1228     if ( !file ) throw -12;
1229     };
1230    
1231    
1232     /**
1233     * Check if LEVEL0 file and DB connection have really be opened
1234     */
1235     void PamelaDBOperations::CheckConnection(){
1236     //
1237     // check connection
1238     //
1239     if( !conn ) throw -1;
1240     bool connect = conn->IsConnected();
1241     if( !connect ) throw -1;
1242     //
1243     if ( IsDebug() ) printf("\n DB INFORMATIONS:\n SQL: %s Version: %s Host %s Port %i \n\n",conn->GetDBMS(),conn->ServerInfo(),conn->GetHost(),conn->GetPort());
1244     //
1245     if ( !dworbit && strcmp(this->GetRootName().Data(),"") ) throw -27;
1246     //
1247     // set DB timezone to UTC
1248     //
1249     stringstream oss;
1250     //
1251     oss.str("");
1252     oss << "SET time_zone='+0:00';";
1253     TSQLResult *result = 0;
1254     result = conn->Query(oss.str().c_str());
1255     if ( !result ) throw -10;
1256     oss.str("");
1257     oss << "SET wait_timeout=173000;";
1258     conn->Query(oss.str().c_str());
1259     //
1260     }
1261    
1262     /**
1263     * Lock tables
1264     */
1265     void PamelaDBOperations::LockTables(){
1266     //
1267     // check connection
1268     //
1269     if( !conn ) throw -1;
1270     bool connect = conn->IsConnected();
1271     if( !connect ) throw -1;
1272     //
1273     stringstream oss;
1274     //
1275     oss.str("");
1276 pam-fi 1.4 oss << "lock table GL_RUN write, GL_ROOT write, GL_RAW write, GL_TIMESYNC write, GL_RESURS_OFFSET write, GL_PARAM write, GL_TLE write, GL_RUN_FRAGMENTS write, GL_RUN_TRASH write, GL_CALO_CALIB write, GL_CALOPULSE_CALIB write, GL_TRK_CALIB write, GL_S4_CALIB write, ROOT_TABLE_MERGING write, ROOT_TABLE_BAD write, ROOT_TABLE write, _RUNID_GEN write;";
1277 mocchiut 1.1 TSQLResult *result = 0;
1278     result = conn->Query(oss.str().c_str());
1279     if ( !result ) throw -10;
1280     //
1281     }
1282    
1283     /**
1284     * Lock tables
1285     */
1286     void PamelaDBOperations::UnLockTables(){
1287     //
1288     // check connection
1289     //
1290     if( !conn ) throw -1;
1291     bool connect = conn->IsConnected();
1292     if( !connect ) throw -1;
1293     //
1294     stringstream oss;
1295     //
1296     oss.str("");
1297     oss << "unlock tables;";
1298     TSQLResult *result = 0;
1299     result = conn->Query(oss.str().c_str());
1300     if ( !result ) throw -10;
1301     //
1302     }
1303    
1304     /**
1305     * Return the correct packet number if we went back to zero
1306     */
1307     Long64_t PamelaDBOperations::PKT(UInt_t pkt_num){
1308     //
1309 mocchiut 1.2 // if ( IsDebug() ) printf(" pkt conversion: pkt_num is %u pktfirst is %u (UInt_t)(16777214/2)) is %u \n",pkt_num,ppktfirst,(UInt_t)(16777214/2));
1310 mocchiut 1.1 //
1311     if ( pkt_num < (ppktfirst/2) && ppktfirst > (16777214/2) ){
1312 mocchiut 1.2 // if ( IsDebug() ) printf(" rise up pktnum %lld \n",(Long64_t)pkt_num+16777215LL);
1313 mocchiut 1.1 return((Long64_t)pkt_num+16777215LL);
1314     };
1315     //
1316     if ( pkt_num > ((Long64_t)ppktfirst*2) && pkt_num > (16777214/2) ){
1317 mocchiut 1.2 // if ( IsDebug() ) printf(" rise down pktnum %lld \n",(Long64_t)pkt_num-16777215LL);
1318 mocchiut 1.1 return((Long64_t)pkt_num-16777215LL);
1319     };
1320     //
1321 mocchiut 1.2 // if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)pkt_num);
1322 mocchiut 1.1 return((Long64_t)pkt_num);
1323     //
1324     };
1325    
1326     /**
1327     * Return the correct On Board Time if we went back to zero
1328     */
1329     Long64_t PamelaDBOperations::OBT(UInt_t obt){
1330     //
1331 mocchiut 1.2 // if ( IsDebug() ) printf(" obt conversion: obt is %u obtfirst is %u (numeric_limits<UInt_t>::max()/2) is %u \n",obt,pobtfirst,(UInt_t)(numeric_limits<UInt_t>::max()/2));
1332 mocchiut 1.1 //
1333     if ( obt < (pobtfirst/2) && pobtfirst > (numeric_limits<UInt_t>::max()/2) ){
1334 mocchiut 1.2 // if ( IsDebug() ) printf(" rise up obt %lld \n",(Long64_t)obt+(Long64_t)numeric_limits<UInt_t>::max());
1335 mocchiut 1.1 return((Long64_t)obt+(Long64_t)numeric_limits<UInt_t>::max());
1336     };
1337     //
1338     if ( obt > ((Long64_t)pobtfirst*2) && obt > (numeric_limits<UInt_t>::max()/2) ){
1339 mocchiut 1.2 // if ( IsDebug() ) printf(" pobtfirst*2 %lld \n",((Long64_t)pobtfirst*2));
1340     // if ( IsDebug() ) printf(" rise down pktnum %lld \n", (Long64_t)obt-(Long64_t)numeric_limits<UInt_t>::max());
1341 mocchiut 1.1 return((Long64_t)obt-(Long64_t)numeric_limits<UInt_t>::max());
1342     };
1343     //
1344 mocchiut 1.2 // if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)obt);
1345 mocchiut 1.1 return((Long64_t)obt);
1346     };
1347    
1348     /**
1349     *
1350     * Fill the glrun class with infos about the run when we have both runtrailer and runheader
1351     *
1352     */
1353     void PamelaDBOperations::FillClass(){
1354     this->FillClass(false,false,-1,-1);
1355     };
1356    
1357     /**
1358     *
1359     * Fill the glrun class with infos about the run when we have both runtrailer and runheader
1360     *
1361     */
1362     void PamelaDBOperations::FillClass(Bool_t mishead, Bool_t mistrail, Int_t firstev, Int_t lastev){
1363     //
1364     TTree *T = 0;
1365     T = (TTree*)file->Get("Physics");
1366     if ( !T || T->IsZombie() ) throw -16;
1367     //
1368     EventHeader *eh = 0;
1369     PscuHeader *ph = 0;
1370     T->SetBranchAddress("Header", &eh);
1371     PacketType *pctp=0;
1372     EventCounter *codt=0;
1373     EventCounter *codh=0;
1374     UInt_t firstObt = 0;
1375     UInt_t lastObt = 0;
1376     UInt_t firstPkt = 0;
1377     UInt_t lastPkt = 0;
1378     UInt_t rhtime = 0;
1379     UInt_t rttime = 0;
1380 mocchiut 1.3 //
1381     if ( IsDebug() ) printf(" A firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1382     //
1383 mocchiut 1.1 if ( !mishead ){
1384     codh = ehh->GetCounter();
1385 mocchiut 1.3 if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1) ){
1386     if ( IsDebug() ) printf(" B firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1387 mocchiut 1.1 firstev = 1;
1388     lastev = 0;
1389     } else {
1390     firstev = codh->Get(pctp->Physics);
1391     };
1392     rhtime = this->GetAbsTime(phh->GetOrbitalTime());
1393     glrun->Set_GL_RUNH(runh,phh);
1394     firstObt = glrun->GetRUNHEADER_OBT();
1395     firstPkt = glrun->GetRUNHEADER_PKT();
1396     };
1397     if ( !mistrail ){
1398     codt = eht->GetCounter();
1399 mocchiut 1.3 if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1)){
1400     if ( IsDebug() ) printf(" C firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1401 mocchiut 1.1 lastev = 0;
1402     firstev = lastev+1;
1403     } else {
1404     lastev = codt->Get(pctp->Physics)-1;
1405     };
1406     rttime = this->GetAbsTime(pht->GetOrbitalTime());
1407     glrun->Set_GL_RUNT(runt,pht);
1408     lastObt = glrun->GetRUNTRAILER_OBT();
1409     lastPkt = glrun->GetRUNTRAILER_PKT();
1410     };
1411     //
1412     if ( mishead && mistrail && lastev+1 == firstev ) throw -14; // run with no events, no runtrailer, no runheader... unsupported should never arrive here
1413     //
1414     if ( mishead ) {
1415     glrun->Set_GL_RUNH0();
1416     //
1417 mocchiut 1.3 if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1) ){
1418 mocchiut 1.1 firstObt = lastObt;
1419     firstPkt = lastPkt;
1420     rhtime = rttime;
1421     } else {
1422     T->GetEntry(firstev);
1423     ph = eh->GetPscuHeader();
1424     firstObt = ph->GetOrbitalTime();
1425     rhtime = this->GetAbsTime(firstObt);
1426     firstPkt = ph->GetCounter();
1427     };
1428     //
1429     glrun->SetRUNHEADER_PKT(firstPkt);
1430     glrun->SetRUNHEADER_OBT(firstObt);
1431     //
1432     };
1433     if ( mistrail ){
1434     glrun->Set_GL_RUNT0();
1435     //
1436 mocchiut 1.3 if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1) ){
1437 mocchiut 1.1 lastObt = firstObt;
1438     lastPkt = firstPkt;
1439     rttime = rhtime;
1440     } else {
1441     T->GetEntry(lastev);
1442     ph = eh->GetPscuHeader();
1443     lastObt = ph->GetOrbitalTime();
1444     rttime = this->GetAbsTime(lastObt);
1445     lastPkt = ph->GetCounter();
1446     };
1447     //
1448     glrun->SetRUNTRAILER_OBT(lastObt);
1449     glrun->SetRUNTRAILER_PKT(lastPkt);
1450     //
1451     };
1452     glrun->SetEV_FROM((UInt_t)firstev);
1453     glrun->SetEV_TO((UInt_t)lastev);
1454     glrun->SetNEVENTS((UInt_t)lastev-(UInt_t)firstev+1);
1455     //
1456     if ( IsDebug() ) printf(" firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1457     //
1458     this->SetCommonGLRUN(rhtime,rttime);
1459 mocchiut 1.2 this->SetPhysEndRunVariables();
1460 mocchiut 1.1 //
1461     };
1462    
1463     //
1464     // PUBLIC FUNCTIONS
1465     //
1466    
1467 pam-fi 1.4 // /**
1468     // * Insert a new row into GL_RAW table.
1469     // */
1470     // Int_t PamelaDBOperations::insertPamelaRawFile(){
1471     // //
1472     // stringstream oss;
1473     // //
1474     // Bool_t idr = this->SetID_RAW();
1475     // if ( idr ) return(1);
1476     // //
1477     // oss.str("");
1478     // if ( STATIC ){
1479     // oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('"
1480     // << this->GetRawPath().Data() << "', '" << this->GetRawFile().Data() << "')";
1481     // } else {
1482     // oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('$PAM_RAW', '" << this->GetRawFile().Data() << "')";
1483     // };
1484     // if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;
1485     // //
1486     // idr = this->SetID_RAW();
1487     // if ( !idr ) throw -11;
1488     // //
1489     // return(0);
1490     // }
1491 mocchiut 1.1 /**
1492     * Insert a new row into GL_RAW table.
1493     */
1494     Int_t PamelaDBOperations::insertPamelaRawFile(){
1495 pam-fi 1.4
1496     //
1497     Bool_t idr = this->SetID_RAW();
1498     if ( idr ) return(1);
1499    
1500     GL_RAW glraw = GL_RAW();
1501    
1502     glraw.PATH = GetRawPath();
1503     glraw.NAME = GetRawFile();
1504     glraw.BOOT_NUMBER = 0;//???
1505    
1506     if( insertPamelaRawFile(&glraw) )return(1);
1507     //
1508     idr = this->SetID_RAW();
1509     if ( !idr ) throw -11;
1510    
1511     return(0);
1512     }
1513     /**
1514     * Insert a new row into GL_RAW table.
1515     */
1516     Int_t PamelaDBOperations::insertPamelaRawFile(GL_RAW *glraw){
1517 mocchiut 1.1 //
1518 pam-fi 1.4 if(!glraw)return(1);//??
1519     //
1520     stringstream oss;
1521     //
1522     oss.str("");
1523     if ( STATIC ){
1524     oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('"
1525     << glraw->PATH << "', '" << glraw->NAME << "')";
1526     } else {
1527     oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('$PAM_RAW', '" << glraw->NAME << "')";
1528     };
1529     if ( debug ) cout <<oss.str().c_str() <<endl;
1530     if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;
1531     //
1532     oss.str("");
1533     oss << "SELECT ID FROM GL_RAW WHERE NAME=\""<<glraw->NAME<<"\";";
1534     if ( debug ) cout << oss.str().c_str()<<endl;
1535     if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;
1536     //
1537     TSQLResult *result = 0;
1538     TSQLRow *row = 0;
1539     result = conn->Query(oss.str().c_str());
1540     if ( result == NULL ) throw -4;
1541     row = result->Next();
1542     if ( !row ) return(1);
1543     glraw->ID = (UInt_t)atoll(row->GetField(0));
1544     if ( debug ) printf(" The ID of the RAW file is %u \n",glraw->ID);
1545     delete result;
1546     delete row;
1547     //
1548     return(0);
1549 mocchiut 1.1 }
1550    
1551    
1552     /**
1553     * Look for one timesync information in the file and
1554     * fill the GL_TIMESYNC table. It will look for: 1) TS-MCMD 2) TS info in the RunHeader 3) TS info in the runtrailer, if none exists exit with error
1555     */
1556     Int_t PamelaDBOperations::insertPamelaGL_TIMESYNC(){
1557     //
1558     Int_t signal = 0;
1559     UInt_t idresof = 0;
1560     stringstream oss;
1561     TSQLResult *result = 0;
1562     TSQLRow *row = 0;
1563     UInt_t OBT = 0;
1564     UInt_t TYPE = 0;
1565     UInt_t TSYNC = 0;
1566     UInt_t t0 = 0;
1567     Bool_t existsts = false;
1568     //
1569     if ( chewbacca ){
1570     //
1571     OBT = chobtts * 1000;
1572     TSYNC = chlastts;
1573     t0 = chresursts;
1574     TYPE = 777;
1575     oss.str("");
1576     oss << "select * from GL_RESURS_OFFSET where OFFSET_DATE=FROM_UNIXTIME("<< t0 <<") limit 1;";
1577     if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
1578     result = conn->Query(oss.str().c_str());
1579     if ( !result ) throw -10;
1580     row = result->Next();
1581     idresof = (UInt_t)atoll(row->GetField(0));
1582     existsts = true;
1583     goto eout;
1584     //
1585     } else {
1586     //
1587     //signal = this->SetUpperLimits();
1588     //
1589     if ( this->GetID_RAW() == 0 ) throw -11;
1590     //
1591     oss.str("");
1592     oss << "SELECT YEAR(OFFSET_DATE),MONTH(OFFSET_DATE),DAY(OFFSET_DATE),HOUR(OFFSET_DATE),MINUTE(OFFSET_DATE),SECOND(OFFSET_DATE),ID FROM GL_RESURS_OFFSET WHERE SPECIAL_FILE='"
1593     << this->GetRawFile().Data() << "';";
1594     if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
1595     result = conn->Query(oss.str().c_str());
1596     if ( !result ) throw -10;
1597     row = result->Next();
1598     //
1599     if ( !row ){
1600     oss.str("");
1601     oss << "SELECT YEAR(OFFSET_DATE),MONTH(OFFSET_DATE),DAY(OFFSET_DATE),HOUR(OFFSET_DATE),MINUTE(OFFSET_DATE),SECOND(OFFSET_DATE),ID FROM GL_RESURS_OFFSET WHERE FROM_ORBIT< "
1602     << dworbit << " order by FROM_ORBIT desc limit 1;";
1603     if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
1604     result = conn->Query(oss.str().c_str());
1605     if ( !result ) throw -10;
1606     row = result->Next();
1607     if ( !row ) throw -10;
1608     };
1609     //
1610     idresof = (UInt_t)atoll(row->GetField(6));
1611     //
1612     TTimeStamp tu = TTimeStamp((UInt_t)atoi(row->GetField(0)),(UInt_t)atoi(row->GetField(1)),(UInt_t)atoi(row->GetField(2)),(UInt_t)atoi(row->GetField(3)),(UInt_t)atoi(row->GetField(4)),(UInt_t)atoi(row->GetField(5)),0,true,0);
1613     t0 = (UInt_t)tu.GetSec();
1614     if ( IsDebug() ) printf(" t0 is %u ti is %s %s %s %s %s %s %s\n",t0,row->GetField(0),row->GetField(1),row->GetField(2),row->GetField(3),row->GetField(4),row->GetField(5),row->GetField(6));
1615     //
1616     /*
1617     * Verify that the TIMESYNC have been not already processed
1618     */
1619     oss.str("");
1620     oss << " SELECT COUNT(GL_TIMESYNC.ID),GL_TIMESYNC.OBT0,GL_TIMESYNC.TIMESYNC FROM GL_TIMESYNC "
1621     << " LEFT JOIN GL_RAW "
1622     << " ON GL_RAW.ID = GL_TIMESYNC.ID_RAW "
1623     << " WHERE GL_TIMESYNC.ID_RAW = " << this->GetID_RAW()
1624     << " GROUP BY GL_TIMESYNC.OBT0;";
1625     if ( IsDebug() ) printf(" check for old timesync: query is \n %s \n",oss.str().c_str());
1626     result = conn->Query(oss.str().c_str());
1627     if (result == NULL) throw -10;
1628     row = result->Next();
1629     if ((row != NULL) && ((UInt_t)atoll(row->GetField(0)) > 0)){
1630     if ( IsDebug() ) printf(" found a timesync t0 is %u \n",t0);
1631     toffset = (UInt_t)atoll(row->GetField(2)) - (UInt_t)(this->OBT((UInt_t)atoll(row->GetField(1)))/1000) + t0;
1632     //
1633     tsync = (UInt_t)atoll(row->GetField(2));
1634     obt0 = (UInt_t)atoll(row->GetField(1));
1635     //
1636     if ( PEDANTIC ) throw -67;
1637     return(1);
1638     };
1639     //
1640     TTree *T = 0;
1641     //
1642     UInt_t nevent = 0;
1643     UInt_t recEntries = 0;
1644     //
1645     OBT = 0;
1646     TYPE = 0;
1647     TSYNC = 0;
1648     //
1649     Double_t minimum = 0.;
1650     Double_t maximum = 0.;
1651     Double_t minimum2 = 0.;
1652     Double_t maximum2 = 0.;
1653     //
1654     //
1655     pamela::McmdEvent *mc = 0;
1656     pamela::McmdRecord *mcrc = 0;
1657     TArrayC *mcmddata = 0;
1658     //
1659     minimum = numeric_limits<Double_t>::max();
1660     maximum = numeric_limits<Double_t>::min();
1661     minimum2 = numeric_limits<Double_t>::max();
1662     maximum2 = numeric_limits<Double_t>::min();
1663     //
1664     T = (TTree*)file->Get("Mcmd");
1665     if ( !T || T->IsZombie() ) throw -19;
1666     T->SetBranchAddress("Mcmd",&mc);
1667     //
1668     nevent = T->GetEntries();
1669     //
1670     // loop over events
1671     //
1672     existsts = false;
1673     //
1674     for (UInt_t i=0; i<nevent;i++){
1675     //
1676     T->GetEntry(i);
1677     //
1678     recEntries = mc->Records->GetEntries();
1679     //
1680     for (UInt_t j = 0; j < recEntries; j++){
1681     mcrc = (pamela::McmdRecord*)mc->Records->At(j);
1682     mcmddata = mcrc->McmdData;
1683     //
1684     if (mcrc->ID1 == 0xE0){ // mcmd timesync
1685     //
1686     OBT = (Int_t)(mcrc->MCMD_RECORD_OBT);
1687     //
1688     TSYNC = (((UInt_t)mcmddata->At(0)<<24)&0xFF000000) + (((UInt_t)mcmddata->At(1)<<16)&0x00FF0000) + (((UInt_t)mcmddata->At(2)<<8)&0x0000FF00) + (((UInt_t)mcmddata->At(3))&0x000000FF);
1689     //
1690     TYPE = 55;//224;
1691     //
1692     if ( IsDebug() ) printf("mcmd tsync %i tsync %u obt %u \n",i,TSYNC,OBT);
1693     //
1694     if ( TSYNC && OBT ){
1695     existsts = true;
1696     goto eout;
1697     };
1698     //
1699     };
1700     };
1701     };
1702     if ( !existsts ) { // try with runheader and runtrailer
1703     //
1704     if ( IsDebug() ) printf(" No ts mcmd \n");
1705     signal = 2;
1706     //
1707     TTree *rh=(TTree*)file->Get("RunHeader");
1708     if ( !rh || rh->IsZombie() ) throw -17;
1709     TTree *rt=(TTree*)file->Get("RunTrailer");
1710     if ( !rt || rt->IsZombie() ) throw -18;
1711     //
1712     rh->SetBranchAddress("RunHeader", &runh);
1713     //
1714     rt->SetBranchAddress("RunTrailer", &runt);
1715     //
1716     Int_t nnrhev = rh->GetEntries();
1717     Int_t nnrtev = rt->GetEntries();
1718     if ( IsDebug() ) printf(" ou nevent %i rhev %i rtev %i \n",nevent,nnrhev,nnrtev);
1719     //
1720     if ( nnrhev > 0 ){
1721     for (Int_t i=0; i<nnrhev; i++){
1722     //
1723     rh->GetEntry(i);
1724     //
1725     TSYNC = runh->LAST_TIME_SYNC_INFO;
1726     OBT = runh->OBT_TIME_SYNC * 1000;
1727     //
1728     TYPE = 20;
1729     //
1730     if ( IsDebug() ) printf("runheader %i tsync %u obt %u \n",i,TSYNC,OBT);
1731     //
1732     if ( TSYNC && OBT ){
1733     existsts = true;
1734     goto eout;
1735     };
1736     };
1737     //
1738     };
1739     if ( nnrtev > 0 ){
1740     //
1741     if ( IsDebug() ) printf(" No runheader \n");
1742     signal = 6;
1743     //
1744     for (Int_t i=0; i<nnrtev; i++){
1745     //
1746     rt->GetEntry(i);
1747     //
1748     TSYNC = runt->LAST_TYME_SYNC_INFO;
1749     OBT = runt->OBT_TYME_SYNC * 1000;
1750     //
1751     TYPE = 21;
1752     //
1753     if ( IsDebug() ) printf("runtrailer %i tsync %u obt %u \n",i,TSYNC,OBT);
1754     //
1755     if ( TSYNC && OBT ){
1756     existsts = true;
1757     goto eout;
1758     };
1759     };
1760     //
1761     } else {
1762     if ( IsDebug() ) printf(" No runheader \n");
1763     };
1764     };
1765     //
1766     if ( !existsts ){ // try with inclination mcmd
1767     //
1768     if ( IsDebug() ) printf(" No runtrailer \n");
1769     signal = 14;
1770     //
1771     Double_t timesync = 0.;
1772     for (UInt_t i=0; i<nevent;i++){
1773     //
1774     T->GetEntry(i);
1775     //
1776     recEntries = mc->Records->GetEntries();
1777     // //
1778     for (UInt_t j = 0; j < recEntries; j++){
1779     mcrc = (pamela::McmdRecord*)mc->Records->At(j);
1780     mcmddata = mcrc->McmdData;
1781     //
1782     if (mcrc->ID1 == 0xE2){ // mcmd inclination
1783     timesync = 0.;
1784     timesync = (Double_t)(((((UInt_t)mcmddata->At(0) << 24) & 0xFF000000) + (((UInt_t)mcmddata->At(1) << 16) & 0x00FF0000) + (((UInt_t)mcmddata->At(2) << 8) & 0x0000FF00) + ((UInt_t)mcmddata->At(3) & 0x000000FF))/128.0);
1785     //
1786     if ( timesync > maximum2){
1787     maximum2 = timesync;
1788     OBT = (Int_t)(mcrc->MCMD_RECORD_OBT);
1789     };
1790     };
1791     //
1792     };
1793     };
1794     if ( maximum2 > numeric_limits<Double_t>::min() ){
1795     TSYNC = (UInt_t)(maximum2 + 0.5);
1796     TYPE = 666;
1797     if ( TSYNC && OBT ){
1798     existsts = true;
1799     goto eout;
1800     };
1801     };
1802     };
1803     //
1804     };
1805     //
1806     if ( !existsts && obt0 ){ // insert timesync by hand
1807     //
1808     if ( PEDANTIC ) throw -68;
1809     if ( IsDebug() ) printf(" No incl mcmd \n");
1810     signal = 30;
1811     //
1812     OBT = obt0;
1813     TSYNC = tsync;
1814     TYPE = 999;
1815     existsts = true;
1816     goto eout;
1817     };
1818     //
1819     eout:
1820     //
1821     if ( !existsts ) throw -3;
1822     //
1823     oss.str("");
1824     oss << "INSERT INTO GL_TIMESYNC (ID_RAW,TYPE,OBT0,TIMESYNC,ID_RESURS_OFFSET) VALUES ('"
1825     << this->GetID_RAW() << "','"//224'"
1826     << dec << (UInt_t)TYPE << "','"
1827     << dec << (UInt_t)OBT << "','"
1828     << dec << (UInt_t)TSYNC << "','"
1829     << dec << (UInt_t)idresof << "');";
1830     conn->Query(oss.str().c_str());
1831     if ( IsDebug() ) printf(" Query the GL_TIMESYNC table to fill it:\n %s \n",oss.str().c_str());
1832     if ( conn->GetErrorCode() ){
1833     printf(" OK, you got an error because the database structure you are using is not up to date\n Using backward compability code, hence you can continue safetly \n");
1834     oss.str("");
1835     oss << "INSERT INTO GL_TIMESYNC (ID_RAW,TYPE,OBT0,TIMESYNC) VALUES ('"
1836     << this->GetID_RAW() << "','"//224'"
1837     << dec << (UInt_t)TYPE << "','"
1838     << dec << (UInt_t)OBT << "','"
1839     << dec << (UInt_t)TSYNC << "');";
1840     conn->Query(oss.str().c_str());
1841     if ( IsDebug() ) printf(" Query the GL_TIMESYNC table to fill it:\n %s \n",oss.str().c_str());
1842     };
1843     //
1844     if ( IsDebug() ) printf(" found a timesync t0 is %u \n",t0);
1845     //
1846     toffset = (UInt_t)TSYNC - (UInt_t)(this->OBT(OBT)/1000) + t0;
1847     //
1848     tsync = TSYNC;
1849     obt0 = OBT;
1850     //
1851     delete result;
1852     return(signal);
1853     }
1854    
1855 pam-fi 1.4 // /**
1856     // * Insert all the new rows into GL_ROOT.
1857     // * The raw file indicates in the parameters should be already been stored in the database.
1858     // */
1859     // Int_t PamelaDBOperations::insertPamelaRootFile(){
1860     // stringstream oss;
1861     // TSQLResult *result = 0;
1862     // TSQLRow *row = 0;
1863     // UInt_t idtimesync = 0;
1864     // //
1865     // //
1866     // if ( chewbacca ){
1867     // oss.str("");
1868     // oss << " SELECT ID FROM GL_TIMESYNC where TIMESYNC="<<chlastts<<" AND OBT0="<<chobtts*1000<<" limit 1;";
1869     // if ( debug ) printf(" query is %s \n",oss.str().c_str());
1870     // result = conn->Query(oss.str().c_str());
1871     // //
1872     // if ( !result ) throw -3;
1873     // //
1874     // row = result->Next();
1875     // //
1876     // if ( !row ) throw -3;
1877     // idtimesync = (UInt_t)atoll(row->GetField(0));
1878     // } else {
1879     // oss.str("");
1880     // if ( STATIC ){
1881     // oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
1882     // << " LEFT JOIN GL_ROOT "
1883     // << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
1884     // << " WHERE GL_RAW.PATH = '" << this->GetRawPath().Data() << "' AND "
1885     // << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
1886     // } else {
1887     // oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
1888     // << " LEFT JOIN GL_ROOT "
1889     // << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
1890     // << " WHERE GL_RAW.PATH = '$PAM_RAW' AND "
1891     // << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
1892     // };
1893     // result = conn->Query(oss.str().c_str());
1894     // //
1895     // if ( !result ) throw -12;
1896     // //
1897     // row = result->Next();
1898     // //
1899     // if ( !row ) throw -10;
1900     // if ( row != NULL && (UInt_t)atoll(row->GetField(0))>0 ){
1901     // idroot = (UInt_t)atoll(row->GetField(2));
1902     // return(1);
1903     // };
1904     // //
1905     // // determine which timesync has to be used
1906     // //
1907     // oss.str("");
1908     // oss << "SELECT GL_TIMESYNC.ID FROM GL_TIMESYNC LEFT JOIN GL_RAW ON GL_RAW.ID = GL_TIMESYNC.ID_RAW ORDER BY GL_TIMESYNC.ID DESC LIMIT 1;";
1909     // result = conn->Query(oss.str().c_str());
1910     // //
1911     // if ( !result ) throw -3;
1912     // //
1913     // row = result->Next();
1914     // //
1915     // if ( !row ) throw -3;
1916     // idtimesync = (UInt_t)atoll(row->GetField(0));
1917     // };
1918     // //
1919     // oss.str("");
1920     // if ( STATIC ){
1921     // oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"
1922     // << this->GetID_RAW() << "', '" << idtimesync << "', '" << this->GetRootPath().Data() << "', '" << this->GetRootFile().Data() << "')";
1923     // } else {
1924     // oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"
1925     // << this->GetID_RAW() << "', '" << idtimesync << "', '$PAM_L0', '" << this->GetRootFile().Data() << "')";
1926     // };
1927     // //
1928     // if ( debug ) printf(" query is %s \n",oss.str().c_str());
1929     // if (conn->Query(oss.str().c_str()) == 0) throw -4;
1930     // //
1931     // delete result;
1932     // //
1933     // oss.str("");
1934     // // oss << "SELECT ID FROM GL_ROOT WHERE ID_RAW=" << this->GetID_RAW() << ";";
1935     // if ( STATIC ){
1936     // oss << "SELECT ID FROM GL_ROOT WHERE PATH='" << this->GetRootPath().Data() << "' and NAME='"<< this->GetRootFile().Data() <<"';";
1937     // } else {
1938     // oss << "SELECT ID FROM GL_ROOT WHERE PATH='$PAM_L0' and NAME='"<< this->GetRootFile().Data() <<"';";
1939     // };
1940     // //
1941     // if ( debug ) printf(" query is %s \n",oss.str().c_str());
1942     // result = conn->Query(oss.str().c_str());
1943     // if ( !result ) throw -12;
1944     // row = result->Next();
1945     // if ( !row ) throw -3;
1946     // this->SetID_ROOT((UInt_t)atoll(row->GetField(0)));
1947     // if ( debug ) printf(" The ID of the ROOT file is %u \n",this->GetID_ROOT());
1948     // //
1949     // delete result;
1950     // //
1951     // return(0);
1952     // }
1953 mocchiut 1.1 /**
1954     * Insert all the new rows into GL_ROOT.
1955     * The raw file indicates in the parameters should be already been stored in the database.
1956     */
1957     Int_t PamelaDBOperations::insertPamelaRootFile(){
1958 pam-fi 1.4
1959     stringstream oss;
1960     TSQLResult *result = 0;
1961     TSQLRow *row = 0;
1962     //
1963     // ----------------------
1964     // determine the timesync
1965     // ----------------------
1966     UInt_t idtimesync = 0;
1967     //
1968     if ( chewbacca ){
1969     oss.str("");
1970     oss << " SELECT ID FROM GL_TIMESYNC where TIMESYNC="<<chlastts<<" AND OBT0="<<chobtts*1000<<" limit 1;";
1971     if ( debug ) printf(" %s \n",oss.str().c_str());
1972     result = conn->Query(oss.str().c_str());
1973     //
1974     if ( !result ) throw -3;
1975     //
1976     row = result->Next();
1977     //
1978     if ( !row ) throw -3;
1979     idtimesync = (UInt_t)atoll(row->GetField(0));
1980     } else {
1981     oss.str("");
1982     if ( STATIC ){
1983     oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
1984     << " LEFT JOIN GL_ROOT "
1985     << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
1986     << " WHERE GL_RAW.PATH = '" << this->GetRawPath().Data() << "' AND "
1987     << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
1988     } else {
1989     oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
1990     << " LEFT JOIN GL_ROOT "
1991     << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
1992     << " WHERE GL_RAW.PATH = '$PAM_RAW' AND "
1993     << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
1994     };
1995     result = conn->Query(oss.str().c_str());
1996     //
1997     if ( !result ) throw -12;
1998     //
1999     row = result->Next();
2000     //
2001     if ( !row ) throw -10;
2002     if ( row != NULL && (UInt_t)atoll(row->GetField(0))>0 ){
2003     idroot = (UInt_t)atoll(row->GetField(2));
2004     delete row;
2005     delete result;
2006     return(1);
2007     };
2008     //
2009     // determine which timesync has to be used
2010     //
2011     oss.str("");
2012     oss << "SELECT GL_TIMESYNC.ID FROM GL_TIMESYNC LEFT JOIN GL_RAW ON GL_RAW.ID = GL_TIMESYNC.ID_RAW ORDER BY GL_TIMESYNC.ID DESC LIMIT 1;";
2013     result = conn->Query(oss.str().c_str());
2014     //
2015     if ( !result ) throw -3;
2016     //
2017     row = result->Next();
2018     //
2019     if ( !row ) throw -3;
2020     idtimesync = (UInt_t)atoll(row->GetField(0));
2021     };
2022    
2023     delete row;
2024     delete result;
2025    
2026     // ----------------------
2027     // insert root file
2028     // ----------------------
2029    
2030     GL_ROOT glroot = GL_ROOT();
2031    
2032     glroot.ID_RAW = GetID_RAW();
2033     glroot.ID_TIMESYNC = idtimesync;
2034     glroot.PATH = GetRootPath();
2035     glroot.NAME = GetRootFile();
2036    
2037     if ( insertPamelaRootFile(&glroot) )return 1;
2038    
2039     SetID_ROOT(glroot.ID);
2040    
2041    
2042     return (0);
2043     }
2044     /**
2045     * Insert all the new rows into GL_ROOT.
2046     * The raw file indicates in the parameters should be already been stored in the database.
2047     */
2048     Int_t PamelaDBOperations::insertPamelaRootFile(GL_ROOT *glroot){
2049    
2050    
2051    
2052 mocchiut 1.1 stringstream oss;
2053     TSQLResult *result = 0;
2054     TSQLRow *row = 0;
2055     //
2056     //
2057     oss.str("");
2058     if ( STATIC ){
2059     oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"
2060 pam-fi 1.4 << glroot->ID_RAW << "', '" << glroot->ID_TIMESYNC << "', '" << glroot->PATH << "', '" << glroot->NAME << "')";
2061 mocchiut 1.1 } else {
2062     oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"
2063 pam-fi 1.4 << glroot->ID_RAW << "', '" << glroot->ID_TIMESYNC << "', '$PAM_L0', '" << glroot->NAME << "')";
2064 mocchiut 1.1 };
2065     //
2066 pam-fi 1.4 if ( debug ) printf("%s \n",oss.str().c_str());
2067 mocchiut 1.1 if (conn->Query(oss.str().c_str()) == 0) throw -4;
2068     //
2069     delete result;
2070     //
2071     oss.str("");
2072     // oss << "SELECT ID FROM GL_ROOT WHERE ID_RAW=" << this->GetID_RAW() << ";";
2073     if ( STATIC ){
2074 pam-fi 1.4 oss << "SELECT ID FROM GL_ROOT WHERE PATH='" << glroot->PATH << "' and NAME='"<< glroot->NAME <<"';";
2075 mocchiut 1.1 } else {
2076 pam-fi 1.4 oss << "SELECT ID FROM GL_ROOT WHERE PATH='$PAM_L0' and NAME='"<< glroot->NAME <<"';";
2077 mocchiut 1.1 };
2078     //
2079 pam-fi 1.4 if ( debug ) printf("%s \n",oss.str().c_str());
2080 mocchiut 1.1 result = conn->Query(oss.str().c_str());
2081     if ( !result ) throw -12;
2082     row = result->Next();
2083     if ( !row ) throw -3;
2084 pam-fi 1.4
2085     glroot->ID = (UInt_t)atoll(row->GetField(0));
2086    
2087     if ( debug ) printf(" The ID of the ROOT file is %u \n",glroot->ID);
2088 mocchiut 1.1 //
2089     delete result;
2090     //
2091     return(0);
2092     }
2093    
2094     /**
2095     * Assign the BOOT_NUMBER to the raw file.
2096     */
2097     Int_t PamelaDBOperations::assignBOOT_NUMBER(){
2098     Bool_t found = false;
2099     UInt_t idRaw = 0;
2100     UInt_t bn = 0;
2101     stringstream oss;
2102     TSQLResult *result = 0;
2103     TSQLRow *row = 0;
2104     if ( chewbacca ){
2105     if ( chboot == 1 ){
2106     // not found!
2107     found = false;
2108     } else {
2109     found = true;
2110     this->SetBOOTnumber(chboot);
2111     };
2112     } else {
2113     oss.str("");
2114     if ( STATIC ){
2115     oss << "SELECT ID, BOOT_NUMBER FROM GL_RAW WHERE "
2116     << " PATH = '" << this->GetRawPath().Data() << "' AND "
2117     << " NAME = '" << this->GetRawFile().Data() << "' ";
2118     } else {
2119     oss << "SELECT ID, BOOT_NUMBER FROM GL_RAW WHERE "
2120     << " PATH = '$PAM_RAW' AND "
2121     << " NAME = '" << this->GetRawFile().Data() << "' ";
2122     };
2123     result = conn->Query(oss.str().c_str());
2124     //
2125     if ( !result ) throw -4;;
2126     row = result->Next();
2127     if ( !row ) return(16);
2128     if ( row->GetField(1) ){
2129     this->SetBOOTnumber((UInt_t)atoll(row->GetField(1)));
2130     return(1);
2131     };
2132     if ( !row->GetField(0) ) throw -26;
2133     //
2134     idRaw = (UInt_t)atoll(row->GetField(0));
2135     //
2136     //
2137     //
2138     TTree *trDumpEv = 0;
2139     trDumpEv = (TTree*)file->Get("VarDump");
2140     if ( !trDumpEv || trDumpEv->IsZombie() ) throw -20;
2141     //
2142     VarDumpEvent *vde = 0;
2143     VarDumpRecord *vdr = 0;
2144     //
2145     trDumpEv->SetBranchAddress("VarDump", &vde);
2146     if ( trDumpEv->GetEntries() > 0 ){
2147     found = false;
2148     for ( Int_t i = 0; i < trDumpEv->GetEntries(); i++){
2149     trDumpEv->GetEntry(i);
2150     // vde->Records->GetEntries();
2151     if ( vde->Records->GetEntries()>5 ){
2152     found = true;
2153     goto fill;
2154     };
2155     };
2156     fill:
2157     if ( found ){
2158     //
2159     vdr = (VarDumpRecord*)vde->Records->At(6);
2160     //
2161     this->SetBOOTnumber((Int_t)vdr->VAR_VALUE);
2162     //
2163     } else {
2164     if ( !this->GetBOOTnumber() && !this->AutoBoot()) return(4);
2165     };
2166     } else {
2167     if ( !this->GetBOOTnumber() && !this->AutoBoot()) return(2);
2168     };
2169     //
2170     };
2171     //
2172     Bool_t afound = false;
2173     if ( !found && this->AutoBoot()){
2174     afound = true;
2175     //
2176     // Search for other files with similar timesync
2177     //
2178     if ( IsDebug() ) printf(" tsync %u obt0 %u \n",tsync,obt0);
2179     UInt_t upperts = tsync-(obt0/1000)+5;
2180     UInt_t lowerts = tsync-(obt0/1000)-5;
2181     if ( chewbacca ){
2182     oss.str("");
2183     oss << "select BOOT_NUMBER from ROOT_TABLE where LAST_TIME_SYNC_INFO-(OBT_TIME_SYNC)<"
2184     << upperts
2185     << " AND LAST_TIME_SYNC_INFO-(OBT_TIME_SYNC)>"
2186     << lowerts
2187     << " AND BOOT_NUMBER>1;";
2188     } else {
2189     oss.str("");
2190     oss << "select GL_RAW.BOOT_NUMBER from GL_TIMESYNC LEFT JOIN GL_RAW ON GL_RAW.ID = GL_TIMESYNC.ID_RAW where TIMESYNC-(OBT0/1000)<"
2191     << upperts
2192     << " AND TIMESYNC-(OBT0/1000)>"
2193     << lowerts
2194     << " AND GL_RAW.BOOT_NUMBER>0 GROUP BY GL_TIMESYNC.OBT0;";
2195     };
2196     result = conn->Query(oss.str().c_str());
2197     if ( IsDebug() && !chewbacca ) printf(" Query the GL_TIMESYNC table to find boot number:\n %s \n",oss.str().c_str());
2198     if ( IsDebug() && chewbacca ) printf(" Query the ROOT_TABLE table to find boot number:\n %s \n",oss.str().c_str());
2199     //
2200     if ( !result ) throw -4;;
2201     found = true;
2202     if ( result->GetRowCount()<3 ){
2203     if ( IsDebug() ) printf(" AGH! no results!\n");
2204     found = false;
2205     } else {
2206     row = result->Next();
2207     bn = (UInt_t)atoll(row->GetField(0));
2208     for ( Int_t r=1; r<result->GetRowCount() ;r++){
2209     if ( !row ) throw -4;
2210     if ( IsDebug() ) printf(" BOOT number is %s \n",row->GetField(0));
2211     if ( bn != (UInt_t)atoll(row->GetField(0)) ){
2212     if ( IsDebug() ) printf(" AGH! bn = %u here instead %u \n",bn,(UInt_t)atoll(row->GetField(0)));
2213     found = false;
2214     };
2215     row = result->Next();
2216     };
2217     };
2218     };
2219     //
2220     Int_t sgn = 0;
2221     //
2222     if ( !found && !BOOTNO ){
2223     throw -29;
2224     } else {
2225     if ( afound ){
2226     this->SetBOOTnumber(bn);
2227     sgn = 8;
2228     };
2229     };
2230     //
2231     if ( !chewbacca ){
2232     oss.str("");
2233     oss << " UPDATE GL_RAW "
2234     << " SET GL_RAW.BOOT_NUMBER = '" << dec << this->GetBOOTnumber() << "'"
2235     << " WHERE GL_RAW.ID = '" << idRaw << "'";
2236     conn->Query(oss.str().c_str());
2237     };
2238     //
2239     delete result;
2240     return(sgn);
2241     };
2242    
2243     /**
2244     * Scan runtrailer packet, fill the GL_RUN table and
2245     * check for missing and truncated runs
2246     */
2247     Int_t PamelaDBOperations::insertPamelaRUN(){
2248     Int_t signal = 0;
2249     //
2250     stringstream oss;
2251     oss.str("");
2252     //
2253     // signal = this->SetUpperLimits();
2254    
2255     //
2256     // loop on runheader and runtrailer events
2257     //
2258     TTree *rh=(TTree*)file->Get("RunHeader");
2259     if ( !rh || rh->IsZombie() ) throw -17;
2260     TTree *rt=(TTree*)file->Get("RunTrailer");
2261     if ( !rt || rt->IsZombie() ) throw -18;
2262     //
2263     PacketType *pctp=0;
2264     EventCounter *cod=0;
2265     //
2266     rh->SetBranchAddress("RunHeader", &runh);
2267     rh->SetBranchAddress("Header", &ehh);
2268     //
2269     rt->SetBranchAddress("RunTrailer", &runt);
2270     rt->SetBranchAddress("Header", &eht);
2271     //
2272     TTree *T = (TTree*)file->Get("Physics");
2273     if ( !T || T->IsZombie() ) throw -16;
2274     EventHeader *eh = 0;
2275     T->SetBranchAddress("Header", &eh);
2276     //
2277     if ( !(rh->GetEntries()) && !(rt->GetEntries()) && !(T->GetEntries()) ) return(16);
2278     //
2279     UInt_t obtt = 0;
2280     UInt_t obth = 0;
2281     UInt_t pktt = 0;
2282     UInt_t pkth = 0;
2283     Int_t pth = -1;
2284     Int_t ptht = -1;
2285     Int_t evbeft = 0;
2286     Int_t evbefh = 0;
2287     UInt_t tcod;
2288     //
2289     // no runtrailers in the file!
2290     //
2291     if ( !rtev ){
2292     if ( !rhev ){
2293     if ( IsDebug() ) printf(" No runheaders nor runtrailers!! \n");
2294     if ( !(upperentry-chminentry) ){
2295     if ( IsDebug() ) printf(" No physics events nor runs in the file \n"); // di nuovo potrebbe esserci un runtrailer senza eventi (riempimento MM)
2296     // throw -8;
2297     return 0; // one could check if there is any calibration no need to exit with error
2298     } else {
2299     this->HandleRunFragments(true,true,chminentry,upperentry); // no runtrailers ma potrebbe esserci un runheader ora...
2300     };
2301     } else {
2302     //
2303     // we have runheaders but not runtrailers!
2304     //
2305     if ( debug ) printf(" We have runheaders (%i) but not runtrailers (%i) ! \n",rhev,rtev);
2306     for ( pth=0; pth < rhev; pth++ ){
2307     rh->GetEntry(pth);
2308     phh = ehh->GetPscuHeader();
2309     pkth = phh->GetCounter();
2310     obth = phh->GetOrbitalTime();
2311     if ( PKT(pkth) >= PKT(pktfirst) && PKT(pkth) <= upperpkt ){
2312     cod = ehh->GetCounter();
2313     tcod = (UInt_t)cod->Get(pctp->Physics);
2314     evbefh = TMath::Max(chminentry,tcod);
2315 mocchiut 1.2 // if ( (UInt_t)evbefh == upperentry ) evbefh = upperentry + 1; // this does not work due to the Counter bug in chewbacca
2316 mocchiut 1.1 if ( (UInt_t)evbefh == upperentry || !upperentry ) evbefh = upperentry + 1;
2317 mocchiut 1.2 //
2318     if ( debug ) printf(" evbefh %i upperentry %u \n",evbefh,upperentry);
2319 mocchiut 1.1 //
2320     this->HandleRunFragments(false,true,evbefh,upperentry);
2321     //
2322     };
2323     };
2324     //
2325     };
2326     //
2327     } else {
2328     //
2329     Int_t conptt = -1;
2330     for (Int_t ptt=0; ptt<rtev; ptt++){
2331     //
2332     rt->GetEntry(ptt);
2333     pht = eht->GetPscuHeader();
2334     pktt = pht->GetCounter();
2335     obtt = pht->GetOrbitalTime();
2336     //
2337     if ( PKT(pktt) >= PKT(pktfirst) && PKT(pktt) <= upperpkt ){
2338     //
2339     conptt++;
2340     //
2341     cod = eht->GetCounter();
2342     ptht = cod->Get(pctp->RunHeader) - 1;
2343     // evbeft = cod->Get(pctp->Physics);
2344     tcod = (UInt_t)cod->Get(pctp->Physics);
2345     if ( !tcod ) tcod = 1;
2346     evbeft = TMath::Min(upperentry,(tcod-1));
2347     if ( debug ) printf(" Loop in runtrailers, evbeft is %u upperentry %u cod->getetc %u \n",evbeft,upperentry,cod->Get(pctp->Physics));
2348     //
2349     // if ( !conptt && !(ptht+1) ){ // here we assume ptht+1 = 0 at the beginning of the interval that could not be true if the interval start from middle file... it must be equal to the number of RH before the interval that is not counted anywhere
2350     if ( !conptt && (ptht+1) == nrhbef ){
2351     //
2352     if ( IsDebug() ) printf(" Piece of run at the beginning of the file %i %i %u \n",ptht,pth,ptt);
2353     //
2354     this->HandleRunFragments(true,false,chminentry,(evbeft));
2355     //
2356     pth = ptht; // ??
2357     //
2358     } else if ( pth == ptht ){
2359     //
2360     if ( IsDebug() ) printf(" Missing header %i %i %u\n",ptht,pth,ptt);
2361     //
2362     if ( (ptt-1) < 0 ) throw -15; // should never arrive here!
2363     rt->GetEntry(ptt-1);
2364     cod = eht->GetCounter();
2365     tcod = (UInt_t)cod->Get(pctp->Physics);
2366     evbefh = TMath::Max(chminentry,tcod);
2367     //evbefh = cod->Get(pctp->Physics);
2368     rt->GetEntry(ptt);
2369     pht = eht->GetPscuHeader();
2370     //
2371     if ( IsDebug() ) printf(" Try to find the beginning of a run which has only the runtrailer %i %i %u \n",ptht,pth,ptt);
2372     if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' %u %u %u \n",pkth,obth,obtt);
2373     //
2374     this->HandleMissingHoT(true,false,evbefh,(evbeft));
2375     //
2376     } else {
2377     //
2378     rh->GetEntry(ptht);
2379     phh = ehh->GetPscuHeader();
2380     pkth = phh->GetCounter();
2381     obth = phh->GetOrbitalTime();
2382     cod = ehh->GetCounter();
2383     tcod = (UInt_t)cod->Get(pctp->Physics);
2384     if ( !tcod ) tcod = 1;
2385     evbefh = TMath::Max(chminentry,(tcod-1));
2386     //
2387     if ( PKT(pkth) >= PKT(pktfirst) && PKT(pkth) <= upperpkt ){
2388     if ( IsDebug() ) printf(" Could be a good run, we have a runheader followed by a runtrailer %i %i %u\n",ptht,pth,ptt);
2389     //
2390     // evbefh = cod->Get(pctp->Physics);
2391     if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' %u %u %u \n",pkth,obth,obtt);
2392     //
2393     // handle this run
2394     //
2395     this->HandleRun();
2396     //
2397     //
2398     if ( debug ) printf(" Standard case, evbefh is %u chminentry %u cod->getetc %u \n",evbefh,chminentry,cod->Get(pctp->Physics));
2399     //
2400     } else {
2401     // missing header in the considered interval!
2402     if ( debug ) printf(" Missing header in the considered interval \n");
2403     this->HandleRunFragments(true,false,evbefh,evbeft);
2404     };
2405     //
2406     if ( PKT(pkth)>PKT(pktfirst) && OBT(obth)>OBT(obtfirst) && PKT(pkth)<=(upperpkt) && !conptt ){
2407     //
2408     if ( IsDebug() ) printf(" Piece of run at the beginning of the file WITH NO RUNTRAILER evbefh = %u \n",evbefh);
2409     //
2410     if ( evbefh == 0 ) {
2411     //
2412     if ( !chewbacca ){
2413     signal = 8;
2414     if ( IsDebug() ) printf(" Not supported yet: run with no events, no runtrailer, no runheader \n");
2415     } else {
2416     if ( debug ) printf(" The file does not start with a physics packet, no problem continue \n");
2417     };
2418     //
2419     } else {
2420     //
2421     this->HandleRunFragments(true,true,chminentry,(evbefh));
2422     //
2423     };
2424     };
2425     //
2426     //
2427     if ( (ptht - pth) > 1 ){
2428     //
2429     if ( IsDebug() ) printf(" Missing runtrailers! \n");
2430     if ( IsDebug() ) printf(" Attention there is a jump in the runheader counter %i %i %u \n",ptht,pth,ptt);
2431     // is not the consecutive header
2432     while ( pth != ptht ){
2433     //
2434     // treat the header(s) in the middle and then go to the next header, repeat until you reach the correct header.
2435     //
2436     pth++;
2437     //
2438     rh->GetEntry(pth+1);
2439     phh = ehh->GetPscuHeader();
2440     pktt = phh->GetCounter();
2441     obtt = phh->GetOrbitalTime();
2442     cod = ehh->GetCounter();
2443     // evbeft = cod->Get(pctp->Physics);
2444     tcod = (UInt_t)cod->Get(pctp->Physics);
2445     if ( !tcod ) tcod = 1;
2446     evbeft = TMath::Min(upperentry,(tcod-1));
2447     rh->GetEntry(pth);
2448     phh = ehh->GetPscuHeader();
2449     cod = ehh->GetCounter();
2450     pkth = phh->GetCounter();
2451     obth = phh->GetOrbitalTime();
2452     //evbefh = cod->Get(pctp->Physics);
2453     tcod = (UInt_t)cod->Get(pctp->Physics);
2454     evbefh = TMath::Max(chminentry,tcod);
2455     //
2456     if ( PKT(pkth) >= PKT(pktfirst) && PKT(pkth) <= upperpkt && pth != ptht ){
2457     //
2458     if ( IsDebug() ) printf(" Try to find the end of a run which has only the runheader %i %i %u \n",ptht,pth,ptt);
2459     if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' %u %u %u \n",pkth,obth,obtt);
2460     //
2461     this->HandleMissingHoT(false,true,evbefh,evbeft);
2462     //
2463     };
2464     };
2465     //
2466     } else if ( !(ptht - pth) ){
2467     //
2468     if ( IsDebug() ) printf(" Missing runheader! \n");
2469     if ( IsDebug() ) printf(" Attention! the runheader counter did not changed %i %i %u \n",ptht,pth,ptt);
2470     if ( IsDebug() ) printf(" The run should have already been handled by HandleRun() \n");
2471     if ( PEDANTIC ) throw -87;
2472     //
2473     } else {
2474     //
2475     // go on with next header
2476     //
2477     pth = ptht;
2478     };
2479     //
2480     };
2481     //
2482     // if ( ptt+1 == rtev){
2483     if ( conptt+1 == nrtev ){
2484     // if ( conptt+1 == (nrtev+nrtbef )){
2485     ptht++;
2486     if ( ptht < rhev ){
2487     rh->GetEntry(ptht);
2488     phh = ehh->GetPscuHeader();
2489     pkth = phh->GetCounter();
2490     obth = phh->GetOrbitalTime();
2491     cod = ehh->GetCounter();
2492     tcod = (UInt_t)cod->Get(pctp->Physics);
2493     evbefh = TMath::Max(chminentry,tcod);
2494     if ( PKT(pkth) >= PKT(pktfirst) && PKT(pkth) <= upperpkt ){
2495     // evbefh = cod->Get(pctp->Physics);
2496     if ( IsDebug() ) printf(" Piece of run at the end of file %u %u %u \n",pkth,obth,obtt);
2497     if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''' %i %i %u \n",ptht,pth,ptt);
2498     if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''' %u \n",rhev);
2499     if ( IsDebug() ) printf(" evbefh %u upperentry %u \n",(UInt_t)evbefh,upperentry);
2500     //
2501     this->HandleRunFragments(false,true,evbefh,upperentry);
2502     //
2503     };
2504     } else {
2505     //
2506     // check if we have a fragment with no header
2507     //
2508     if ( (UInt_t)evbeft < upperentry-1 && upperentry>0 ){
2509     if ( IsDebug() ) printf(" Piece of run at the end of the file with NO RUNHEADER! evbeft %u upperentry-1 %u \n",(UInt_t)evbeft,upperentry-1);
2510     //
2511     if ( (ptt-1) < 0 ) throw -15; // should never arrive here!
2512     rt->GetEntry(ptt-1);
2513     cod = eht->GetCounter();
2514     tcod = (UInt_t)cod->Get(pctp->Physics);
2515     evbefh = TMath::Max(chminentry,tcod);
2516     // evbefh = cod->Get(pctp->Physics);
2517     rt->GetEntry(ptt);
2518     pht = eht->GetPscuHeader();
2519     this->HandleRunFragments(true,true,evbefh,upperentry);
2520     };
2521     };
2522     };
2523     //
2524     };
2525     };
2526     };
2527     //
2528     return(signal);
2529     };
2530    
2531     /**
2532     *
2533     * Check if the run has already been inserted
2534     *
2535     */
2536     Bool_t PamelaDBOperations::IsRunAlreadyInserted(){
2537     //
2538     TSQLResult *result = 0;
2539     TSQLRow *row = 0;
2540     //
2541     stringstream oss;
2542     oss.str("");
2543     //
2544     // the where clause is of the type: boot_number = _our_boot && (
2545     // ( runhead_time >= (_our_runhead_time-10) && runtrail_time <= (_our_runtrail_time+10) &&
2546     // ( runhead_obt >= _our_runheadobt || runhead_pkt >= _our_runheadpkt ) &&
2547     // ( runtrail_obt >= _our_runtrailobt || runtrail_pkt >= _our_runtrailpkt ) )
2548     // ||
2549     // ( runhead_time <= _our_runhead_time && runtrail_time >= _our_runtrail_time &&
2550     // ( runhead_obt <= _our_runheadobt || runhead_pkt <= _our_runheadpkt ) &&
2551     // ( runtrail_obt <= _our_runtrailobt || runtrail_pkt <= _our_runtrailpkt ) )
2552     // ||
2553     // ( runhead_time = _our_runhead_time && runtrail_time = _our_runtrail_time && nevents > 100 )
2554     // )
2555     // ||
2556     // ( runhead_time = _our_runhead_time && runtrail_time > _our_runtrail_time && nevents > 100 )
2557     // )
2558     // ||
2559     // ( runhead_time < _our_runhead_time && runtrail_time = _our_runtrail_time && nevents > 100 )
2560     // )
2561     //
2562     oss << " SELECT ID,NEVENTS,TRK_CALIB_USED,PKT_COUNTER FROM GL_RUN WHERE "
2563     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
2564     << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
2565     << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
2566     << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
2567     << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2568     << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
2569     << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
2570     << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2571     << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
2572     << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
2573     << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2574     << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR ";
2575     if ( glrun->GetNEVENTS() < 100 ){
2576     oss<<" RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << "))); ";
2577     } else {
2578     oss << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ")) OR "
2579     << " (RUNHEADER_TIME=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND " // these two lines in a certain way disable the patch below...
2580     << " RUNTRAILER_TIME=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND NEVENTS>100) OR" //
2581     << " (RUNHEADER_TIME=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND " //
2582     << " RUNTRAILER_TIME>" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND NEVENTS>100) OR" //
2583     << " (RUNHEADER_TIME<" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND " //
2584     << " RUNTRAILER_TIME=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND NEVENTS>100)" //
2585     << " );";
2586     };
2587     //
2588     if ( IsDebug() ) printf(" THIS RUN: RUNHEADER_OBT %u RUNTRAILER_OBT %u RUNHEADER_PKT %u RUNTRAILER_PKT %u NEVENTS %u\n", glrun->GetRUNHEADER_OBT(),glrun->GetRUNTRAILER_OBT(),glrun->GetRUNHEADER_PKT(),glrun->GetRUNTRAILER_PKT(),glrun->GetNEVENTS());
2589     if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
2590     result = conn->Query(oss.str().c_str());
2591     //
2592     if ( !result ) throw -4;
2593     //
2594     row = result->Next();
2595     //
2596     if ( !row ){
2597     if ( IsDebug() ) printf(" The run is new \n");
2598     if ( IsDebug() ) printf(" -> fill the DB \n");
2599     return(false); // the file has not been inserted in the DB, go on.
2600     };
2601     //
2602     Bool_t signal = true;
2603     //
2604     while ( row != NULL ){
2605     if ( IsDebug() ) printf(" A run exists with runheader and runtrailer time and packets compatible with this one \n");
2606     //
2607     // the run has already been inserted
2608     //
2609     if ( signal && IsDebug() ) printf(" The run has already been inserted\n");
2610     if ( PEDANTIC ) throw -86;
2611     return(true); //<<<<<<<<<<<<<<<<<<<<<<<< patch follows, uncomment here
2612     //
2613     // PATCH!
2614     // we keep the processing run if (in order of growing importance) 1) we have the runtrailer while the old run doesn't have it 2) we have the runheader
2615     // while the old run doesn't have it 3) we have more events than the old run
2616     //
2617     if ( glrun->GetNEVENTS() > (UInt_t)atoll(row->GetField(1)) ){
2618     //
2619     if ( IsDebug() ) printf(" The new run has more events than the old one \n");
2620     glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2621 mocchiut 1.2 // oss.str("");
2622     // oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2623     // if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());
2624     // conn->Query(oss.str().c_str());
2625 mocchiut 1.1 if ( signal ) signal = false;
2626     goto gonext;
2627     //
2628     } else if ( glrun->GetNEVENTS() < (UInt_t)atoll(row->GetField(1)) ){
2629     if ( IsDebug() ) printf(" The new run has less events than the old one \n");
2630     if ( IsDebug() ) printf(" The run is already inserted \n");
2631     goto gonext;
2632     };
2633     //
2634     if ( glrun->GetTRK_CALIB() && !(UInt_t)atoll(row->GetField(2)) ){
2635     //
2636     if ( IsDebug() ) printf(" The new run has the same number of events and the runheader the old one miss the runheader \n");
2637     //
2638     glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2639 mocchiut 1.2 // oss.str("");
2640     // oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2641     // if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());
2642     // conn->Query(oss.str().c_str());
2643 mocchiut 1.1 //
2644     if ( signal ) signal = false;
2645     goto gonext;
2646     } else if ( !glrun->GetTRK_CALIB() && (UInt_t)atoll(row->GetField(2)) ){
2647     if ( IsDebug() ) printf(" The new run has the same number of events but miss the runheader the old has the runheader \n");
2648     if ( IsDebug() ) printf(" The run is already inserted \n");
2649     goto gonext;
2650     };
2651     //
2652     if ( glrun->GetPKT_COUNTER() && !(UInt_t)atoll(row->GetField(3)) ){
2653     //
2654     if ( IsDebug() ) printf(" The new run has the same number of events, the runheader and the runtrailer the old one miss the runtrailer \n");
2655     //
2656     glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2657 mocchiut 1.2 // oss.str("");
2658     // oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2659     // if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());
2660     // conn->Query(oss.str().c_str());
2661 mocchiut 1.1 if ( signal ) signal = false;
2662     //
2663     };
2664     //
2665     gonext:
2666     // END PATCH!
2667     //
2668     row = result->Next();
2669     //
2670     };
2671     //
2672     delete result;
2673     //
2674     if ( signal && IsDebug() ) printf(" The run has already been inserted \n");
2675     if ( !signal && IsDebug() ) printf(" The run existed and has been overridden, fill the DB \n");
2676     if ( PEDANTIC ) throw -86;
2677     return(signal);
2678     };
2679    
2680     /**
2681     * Handle runs which seems to be good ones.
2682     **/
2683     void PamelaDBOperations::HandleRun(){
2684     ULong64_t chkpkt = 0;
2685     ULong64_t pktt = (ULong64_t)PKT(pht->GetCounter());
2686     ULong64_t pkth = (ULong64_t)PKT(phh->GetCounter());
2687     //
2688     chkpkt = pkth + (ULong64_t)runt->PKT_COUNTER + 1ULL + 1ULL;
2689     //
2690     if ( labs(chkpkt-pktt)<2 ){
2691     //
2692     if ( IsDebug() ) printf(" check %llu pktt %llu \n",chkpkt,pktt);
2693     //
2694     // it must be a good run, fill the db
2695     //
2696     this->FillClass();
2697     //
2698     if ( !IsRunAlreadyInserted() ){
2699     glrun->SetID(this->AssignRunID());
2700     glrun->SetID_RUN_FRAG(0);
2701     glrun->Fill_GL_RUN(conn);
2702     };
2703     } else {
2704     //
2705     if ( IsDebug() ) printf(" oh no! the distance between runheader and runtrailer seems wrong: check %llu pktt %llu \n",chkpkt,pktt);
2706     if ( IsDebug() ) printf(" try to recover run(s) without runheader and runtrailer between runheader and runtrailer\n");
2707     //
2708     this->HandleSuspiciousRun();
2709     //
2710     };
2711     //
2712     //
2713     return;
2714     };
2715    
2716    
2717     /**
2718     * Handle run fragments at the beginning or at the end of the file
2719     **/
2720     void PamelaDBOperations::HandleRunFragments(Bool_t mishead, Bool_t mistrail, UInt_t firstev, UInt_t lastev){
2721     //
2722     UInt_t rhfirstev = firstev;
2723     UInt_t rtlastev = lastev;
2724     Bool_t found = false;
2725     Bool_t foundinrun = false;
2726     //
2727     TSQLResult *result = 0;
2728     TSQLRow *row = 0;
2729     //
2730     stringstream oss;
2731     oss.str("");
2732     //
2733     // is the piece of run good (no other packets inside)?
2734     //
2735     if ( !this->IsRunConsistent(mishead,mistrail,firstev,lastev)){
2736     //
2737     // if not, handle other pieces and continue with the first one
2738     //
2739     if ( IsDebug() ) printf("The run is not consistent, it contains non-physics packets! The run has been handled \n");
2740     //
2741     } else {
2742     //
2743 mocchiut 1.2 // we have now the good first piece of a run, fill the glrun object
2744     //
2745     if ( rhfirstev != firstev && !mishead ) mishead = true;
2746     if ( rtlastev != lastev && !mistrail ) mistrail = true;
2747 mocchiut 1.1 //
2748 mocchiut 1.2 this->FillClass(mishead,mistrail,firstev,lastev);
2749 mocchiut 1.1 //
2750 mocchiut 1.2 if ( IsDebug() ) printf("The run is good, is it the other piece in the GL_RUN_FRAGMENTS table?\n");
2751     if ( IsDebug() ) printf(" C THIS RUN: RUNHEADER_OBT %u RUNTRAILER_OBT %u RUNHEADER_PKT %u RUNTRAILER_PKT %u \n", glrun->GetRUNHEADER_OBT(),glrun->GetRUNTRAILER_OBT(),glrun->GetRUNHEADER_PKT(),glrun->GetRUNTRAILER_PKT());
2752 mocchiut 1.1 //
2753 mocchiut 1.2 // First of all insert the run in the fragment table...
2754 mocchiut 1.1 //
2755     oss.str("");
2756 mocchiut 1.2 oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE "
2757     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
2758     << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
2759     << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
2760     << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
2761     << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2762     << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
2763     << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
2764     << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2765     << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
2766     << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
2767     << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2768     << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
2769     << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
2770 mocchiut 1.1 //
2771 mocchiut 1.2 if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
2772 mocchiut 1.1 result = conn->Query(oss.str().c_str());
2773     //
2774     if ( !result ) throw -4;
2775     //
2776     row = result->Next();
2777     //
2778 mocchiut 1.2 if ( !row ){
2779     //
2780     // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
2781     //
2782     if ( IsDebug() ) printf(" The run is new \n");
2783     if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
2784     //
2785     glrun->SetID(this->AssignRunID());
2786     glrun->SetID_RUN_FRAG(0);
2787     glrun->Fill_GL_RUN_FRAGMENTS(conn);
2788     //
2789     } else {
2790     if ( IsDebug() ) printf(" The run is already present in the fragment table \n");
2791     if ( PEDANTIC ) throw -69;
2792     return;
2793     };
2794     //
2795     if ( chewbacca && mishead && mistrail ) goto justcheck;
2796     //
2797     // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?
2798     //
2799     if ( mishead && ( rhfirstev == firstev || chewbacca ) ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is
2800     // missing it no way we can found a piece in the frag table
2801 mocchiut 1.1 //
2802     oss.str("");
2803 mocchiut 1.2 oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN_FRAGMENTS WHERE "
2804 mocchiut 1.1 << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2805     << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2806     << " ID != " << glrun->ID
2807 mocchiut 1.2 << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
2808 mocchiut 1.1 //
2809 mocchiut 1.2 if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());
2810 mocchiut 1.1 result = conn->Query(oss.str().c_str());
2811     //
2812     if ( !result ) throw -4;
2813     //
2814     row = result->Next();
2815     //
2816 mocchiut 1.2 if ( !row && NoFrag() ){
2817     //
2818     oss.str("");
2819     oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "
2820     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2821     << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2822     << " ID != " << glrun->ID
2823     << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
2824     //
2825     if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
2826     result = conn->Query(oss.str().c_str());
2827     //
2828     if ( !result ) throw -4;
2829     //
2830     foundinrun = true;
2831     //
2832     row = result->Next();
2833     //
2834     };
2835 mocchiut 1.1 //
2836 mocchiut 1.2 if ( !row ){
2837     if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
2838     found = false;
2839     } else {
2840     //
2841     found = false; // default value
2842     //
2843     if ( IsDebug() ) printf(" Found a possible candidate, checking if it is the good one... \n");
2844 mocchiut 1.1 //
2845 mocchiut 1.2 // if we have both runheader and runtrailer we can check with pkt_counter:
2846 mocchiut 1.1 //
2847 mocchiut 1.2 if ( !mistrail && (UInt_t)atoll(row->GetField(1)) != 0 ){
2848     ULong64_t chkpkt = 0;
2849     ULong64_t pktt = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
2850     ULong64_t pkth = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
2851     //
2852     chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;
2853 mocchiut 1.1 //
2854 mocchiut 1.2 if ( labs(chkpkt-pktt)<2 ){
2855     //
2856     if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
2857     //
2858     found = true;
2859     //
2860     } else {
2861     //
2862     if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);
2863     //
2864     found = false;
2865     //
2866     };
2867     };
2868     if ( !found && chewbacca ) goto justcheck;
2869     if ( !found ){
2870 mocchiut 1.1 //
2871 mocchiut 1.2 // if we arrive here we were not able to decide if the two pieces matches using only the pkt counter information, we must check times and obts
2872 mocchiut 1.1 //
2873 mocchiut 1.2 ULong64_t chkpkt1 = 0;
2874     ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
2875     ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
2876     chkpkt1 = labs(orunh1-dbrunt1);
2877 mocchiut 1.1 //
2878 mocchiut 1.2 ULong64_t chkpkt2 = 0;
2879     ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNHEADER_OBT());
2880     ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
2881     chkpkt2 = labs(orunh2-dbrunt2);
2882 mocchiut 1.1 //
2883 mocchiut 1.2 ULong64_t chkpkt3 = 0;
2884     ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNHEADER_TIME());
2885     ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
2886     chkpkt3 = labs(orunh3-dbrunt3);
2887 mocchiut 1.1 //
2888 mocchiut 1.2 if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
2889     // if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){
2890     //
2891     if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
2892     //
2893     found = true;
2894     //
2895     } else {
2896     //
2897     if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
2898     //
2899     found = false;
2900     //
2901     };
2902 mocchiut 1.1 };
2903     };
2904 mocchiut 1.2 //
2905     if ( found ){
2906     //
2907     // we have found the missing piece, glue the two together, merge the informations, fill the gl_run table (check first runs do not exists), delete entry in frag table
2908     //
2909     if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
2910     //
2911     if ( foundinrun ){
2912     glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
2913     glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2914     };
2915 mocchiut 1.1 //
2916 mocchiut 1.2 GL_RUN *glrun1 = new GL_RUN();
2917 mocchiut 1.1 //
2918 mocchiut 1.2 // UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
2919     //
2920     oss.str("");
2921     oss << " ID="<<row->GetField(0)<<";";
2922     //
2923     glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runheader infos
2924     //
2925     // merge infos
2926     //
2927     UInt_t apkt = PKT(glrun1->GetRUNTRAILER_PKT());
2928     ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());
2929     UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());
2930     ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());
2931     if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
2932     TTree *T= 0;
2933     T = (TTree*)file->Get("Physics");
2934     if ( !T || T->IsZombie() ) throw -16;
2935     EventHeader *eh = 0;
2936     PscuHeader *ph = 0;
2937     T->SetBranchAddress("Header", &eh);
2938     while ( apkt > bpkt && aobt > bobt && firstev < lastev ){
2939     T->GetEntry(firstev);
2940     ph = eh->GetPscuHeader();
2941     bpkt = PKT(ph->GetCounter());
2942     bobt = OBT(ph->GetOrbitalTime());
2943     firstev++;
2944     if ( PEDANTIC ) throw -71;
2945     };
2946     if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
2947 mocchiut 1.1 //
2948 mocchiut 1.2 glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
2949     glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
2950     glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
2951     glrun1->SetRUNTRAILER_OBT(glrun->GetRUNTRAILER_OBT());
2952     glrun1->SetRUNTRAILER_PKT(glrun->GetRUNTRAILER_PKT());
2953     //
2954     glrun->SetEV_FROM(firstev);
2955     glrun->SetNEVENTS(lastev-firstev+1);
2956     //
2957     glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
2958     glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
2959     glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
2960     glrun->SetCOMPILATIONTIMESTAMP(glrun1->GetCOMPILATIONTIMESTAMP());
2961     glrun->SetFAV_WRK_SCHEDULE(glrun1->GetFAV_WRK_SCHEDULE());
2962     glrun->SetEFF_WRK_SCHEDULE(glrun1->GetEFF_WRK_SCHEDULE());
2963     glrun->SetPRH_VAR_TRG_MODE_A(glrun1->GetPRH_VAR_TRG_MODE_A());
2964     glrun->SetPRH_VAR_TRG_MODE_B(glrun1->GetPRH_VAR_TRG_MODE_B());
2965     glrun->SetACQ_BUILD_INFO(glrun1->GetACQ_BUILD_INFO());
2966     glrun->SetACQ_VAR_INFO(glrun1->GetACQ_VAR_INFO());
2967     glrun->SetRM_ACQ_AFTER_CALIB(glrun1->GetRM_ACQ_AFTER_CALIB());
2968     glrun->SetRM_ACQ_SETTING_MODE(glrun1->GetRM_ACQ_SETTING_MODE());
2969     glrun->SetTRK_CALIB_USED(glrun1->GetTRK_CALIB_USED());
2970     glrun->SetCAL_DSP_MASK(glrun1->GetCAL_DSP_MASK());
2971     glrun->SetLAST_TIMESYNC(glrun1->GetLAST_TIMESYNC());
2972     glrun->SetOBT_TIMESYNC(glrun1->GetOBT_TIMESYNC());
2973     //
2974     if ( glrun1->GetPHYSENDRUN_MASK_S3S2S12() ) glrun->SetPHYSENDRUN_MASK_S3S2S12(glrun1->GetPHYSENDRUN_MASK_S3S2S12());
2975     if ( glrun1->GetPHYSENDRUN_MASK_S11CRC() ) glrun->SetPHYSENDRUN_MASK_S11CRC(glrun1->GetPHYSENDRUN_MASK_S11CRC());
2976     //
2977     if ( !IsRunAlreadyInserted() ){
2978     //
2979     // glrun->SetID(this->AssignRunID());
2980     glrun->SetID_RUN_FRAG(glrun1->GetID());
2981     glrun->Fill_GL_RUN(conn);
2982 mocchiut 1.1 //
2983 mocchiut 1.2 // set id number
2984 mocchiut 1.1 //
2985 mocchiut 1.2 glrun1->SetID_RUN_FRAG(glrun->GetID());
2986     glrun1->Fill_GL_RUN(conn);
2987 mocchiut 1.1 //
2988     };
2989 mocchiut 1.2 // delete old entry in fragment table
2990     //
2991     glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2992     glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2993 mocchiut 1.1 //
2994 mocchiut 1.2 delete glrun1;
2995 mocchiut 1.1 //
2996     //
2997 mocchiut 1.2 return;
2998 mocchiut 1.1 //
2999     };
3000     //
3001     };
3002     //
3003 mocchiut 1.2 if ( mistrail && ( rtlastev == lastev || chewbacca )) { // look for runtrailer (only when at the end of the file, if at the beginning and the runh is
3004     // missing it no way we can found a piece in the frag table
3005 mocchiut 1.1 //
3006     oss.str("");
3007 mocchiut 1.2 oss << " SELECT ID,PKT_COUNTER,RUNHEADER_TIME,RUNHEADER_OBT,RUNTRAILER_PKT,RUNHEADER_PKT FROM GL_RUN_FRAGMENTS WHERE "
3008 mocchiut 1.1 << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3009     << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
3010     << " ID != " << glrun->ID
3011 mocchiut 1.2 << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
3012 mocchiut 1.1 //
3013 mocchiut 1.2 if ( IsDebug() ) printf(" look for runtrailer in the fragments table: query is \n %s \n",oss.str().c_str());
3014 mocchiut 1.1 result = conn->Query(oss.str().c_str());
3015     //
3016     if ( !result ) throw -4;
3017     //
3018     row = result->Next();
3019     //
3020 mocchiut 1.2 if ( !row && NoFrag() ){
3021     //
3022     oss.str("");
3023     oss << " SELECT ID,PKT_COUNTER,RUNHEADER_TIME,RUNHEADER_OBT,RUNTRAILER_PKT,RUNHEADER_PKT FROM GL_RUN WHERE "
3024     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3025     << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
3026     << " ID != " << glrun->ID
3027     << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
3028     //
3029     if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
3030     result = conn->Query(oss.str().c_str());
3031     //
3032     if ( !result ) throw -4;
3033     //
3034     foundinrun = true;
3035     row = result->Next();
3036     //
3037     };
3038 mocchiut 1.1 //
3039 mocchiut 1.2 if ( !row ){
3040     if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
3041     found = false;
3042     } else {
3043     //
3044     found = false; // default value
3045     //
3046     if ( IsDebug() ) printf(" Found a possible candidate, checking if it is the good one... \n");
3047 mocchiut 1.1 //
3048 mocchiut 1.2 // if we have both runheader and runtrailer we can check with pkt_counter:
3049 mocchiut 1.1 //
3050 mocchiut 1.2 if ( !mishead && (UInt_t)atoll(row->GetField(1)) != 0 ){
3051     ULong64_t chkpkt = 0;
3052     ULong64_t pktt = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
3053     ULong64_t pkth = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
3054 mocchiut 1.1 //
3055 mocchiut 1.2 chkpkt = pkth + (ULong64_t)((UInt_t)atoll(row->GetField(1))) + 1ULL + 1ULL;
3056 mocchiut 1.1 //
3057 mocchiut 1.2 if ( labs(chkpkt-pktt)<2 ){
3058     //
3059     if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
3060     //
3061     found = true;
3062     //
3063     } else {
3064     //
3065     if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);
3066     //
3067     found = false;
3068     //
3069     };
3070     };
3071     if ( !found && chewbacca ) goto justcheck;
3072     if ( !found ){
3073     //
3074     // if we arrive here we were not able to decide if the two pieces matches using only the pkt counter information, we must check times and obts
3075 mocchiut 1.1 //
3076 mocchiut 1.2 ULong64_t chkpkt1 = 0;
3077     ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
3078     ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
3079     chkpkt1 = labs(orunh1-dbrunt1);
3080 mocchiut 1.1 //
3081 mocchiut 1.2 ULong64_t chkpkt2 = 0;
3082     ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNTRAILER_OBT());
3083     ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
3084     chkpkt2 = labs(orunh2-dbrunt2);
3085 mocchiut 1.1 //
3086 mocchiut 1.2 ULong64_t chkpkt3 = 0;
3087     ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNTRAILER_TIME());
3088     ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
3089     chkpkt3 = labs(orunh3-dbrunt3);
3090 mocchiut 1.1 //
3091 mocchiut 1.2 if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
3092     //
3093     if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
3094     //
3095     found = true;
3096     //
3097     } else {
3098     //
3099     if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
3100     //
3101     found = false;
3102     //
3103     };
3104 mocchiut 1.1 };
3105     };
3106 mocchiut 1.2 //
3107     if ( found ){
3108     //
3109     // we have found the missing piece, glue the two together, merge the informations, fill the gl_run table (check first runs do not exists), delete entry in frag table
3110     //
3111     if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
3112     //
3113     if ( foundinrun ){
3114     glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3115     glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
3116     };
3117 mocchiut 1.1 //
3118 mocchiut 1.2 GL_RUN *glrun1 = new GL_RUN();
3119 mocchiut 1.1 //
3120 mocchiut 1.2 // UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
3121 mocchiut 1.1 //
3122 mocchiut 1.2 oss.str("");
3123     oss << " ID="<<row->GetField(0)<<";";
3124     //
3125     glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runtrailer infos
3126 mocchiut 1.1 //
3127 mocchiut 1.2 // merge infos
3128 mocchiut 1.1 //
3129 mocchiut 1.2 UInt_t apkt = PKT(glrun->GetRUNTRAILER_PKT());
3130     ULong64_t aobt = OBT(glrun->GetRUNTRAILER_OBT());
3131     UInt_t bpkt = PKT(glrun1->GetRUNHEADER_PKT());
3132     ULong64_t bobt = OBT(glrun1->GetRUNHEADER_OBT());
3133     if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);
3134     TTree *T= 0;
3135     T = (TTree*)file->Get("Physics");
3136     if ( !T || T->IsZombie() ) throw -16;
3137     EventHeader *eh = 0;
3138     PscuHeader *ph = 0;
3139     T->SetBranchAddress("Header", &eh);
3140     while ( apkt > bpkt && aobt > bobt && lastev > 0 ){
3141     T->GetEntry(lastev);
3142     ph = eh->GetPscuHeader();
3143     apkt = PKT(ph->GetCounter());
3144     aobt = OBT(ph->GetOrbitalTime());
3145     lastev--;
3146     if ( PEDANTIC ) throw -72;
3147     };
3148     if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);
3149     //
3150     glrun->SetEV_TO(lastev);
3151     glrun->SetNEVENTS(lastev-firstev+1);
3152     glrun->SetPKT_COUNTER(glrun1->GetPKT_COUNTER());
3153     glrun->SetPKT_READY_COUNTER(glrun1->GetPKT_READY_COUNTER());
3154     glrun->SetRUNTRAILER_TIME(glrun1->GetRUNTRAILER_TIME());
3155     glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());
3156     glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());
3157     //
3158     glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());
3159     glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());
3160     glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());
3161     glrun1->SetCOMPILATIONTIMESTAMP(glrun->GetCOMPILATIONTIMESTAMP());
3162     glrun1->SetFAV_WRK_SCHEDULE(glrun->GetFAV_WRK_SCHEDULE());
3163     glrun1->SetEFF_WRK_SCHEDULE(glrun->GetEFF_WRK_SCHEDULE());
3164     glrun1->SetPRH_VAR_TRG_MODE_A(glrun->GetPRH_VAR_TRG_MODE_A());
3165     glrun1->SetPRH_VAR_TRG_MODE_B(glrun->GetPRH_VAR_TRG_MODE_B());
3166     glrun1->SetACQ_BUILD_INFO(glrun->GetACQ_BUILD_INFO());
3167     glrun1->SetACQ_VAR_INFO(glrun->GetACQ_VAR_INFO());
3168     glrun1->SetRM_ACQ_AFTER_CALIB(glrun->GetRM_ACQ_AFTER_CALIB());
3169     glrun1->SetRM_ACQ_SETTING_MODE(glrun->GetRM_ACQ_SETTING_MODE());
3170     glrun1->SetTRK_CALIB_USED(glrun->GetTRK_CALIB_USED());
3171     glrun1->SetCAL_DSP_MASK(glrun->GetCAL_DSP_MASK());
3172     glrun1->SetLAST_TIMESYNC(glrun->GetLAST_TIMESYNC());
3173     glrun1->SetOBT_TIMESYNC(glrun->GetOBT_TIMESYNC());
3174     //
3175     if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ) glrun1->SetPHYSENDRUN_MASK_S3S2S12(glrun->GetPHYSENDRUN_MASK_S3S2S12());
3176     if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ) glrun1->SetPHYSENDRUN_MASK_S11CRC(glrun->GetPHYSENDRUN_MASK_S11CRC());
3177     //
3178     if ( !IsRunAlreadyInserted() ){
3179     //
3180     // glrun->SetID(this->AssignRunID());
3181 mocchiut 1.1 //
3182 mocchiut 1.2 glrun->SetID_RUN_FRAG(glrun1->GetID());
3183     glrun->Fill_GL_RUN(conn);
3184 mocchiut 1.1 //
3185 mocchiut 1.2 // set id number
3186 mocchiut 1.1 //
3187 mocchiut 1.2 glrun1->SetID_RUN_FRAG(glrun->GetID());
3188     glrun1->Fill_GL_RUN(conn);
3189 mocchiut 1.1 //
3190     };
3191 mocchiut 1.2 //
3192     // delete old entries in fragment table
3193     //
3194     glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3195     glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3196     //
3197     delete glrun1;
3198     //
3199     return;
3200     //
3201 mocchiut 1.1 };
3202 mocchiut 1.2 //
3203 mocchiut 1.1 };
3204     //
3205 mocchiut 1.2 justcheck:
3206     //
3207     if ( !found ){
3208 mocchiut 1.1 //
3209 mocchiut 1.2 if ( IsDebug() ) printf(" not found, check if we have already processed the file \n ");
3210 mocchiut 1.1 //
3211 mocchiut 1.2 // not found, has this run already inserted in the GL_RUN or in the GL_RUN_FRAGMENTS table?
3212 mocchiut 1.1 //
3213     oss.str("");
3214 mocchiut 1.2 oss << " SELECT ID FROM GL_RUN WHERE "
3215     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3216     << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3217     << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3218     << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3219     << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3220     << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3221     << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3222     << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3223     << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3224     << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3225     << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3226     << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3227     << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3228 mocchiut 1.1 //
3229 mocchiut 1.2 if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3230     result = conn->Query(oss.str().c_str());
3231 mocchiut 1.1 //
3232 mocchiut 1.2 if ( !result ) throw -4;
3233 mocchiut 1.1 //
3234 mocchiut 1.2 row = result->Next();
3235 mocchiut 1.1 //
3236 mocchiut 1.2 if ( row ){
3237     if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");
3238     if ( PEDANTIC ) throw -70;
3239     } else {
3240     if ( NoFrag() ){
3241     glrun->SetID_RUN_FRAG(glrun->GetID());
3242     glrun->Fill_GL_RUN(conn);
3243     glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3244     };
3245 mocchiut 1.1 };
3246     };
3247     }; // EEE
3248     //
3249     return;
3250     };
3251    
3252    
3253     /**
3254     * Handle run without header or trailer
3255     **/
3256     void PamelaDBOperations::HandleMissingHoT(Bool_t mishead, Bool_t mistrail, UInt_t firstev, UInt_t lastev){
3257     //
3258     //
3259     // is the piece of run good (no other packets inside)?
3260     //
3261     if ( !this->IsRunConsistent(mishead,mistrail,firstev,lastev)){
3262     //
3263     // if not, handle other pieces and continue with the first one
3264     //
3265     if ( IsDebug() ) printf("The run is not consistent, it contains non-physics packets! The run has been handled \n");
3266     //
3267     } else {
3268     //
3269     this->FillClass(mishead,mistrail,firstev,lastev);
3270     //
3271     if ( !IsRunAlreadyInserted() ){
3272     glrun->SetID(this->AssignRunID());
3273     glrun->SetID_RUN_FRAG(0);
3274     glrun->Fill_GL_RUN(conn); // it'ok we arrive here only inside a file hence in the middle of the runs...
3275     };
3276     //
3277     };
3278     //
3279     return;
3280     };
3281    
3282     /**
3283     *
3284     * check if we have non-physics packets inside the run
3285     *
3286     */
3287     Bool_t PamelaDBOperations::IsRunConsistent(Bool_t mishead, Bool_t mistrail, UInt_t &firstev, UInt_t &lastev){
3288     //
3289     EventCounter *code=0;
3290     //
3291     UInt_t nevent = 0;
3292     UInt_t checkfirst = 0;
3293     UInt_t checklast = 0;
3294     UInt_t firstentry = 0;
3295     UInt_t lastentry = 0;
3296     UInt_t firstTime = 0;
3297     UInt_t lastTime = 0;
3298     UInt_t firstPkt = 0;
3299     UInt_t lastPkt = 0;
3300     UInt_t firstObt = 0;
3301     UInt_t lastObt = 0;
3302     //
3303     pcksList packetsNames;
3304     pcksList::iterator Iter;
3305     getPacketsNames(packetsNames);
3306     //
3307     TTree *T= 0;
3308     T =(TTree*)file->Get("Physics");
3309     if ( !T || T->IsZombie() ) throw -16;
3310     EventHeader *eh = 0;
3311     PscuHeader *ph = 0;
3312     T->SetBranchAddress("Header", &eh);
3313     nevent = T->GetEntries();
3314     //
3315     //
3316     if ( firstev == lastev+1 || lastev == firstev ) { // no events inside the run!
3317     //if ( firstev <= lastev+1 ) { // no events inside the run!
3318     if ( IsDebug() ) printf(" Checking but no events in the run! \n");
3319     // return true is correct
3320     return(true);
3321     //
3322     } else {
3323     //
3324     T->GetEntry(firstev);
3325     code = eh->GetCounter();
3326     checkfirst = 0;
3327     for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3328 mocchiut 1.2 if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));
3329     };
3330 mocchiut 1.1 if ( IsDebug() ) printf(" Check first is %i firstev is %i\n",checkfirst,firstev);
3331     //
3332     T->GetEntry(lastev);
3333     code = eh->GetCounter();
3334     checklast = 0;
3335     for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3336 mocchiut 1.2 if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));
3337     };
3338 mocchiut 1.1 if ( IsDebug() ) printf(" Check last is %i lastev is %i\n",checklast,lastev);
3339     //
3340     if ( checkfirst == checklast ){
3341     //
3342     if ( IsDebug() ) printf(" No packets but physics inside the run, I will consider it as good\n");
3343     //
3344     return(true);
3345     //
3346     } else {
3347     //
3348     if ( IsDebug() ) printf(" There are no-phyics packets inside the run!\n");
3349     //
3350     // HERE WE MUST HANDLE THAT RUNS AND GO BACK
3351     //
3352 mocchiut 1.2 // if ( IsDebug() ) printf(" Never seen this case, try to handle it anyway, it was throw -95\n");
3353 mocchiut 1.1 //
3354     Bool_t emptyruns = false;
3355     UInt_t check = 0;
3356     UInt_t lastevtemp = lastev;
3357     UInt_t firstevno = firstev;
3358     //
3359     for (UInt_t i=firstev; i<=lastev; i++){
3360     //
3361     T->GetEntry(i);
3362     code = eh->GetCounter();
3363     //
3364     check = 0;
3365     //
3366     for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3367     if ( strcmp(*Iter,"Physics") ) check += code->Get(GetPacketType(*Iter));
3368     };
3369     //
3370     if ( checkfirst < check || i == lastev ){
3371     //
3372     firstentry = firstevno;
3373     //
3374     if ( checkfirst < check ){
3375     lastentry = i-1;
3376     } else {
3377     lastentry = i;
3378     };
3379     //
3380     if ( IsDebug() ) printf(" Run between %i and %i entries\n",firstentry,lastentry);
3381     //
3382     glrun->SetEV_FROM(firstentry);
3383     glrun->SetEV_TO(lastentry);
3384     if ( lastentry == (firstentry-1) ){ // no physics packets inside physics run with no runheader no runtrailer
3385     if ( IsDebug() ) printf(" no physics packets inside physics run with no runheader no runtrailer\n");
3386     lastentry--;
3387     };
3388     glrun->SetNEVENTS(lastentry-firstentry+1);
3389     //
3390     glrun->Set_GL_RUNH0();
3391     glrun->Set_GL_RUNT0();
3392     //
3393     glrun->SetLAST_TIMESYNC(0);
3394     glrun->SetOBT_TIMESYNC(0);
3395     //
3396     T->GetEntry(firstentry);
3397     ph = eh->GetPscuHeader();
3398     firstObt = ph->GetOrbitalTime();
3399     firstTime = this->GetAbsTime(firstObt);
3400     firstPkt = ph->GetCounter();
3401     //
3402     T->GetEntry(lastentry);
3403     ph = eh->GetPscuHeader();
3404     lastObt = ph->GetOrbitalTime();
3405     lastTime = this->GetAbsTime(lastObt);
3406     lastPkt = ph->GetCounter();
3407     //
3408     glrun->SetRUNHEADER_PKT(firstPkt);
3409 mocchiut 1.2 glrun->SetRUNTRAILER_PKT(lastPkt);
3410     //
3411     glrun->SetRUNHEADER_OBT(firstObt);
3412     glrun->SetRUNTRAILER_OBT(lastObt);
3413     //
3414     if ( IsDebug() ) printf(" A THIS RUN: RUNHEADER_OBT %u RUNTRAILER_OBT %u RUNHEADER_PKT %u RUNTRAILER_PKT %u \n", glrun->GetRUNHEADER_OBT(),glrun->GetRUNTRAILER_OBT(),glrun->GetRUNHEADER_PKT(),glrun->GetRUNTRAILER_PKT());
3415     if ( firstev == firstentry && !emptyruns && !mishead ){
3416     glrun->Set_GL_RUNH(runh,phh);
3417     firstTime = this->GetAbsTime(phh->GetOrbitalTime());
3418     if ( IsDebug() ) printf(" We have the runheader \n");
3419     };
3420     if ( lastev == i && !mistrail ){
3421     glrun->Set_GL_RUNT(runt,pht);
3422     lastTime = this->GetAbsTime(pht->GetOrbitalTime());
3423     if ( IsDebug() ) printf(" We have the runtrailer \n");
3424     };
3425     //
3426     if ( IsDebug() ) printf(" B THIS RUN: RUNHEADER_OBT %u RUNTRAILER_OBT %u RUNHEADER_PKT %u RUNTRAILER_PKT %u \n", glrun->GetRUNHEADER_OBT(),glrun->GetRUNTRAILER_OBT(),glrun->GetRUNHEADER_PKT(),glrun->GetRUNTRAILER_PKT());
3427     if ( lastentry == (firstentry-2) ){ // no events in the run
3428     emptyruns = true;
3429     if ( IsDebug() ) printf(" No events in the run \n");
3430     lastTime = firstTime;
3431     if ( (UInt_t)firstTime == this->GetAbsTime(phh->GetOrbitalTime()) ){
3432     lastObt = glrun->RUNHEADER_OBT;
3433     lastPkt = glrun->RUNHEADER_PKT;
3434     } else {
3435     lastObt = firstObt;
3436     lastPkt = firstPkt;
3437     };
3438     glrun->SetRUNTRAILER_PKT(lastPkt);
3439     glrun->SetRUNTRAILER_OBT(lastObt);
3440     lastentry++;
3441     };
3442     //
3443     this->SetCommonGLRUN(firstTime,lastTime);
3444     this->SetPhysEndRunVariables();
3445     //
3446     if ( chminentry == firstentry ){ // EEE
3447     if ( IsDebug() ) printf(" Inside isrunconsistent found a fragment of run at the beginning of the file, put it in the fragment table \n");
3448     //
3449     // this->HandleRunFragments(true,mistrail,firstentry,lastentry); // cannot call it here since it enters a loop which will destroy the already stored variables if we arrive here from HandleRunFragments
3450     //
3451    
3452    
3453    
3454    
3455    
3456    
3457    
3458    
3459    
3460    
3461    
3462    
3463    
3464     mishead = true;
3465    
3466    
3467     UInt_t rhfirstev = firstentry;
3468     // UInt_t rtlastev = lastentry;
3469     Bool_t found = false;
3470     Bool_t foundinrun = false;
3471     //
3472     TSQLResult *result = 0;
3473     TSQLRow *row = 0;
3474     //
3475     stringstream oss;
3476     oss.str("");
3477     //
3478     // we have now the good first piece of a run, fill the glrun object
3479     //
3480     // if ( rhfirstev != firstev && !mishead ) mishead = true;
3481     // if ( rtlastev != lastev && !mistrail ) mistrail = true;
3482     //
3483     // this->FillClass(mishead,mistrail,firstev,lastev);
3484     //
3485     if ( IsDebug() ) printf("zz The run is good, is it the other piece in the GL_RUN_FRAGMENTS table?\n");
3486     if ( IsDebug() ) printf("zz C THIS RUN: RUNHEADER_OBT %u RUNTRAILER_OBT %u RUNHEADER_PKT %u RUNTRAILER_PKT %u \n", glrun->GetRUNHEADER_OBT(),glrun->GetRUNTRAILER_OBT(),glrun->GetRUNHEADER_PKT(),glrun->GetRUNTRAILER_PKT());
3487     //
3488     // First of all insert the run in the fragment table...
3489     //
3490     oss.str("");
3491     oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE "
3492     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3493     << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3494     << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3495     << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3496     << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3497     << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3498     << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3499     << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3500     << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3501     << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3502     << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3503     << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3504     << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3505     //
3506     if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3507     result = conn->Query(oss.str().c_str());
3508     //
3509     if ( !result ) throw -4;
3510     //
3511     row = result->Next();
3512     //
3513     if ( !row ){
3514     //
3515     // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
3516     //
3517     if ( IsDebug() ) printf(" The run is new \n");
3518     if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
3519     //
3520     glrun->SetID(this->AssignRunID());
3521     glrun->SetID_RUN_FRAG(0);
3522     glrun->Fill_GL_RUN_FRAGMENTS(conn);
3523     //
3524     } else {
3525     if ( IsDebug() ) printf(" The run is already present in the fragment table \n");
3526     if ( PEDANTIC ) throw -69;
3527     // return;
3528     };
3529     //
3530     if ( chewbacca && mishead && mistrail ) goto zjustcheck;
3531     //
3532     // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?
3533     //
3534     if ( mishead && ( rhfirstev == firstev || chewbacca ) ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is
3535     // missing it no way we can found a piece in the frag table
3536     //
3537     oss.str("");
3538     oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN_FRAGMENTS WHERE "
3539     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3540     << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3541     << " ID != " << glrun->ID
3542     << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
3543     //
3544     if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());
3545     result = conn->Query(oss.str().c_str());
3546     //
3547     if ( !result ) throw -4;
3548     //
3549     row = result->Next();
3550     //
3551     if ( !row && NoFrag() ){
3552     //
3553     oss.str("");
3554     oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "
3555     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3556     << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3557     << " ID != " << glrun->ID
3558     << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
3559     //
3560     if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
3561     result = conn->Query(oss.str().c_str());
3562     //
3563     if ( !result ) throw -4;
3564     //
3565     foundinrun = true;
3566     //
3567     row = result->Next();
3568     //
3569     };
3570     //
3571     if ( !row ){
3572     if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
3573     found = false;
3574     } else {
3575     //
3576     found = false; // default value
3577     //
3578     if ( IsDebug() ) printf(" Found a possible candidate, checking if it is the good one... \n");
3579     //
3580     // if we have both runheader and runtrailer we can check with pkt_counter:
3581     //
3582     if ( !mistrail && (UInt_t)atoll(row->GetField(1)) != 0 ){
3583     ULong64_t chkpkt = 0;
3584     ULong64_t pktt = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
3585     ULong64_t pkth = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
3586     //
3587     chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;
3588     //
3589     if ( labs(chkpkt-pktt)<2 ){
3590     //
3591     if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
3592     //
3593     found = true;
3594     //
3595     } else {
3596     //
3597     if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);
3598     //
3599     found = false;
3600     //
3601     };
3602     };
3603     if ( !found && chewbacca ) goto zjustcheck;
3604     if ( !found ){
3605     //
3606     // if we arrive here we were not able to decide if the two pieces matches using only the pkt counter information, we must check times and obts
3607     //
3608     ULong64_t chkpkt1 = 0;
3609     ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
3610     ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
3611     chkpkt1 = labs(orunh1-dbrunt1);
3612     //
3613     ULong64_t chkpkt2 = 0;
3614     ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNHEADER_OBT());
3615     ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
3616     chkpkt2 = labs(orunh2-dbrunt2);
3617     //
3618     ULong64_t chkpkt3 = 0;
3619     ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNHEADER_TIME());
3620     ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
3621     chkpkt3 = labs(orunh3-dbrunt3);
3622     //
3623     if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
3624     // if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){
3625     //
3626     if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
3627     //
3628     found = true;
3629     //
3630     } else {
3631     //
3632     if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
3633     //
3634     found = false;
3635     //
3636     };
3637     };
3638     };
3639     //
3640     if ( found ){
3641     //
3642     // we have found the missing piece, glue the two together, merge the informations, fill the gl_run table (check first runs do not exists), delete entry in frag table
3643     //
3644     if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
3645     //
3646     if ( foundinrun ){
3647     glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3648     glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
3649     };
3650     //
3651     GL_RUN *glrun1 = new GL_RUN();
3652     //
3653     // UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
3654     //
3655     oss.str("");
3656     oss << " ID="<<row->GetField(0)<<";";
3657     //
3658     glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runheader infos
3659     //
3660     // merge infos
3661     //
3662     UInt_t apkt = PKT(glrun1->GetRUNTRAILER_PKT());
3663     ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());
3664     UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());
3665     ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());
3666     if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
3667     TTree *T= 0;
3668     T = (TTree*)file->Get("Physics");
3669     if ( !T || T->IsZombie() ) throw -16;
3670     EventHeader *eh = 0;
3671     PscuHeader *ph = 0;
3672     T->SetBranchAddress("Header", &eh);
3673     while ( apkt > bpkt && aobt > bobt && firstev < lastev ){
3674     T->GetEntry(firstev);
3675     ph = eh->GetPscuHeader();
3676     bpkt = PKT(ph->GetCounter());
3677     bobt = OBT(ph->GetOrbitalTime());
3678     firstev++;
3679     if ( PEDANTIC ) throw -71;
3680     };
3681     if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
3682     //
3683     glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
3684     glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
3685     glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
3686     glrun1->SetRUNTRAILER_OBT(glrun->GetRUNTRAILER_OBT());
3687     glrun1->SetRUNTRAILER_PKT(glrun->GetRUNTRAILER_PKT());
3688     //
3689     glrun->SetEV_FROM(firstev);
3690     glrun->SetNEVENTS(lastev-firstev+1);
3691     //
3692     glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
3693     glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
3694     glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
3695     glrun->SetCOMPILATIONTIMESTAMP(glrun1->GetCOMPILATIONTIMESTAMP());
3696     glrun->SetFAV_WRK_SCHEDULE(glrun1->GetFAV_WRK_SCHEDULE());
3697     glrun->SetEFF_WRK_SCHEDULE(glrun1->GetEFF_WRK_SCHEDULE());
3698     glrun->SetPRH_VAR_TRG_MODE_A(glrun1->GetPRH_VAR_TRG_MODE_A());
3699     glrun->SetPRH_VAR_TRG_MODE_B(glrun1->GetPRH_VAR_TRG_MODE_B());
3700     glrun->SetACQ_BUILD_INFO(glrun1->GetACQ_BUILD_INFO());
3701     glrun->SetACQ_VAR_INFO(glrun1->GetACQ_VAR_INFO());
3702     glrun->SetRM_ACQ_AFTER_CALIB(glrun1->GetRM_ACQ_AFTER_CALIB());
3703     glrun->SetRM_ACQ_SETTING_MODE(glrun1->GetRM_ACQ_SETTING_MODE());
3704     glrun->SetTRK_CALIB_USED(glrun1->GetTRK_CALIB_USED());
3705     glrun->SetCAL_DSP_MASK(glrun1->GetCAL_DSP_MASK());
3706     glrun->SetLAST_TIMESYNC(glrun1->GetLAST_TIMESYNC());
3707     glrun->SetOBT_TIMESYNC(glrun1->GetOBT_TIMESYNC());
3708     //
3709     if ( glrun1->GetPHYSENDRUN_MASK_S3S2S12() ) glrun->SetPHYSENDRUN_MASK_S3S2S12(glrun1->GetPHYSENDRUN_MASK_S3S2S12());
3710     if ( glrun1->GetPHYSENDRUN_MASK_S11CRC() ) glrun->SetPHYSENDRUN_MASK_S11CRC(glrun1->GetPHYSENDRUN_MASK_S11CRC());
3711     //
3712     if ( !IsRunAlreadyInserted() ){
3713     //
3714     // glrun->SetID(this->AssignRunID());
3715     glrun->SetID_RUN_FRAG(glrun1->GetID());
3716     glrun->Fill_GL_RUN(conn);
3717     //
3718     // set id number
3719     //
3720     glrun1->SetID_RUN_FRAG(glrun->GetID());
3721     glrun1->Fill_GL_RUN(conn);
3722     //
3723     };
3724     // delete old entry in fragment table
3725     //
3726     glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3727     glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3728     //
3729     delete glrun1;
3730     //
3731     //
3732     // return;
3733     //
3734     };
3735     //
3736 mocchiut 1.1 };
3737 mocchiut 1.2 //
3738     //
3739     zjustcheck:
3740     //
3741     if ( !found ){
3742     //
3743     if ( IsDebug() ) printf(" not found, check if we have already processed the file \n ");
3744     //
3745     // not found, has this run already inserted in the GL_RUN or in the GL_RUN_FRAGMENTS table?
3746     //
3747     oss.str("");
3748     oss << " SELECT ID FROM GL_RUN WHERE "
3749     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3750     << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3751     << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3752     << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3753     << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3754     << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3755     << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3756     << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3757     << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3758     << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3759     << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3760     << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3761     << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3762     //
3763     if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3764     result = conn->Query(oss.str().c_str());
3765     //
3766     if ( !result ) throw -4;
3767     //
3768     row = result->Next();
3769     //
3770     if ( row ){
3771     if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");
3772     if ( PEDANTIC ) throw -70;
3773     } else {
3774     if ( NoFrag() ){
3775     glrun->SetID_RUN_FRAG(glrun->GetID());
3776     glrun->Fill_GL_RUN(conn);
3777     glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3778     };
3779     };
3780     }; // EEE
3781 mocchiut 1.1
3782    
3783    
3784    
3785    
3786    
3787    
3788    
3789    
3790    
3791    
3792    
3793    
3794    
3795    
3796    
3797    
3798    
3799    
3800    
3801    
3802    
3803    
3804    
3805    
3806    
3807    
3808    
3809    
3810    
3811    
3812    
3813    
3814     } else {
3815 mocchiut 1.2 if ( !IsRunAlreadyInserted() ){
3816     glrun->SetID(this->AssignRunID());
3817     glrun->SetID_RUN_FRAG(0);
3818     glrun->Fill_GL_RUN(conn);
3819     };
3820 mocchiut 1.1 }; // EEE
3821     //
3822     firstevno = lastentry + 1;
3823     //
3824     checkfirst = check;
3825     //
3826     };
3827     //
3828     if ( check == checklast && i != lastev ){
3829     lastevtemp = i - 1;
3830     i = lastev - 1;
3831     };
3832     //
3833     };
3834     //
3835     lastev = lastevtemp;
3836     //
3837     return(false);
3838     //
3839     };
3840     };
3841     //
3842     return(false); // should never arrive here
3843     };
3844    
3845     /**
3846     *
3847     * we end up here when we have a runheader and a runtrailer but they seems not belonging to the same run since the number of events does not coincide with the
3848     * number of event written in the runtrailer. We try to split into different runs scanning the physics events from the runheader to the runtrailer and
3849     * looking for non-physics packets inside.
3850     *
3851     */
3852     void PamelaDBOperations::HandleSuspiciousRun(){
3853     //
3854     PacketType *pctp=0;
3855     EventCounter *codt=0;
3856     EventCounter *codh=0;
3857     EventCounter *code=0;
3858     UInt_t firstev = 0;
3859     UInt_t lastev = 0;
3860     UInt_t nevent = 0;
3861     UInt_t checkfirst = 0;
3862     UInt_t checklast = 0;
3863     UInt_t firstentry = 0;
3864     UInt_t lastentry = 0;
3865     UInt_t firstTime = 0;
3866     UInt_t lastTime = 0;
3867     UInt_t firstPkt = 0;
3868     UInt_t lastPkt = 0;
3869     UInt_t firstObt = 0;
3870     UInt_t lastObt = 0;
3871     //
3872     pcksList packetsNames;
3873     pcksList::iterator Iter;
3874     getPacketsNames(packetsNames);
3875     //
3876     TTree *rh=0;
3877     rh = (TTree*)file->Get("RunHeader");
3878     if ( !rh || rh->IsZombie() ) throw -17;
3879     TTree *T=0;
3880     T =(TTree*)file->Get("Physics");
3881     if ( !T || T->IsZombie() ) throw -16;
3882     EventHeader *eh = 0;
3883     PscuHeader *ph = 0;
3884     T->SetBranchAddress("Header", &eh);
3885     nevent = T->GetEntries();
3886     //
3887     codt = eht->GetCounter();
3888     codh = ehh->GetCounter();
3889     firstev = codh->Get(pctp->Physics);
3890     lastev = codt->Get(pctp->Physics)-1;
3891     if ( IsDebug() ) printf(" From the current runheader firstev is %u from the runtrailer lastev is %u \n",firstev,lastev);
3892     //
3893     if ( firstev == lastev+1 ) { // no events inside the run!
3894     if ( IsDebug() ) printf(" Checking but no events in the run! \n");
3895     //
3896     this->FillClass();
3897     if ( !IsRunAlreadyInserted() ){
3898     glrun->SetID(this->AssignRunID());
3899     glrun->SetID_RUN_FRAG(0);
3900     glrun->Fill_GL_RUN(conn);
3901     };
3902     //
3903     } else {
3904     //
3905     UInt_t nrunh = 0 + codh->Get(pctp->RunHeader);
3906     UInt_t nrunh1 = 0 + codh->Get(pctp->RunHeader);
3907     T->GetEntry(firstev);
3908     code = eh->GetCounter();
3909     checkfirst = 0;
3910     for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3911 mocchiut 1.2 if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));
3912     if ( !strcmp(*Iter,"RunHeader") ) nrunh1++;
3913     };
3914 mocchiut 1.1 if ( IsDebug() ) printf(" Check first is %i \n",checkfirst);
3915     //
3916     T->GetEntry(lastev);
3917     code = eh->GetCounter();
3918     checklast = 0;
3919     for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3920 mocchiut 1.2 if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));
3921     };
3922 mocchiut 1.1 if ( IsDebug() ) printf(" Check last is %i \n",checklast);
3923     //
3924     if ( checkfirst == checklast ){
3925     //
3926     if ( IsDebug() ) printf(" No packets but physics inside the run, I will consider it as good\n");
3927     //
3928     this->FillClass();
3929     if ( !IsRunAlreadyInserted() ){
3930     glrun->SetID(this->AssignRunID());
3931     glrun->SetID_RUN_FRAG(0);
3932     glrun->Fill_GL_RUN(conn);
3933     };
3934     //
3935     } else {
3936     //
3937     if ( IsDebug() ) printf(" There are no-physics packets inside the run, try to separate runs \n");
3938     //
3939     Bool_t emptyruns = false;
3940     UInt_t check = 0;
3941     UInt_t firstevno = firstev;
3942     //
3943     for (UInt_t i=firstev; i<=lastev; i++){
3944     //
3945     T->GetEntry(i);
3946     code = eh->GetCounter();
3947     //
3948     check = 0;
3949     //
3950     for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3951     if ( strcmp(*Iter,"Physics") ) check += code->Get(GetPacketType(*Iter));
3952     if ( !strcmp(*Iter,"RunHeader") ) nrunh++;
3953     };
3954     //
3955     if ( checkfirst < check || i == lastev ){
3956     //
3957     firstentry = firstevno;
3958     //
3959     if ( checkfirst < check ){
3960     lastentry = i-1;
3961     } else {
3962     lastentry = i;
3963     };
3964     //
3965     if ( IsDebug() ) printf(" Run between %i and %i entries\n",firstentry,lastentry);
3966     //
3967     glrun->SetEV_FROM(firstentry);
3968     glrun->SetEV_TO(lastentry);
3969     if ( lastentry == (firstentry-1) ){ // no physics packets inside physics run with no runheader no runtrailer
3970     if ( IsDebug() ) printf(" no physics packets inside physics run with no runheader no runtrailer\n");
3971     lastentry--;
3972     };
3973     glrun->SetNEVENTS(lastentry-firstentry+1);
3974     //
3975     glrun->Set_GL_RUNH0();
3976     glrun->Set_GL_RUNT0();
3977     //
3978     glrun->SetLAST_TIMESYNC(0);
3979     glrun->SetOBT_TIMESYNC(0);
3980     //
3981     T->GetEntry(firstentry);
3982     ph = eh->GetPscuHeader();
3983     firstObt = ph->GetOrbitalTime();
3984     firstTime = this->GetAbsTime(firstObt);
3985     firstPkt = ph->GetCounter();
3986     //
3987     T->GetEntry(lastentry);
3988     ph = eh->GetPscuHeader();
3989     lastObt = ph->GetOrbitalTime();
3990     lastTime = this->GetAbsTime(lastObt);
3991     lastPkt = ph->GetCounter();
3992     //
3993     glrun->SetRUNHEADER_PKT(firstPkt);
3994     glrun->SetRUNTRAILER_PKT(lastPkt);
3995     //
3996     glrun->SetRUNHEADER_OBT(firstObt);
3997     glrun->SetRUNTRAILER_OBT(lastObt);
3998     //
3999     if ( IsDebug() ) printf(" AA THIS RUN: RUNHEADER_OBT %u RUNTRAILER_OBT %u RUNHEADER_PKT %u RUNTRAILER_PKT %u \n", glrun->GetRUNHEADER_OBT(),glrun->GetRUNTRAILER_OBT(),glrun->GetRUNHEADER_PKT(),glrun->GetRUNTRAILER_PKT());
4000     //
4001     if ( (firstev == firstentry && !emptyruns) || nrunh == (nrunh1 + 1) ){
4002     rh->GetEntry(nrunh1-1);
4003     phh = ehh->GetPscuHeader();
4004     nrunh1++;
4005     glrun->Set_GL_RUNH(runh,phh);
4006     firstTime = this->GetAbsTime(phh->GetOrbitalTime());
4007     if ( IsDebug() ) printf(" We have the runheader \n");
4008     };
4009     if ( lastev == i && checkfirst == check ){
4010     glrun->Set_GL_RUNT(runt,pht);
4011     lastTime = this->GetAbsTime(pht->GetOrbitalTime());
4012     if ( IsDebug() ) printf(" We have the runtrailer \n");
4013     };
4014     if ( IsDebug() ) printf(" BB THIS RUN: RUNHEADER_OBT %u RUNTRAILER_OBT %u RUNHEADER_PKT %u RUNTRAILER_PKT %u \n", glrun->GetRUNHEADER_OBT(),glrun->GetRUNTRAILER_OBT(),glrun->GetRUNHEADER_PKT(),glrun->GetRUNTRAILER_PKT());
4015     //
4016     if ( lastentry == (firstentry-2) ){ // no events in the run
4017     emptyruns = true;
4018     if ( IsDebug() ) printf(" No events in the run \n");
4019     lastTime = firstTime;
4020     if ( (UInt_t)firstTime == this->GetAbsTime(phh->GetOrbitalTime()) ){
4021     lastObt = glrun->RUNHEADER_OBT;
4022     lastPkt = glrun->RUNHEADER_PKT;
4023     } else {
4024     lastObt = firstObt;
4025     lastPkt = firstPkt;
4026     };
4027     glrun->SetRUNTRAILER_PKT(lastPkt);
4028     glrun->SetRUNTRAILER_OBT(lastObt);
4029     lastentry++;
4030     };
4031     //
4032     this->SetCommonGLRUN(firstTime,lastTime);
4033 mocchiut 1.2 this->SetPhysEndRunVariables();
4034 mocchiut 1.1 //
4035     if ( !IsRunAlreadyInserted() ){
4036     glrun->SetID(this->AssignRunID());
4037     glrun->SetID_RUN_FRAG(0);
4038     glrun->Fill_GL_RUN(conn);
4039     };
4040     //
4041     if ( i == lastev && checkfirst < check ){ // if the last event gives a wrong check...
4042     //
4043     firstentry = i;
4044     //
4045     lastentry = i;
4046     //
4047     if ( IsDebug() ) printf(" Run between %i and %i entries\n",firstentry,lastentry);
4048     //
4049     glrun->SetEV_FROM(firstentry);
4050     glrun->SetEV_TO(lastentry);
4051     glrun->SetNEVENTS(lastentry-firstentry+1);
4052     //
4053     glrun->Set_GL_RUNH0();
4054     //
4055     glrun->SetLAST_TIMESYNC(0);
4056     glrun->SetOBT_TIMESYNC(0);
4057     //
4058     T->GetEntry(firstentry);
4059     ph = eh->GetPscuHeader();
4060     firstObt = ph->GetOrbitalTime();
4061     firstTime = this->GetAbsTime(firstObt);
4062     firstPkt = ph->GetCounter();
4063     //
4064     glrun->SetRUNHEADER_PKT(firstPkt);
4065     //
4066     glrun->SetRUNHEADER_OBT(firstObt);
4067     //
4068     glrun->Set_GL_RUNT(runt,pht);
4069     lastTime = this->GetAbsTime(pht->GetOrbitalTime());
4070     if ( IsDebug() ) printf(" We have the runtrailer \n");
4071     //
4072     this->SetCommonGLRUN(firstTime,lastTime);
4073 mocchiut 1.2 this->SetPhysEndRunVariables();
4074 mocchiut 1.1 //
4075     if ( !IsRunAlreadyInserted() ){
4076     glrun->SetID(this->AssignRunID());
4077     glrun->SetID_RUN_FRAG(0);
4078     glrun->Fill_GL_RUN(conn);
4079     };
4080     };
4081     //
4082     firstevno = lastentry + 1;
4083     //
4084     checkfirst = check;
4085     //
4086     };
4087     //
4088     if ( check == checklast && i != lastev ) i = lastev - 1; // >>>>>>>>>>>>>>>>>>>>>>
4089     //
4090     };
4091     };
4092     };
4093     //
4094     return;
4095     };
4096    
4097    
4098     /**
4099     * Scan calorimeter calibrations packets, fill the GL_CALO_CALIB table
4100     */
4101     Int_t PamelaDBOperations::insertCALO_CALIB(){
4102     //
4103     TSQLResult *result = 0;
4104     TSQLRow *row = 0;
4105     //
4106     stringstream oss;
4107     oss.str("");
4108     //
4109     CalibCalPedEvent *calibCalPed = 0;
4110     TTree *tr = 0;
4111     EventHeader *eh = 0;
4112     PscuHeader *ph = 0;
4113     //
4114     UInt_t nevents = 0;
4115     UInt_t fromtime = 0;
4116     UInt_t totime = 0;
4117     UInt_t obt = 0;
4118     UInt_t pkt = 0;
4119     //
4120     tr = (TTree*)file->Get("CalibCalPed");
4121     if ( !tr || tr->IsZombie() ) throw -21;
4122     //
4123     tr->SetBranchAddress("CalibCalPed", &calibCalPed);
4124     tr->SetBranchAddress("Header", &eh);
4125     nevents = tr->GetEntries();
4126     //
4127     if ( !nevents ) return(1);
4128     //
4129     for (UInt_t i=0; i < nevents; i++){
4130     tr->GetEntry(i);
4131     for (UInt_t section = 0; section < 4; section++){
4132     //
4133     if ( calibCalPed->cstwerr[section] ){
4134     valid = 1;
4135     if ( calibCalPed->cperror[section] ) valid = 0;
4136     ph = eh->GetPscuHeader();
4137     obt = ph->GetOrbitalTime();
4138     pkt = ph->GetCounter();
4139     fromtime = this->GetAbsTime(ph->GetOrbitalTime());
4140     if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->PKT(pkt) <= upperpkt && this->OBT(obt) >= this->OBT(obtfirst) && this->OBT(obt) <= upperobt ){
4141     //
4142     if ( IsDebug() ) printf(" Calo calibration for section %i at time %u obt %u pkt %u \n",section,fromtime,obt,pkt);
4143     //
4144     // check if the calibration has already been inserted
4145     //
4146     oss.str("");
4147     oss << " SELECT ID FROM GL_CALO_CALIB WHERE "
4148     << " SECTION = "<< section << " AND "
4149     << " BOOT_NUMBER = "<< this->GetBOOTnumber() << " AND "
4150     << " OBT = "<< obt << " AND "
4151     << " PKT = "<< pkt << ";";
4152     //
4153     if ( IsDebug() ) printf(" Check if the calo calibration has already been inserted: query is \n %s \n",oss.str().c_str());
4154     result = conn->Query(oss.str().c_str());
4155     //
4156     if ( !result ) throw -4;
4157     //
4158     row = result->Next();
4159     //
4160     if ( row ){
4161     //
4162     if ( IsDebug() ) printf(" Calo calibration already inserted in the DB\n");
4163     if ( PEDANTIC ) throw -73;
4164     //
4165     } else {
4166     //
4167     // we have to insert a new calibration, check where to place it
4168     //
4169     oss.str("");
4170     oss << " SELECT ID,TO_TIME FROM GL_CALO_CALIB WHERE "
4171     << " SECTION = "<< section << " AND "
4172     << " FROM_TIME < "<< fromtime << " AND "
4173     << " TO_TIME > "<< fromtime << ";";
4174     //
4175     if ( IsDebug() ) printf(" Check where to place the calo calibration: query is \n %s \n",oss.str().c_str());
4176     result = conn->Query(oss.str().c_str());
4177     //
4178     if ( !result ) throw -4;
4179     //
4180     row = result->Next();
4181     //
4182     if ( !row ){
4183     //
4184     // no calibrations in the db contain our calibration
4185     //
4186     if ( IsDebug() ) printf(" Calibration with fromtime lower than others to be inserted in the DB for section %i \n",section);
4187     if ( fromtime < 1150871000 ){ //1150866904
4188     if ( IsDebug() ) printf(" First PAMELA flight calibration at time %u \n",fromtime);
4189     fromtime = 0;// the first flight calibration was taken at about 1156429100 s, this line allow to analyze first runs in raw mode
4190     };
4191     //
4192     oss.str("");
4193     oss << " SELECT FROM_TIME FROM GL_CALO_CALIB WHERE "
4194     << " SECTION = "<< section << " AND "
4195     << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";
4196     //
4197     if ( IsDebug() ) printf(" Check the upper limit for calibration: query is \n %s \n",oss.str().c_str());
4198     result = conn->Query(oss.str().c_str());
4199     //
4200     if ( !result ) throw -4;
4201     //
4202     row = result->Next();
4203     if ( !row ){
4204     totime = numeric_limits<UInt_t>::max();
4205     } else {
4206     totime = (UInt_t)atoll(row->GetField(0));
4207     };
4208     //
4209     } else {
4210     //
4211     // determine upper and lower limits and make space for the new calibration
4212     //
4213     totime = (UInt_t)atoll(row->GetField(1));
4214     //
4215     oss.str("");
4216     oss << " UPDATE GL_CALO_CALIB SET "
4217     << " TO_TIME = "<< fromtime << " WHERE " // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[
4218     << " ID = "<< row->GetField(0) << ";";
4219     //
4220     if ( IsDebug() ) printf(" Make space for the new calibration: query is \n %s \n",oss.str().c_str());
4221     result = conn->Query(oss.str().c_str());
4222     //
4223     if ( !result ) throw -4;
4224     //
4225     };
4226     //
4227     oss.str("");
4228     oss << " INSERT INTO GL_CALO_CALIB (ID,ID_ROOT_L0,EV_ROOT,FROM_TIME,TO_TIME,SECTION,OBT,PKT,BOOT_NUMBER,VALIDATION) "
4229     << " VALUES (NULL,' "
4230     << idroot << "','"
4231     << i << "','"
4232     << fromtime << "','"
4233     << totime << "','"
4234     << section << "','"
4235     << obt << "','"
4236     << pkt << "','"
4237     << this->GetBOOTnumber() << "','"
4238     << valid << "');";
4239     //
4240     if ( IsDebug() ) printf(" Insert the new calibration: query is \n %s \n",oss.str().c_str());
4241     //
4242     result = conn->Query(oss.str().c_str());
4243     //
4244     if ( !result ) throw -4;
4245     //
4246     };
4247     //
4248     } else {
4249     //
4250     if ( IsDebug() ) printf(" Calo calibration for section %i at time %u obt %u pkt %u OUTSIDE the considered interval \n",section,fromtime,obt,pkt);
4251     // if ( PEDANTIC ) throw -74;
4252     //
4253     };
4254     //
4255     };
4256     };
4257     };
4258     //
4259     return(0);
4260     };
4261    
4262    
4263     /**
4264     * Scan calorimeter calibrations packets, fill the GL_CALO_CALIB table
4265     */
4266     Int_t PamelaDBOperations::insertCALOPULSE_CALIB(){
4267     //
4268     TSQLResult *result = 0;
4269     TSQLRow *row = 0;
4270     //
4271     stringstream oss;
4272     oss.str("");
4273     //
4274     oss << " DESCRIBE GL_CALOPULSE_CALIB;";
4275     if ( IsDebug() ) printf(" Check if the GL_CALOPULSE_CALIB table exists: query is \n %s \n",oss.str().c_str());
4276     result = conn->Query(oss.str().c_str());
4277     //
4278     if ( conn->GetErrorCode() ){
4279     if ( IsDebug() ) printf(" The GL_CALOPULSE_CALIB table does not exists! \n");
4280     throw -30;
4281     };
4282     //
4283     // CaloPulse1
4284     //
4285     CalibCalPulse1Event *cp1 = 0;
4286     TTree *tr = 0;
4287     EventHeader *eh = 0;
4288     PscuHeader *ph = 0;
4289     //
4290     UInt_t nevents = 0;
4291     UInt_t fromtime = 0;
4292     UInt_t totime = 0;
4293     UInt_t obt = 0;
4294     UInt_t pkt = 0;
4295     //
4296     tr = (TTree*)file->Get("CalibCalPulse1");
4297     if ( !tr || tr->IsZombie() ) throw -31;
4298     //
4299     tr->SetBranchAddress("CalibCalPulse1", &cp1);
4300     tr->SetBranchAddress("Header", &eh);
4301     nevents = tr->GetEntries();
4302     //
4303     if ( nevents > 0 ){
4304     //
4305     for (UInt_t i=0; i < nevents; i++){
4306     tr->GetEntry(i);
4307     for (UInt_t section = 0; section < 4; section++){
4308     //
4309     if ( cp1->pstwerr[section] && cp1->unpackError == 0 ){
4310     valid = 1;
4311     if ( cp1->pperror[section] ) valid = 0;
4312     ph = eh->GetPscuHeader();
4313     obt = ph->GetOrbitalTime();
4314     pkt = ph->GetCounter();
4315     fromtime = this->GetAbsTime(ph->GetOrbitalTime());
4316     if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->PKT(pkt) <= upperpkt && this->OBT(obt) >= this->OBT(obtfirst) && this->OBT(obt) <= upperobt ){
4317     // if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->OBT(obt) >= this->OBT(obtfirst) ){
4318     //
4319     if ( IsDebug() ) printf(" Calo pulse1 calibration for section %i at time %u obt %u pkt %u \n",section,fromtime,obt,pkt);
4320     //
4321     // check if the calibration has already been inserted
4322     //
4323     oss.str("");
4324     oss << " SELECT ID FROM GL_CALOPULSE_CALIB WHERE "
4325     << " SECTION = "<< section << " AND "
4326     << " PULSE_AMPLITUDE = 0 AND "
4327     << " BOOT_NUMBER = "<< this->GetBOOTnumber() << " AND "
4328     << " OBT = "<< obt << " AND "
4329     << " PKT = "<< pkt << ";";
4330     //
4331     if ( IsDebug() ) printf(" Check if the calo pulse1 calibration has already been inserted: query is \n %s \n",oss.str().c_str());
4332     result = conn->Query(oss.str().c_str());
4333     //
4334     if ( !result ) throw -4;
4335     //
4336     row = result->Next();
4337     //
4338     if ( row ){
4339     //
4340     if ( IsDebug() ) printf(" Calo pulse1 calibration already inserted in the DB\n");
4341     if ( PEDANTIC ) throw -75;
4342     //
4343     } else {
4344     //
4345     // we have to insert a new calibration, check where to place it
4346     //
4347     oss.str("");
4348     oss << " SELECT ID,TO_TIME FROM GL_CALOPULSE_CALIB WHERE "
4349     << " SECTION = "<< section << " AND "
4350     << " PULSE_AMPLITUDE = 0 AND "
4351     << " SECTION = "<< section << " AND "
4352     << " FROM_TIME < "<< fromtime << " AND "
4353     << " TO_TIME > "<< fromtime << ";";
4354     //
4355     if ( IsDebug() ) printf(" Check where to place the pulse1 calo calibration: query is \n %s \n",oss.str().c_str());
4356     result = conn->Query(oss.str().c_str());
4357     //
4358     if ( !result ) throw -4;
4359     //
4360     row = result->Next();
4361     //
4362     if ( !row ){
4363     //
4364     // no calibrations in the db contain our calibration
4365     //
4366     if ( IsDebug() ) printf(" Pulse1 calibration with fromtime lower than others to be inserted in the DB for section %i \n",section);
4367     if ( fromtime < 1150871000 ){ //1150866904
4368     if ( IsDebug() ) printf(" First PAMELA flight calibration at time %u \n",fromtime);
4369     fromtime = 0;// the first flight calibration was taken at about 1156429100 s, this line allow to analyze first runs in raw mode
4370     };
4371     //
4372     oss.str("");
4373     oss << " SELECT FROM_TIME FROM GL_CALOPULSE_CALIB WHERE "
4374     << " PULSE_AMPLITUDE = 0 AND "
4375     << " SECTION = "<< section << " AND "
4376     << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";
4377     //
4378     if ( IsDebug() ) printf(" Check the upper limit for pulse1 calibration: query is \n %s \n",oss.str().c_str());
4379     result = conn->Query(oss.str().c_str());
4380     //
4381     if ( !result ) throw -4;
4382     //
4383     row = result->Next();
4384     if ( !row ){
4385     totime = numeric_limits<UInt_t>::max();
4386     } else {
4387     totime = (UInt_t)atoll(row->GetField(0));
4388     };
4389     //
4390     } else {
4391     //
4392     // determine upper and lower limits and make space for the new calibration
4393     //
4394     totime = (UInt_t)atoll(row->GetField(1));
4395     //
4396     oss.str("");
4397     oss << " UPDATE GL_CALOPULSE_CALIB SET "
4398     << " TO_TIME = "<< fromtime << " WHERE " // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[
4399     << " ID = "<< row->GetField(0) << ";";
4400     //
4401     if ( IsDebug() ) printf(" Make space for the new pulse1 calibration: query is \n %s \n",oss.str().c_str());
4402     result = conn->Query(oss.str().c_str());
4403     //
4404     if ( !result ) throw -4;
4405     //
4406     };
4407     //
4408     oss.str("");
4409     oss << " INSERT INTO GL_CALOPULSE_CALIB (ID,ID_ROOT_L0,EV_ROOT,FROM_TIME,TO_TIME,SECTION,PULSED_STRIP,PULSE_AMPLITUDE,OBT,PKT,BOOT_NUMBER,VALIDATION) "
4410     << " VALUES (NULL,' "
4411     << idroot << "','"
4412     << i << "','"
4413     << fromtime << "','"
4414     << totime << "','"
4415     << section << "',NULL,'0','"
4416     << obt << "','"
4417     << pkt << "','"
4418     << this->GetBOOTnumber() << "','"
4419     << valid << "');";
4420     //
4421     if ( IsDebug() ) printf(" Insert the new pulse1 calibration: query is \n %s \n",oss.str().c_str());
4422     //
4423     result = conn->Query(oss.str().c_str());
4424     //
4425     if ( !result ) throw -4;
4426     //
4427     };
4428     //
4429     } else {
4430     //
4431     if ( IsDebug() ) printf(" Pulse1 calo calibration for section %i at time %u obt %u pkt %u OUTSIDE the considered time interval \n",section,fromtime,obt,pkt);
4432     // if ( PEDANTIC ) throw -76;
4433     //
4434     };
4435     //
4436     };
4437     };
4438     };
4439     };
4440     //
4441     // CaloPulse2
4442     //
4443     tr->Reset();
4444     CalibCalPulse2Event *cp2 = 0;
4445     tr = 0;
4446     //
4447     nevents = 0;
4448     fromtime = 0;
4449     totime = 0;
4450     obt = 0;
4451     pkt = 0;
4452     //
4453     tr = (TTree*)file->Get("CalibCalPulse2");
4454     if ( !tr || tr->IsZombie() ) throw -32;
4455     //
4456     tr->SetBranchAddress("CalibCalPulse2", &cp2);
4457     tr->SetBranchAddress("Header", &eh);
4458     nevents = tr->GetEntries();
4459     //
4460     if ( nevents > 0 ){
4461     //
4462     for (UInt_t i=0; i < nevents; i++){
4463     tr->GetEntry(i);
4464     for (UInt_t section = 0; section < 4; section++){
4465     //
4466     if ( cp2->pstwerr[section] && cp2->unpackError == 0 ){
4467     valid = 1;
4468     if ( cp2->pperror[section] ) valid = 0;
4469     ph = eh->GetPscuHeader();
4470     obt = ph->GetOrbitalTime();
4471     pkt = ph->GetCounter();
4472     fromtime = this->GetAbsTime(ph->GetOrbitalTime());
4473     if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->PKT(pkt) <= upperpkt && this->OBT(obt) >= this->OBT(obtfirst) && this->OBT(obt) <= upperobt ){
4474     // if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->OBT(obt) >= this->OBT(obtfirst) ){
4475     //
4476     if ( IsDebug() ) printf(" Calo pulse2 calibration for section %i at time %u obt %u pkt %u \n",section,fromtime,obt,pkt);
4477     //
4478     // check if the calibration has already been inserted
4479     //
4480     oss.str("");
4481     oss << " SELECT ID FROM GL_CALOPULSE_CALIB WHERE "
4482     << " SECTION = "<< section << " AND "
4483     << " PULSE_AMPLITUDE != 0 AND "
4484     << " BOOT_NUMBER = "<< this->GetBOOTnumber() << " AND "
4485     << " OBT = "<< obt << " AND "
4486     << " PKT = "<< pkt << ";";
4487     //
4488     if ( IsDebug() ) printf(" Check if the calo pulse2 calibration has already been inserted: query is \n %s \n",oss.str().c_str());
4489     result = conn->Query(oss.str().c_str());
4490     //
4491     if ( !result ) throw -4;
4492     //
4493     row = result->Next();
4494     //
4495     if ( row ){
4496     //
4497     if ( IsDebug() ) printf(" Calo pulse2 calibration already inserted in the DB\n");
4498     if ( PEDANTIC ) throw -77;
4499     //
4500     } else {
4501     //
4502     // we have to insert a new calibration
4503     //
4504     //
4505     // Determine the amplitude of the pulse
4506     //
4507     UInt_t pampli = 1;
4508     UInt_t pstrip = 0;
4509     UInt_t se = 0;
4510     if ( section == 1 ) se = 2;
4511     if ( section == 2 ) se = 3;
4512     if ( section == 3 ) se = 1;
4513     for (Int_t ii=0;ii<16;ii++){
4514     if ( cp2->calpuls[se][0][ii] > 10000. ){
4515     pampli = 2;
4516     pstrip = ii;
4517     };
4518     };
4519     if ( pampli == 1 ){
4520     Bool_t found = false;
4521     Float_t delta=0.;
4522     UInt_t cstr = 0;
4523     while ( !found && cstr < 16 ){
4524     for (Int_t ii=0;ii<16;ii++){
4525     delta = cp2->calpuls[se][0][ii] - cp2->calpuls[se][0][cstr];
4526     if ( IsDebug() ) printf(" cstr is %u ii is %i delta is %f \n",cstr,ii,delta);
4527     if ( delta > 500. ){
4528     pampli = 1;
4529     pstrip = ii;
4530     found = true;
4531     if ( IsDebug() ) printf(" FOUND cstr is %u ii is %i delta is %f \n",cstr,ii,delta);
4532     };
4533     };
4534     cstr++;
4535     };
4536     if ( !found ) pstrip = 100;
4537     };
4538     if ( IsDebug() ) printf(" The amplitude of the pulser is %u (where 1 = low pulse, 2 = high pulse), pulsed strip is %u \n",pampli,pstrip);
4539     //
4540     // we have to insert a new calibration, check where to place it
4541     //
4542     oss.str("");
4543     oss << " SELECT ID,TO_TIME FROM GL_CALOPULSE_CALIB WHERE "
4544     << " SECTION = "<< section << " AND "
4545     << " PULSE_AMPLITUDE = " << pampli << " AND "
4546     << " SECTION = "<< section << " AND "
4547     << " FROM_TIME < "<< fromtime << " AND "
4548     << " TO_TIME > "<< fromtime << ";";
4549     //
4550     if ( IsDebug() ) printf(" Check where to place the pulse2 calo calibration: query is \n %s \n",oss.str().c_str());
4551     result = conn->Query(oss.str().c_str());
4552     //
4553     if ( !result ) throw -4;
4554     //
4555     row = result->Next();
4556     //
4557     if ( !row ){
4558     //
4559     // no calibrations in the db contain our calibration
4560     //
4561     if ( IsDebug() ) printf(" Pulse2 calibration with fromtime lower than others to be inserted in the DB for section %i \n",section);
4562     if ( fromtime < 1150871000 ){ //1150866904
4563     if ( IsDebug() ) printf(" First PAMELA flight calibration at time %u \n",fromtime);
4564     fromtime = 0;// the first flight calibration was taken at about 1156429100 s, this line allow to analyze first runs in raw mode
4565     };
4566     //
4567     oss.str("");
4568     oss << " SELECT FROM_TIME FROM GL_CALOPULSE_CALIB WHERE "
4569     << " PULSE_AMPLITUDE = " << pampli << " AND "
4570     << " SECTION = "<< section << " AND "
4571     << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";
4572     //
4573     if ( IsDebug() ) printf(" Check the upper limit for pulse2 calibration: query is \n %s \n",oss.str().c_str());
4574     result = conn->Query(oss.str().c_str());
4575     //
4576     if ( !result ) throw -4;
4577     //
4578     row = result->Next();
4579     if ( !row ){
4580     totime = numeric_limits<UInt_t>::max();
4581     } else {
4582     totime = (UInt_t)atoll(row->GetField(0));
4583     };
4584     //
4585     } else {
4586     //
4587     // determine upper and lower limits and make space for the new calibration
4588     //
4589     totime = (UInt_t)atoll(row->GetField(1));
4590     //
4591     oss.str("");
4592     oss << " UPDATE GL_CALOPULSE_CALIB SET "
4593     << " TO_TIME = "<< fromtime << " WHERE " // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[
4594     << " ID = "<< row->GetField(0) << ";";
4595     //
4596     if ( IsDebug() ) printf(" Make space for the new pulse2 calibration: query is \n %s \n",oss.str().c_str());
4597     result = conn->Query(oss.str().c_str());
4598     //
4599     if ( !result ) throw -4;
4600     //
4601     };
4602     //
4603     // Fill the DB
4604     //
4605     oss.str("");
4606     // oss << " INSERT INTO GL_CALOPULSE_CALIB (ID,ID_ROOT_L0,EV_ROOT,FROM_TIME,TO_TIME,SECTION,OBT,PKT,BOOT_NUMBER,VALIDATION) "
4607     oss << " INSERT INTO GL_CALOPULSE_CALIB (ID,ID_ROOT_L0,EV_ROOT,FROM_TIME,TO_TIME,SECTION,PULSED_STRIP,PULSE_AMPLITUDE,OBT,PKT,BOOT_NUMBER,VALIDATION) "
4608     << " VALUES (NULL,' "
4609     << idroot << "','"
4610     << i << "','"
4611     << fromtime << "','"
4612     << totime << "','"
4613     << section << "','"
4614     << pstrip << "','"
4615     << pampli << "','"
4616     << obt << "','"
4617     << pkt << "','"
4618     << this->GetBOOTnumber() << "','"
4619     << valid << "');";
4620     //
4621     if ( IsDebug() ) printf(" Insert the new pulse2 calibration: query is \n %s \n",oss.str().c_str());
4622     //
4623     result = conn->Query(oss.str().c_str());
4624     //
4625     if ( !result ) throw -4;
4626     //
4627     };
4628     //
4629     } else {
4630     //
4631     if ( IsDebug() ) printf(" Pulse2 calo calibration for section %i at time %u obt %u pkt %u OUTSIDE the considered time interval \n",section,fromtime,obt,pkt);
4632     // if ( PEDANTIC ) throw -78;
4633     //
4634     };
4635     //
4636     };
4637     };
4638     };
4639     };
4640     //
4641     return(0);
4642     };
4643    
4644 pam-fi 1.4 // /**
4645     // * Fill the GL_TRK_CALIB table
4646     // */
4647     // void PamelaDBOperations::HandleTRK_CALIB(Bool_t pk1, Bool_t pk2){
4648     // //
4649     // TSQLResult *result = 0;
4650     // TSQLRow *row = 0;
4651     // //
4652     // stringstream oss;
4653     // oss.str("");
4654     // //
4655     // UInt_t totime = 0;
4656     // //
4657     // if ( !pk1 && !pk2 ){
4658     // if ( IsDebug() ) printf(" Cannot handle trk calibration with both packet missing!\n");
4659     // return;
4660     // };
4661     // //
4662     // // check if the calibration has already been inserted
4663     // //
4664     // oss.str("");
4665     // oss << " SELECT ID FROM GL_TRK_CALIB WHERE "
4666     // << " BOOT_NUMBER = "<< this->GetBOOTnumber(); //
4667     // oss << " AND ( ( ";
4668     // if ( pk1 ){
4669     // oss << " OBT1 = "<< obt1 << " AND "
4670     // << " PKT1 = "<< pkt1
4671     // << " ) OR ( ";
4672     // } else {
4673     // oss << " PKT1 = "<< pkt2-1
4674     // << " ) OR ( ";
4675     // };
4676     // if ( pk2 ){
4677     // oss << " OBT2 = "<< obt2 << " AND "
4678     // << " PKT2 = "<< pkt2;
4679     // } else {
4680     // oss << " PKT2 = "<< pkt1+1;
4681     // };
4682     // oss << " ) );";
4683     // //
4684     // if ( IsDebug() ) printf(" Check if the trk calibration has already been inserted: query is \n %s \n",oss.str().c_str());
4685     // result = conn->Query(oss.str().c_str());
4686     // //
4687     // if ( !result ) throw -4;
4688     // //
4689     // row = result->Next();
4690     // //
4691     // if ( row ){
4692     // //
4693     // if ( IsDebug() ) printf(" Trk calibration already inserted in the DB\n");
4694     // if ( PEDANTIC ) throw -80;
4695     // //
4696     // } else {
4697     // //
4698     // // we have to insert a new calibration, check where to place it
4699     // //
4700     // oss.str("");
4701     // oss << " SELECT ID,TO_TIME FROM GL_TRK_CALIB WHERE "
4702     // << " FROM_TIME < "<< fromtime << " AND "
4703     // << " TO_TIME > "<< fromtime << ";";
4704     // //
4705     // if ( IsDebug() ) printf(" Check where to place the trk calibration: query is \n %s \n",oss.str().c_str());
4706     // result = conn->Query(oss.str().c_str());
4707     // //
4708     // if ( !result ) throw -4;
4709     // //
4710     // row = result->Next();
4711     // //
4712     // if ( !row ){
4713     // //
4714     // // no calibrations in the db contain our calibration
4715     // //
4716     // if ( IsDebug() ) printf(" Calibration with fromtime lower than others to be inserted in the DB\n");
4717     // if ( fromtime < 1150871000 ) fromtime = 0; // the first flight calibration was taken at about 1150863300 s, this line allows to analyze first runs in raw mode
4718     // //
4719     // oss.str("");
4720     // oss << " SELECT FROM_TIME FROM GL_TRK_CALIB WHERE "
4721     // << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";
4722     // //
4723     // if ( IsDebug() ) printf(" Check the upper limit for calibration: query is \n %s \n",oss.str().c_str());
4724     // result = conn->Query(oss.str().c_str());
4725     // //
4726     // if ( !result ) throw -4;
4727     // //
4728     // row = result->Next();
4729     // if ( !row ){
4730     // totime = numeric_limits<UInt_t>::max();
4731     // } else {
4732     // totime = (UInt_t)atoll(row->GetField(0));
4733     // };
4734     // //
4735     // } else {
4736     // //
4737     // // determine upper and lower limits and make space for the new calibration
4738     // //
4739     // totime = (UInt_t)atoll(row->GetField(1));
4740     // //
4741     // oss.str("");
4742     // oss << " UPDATE GL_TRK_CALIB SET "
4743     // << " TO_TIME = "<< fromtime << " WHERE " // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[
4744     // << " ID = "<< row->GetField(0) << ";";
4745     // //
4746     // if ( IsDebug() ) printf(" Make space for the new trk calibration: query is \n %s \n",oss.str().c_str());
4747     // result = conn->Query(oss.str().c_str());
4748     // //
4749     // if ( !result ) throw -4;
4750     // //
4751     // };
4752     // //
4753     // oss.str("");
4754     // oss << " INSERT INTO GL_TRK_CALIB (ID,ID_ROOT_L0,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,FROM_TIME,TO_TIME,OBT1,PKT1,OBT2,PKT2,BOOT_NUMBER,VALIDATION) "
4755     // << " VALUES (NULL,' "
4756     // << idroot << "',";
4757     // //
4758     // if ( !pk1 ){
4759     // oss << "NULL,";
4760     // } else {
4761     // oss << "'"
4762     // << t1 << "',";
4763     // };
4764     // //
4765     // if ( !pk2 ){
4766     // oss << "NULL,'";
4767     // } else {
4768     // oss << "'"
4769     // << t2 << "','";
4770     // };
4771     // //
4772     // oss << fromtime << "','"
4773     // << totime << "','"
4774     // << obt1 << "','"
4775     // << pkt1 << "','"
4776     // << obt2 << "','"
4777     // << pkt2 << "','"
4778     // << this->GetBOOTnumber() << "','"
4779     // << valid << "');";
4780     // //
4781     // if ( IsDebug() ) printf(" Insert the new trk calibration: query is \n %s \n",oss.str().c_str());
4782     // //
4783     // result = conn->Query(oss.str().c_str());
4784     // //
4785     // if ( !result ) throw -4;
4786     // //
4787     // };
4788     // //
4789     // };
4790 mocchiut 1.1 /**
4791     * Fill the GL_TRK_CALIB table
4792     */
4793     void PamelaDBOperations::HandleTRK_CALIB(Bool_t pk1, Bool_t pk2){
4794 pam-fi 1.4
4795     GL_TRK_CALIB *glcal = new GL_TRK_CALIB();
4796     //
4797     glcal->ID = 0;
4798     glcal->ID_ROOT_L0 = GetID_ROOT();
4799     glcal->EV_ROOT_CALIBTRK1 = t1;
4800     glcal->EV_ROOT_CALIBTRK2 = t2;
4801     glcal->FROM_TIME = fromtime;
4802     glcal->TO_TIME = 0;
4803     glcal->OBT1 = obt1;
4804     glcal->OBT2 = obt2;
4805     glcal->PKT1 = pkt1;
4806     glcal->PKT2 = pkt2;
4807     glcal->BOOT_NUMBER = GetBOOTnumber();
4808     glcal->VALIDATION = valid;
4809     //
4810     HandleTRK_CALIB(glcal);
4811     //
4812     delete glcal;
4813     }
4814     /**
4815     * Fill the GL_TRK_CALIB table
4816     */
4817     void PamelaDBOperations::HandleTRK_CALIB(GL_TRK_CALIB *glcal){
4818    
4819     Bool_t pk1 = (glcal->OBT1>0&&glcal->PKT1>0);
4820     Bool_t pk2 = (glcal->OBT2>0&&glcal->PKT2>0);
4821     UInt_t boot_number = glcal->BOOT_NUMBER;
4822     UInt_t obt1 = glcal->OBT1;
4823     UInt_t obt2 = glcal->OBT2;
4824     UInt_t pkt1 = glcal->PKT1;
4825     UInt_t pkt2 = glcal->PKT2;
4826     UInt_t fromtime = glcal->FROM_TIME;
4827     UInt_t totime = 0;
4828     UInt_t idroot = glcal->ID_ROOT_L0;
4829     UInt_t t1 = glcal->EV_ROOT_CALIBTRK1;
4830     UInt_t t2 = glcal->EV_ROOT_CALIBTRK2;
4831     UInt_t valid = glcal->VALIDATION;
4832     //
4833     TSQLResult *result = 0;
4834     TSQLRow *row = 0;
4835     //
4836     stringstream oss;
4837     oss.str("");
4838 mocchiut 1.1 //
4839     //
4840 pam-fi 1.4 if ( !pk1 && !pk2 ){
4841     if ( IsDebug() ) printf(" Cannot handle trk calibration with both packet missing!\n");
4842     return;
4843     };
4844 mocchiut 1.1 //
4845 pam-fi 1.4 // check if the calibration has already been inserted
4846 mocchiut 1.1 //
4847     oss.str("");
4848 pam-fi 1.4 oss << " SELECT ID FROM GL_TRK_CALIB WHERE "
4849     << " BOOT_NUMBER = "<< boot_number; //
4850     oss << " AND FROM_TIME="<<fromtime; /// NEWNEWNEW -- VA BENE ?!?!?!?!
4851     oss << " AND ( ( ";
4852     if ( pk1 ){
4853     oss << " OBT1 = "<< obt1 << " AND "
4854     << " PKT1 = "<< pkt1
4855     << " ) OR ( ";
4856     } else {
4857     oss << " PKT1 = "<< pkt2-1
4858     << " ) OR ( ";
4859     };
4860     if ( pk2 ){
4861     oss << " OBT2 = "<< obt2 << " AND "
4862     << " PKT2 = "<< pkt2;
4863     } else {
4864     oss << " PKT2 = "<< pkt1+1;
4865     };
4866     oss << " ) );";
4867 mocchiut 1.1 //
4868 pam-fi 1.4 if ( IsDebug() ) printf(" Check if the trk calibration has already been inserted: query is \n %s \n",oss.str().c_str());
4869 mocchiut 1.1 result = conn->Query(oss.str().c_str());
4870     //
4871     if ( !result ) throw -4;
4872     //
4873     row = result->Next();
4874     //
4875 pam-fi 1.4 if ( row ){
4876     //
4877     if ( IsDebug() ) printf(" Trk calibration already inserted in the DB\n");
4878     if ( PEDANTIC ) throw -80;
4879     //
4880 mocchiut 1.1 } else {
4881 pam-fi 1.4 //
4882     // we have to insert a new calibration, check where to place it
4883     //
4884     oss.str("");
4885     oss << " SELECT ID,TO_TIME FROM GL_TRK_CALIB WHERE "
4886     << " FROM_TIME < "<< fromtime << " AND "
4887     << " TO_TIME > "<< fromtime << ";";
4888     //
4889     if ( IsDebug() ) printf(" Check where to place the trk calibration: query is \n %s \n",oss.str().c_str());
4890     result = conn->Query(oss.str().c_str());
4891     //
4892     if ( !result ) throw -4;
4893     //
4894     row = result->Next();
4895     //
4896     if ( !row ){
4897     //
4898     // no calibrations in the db contain our calibration
4899     //
4900     if ( IsDebug() ) printf(" Calibration with fromtime lower than others to be inserted in the DB\n");
4901     if ( fromtime < 1150871000 ) fromtime = 0; // the first flight calibration was taken at about 1150863300 s, this line allows to analyze first runs in raw mode
4902     //
4903     oss.str("");
4904     oss << " SELECT FROM_TIME FROM GL_TRK_CALIB WHERE "
4905     << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";
4906     //
4907     if ( IsDebug() ) printf(" Check the upper limit for calibration: query is \n %s \n",oss.str().c_str());
4908     result = conn->Query(oss.str().c_str());
4909     //
4910     if ( !result ) throw -4;
4911     //
4912     row = result->Next();
4913     if ( !row ){
4914     totime = numeric_limits<UInt_t>::max();
4915     } else {
4916     totime = (UInt_t)atoll(row->GetField(0));
4917     };
4918     //
4919     } else {
4920     //
4921     // determine upper and lower limits and make space for the new calibration
4922     //
4923     totime = (UInt_t)atoll(row->GetField(1));
4924     //
4925     oss.str("");
4926     oss << " UPDATE GL_TRK_CALIB SET "
4927     << " TO_TIME = "<< fromtime << " WHERE " // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[
4928     << " ID = "<< row->GetField(0) << ";";
4929     //
4930     if ( IsDebug() ) printf(" Make space for the new trk calibration: query is \n %s \n",oss.str().c_str());
4931     result = conn->Query(oss.str().c_str());
4932     //
4933     if ( !result ) throw -4;
4934     //
4935     };
4936     //
4937     oss.str("");
4938     oss << " INSERT INTO GL_TRK_CALIB (ID,ID_ROOT_L0,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,FROM_TIME,TO_TIME,OBT1,PKT1,OBT2,PKT2,BOOT_NUMBER,VALIDATION) "
4939     << " VALUES (NULL,' "
4940     << idroot << "',";
4941     //
4942     if ( !pk1 ){
4943     oss << "NULL,";
4944     } else {
4945     oss << "'"
4946     << t1 << "',";
4947     };
4948     //
4949     if ( !pk2 ){
4950     oss << "NULL,'";
4951     } else {
4952     oss << "'"
4953     << t2 << "','";
4954     };
4955     //
4956     oss << fromtime << "','"
4957     << totime << "','"
4958     << obt1 << "','"
4959     << pkt1 << "','"
4960     << obt2 << "','"
4961     << pkt2 << "','"
4962     << boot_number << "','"
4963     << valid << "');";
4964     //
4965     if ( IsDebug() ) printf(" Insert the new trk calibration: query is \n %s \n",oss.str().c_str());
4966     //
4967     result = conn->Query(oss.str().c_str());
4968     //
4969     if ( !result ) throw -4;
4970     //
4971 mocchiut 1.1 };
4972 pam-fi 1.4
4973 mocchiut 1.1 oss.str("");
4974 pam-fi 1.4 oss << " SELECT ID FROM GL_TRK_CALIB ORDER BY ID DESC LIMIT 1 ;";
4975     if ( IsDebug() ) cout << oss.str().c_str() << endl;
4976 mocchiut 1.1 result = conn->Query(oss.str().c_str());
4977 pam-fi 1.4 if ( !result ) throw -4;;
4978     row = result->Next();
4979     if(row)glcal->ID = (UInt_t)atoll(row->GetField(0));
4980    
4981 mocchiut 1.1 //
4982     };
4983    
4984     /**
4985     * Scan tracker calibrations packets, fill the GL_TRK_CALIB table
4986     */
4987     Int_t PamelaDBOperations::insertTRK_CALIB(){
4988     //
4989 pam-fi 1.4 CalibTrk1Event *caltrk1 = 0;
4990     CalibTrk2Event *caltrk2 = 0;
4991     TTree *tr1 = 0;
4992     TTree *tr2 = 0;
4993     EventHeader *eh1 = 0;
4994     PscuHeader *ph1 = 0;
4995     EventHeader *eh2 = 0;
4996     PscuHeader *ph2 = 0;
4997     //
4998     PacketType *pctp=0;
4999     EventCounter *codt2=0;
5000     //
5001     Int_t nevents1 = 0;
5002     Int_t nevents2 = 0;
5003 mocchiut 1.1 //
5004 pam-fi 1.4 fromtime = 0;
5005 mocchiut 1.1 //
5006 pam-fi 1.4 obt1 = 0;
5007     pkt1 = 0;
5008     obt2 = 0;
5009     pkt2 = 0;
5010 mocchiut 1.1 //
5011 pam-fi 1.4 tr1 = (TTree*)file->Get("CalibTrk1");
5012     if ( !tr1 || tr1->IsZombie() ) throw -22;
5013     tr2 = (TTree*)file->Get("CalibTrk2");
5014     if ( !tr2 || tr2->IsZombie() ) throw -23;
5015     //
5016     tr1->SetBranchAddress("CalibTrk1", &caltrk1);
5017     tr1->SetBranchAddress("Header", &eh1);
5018     nevents1 = tr1->GetEntries();
5019     tr2->SetBranchAddress("CalibTrk2", &caltrk2);
5020     tr2->SetBranchAddress("Header", &eh2);
5021     nevents2 = tr2->GetEntries();
5022     //
5023     if ( !nevents1 && !nevents2 ) return(1);
5024     //
5025     t2 = -1;
5026     Int_t pret2 = 0;
5027     Int_t t2t1cal = 0;
5028     //
5029     bool MISSING_pkt1 = true;
5030     bool MISSING_pkt2 = true;
5031     int ncalib = 0;
5032     bool try_to_recover = false;
5033 mocchiut 1.1 //
5034 pam-fi 1.4 for (t1=0; t1 < nevents1; t1++){//loop over packet1
5035     //
5036     pret2 = t2;
5037     tr1->GetEntry(t1);
5038 mocchiut 1.1 //
5039 pam-fi 1.4 ph1 = eh1->GetPscuHeader();
5040     obt1 = ph1->GetOrbitalTime();
5041     pkt1 = ph1->GetCounter();
5042     fromtime = GetAbsTime(ph1->GetOrbitalTime());
5043 mocchiut 1.1 //
5044 pam-fi 1.4 // chek if the packet number and obt are consistent with the other packets ???
5045 mocchiut 1.1 //
5046 pam-fi 1.4 if ( PKT(pkt1) >= PKT(pktfirst) && PKT(pkt1) <= upperpkt && OBT(obt1) >= OBT(obtfirst) && OBT(obt1) <= upperobt ){
5047     // if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->OBT(obt1) >= this->OBT(obtfirst) ){
5048     //
5049     if ( IsDebug() ) printf("\n Trk calibration1 %u at time %u obt %u pkt %u \n",t1,fromtime,obt1,pkt1);
5050     //
5051     valid = ValidateTrkCalib( caltrk1, eh1 );
5052     if ( IsDebug() ) cout << " pkt1 validation --> "<<valid<<endl;
5053     //
5054     // Do we have the second calibration packet?
5055     //
5056     if ( IsDebug() ) cout << " Loop over calibration2 to search associated calibration: "<<endl;
5057     while ( t2t1cal < t1+1 ){ // get the calibration packet2 that follows the packet1
5058     //
5059     t2++;
5060     //
5061     pret2 = t2 - 1; // EMILIANO
5062     //
5063     if ( t2 < nevents2 ){
5064     tr2->GetEntry(t2);
5065     codt2 = eh2->GetCounter();
5066     t2t1cal = codt2->Get(pctp->CalibTrk1);
5067     //
5068     ph2 = eh2->GetPscuHeader();
5069     obt2 = ph2->GetOrbitalTime();
5070     pkt2 = ph2->GetCounter();
5071     //
5072     if ( IsDebug() ) printf(" >> trk calibration2 at obt %u pkt %u t2 is %u , t2t1cal is %u \n",obt2,pkt2,t2,t2t1cal);
5073     // if ( caltrk2->unpackError != 0 || caltrk2->good0 == 0 ) valid = 0; // CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT2
5074     //
5075     } else {
5076     //
5077     // running out of vector without finding the corresponding calibration, sig
5078     //
5079     if ( IsDebug() ) printf(" t2 >= nevents2 \n");
5080     pret2 = t2;
5081     obt2 = 0;
5082     // pkt2 = pkt1+2;
5083     pkt2 = 0;
5084     t2t1cal = t1+1;
5085     };
5086     // if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) && (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){
5087    
5088     // EMILIANO
5089     // if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) || (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){
5090     // // if ( this->PKT(pkt2) < this->PKT(pktfirst) && this->OBT(obt2) < this->OBT(obtfirst) ){
5091     // if ( IsDebug() ) printf(" running out of vector without finding the corresponding calibration, sig \n");
5092     // //
5093     // // running out of vector without finding the corresponding calibration, sig
5094     // //
5095     // pret2 = t2;
5096     // obt2 = 0;
5097     // // pkt2 = pkt1+2;
5098     // pkt2 = 0;
5099     // t2t1cal = t1+1;
5100     // };
5101    
5102    
5103     //
5104     };
5105     //
5106     if ( IsDebug() ) printf(" Check if trk calibration2 is the right one \n");
5107     //
5108     // EMILIANO
5109     if ( ( PKT(pkt2) < PKT(pktfirst) || PKT(pkt2) > upperpkt) || (OBT(obt2) < OBT(obtfirst) || OBT(obt2) > upperobt) ){
5110     // if ( this->PKT(pkt2) < this->PKT(pktfirst) && this->OBT(obt2) < this->OBT(obtfirst) ){
5111     if ( IsDebug() ) printf(" *WARNING* The calibration found is outside the interval, sig \n");
5112     //
5113     // running out of vector without finding the corresponding calibration, sig
5114     //
5115     pret2 = t2;
5116     obt2 = 0;
5117     pkt2 = 0;
5118     };
5119     if ( PKT(pkt2) == PKT(pkt1)+1 ){
5120     if ( IsDebug() ) cout << " ...OK"<<endl;
5121     // =======================
5122     // The calibration is good
5123     // =======================
5124     //
5125     // if ( IsDebug() ) printf(" Found trk calibration2 at obt %u pkt %u t2 is %u \n",obt2,pkt2,t2);
5126     // if ( IsDebug() ) printf(" Trk calibration2 at obt %u pkt %u t2 is %u is good \n",obt2,pkt2,t2);
5127     // if ( IsDebug() ) printf("\n Trk calibration2 at time %u obt %u pkt %u \n",fromtime,obt2,pkt2);
5128     if ( IsDebug() ) printf(" Trk calibration2 %u at time %u obt %u pkt %u \n",t2,fromtime,obt2,pkt2);
5129     //
5130     UInt_t valid2 = ValidateTrkCalib( caltrk2, eh2 );
5131     if ( IsDebug() ) cout << " pkt2 validation --> "<<valid2<<endl;
5132     // valid = valid & valid2;
5133     valid = valid & valid2; //QUESTO VA CAMBIATO
5134     //
5135     // Handle good calib
5136     //
5137     MISSING_pkt1 = false;
5138     MISSING_pkt2 = false;
5139     // this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5140     //
5141     // Check for missing calibtrk1
5142     //
5143     if ( t2 != pret2+1 ){
5144     //
5145     if ( IsDebug() ) printf(" Missing the trk calibration1! Next one at obt %u pkt %u t2 is %u pret2 is %u \n",obt2,pkt2,t2,pret2);
5146     //
5147     while ( t2 > pret2+1 ){
5148     //
5149     // handle missing calib1
5150     //
5151     pret2++;
5152     //
5153     obt1 = 0;
5154     pkt1 = 0;
5155     //
5156     tr2->GetEntry(pret2);
5157     ph2 = eh2->GetPscuHeader();
5158     obt2 = ph2->GetOrbitalTime();
5159     pkt2 = ph2->GetCounter();
5160     //
5161     fromtime = this->GetAbsTime(ph2->GetOrbitalTime());
5162     //
5163     valid = 0;
5164     MISSING_pkt1 = true;
5165     MISSING_pkt2 = false;
5166     // this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5167     //
5168     };
5169     //
5170     };
5171     //
5172     } else if ( this->PKT(pkt2) > this->PKT(pkt1)+1 ){
5173     //
5174     // Check for missing calibtrk2
5175     //
5176     if ( IsDebug() ) printf(" Missing the trk calibration2! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);
5177     t2 = pret2;
5178     //
5179     // handle missing calib2
5180     //
5181     obt2 = 0;
5182     pkt2 = 0;
5183     valid = 0;
5184     MISSING_pkt1 = false;
5185     MISSING_pkt2 = true;
5186     // this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5187     //
5188     };
5189     //
5190 mocchiut 1.1 } else {
5191 pam-fi 1.4 //
5192     if ( IsDebug() ) printf(" Trk calibration1 at time %u obt %u pkt %u OUTSIDE the considered time interval \n",fromtime,obt1,pkt1);
5193     // if ( PEDANTIC ) throw -79;
5194     //
5195 mocchiut 1.1 };
5196 pam-fi 1.4 //
5197    
5198     if( !(MISSING_pkt1&MISSING_pkt2) ){
5199     this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5200     ncalib++;
5201     if( MISSING_pkt1||MISSING_pkt2||!valid )try_to_recover=true;
5202     }
5203    
5204     }; //end loop on pkt1
5205 mocchiut 1.1
5206    
5207    
5208 pam-fi 1.4 //
5209     // we have one more calib pkt2 !
5210     //
5211     t2++;
5212     while ( t2 < nevents2 ){
5213 mocchiut 1.1 //
5214 pam-fi 1.4 // handle missing calib1
5215 mocchiut 1.1 //
5216 pam-fi 1.4 if ( IsDebug() ) printf(" t2 is %u nevents2 is %u \n",t2,nevents2);
5217     obt1 = 0;
5218     pkt1 = 0;
5219 mocchiut 1.1 //
5220 pam-fi 1.4 tr2->GetEntry(t2);
5221     ph2 = eh2->GetPscuHeader();
5222     obt2 = ph2->GetOrbitalTime();
5223     pkt2 = ph2->GetCounter();
5224 mocchiut 1.1 //
5225 pam-fi 1.4 fromtime = this->GetAbsTime(ph2->GetOrbitalTime());
5226     valid = 0;
5227     // if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->PKT(pkt1) <= upperpkt && this->OBT(obt1) >= this->OBT(obtfirst) && this->OBT(obt1) <= upperobt ){
5228     // EMILIANO
5229     if ( this->PKT(pkt2) >= this->PKT(pktfirst) && this->PKT(pkt2 <= upperpkt) && this->OBT(obt2) >= this->OBT(obtfirst) && this->OBT(obt2) <= upperobt ){
5230     // if ( this->PKT(pkt2) > this->PKT(pktfirst) || this->OBT(obt2) > this->OBT(obtfirst) ){
5231 mocchiut 1.1 //
5232 pam-fi 1.4 if ( IsDebug() ) printf(" Missing the trk calibration1! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);
5233 mocchiut 1.1 //
5234 pam-fi 1.4 MISSING_pkt1 = true;
5235     MISSING_pkt2 = false;
5236     this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5237     ncalib++;
5238     if( MISSING_pkt1||MISSING_pkt2||!valid )try_to_recover=true;
5239 mocchiut 1.1 //
5240     };
5241     //
5242 pam-fi 1.4 t2++;
5243 mocchiut 1.1 //
5244 pam-fi 1.4 };
5245    
5246     // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
5247     // -----------------------------------------------------------------
5248     // in case of corruption, check if the calibration can be recovered
5249     // from another chewbacca file
5250     // -----------------------------------------------------------------
5251     // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
5252    
5253     // cout <<" TRY TO RECOVER ?? "<<try_to_recover<<endl;
5254    
5255     if(chewbacca&&try_to_recover){
5256    
5257    
5258     if ( IsDebug() ) cout << endl << ">>>> TRY TO RECOVER TRACKER CALIBRATIONS <<<<"<<endl;
5259    
5260     TSQLResult *result = 0;
5261     TSQLRow *row = 0;
5262 mocchiut 1.1 //
5263 pam-fi 1.4 stringstream oss;
5264     oss.str("");
5265 mocchiut 1.1 //
5266 pam-fi 1.4
5267     ////////////////////////////////////////////////////////////////////////
5268     // retrieve the name of the current file:
5269     ////////////////////////////////////////////////////////////////////////
5270     oss.str("");
5271     oss << "SELECT NAME FROM GL_ROOT where ID=" << GetID_ROOT() <<";";
5272     if ( IsDebug() ) cout << oss.str().c_str() << endl;
5273    
5274     result = conn->Query(oss.str().c_str());
5275     if ( !result ) throw -4;;
5276     row = result->Next();
5277     TString thisfilename = (TString)row->GetField(0);
5278     if ( IsDebug() ) cout << "Current file ==> "<<thisfilename<<endl;
5279    
5280     ////////////////////////////////////////////////////////////////////////
5281     // read all the calibrations inserted
5282     ////////////////////////////////////////////////////////////////////////
5283     oss.str("");
5284     oss << " SELECT ";
5285     oss << " ID,FROM_TIME,OBT1,PKT1,OBT2,PKT2,BOOT_NUMBER,VALIDATION,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,TO_TIME";
5286     oss << " FROM GL_TRK_CALIB ";
5287     oss << " ORDER BY ID DESC LIMIT "<<ncalib<<"; ";
5288     if ( IsDebug() ) cout << oss.str().c_str() << endl;
5289    
5290     result = conn->Query(oss.str().c_str());
5291     if ( !result ) throw -4;;
5292     if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5293    
5294     // -----------------------------------
5295     // loop over calibrations ...
5296     // -----------------------------------
5297     UInt_t nn=0;
5298     do {
5299     row = result->Next();
5300     if(!row)break;
5301    
5302     UInt_t id = (UInt_t)atoll(row->GetField(0));
5303     UInt_t fromtime = (UInt_t)atoll(row->GetField(1));
5304     UInt_t obt1 = (UInt_t)atoll(row->GetField(2));
5305     UInt_t pkt1 = (UInt_t)atoll(row->GetField(3));
5306     UInt_t obt2 = (UInt_t)atoll(row->GetField(4));
5307     UInt_t pkt2 = (UInt_t)atoll(row->GetField(5));
5308     UInt_t boot = (UInt_t)atoll(row->GetField(6));
5309     UInt_t valid = (UInt_t)atoll(row->GetField(7));
5310     bool MISSING_pkt1 = (row->GetFieldLength(8)==0);
5311     bool MISSING_pkt2 = (row->GetFieldLength(9)==0);
5312     UInt_t totime = (UInt_t)atoll(row->GetField(10));
5313    
5314     // -------------------------------------
5315     // ...check if the entry is corrupted...
5316     // -------------------------------------
5317     cout <<"*** "<< MISSING_pkt1 << MISSING_pkt2 << valid <<endl;
5318     bool CORRUPTED = (MISSING_pkt1||MISSING_pkt2||!valid);
5319    
5320     if ( IsDebug() ) cout << "("<<nn<<") ID = "<<id<<" from GL_TRK_CALIB ==> corrupted ? "<<CORRUPTED<<endl;
5321    
5322     // if( !CORRUPTED )continue; // nothing to do
5323    
5324     /////////////////////////////////////////////////////////
5325     // if it is corrupted, ...look for ather chewbacca files
5326     // containing the same calibrations ...
5327     /////////////////////////////////////////////////////////
5328    
5329     bool this_MISSING_pkt1 = false;
5330     bool this_MISSING_pkt2 = false;
5331     int this_t1=0;
5332     int this_t2=0;;
5333     UInt_t this_valid = 0;
5334    
5335     TString path = "";
5336     TString name = "";
5337     TString raw = "";
5338     UInt_t obt0 = 0;
5339     UInt_t timesync = 0;
5340     UInt_t boot_number = 0;
5341     bool FOUND = false;
5342    
5343     if ( IsDebug() ) cout << "------------------------------------------------------------" <<endl;
5344    
5345     // for(int itable=0; itable<2; itable++){
5346     for(int itable=0; itable<1; itable++){
5347    
5348     // ------------------------------------------------------
5349     // loop over both ROOT_TABLE and ROOT_TABLE_BAD
5350     // ------------------------------------------------------
5351    
5352     TString table = "ROOT_TABLE";
5353     if(itable==1)table = "ROOT_TABLE_BAD";
5354    
5355     oss.str("");
5356     oss << " SELECT ";
5357     oss << " FOLDER_NAME,FILE_NAME,OBT_TIME_SYNC,LAST_TIME_SYNC_INFO,BOOT_NUMBER,INPUT_NAME ";
5358     oss << " FROM "<<table;
5359     oss << " WHERE 1 " << endl;
5360     oss << " AND FILE_NAME != \""<< thisfilename<<"\"";
5361     if( !MISSING_pkt1 ){
5362     oss << " AND ";
5363     oss << " PKT_NUMBER_INIT < "<<pkt1;
5364     oss << " AND ";
5365     oss << " PKT_NUMBER_FINAL > "<<pkt1;
5366     oss << " AND ";
5367     oss << " PKT_OBT_INIT < "<<obt1;
5368     oss << " AND ";
5369     oss << " PKT_OBT_FINAL > "<<obt1;
5370     }else{
5371     if(pkt2>1) pkt1 = pkt2-1;//serve dopo
5372     }
5373     if( !MISSING_pkt2 ){
5374     oss << " AND ";
5375     oss << " PKT_NUMBER_INIT < "<<pkt2;
5376     oss << " AND ";
5377     oss << " PKT_NUMBER_FINAL > "<<pkt2;
5378     oss << " AND ";
5379     oss << " PKT_OBT_INIT < "<<obt2;
5380     oss << " AND ";
5381     oss << " PKT_OBT_FINAL > "<<obt2;
5382     }else{
5383     if(pkt1>0) pkt2 = pkt1+1;//serve dopo
5384     }
5385     if( boot> 0 ){
5386     oss << " AND ";
5387     oss << " BOOT_NUMBER = "<<boot;
5388     }else{
5389     }
5390     oss << " ORDER BY BAD_PKT_CALREAD ASC; ";
5391    
5392     TSQLResult *result2 = 0;
5393     TSQLRow *row2 = 0;
5394    
5395     if ( IsDebug() ) cout << oss.str().c_str() << endl;
5396     result2 = conn->Query(oss.str().c_str());
5397     if ( !result2 ) throw -4;;
5398     if ( IsDebug() ) cout <<"Rows: "<<result2->GetRowCount()<<endl;
5399    
5400     // ------------------------------------------------------
5401     // loop over files containing repetition (if any)
5402     // ------------------------------------------------------
5403     do {
5404     row2 = result2->Next();
5405     if(!row2)break;
5406    
5407     // ------------------------------------------------------
5408     // ... a repetition is found ...
5409     // ------------------------------------------------------
5410     path = (TString)row2->GetField(0);
5411     name = (TString)row2->GetField(1);
5412     raw = (TString)row2->GetField(5);
5413     obt0 = (UInt_t)atoll(row2->GetField(2));
5414     timesync = (UInt_t)atoll(row2->GetField(3));
5415     boot_number = (UInt_t)atoll(row2->GetField(4));
5416    
5417     if ( IsDebug() ) cout << "- - - - - - - - - - -" <<endl;
5418     // cout << path <<endl;
5419     cout << "File : " <<name <<endl;
5420     // cout << obt0 <<endl;
5421     // cout << timesync <<endl;
5422     cout << "boot n. : "<<boot_number <<endl;
5423     // cout << raw <<endl;
5424    
5425     // ------------------------------------------------------
5426     // ... retrieve the calibration packets.
5427     // ------------------------------------------------------
5428     TFile *file = new TFile(path+"/"+name);
5429     if(!file)throw -100;
5430     if(file->IsZombie())throw -100;
5431     //
5432     tr1 = (TTree*)file->Get("CalibTrk1");
5433     if ( !tr1 || tr1->IsZombie() ) throw -22;
5434     tr2 = (TTree*)file->Get("CalibTrk2");
5435     if ( !tr2 || tr2->IsZombie() ) throw -23;
5436     //
5437     tr1->SetBranchAddress("CalibTrk1", &caltrk1);
5438     tr1->SetBranchAddress("Header", &eh1);
5439     nevents1 = tr1->GetEntries();
5440     tr2->SetBranchAddress("CalibTrk2", &caltrk2);
5441     tr2->SetBranchAddress("Header", &eh2);
5442     nevents2 = tr2->GetEntries();
5443     for(this_t1=0; this_t1<nevents1; this_t1++){
5444     tr1->GetEntry(this_t1);
5445     if(
5446     (UInt_t)eh1->GetPscuHeader()->GetCounter() == pkt1 &&
5447     true) break;
5448     this_MISSING_pkt1 = true;
5449     }
5450     for(this_t2=0; this_t2<nevents2; this_t2++){
5451     tr2->GetEntry(this_t2);
5452     if(
5453     (UInt_t)eh2->GetPscuHeader()->GetCounter() == pkt2 &&
5454     true) break;
5455     this_MISSING_pkt2 = true;
5456     }
5457     this_valid =
5458     ValidateTrkCalib( caltrk1, eh1, file )
5459     *
5460     ValidateTrkCalib( caltrk2, eh2, file );
5461    
5462     // ---------------------------------------------------------------------
5463     // accept the calibration if it is better than the previous:
5464     //
5465     // - if the new calibration is perfect (both valid packets)
5466     // - if the new calibration has both the packets and the previous does not
5467     // ---------------------------------------------------------------------
5468     if(
5469     ( !this_MISSING_pkt1&&!this_MISSING_pkt2&&this_valid )||
5470     ( (MISSING_pkt1||MISSING_pkt2) && (!this_MISSING_pkt1&&!this_MISSING_pkt2) )||
5471     false)FOUND=true;
5472    
5473     if(file)file->Close();
5474    
5475     if(FOUND)break;
5476    
5477     }while(1);//endl loop over root table entries
5478    
5479     if(FOUND)break;
5480    
5481     }//end loop over tables
5482    
5483     if(FOUND){
5484    
5485     if ( IsDebug() ) cout << " >>> REPETITION FOUND :-) <<<" <<endl;
5486    
5487     ////////////////////////////////////////////
5488     // insert a new entry in GL_TRK_CALIB and
5489     // modify the time-tag of the previous one
5490     ////////////////////////////////////////////
5491    
5492     // ---------------------------------------------------------------------
5493     // step 1: insert a new raw file in GL_RAW
5494     // ---------------------------------------------------------------------
5495     //
5496     // check if the raw file already exist
5497     //
5498     UInt_t id_raw = 0;
5499     oss.str("");
5500     oss << "SELECT ID FROM GL_RAW where NAME=\"" << gSystem->BaseName(raw.Data()) <<"\";";
5501     if ( IsDebug() ) cout << oss.str().c_str() << endl;
5502    
5503     result = conn->Query(oss.str().c_str());
5504     if ( !result ) throw -4;;
5505     if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5506     if( result->GetRowCount() == 0){
5507     if ( IsDebug() ) cout << " << Insert new RAW file >> "<<endl;
5508     // - - - - - - - - - - -
5509     // insert new raw file
5510     // - - - - - - - - - - -
5511     GL_RAW glraw = GL_RAW();
5512     glraw.PATH = gSystem->DirName(raw.Data());
5513     glraw.NAME = gSystem->BaseName(raw.Data());
5514     glraw.BOOT_NUMBER = boot_number;
5515     //
5516     insertPamelaRawFile( &glraw );
5517     //
5518     id_raw = glraw.ID;
5519     }else{
5520     row = result->Next();
5521     id_raw = (UInt_t)atoll(row->GetField(0));
5522     }
5523     if ( IsDebug() ) cout << "ID_RAW = "<<id_raw<<endl;
5524    
5525     // ---------------------------------------------------------------------
5526     // step 1(bis): retrieve the timesync id associated to the file
5527     // (NB, uso lo stesso associato al file iniziale)
5528     // ---------------------------------------------------------------------
5529     UInt_t idtimesync = 0;
5530     oss.str("");
5531     oss << " SELECT ID FROM GL_TIMESYNC where TIMESYNC="<<chlastts<<" AND OBT0="<<chobtts*1000<<" limit 1;";
5532     if ( debug ) printf(" %s \n",oss.str().c_str());
5533     result = conn->Query(oss.str().c_str());
5534     if ( !result ) throw -3;
5535     row = result->Next();
5536     if ( !row ) throw -3;
5537     idtimesync = (UInt_t)atoll(row->GetField(0));
5538     if ( IsDebug() ) cout << "ID_TIMESYNC = "<<idtimesync<<endl;
5539    
5540     // ---------------------------------------------------------------------
5541     // step 2: insert a new root file in GL_ROOT
5542     // ---------------------------------------------------------------------
5543     //
5544     // check if the raw file already exist
5545     //
5546     UInt_t id_root = 0;
5547     oss.str("");
5548     oss << "SELECT ID FROM GL_ROOT where NAME=\"" << gSystem->BaseName(name.Data()) <<"\";";
5549     if ( IsDebug() ) cout << oss.str().c_str() << endl;
5550    
5551     result = conn->Query(oss.str().c_str());
5552     if ( !result ) throw -4;;
5553     if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5554     if( result->GetRowCount() == 0){
5555     if ( IsDebug() ) cout << " << Insert new ROOT file >> "<<endl;
5556     // - - - - - - - - - - -
5557     // insert new root file
5558     // - - - - - - - - - - -
5559     GL_ROOT glroot = GL_ROOT();
5560     glroot.ID_RAW = id_raw;
5561     glroot.ID_TIMESYNC = idtimesync;
5562     glroot.PATH = path;
5563     glroot.NAME = name;
5564     //
5565     insertPamelaRootFile( &glroot );
5566     //
5567     id_root = glroot.ID;
5568     }else{
5569     row = result->Next();
5570     if(row)id_root = (UInt_t)atoll(row->GetField(0));
5571     }
5572     if ( IsDebug() ) cout << "ID_ROOT = "<<id_root<<endl;
5573    
5574     // ---------------------------------------------------------------------
5575     // step 3: modify time-tag of corrupted GL_TRK_CALIB entry
5576     // ---------------------------------------------------------------------
5577     if ( IsDebug() ) cout << " << Modify time-tag of calibration ID="<<id<<" >> "<<endl;
5578     oss.str("");
5579     oss << " UPDATE GL_TRK_CALIB SET "
5580     << " TO_TIME=0 , FROM_TIME=0 WHERE "
5581     << " ID = "<< id << ";";
5582     if ( IsDebug() ) cout << oss.str().c_str() << endl;
5583     result = conn->Query(oss.str().c_str());
5584     if ( !result ) throw -4;;
5585    
5586     // ---------------------------------------------------------------------
5587     // step 4: insert the new calibration:
5588     // ---------------------------------------------------------------------
5589     if ( IsDebug() ) cout << " << Insert new TRK calibration >> "<<endl;
5590     //
5591     GL_TRK_CALIB glcal = GL_TRK_CALIB();
5592     //
5593     glcal.ID_ROOT_L0 = id_root;
5594     glcal.EV_ROOT_CALIBTRK1 = this_t1;
5595     glcal.EV_ROOT_CALIBTRK2 = this_t2;
5596     glcal.FROM_TIME = fromtime;
5597     glcal.TO_TIME = totime;
5598     glcal.OBT1 = obt1;
5599     glcal.OBT2 = obt2;
5600     glcal.PKT1 = pkt1;
5601     glcal.PKT2 = pkt1;
5602     glcal.BOOT_NUMBER = GetBOOTnumber();
5603     glcal.VALIDATION = this_valid;
5604     //
5605     HandleTRK_CALIB(&glcal);
5606     if ( IsDebug() ) cout << "ID = "<<glcal.ID<<endl;
5607     //
5608    
5609     }
5610     if ( IsDebug() ) cout << "------------------------------------------------------------" <<endl;
5611    
5612     }while(1);//end loop over calibrations
5613    
5614    
5615     if( result )delete result;
5616     if( row )delete row;
5617    
5618    
5619    
5620    
5621    
5622    
5623     }
5624    
5625    
5626     // // ------------------------------
5627     // // try to recover the calibration
5628     // // ------------------------------
5629     // cout << "TRY TO RECOVER TRACKER CALIBRATION"<<endl;
5630     // //
5631     // ULong64_t time = 0; //absolute time
5632     // string path[100]; //mettere un limite massimo
5633     // int nrows = 0;
5634     // UInt_t pkt = 0;
5635     // UInt_t obt = 0;
5636     // char *type = "";
5637     // EventHeader *eh = new EventHeader();
5638     // CalibTrk1Event *c = new CalibTrk1Event();
5639    
5640     // //
5641     // if(which_is_not_valid==1 || which_is_not_valid==3){
5642     // //
5643     // cout << "PKT1 --> missing or corrupted "<<endl;
5644     // type = "CalibTrk1";
5645     // pkt = pkt1;
5646     // obt = obt1;
5647     // time = this->GetAbsTime(obt1);
5648     // if( pkt1 == 0 ){//missing
5649     // time = this->GetAbsTime(obt2);
5650     // pkt = pkt2-1;
5651     // }
5652     // //
5653     // }else if (which_is_not_valid==2 || which_is_not_valid==3){
5654     // //
5655     // cout << "PKT2--> missing or corrupted "<<endl;
5656     // type = "CalibTrk2 ";
5657     // pkt = pkt2;
5658     // obt = obt2;
5659     // time = this->GetAbsTime(obt2);
5660     // if( pkt2 == 0 ){//missing
5661     // time = this->GetAbsTime(obt1);
5662     // pkt = pkt1+1;
5663     // }
5664     // //
5665     // }else{
5666     // cout << "this should not happen!!! "<<endl;
5667     // trow -666;
5668     // }
5669    
5670     // nrows = Query_ROOT_TABLE(time,conn,path);// get the list of file which might contain the packet
5671    
5672    
5673     // for(int r=0; r<nrows; r++){ //loop over rows
5674     // if(path)cout << r << " >>>> "<<(path+r)->c_str() << endl;
5675     // /// verifica che il file non sia quello gia` aperto
5676     // }
5677    
5678     // ////////////////////////////////////////////////////////////////////////
5679    
5680     // TSQLResult *result = 0;
5681     // TSQLRow *row = 0;
5682     // //
5683     // stringstream oss;
5684     // oss.str("");
5685     // // ----------------------------------------
5686     // // read the id of last calibration inserted
5687     // // ----------------------------------------
5688     // oss.str("");
5689     // oss << " SELECT ";
5690     // oss << " (ID,ID_ROOT_L0,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,FROM_TIME,TO_TIME,OBT1,PKT1,OBT2,PKT2,BOOT_NUMBER,VALIDATION) ";
5691     // oss << " ORDER BY ID DESC LIMIT 1; ";
5692    
5693     // result = conn->Query(oss.str().c_str());
5694     // row = result->Next();
5695     // if( !row )throw -666;
5696    
5697     // if( result )delete result;
5698     // if( row )delete row;
5699    
5700     // UInt_t id = (UInt_t)atoll(row->GetField(0));
5701    
5702     // // -------------------------------------
5703     // // ...and modify it with new parameters
5704     // // -------------------------------------
5705    
5706    
5707     // }
5708 mocchiut 1.1 //
5709     return(0);
5710     };
5711    
5712    
5713     /**
5714     * Scan S4 calibrations packets, fill the GL_S4_CALIB table
5715     */
5716     Int_t PamelaDBOperations::insertS4_CALIB(){
5717     //
5718     TSQLResult *result = 0;
5719     TSQLRow *row = 0;
5720     //
5721     stringstream oss;
5722     oss.str("");
5723     //
5724     TTree *tr = 0;
5725     EventHeader *eh = 0;
5726     PscuHeader *ph = 0;
5727     //
5728     UInt_t nevents = 0;
5729     UInt_t fromtime = 0;
5730     UInt_t totime = 0;
5731     UInt_t obt = 0;
5732     UInt_t pkt = 0;
5733     //
5734     tr = (TTree*)file->Get("CalibS4");
5735     if ( !tr || tr->IsZombie() ) throw -24;
5736     //
5737     tr->SetBranchAddress("Header", &eh);
5738     //
5739     nevents = tr->GetEntries();
5740     //
5741     if ( !nevents ) return(1);
5742     //
5743     for (UInt_t i = 0; i < nevents; i++){
5744     //
5745     tr->GetEntry(i);
5746     //
5747     ph = eh->GetPscuHeader();
5748     obt = ph->GetOrbitalTime();
5749     pkt = ph->GetCounter();
5750     fromtime = this->GetAbsTime(ph->GetOrbitalTime());
5751     if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->PKT(pkt) <= upperpkt && this->OBT(obt) >= this->OBT(obtfirst) && this->OBT(obt) <= upperobt ){
5752     // if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->OBT(obt) >= this->OBT(obtfirst) ){
5753     //
5754     if ( IsDebug() ) printf(" S4 calibration at time %u obt %u pkt %u \n",fromtime,obt,pkt);
5755     //
5756     // check if the calibration has already been inserted
5757     //
5758     oss.str("");
5759     oss << " SELECT ID FROM GL_S4_CALIB WHERE "
5760     << " BOOT_NUMBER = "<< this->GetBOOTnumber() << " AND "
5761     << " OBT = "<< obt << " AND "
5762     << " PKT = "<< pkt << ";";
5763     //
5764     if ( IsDebug() ) printf(" Check if the S4 calibration has already been inserted: query is \n %s \n",oss.str().c_str());
5765     result = conn->Query(oss.str().c_str());
5766     //
5767     if ( !result ) throw -4;
5768     //
5769     row = result->Next();
5770     //
5771     if ( row ){
5772     //
5773     if ( IsDebug() ) printf(" S4 calibration already inserted in the DB\n");
5774     if ( PEDANTIC ) throw -81;
5775     //
5776     } else {
5777     //
5778     // we have to insert a new calibration, check where to place it
5779     //
5780     oss.str("");
5781     oss << " SELECT ID,TO_TIME FROM GL_S4_CALIB WHERE "
5782     << " FROM_TIME < "<< fromtime << " AND "
5783     << " TO_TIME > "<< fromtime << ";";
5784     //
5785     if ( IsDebug() ) printf(" Check where to place the S4 calibration: query is \n %s \n",oss.str().c_str());
5786     result = conn->Query(oss.str().c_str());
5787     //
5788     if ( !result ) throw -4;
5789     //
5790     row = result->Next();
5791     //
5792     if ( !row ){
5793     //
5794     // no calibrations in the db contain our calibration
5795     //
5796     if ( IsDebug() ) printf(" Calibration with fromtime lower than others to be inserted in the DB \n");
5797     if ( fromtime < 1150871000 ){
5798     if ( IsDebug() ) printf(" First PAMELA flight calibration at time %u \n",fromtime);
5799     fromtime = 0;// the first flight calibration was taken at about 1156429100 s, this line allow to analyze first runs in raw mode
5800     };
5801     //
5802     oss.str("");
5803     oss << " SELECT FROM_TIME FROM GL_S4_CALIB WHERE "
5804     << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";
5805     //
5806     if ( IsDebug() ) printf(" Check the upper limit for calibration: query is \n %s \n",oss.str().c_str());
5807     result = conn->Query(oss.str().c_str());
5808     //
5809     if ( !result ) throw -4;
5810     //
5811     row = result->Next();
5812     if ( !row ){
5813     totime = numeric_limits<UInt_t>::max();
5814     } else {
5815     totime = (UInt_t)atoll(row->GetField(0));
5816     };
5817     //
5818     } else {
5819     //
5820     // determine upper and lower limits and make space for the new calibration
5821     //
5822     totime = (UInt_t)atoll(row->GetField(1));
5823     //
5824     oss.str("");
5825     oss << " UPDATE GL_S4_CALIB SET "
5826     << " TO_TIME = "<< fromtime << " WHERE " // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[
5827     << " ID = "<< row->GetField(0) << ";";
5828     //
5829     if ( IsDebug() ) printf(" Make space for the new calibration: query is \n %s \n",oss.str().c_str());
5830     result = conn->Query(oss.str().c_str());
5831     //
5832     if ( !result ) throw -4;
5833     //
5834     };
5835     //
5836     oss.str("");
5837     oss << " INSERT INTO GL_S4_CALIB (ID,ID_ROOT_L0,EV_ROOT,FROM_TIME,TO_TIME,OBT,PKT,BOOT_NUMBER) "
5838     << " VALUES (NULL,' "
5839     << idroot << "','"
5840     << i << "','"
5841     << fromtime << "','"
5842     << totime << "','"
5843     << obt << "','"
5844     << pkt << "','"
5845     << this->GetBOOTnumber() << "');";
5846     //
5847     if ( IsDebug() ) printf(" Insert the new calibration: query is \n %s \n",oss.str().c_str());
5848     //
5849     result = conn->Query(oss.str().c_str());
5850     //
5851     if ( !result ) throw -4;
5852     //
5853     };
5854     //
5855     } else {
5856     //
5857     if ( IsDebug() ) printf(" S4 calibration at time %u obt %u pkt %u OUTSIDE the considered time interval\n",fromtime,obt,pkt);
5858     // if ( PEDANTIC ) throw -82;
5859     //
5860     };
5861     //
5862     };
5863     //
5864     return(0);
5865     };
5866    
5867     /**
5868     * Scan the fragment table and move old fragments to the GL_RUN table
5869     */
5870     Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(){
5871     return(this->CleanGL_RUN_FRAGMENTS(""));
5872     };
5873    
5874     /**
5875     * Scan the fragment table and move old fragments to the GL_RUN table
5876     */
5877     Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(Bool_t runpieces){
5878     return(this->CleanGL_RUN_FRAGMENTS("",runpieces));
5879     };
5880    
5881     /**
5882     * Scan the fragment table and move old fragments to the GL_RUN table
5883     */
5884     Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(TString fcleanfile){
5885     return(this->CleanGL_RUN_FRAGMENTS("",false));
5886     };
5887    
5888     /**
5889     * Scan the fragment table and move old fragments to the GL_RUN table
5890     */
5891     Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(TString fcleanfile, Bool_t runpieces){
5892     //
5893     TSQLResult *nresult = 0;
5894     TSQLRow *nrow = 0;
5895     TSQLResult *nresult1 = 0;
5896     TSQLRow *nrow1 = 0;
5897     TSQLResult *result = 0;
5898     TSQLRow *row = 0;
5899     TSQLResult *result2 = 0;
5900     TSQLRow *row2 = 0;
5901     //
5902     UInt_t moved = 0;
5903     //
5904     stringstream oss;
5905     oss.str("");
5906     //
5907     // Before moving blindly the runs from GL_RUN_FRAGMENTS to GL_RUN try to find out if we have runs divided in more than two pieces (chewbacca or explicit flag only)
5908     //
5909     if ( runpieces ){
5910     //
5911     UInt_t nid = 0;
5912     UInt_t myid[500];
5913     memset(myid,0,500*sizeof(UInt_t));
5914     //
5915     oss.str("");
5916     oss << "SELECT ID,RUNTRAILER_TIME,RUNTRAILER_PKT,BOOT_NUMBER FROM GL_RUN_FRAGMENTS WHERE INSERT_TIME <= '" << clean_time->AsSQLString() << "'order BY RUNHEADER_TIME asc;";
5917     if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS runs older than %s : query is \n %s \n",clean_time->AsSQLString(),oss.str().c_str());
5918     nresult = conn->Query(oss.str().c_str());
5919     //
5920     if ( nresult ){
5921     //
5922     nrow = nresult->Next();
5923     //
5924     while ( nrow ){
5925     //
5926     UInt_t mbo = (UInt_t)atoll(nrow->GetField(3));
5927     UInt_t mrhp = (UInt_t)atoll(nrow->GetField(2));
5928     UInt_t mrht = (UInt_t)atoll(nrow->GetField(1));
5929     Bool_t anr = true;
5930     Bool_t runisthere = true;
5931     //
5932     for (UInt_t u=0; u<=nid; u++){
5933     if ( (UInt_t)atoll(nrow->GetField(0)) == myid[u] && (UInt_t)atoll(nrow->GetField(0)) != 0 ) runisthere = false;
5934     };
5935     //
5936     // check if the run is still in the fragment table or if we have just move it in the gl_run table!
5937     //
5938     if ( runisthere ){
5939     //
5940     memset(myid,0,500*sizeof(UInt_t));
5941     nid = 0;
5942     myid[nid] = (UInt_t)atoll(nrow->GetField(0));
5943     //
5944     while ( anr ){
5945     //
5946     oss.str("");
5947     oss << "SELECT ID,RUNTRAILER_TIME,RUNTRAILER_PKT,BOOT_NUMBER FROM GL_RUN_FRAGMENTS WHERE BOOT_NUMBER=" << mbo << " AND RUNHEADER_PKT=" << mrhp << "+1 AND ABS(RUNHEADER_TIME-"<< mrht <<")<=1 AND INSERT_TIME <= '" << clean_time->AsSQLString() << "' order BY RUNHEADER_TIME asc;";
5948     if ( IsDebug() ) printf(" In the loop searching for fragmented runs : query is \n %s \n",oss.str().c_str());
5949     //
5950     nresult1 = conn->Query(oss.str().c_str());
5951     //
5952     if ( nresult1 ){
5953     //
5954     if ( nresult1->GetRowCount() == 1 ){
5955     //
5956     // one piece is found
5957     //
5958     nrow1 = nresult1->Next();
5959     //
5960     if ( nrow1 ){
5961     //
5962     nid++;
5963     myid[nid] = (UInt_t)atoll(nrow1->GetField(0));
5964     mbo = (UInt_t)atoll(nrow1->GetField(3));
5965     mrhp = (UInt_t)atoll(nrow1->GetField(2));
5966     mrht = (UInt_t)atoll(nrow1->GetField(1));
5967     if ( debug ) printf(" FOUND A PIECE OF RUN! nid %u myid[nid] %u mbo %u mrhp %u mrht %u \n",nid,myid[nid],mbo,mrhp,mrht);
5968     //
5969     nrow1->Close();
5970     } else {
5971     throw -88;
5972     };
5973     } else {
5974     anr = false;
5975     };
5976     nresult1->Close();
5977     } else {
5978     throw -88;
5979     };
5980     };
5981     //
5982     // handle these runs which are ordered and "good". Does the first contain a valid runheader?
5983     //
5984     oss.str("");
5985     oss << " ID= "<< myid[0];
5986     //
5987     glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);
5988     //
5989     if ( glrun->GetACQ_BUILD_INFO() != 0 ){
5990     //
5991     // the first piece contains a good runheader we can update all the other runs with correct infos!
5992     //
5993     for (UInt_t u=1; u <= nid ; u++){
5994     oss.str("");
5995     oss << "UPDATE GL_RUN_FRAGMENTS SET "
5996     << " RUNHEADER_TIME=" << glrun->GetRUNHEADER_TIME()<< " , "
5997     << " RUNHEADER_OBT=" << glrun->GetRUNHEADER_OBT()<< " , "
5998     << " RUNHEADER_PKT=" << glrun->GetRUNHEADER_PKT()<< " , "
5999     << " COMPILATIONTIMESTAMP=" << glrun->GetCOMPILATIONTIMESTAMP()<< " , "
6000     << " FAV_WRK_SCHEDULE=" << glrun->GetFAV_WRK_SCHEDULE()<< " , "
6001     << " EFF_WRK_SCHEDULE=" << glrun->GetEFF_WRK_SCHEDULE()<< " , "
6002     << " PRH_VAR_TRG_MODE_A=" << glrun->GetPRH_VAR_TRG_MODE_A()<< " , "
6003     << " PRH_VAR_TRG_MODE_B=" << glrun->GetPRH_VAR_TRG_MODE_B()<< " , "
6004     << " ACQ_BUILD_INFO=" << glrun->GetACQ_BUILD_INFO()<< " , "
6005     << " ACQ_VAR_INFO=" << glrun->GetACQ_VAR_INFO()<< " , "
6006     << " RM_ACQ_AFTER_CALIB=" << glrun->GetRM_ACQ_AFTER_CALIB()<< " , "
6007     << " RM_ACQ_SETTING_MODE=" << glrun->GetRM_ACQ_SETTING_MODE()<< " , "
6008     << " TRK_CALIB_USED=" << glrun->GetTRK_CALIB_USED()<< " , "
6009     << " CAL_DSP_MASK=" << glrun->GetCAL_DSP_MASK()<< " , "
6010 mocchiut 1.2 << " LAST_TIMESYNC=" << glrun->GetLAST_TIMESYNC()<< " , ";
6011     //
6012     if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() )
6013     oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12() << " , ";
6014     if ( glrun->GetPHYSENDRUN_MASK_S11CRC() )
6015     oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC() << " , ";
6016     //
6017     oss << " OBT_TIMESYNC=" << glrun->GetOBT_TIMESYNC();
6018     oss << " WHERE ID=" << myid[u] << ";";
6019 mocchiut 1.1 conn->Query(oss.str().c_str());
6020     };
6021     //
6022     } else {
6023     //
6024     // sig no runheader, let set anyway what is possible...
6025     //
6026     for (UInt_t u=1; u <= nid ; u++){
6027     oss.str("");
6028     oss << "UPDATE GL_RUN_FRAGMENTS SET "
6029 mocchiut 1.2 << " RUNHEADER_TIME=" << glrun->GetRUNHEADER_TIME()<< " , ";
6030     //
6031     if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() )
6032     oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , ";
6033     if ( glrun->GetPHYSENDRUN_MASK_S11CRC() )
6034     oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , ";
6035     //
6036     oss << " RUNHEADER_OBT=" << glrun->GetRUNHEADER_OBT()<< " , "
6037 mocchiut 1.1 << " RUNHEADER_PKT=" << glrun->GetRUNHEADER_PKT()<< ";";
6038     conn->Query(oss.str().c_str());
6039     };
6040     };
6041     //
6042     // now let's look for runtrailer if any in the last run
6043     //
6044     oss.str("");
6045     oss << " ID= "<< myid[nid];
6046     //
6047     glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);
6048     //
6049     if ( glrun->GetPKT_READY_COUNTER() != 0 ){
6050     //
6051     // the first piece contains a good runtrailer we can update all the other runs with correct infos!
6052     //
6053     for (UInt_t u=0; u < nid ; u++){
6054     oss.str("");
6055     oss << "UPDATE GL_RUN_FRAGMENTS SET "
6056     << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "
6057     << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , "
6058     << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< " , "
6059 mocchiut 1.2 << " PKT_COUNTER=" << glrun->GetPKT_COUNTER()<< " , ";
6060     //
6061     if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ){
6062     oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
6063     if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ) {
6064     oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
6065     //
6066     oss << " PKT_READY_COUNTER=" << glrun->GetPKT_READY_COUNTER()
6067 mocchiut 1.1 << " WHERE ID=" << myid[u] << ";";
6068     conn->Query(oss.str().c_str());
6069     };
6070     //
6071     } else {
6072     //
6073     // sig no runtrailer, let set anyway what is possible...
6074     //
6075     for (UInt_t u=0; u < nid ; u++){
6076     oss.str("");
6077     oss << "UPDATE GL_RUN_FRAGMENTS SET "
6078     << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "
6079 mocchiut 1.2 << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , ";
6080     //
6081     if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ){
6082     oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
6083     if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ){
6084     oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
6085     //
6086     oss << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< ";";
6087 mocchiut 1.1 conn->Query(oss.str().c_str());
6088     };
6089     };
6090     //
6091     // Now we want to cross indexize the runs
6092     //
6093     for (UInt_t u=0; u < nid ; u++){
6094     oss.str("");
6095     oss << "UPDATE GL_RUN_FRAGMENTS SET "
6096     << " ID_RUN_FRAG=" << myid[u+1] << " where ID=" << myid[u] <<";";
6097     conn->Query(oss.str().c_str());
6098     };
6099     oss.str("");
6100     oss << "UPDATE GL_RUN_FRAGMENTS SET "
6101     << " ID_RUN_FRAG=" << myid[0] << " where ID=" << myid[nid] <<";";
6102     conn->Query(oss.str().c_str());
6103     //
6104     // and now we can move the runs in the GL_RUN table
6105     //
6106     for (UInt_t u=0; u <= nid; u++){
6107     oss.str("");
6108     oss << " ID= "<< myid[u];
6109     //
6110     glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);
6111     //
6112     if ( u == 0 ){
6113     oss.str("");
6114     oss << " SELECT ID,NEVENTS,TRK_CALIB_USED,PKT_COUNTER FROM GL_RUN WHERE "
6115     << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND ("
6116     << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
6117     << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
6118     << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
6119     << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
6120     << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
6121     << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
6122     << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
6123     << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
6124     << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
6125     << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
6126     << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
6127     << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
6128     //
6129     if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
6130     result2 = conn->Query(oss.str().c_str());
6131     //
6132     if ( !result2 ) throw -4;
6133     //
6134     row2 = result2->Next();
6135     //
6136     if ( row2 ){
6137     if ( IsDebug() ) printf(" The already exist in the GL_RUN table! \n");
6138     if ( PEDANTIC ) throw -83;
6139     row2->Close();
6140     };
6141     result2->Close();
6142     };
6143     //
6144     if ( IsDebug() ) printf(" The run is new \n");
6145     if ( IsDebug() ) printf(" -> fill the DB \n");
6146     //
6147     glrun->Fill_GL_RUN(conn);
6148     //
6149     if ( IsDebug() ) printf(" Delete run %u from the GL_RUN_FRAGMENTS table \n",myid[u]);
6150     //
6151     glrun->DeleteRun(conn,myid[u],"GL_RUN_FRAGMENTS");
6152     //
6153     moved++;
6154     //
6155     };
6156     //
6157     };
6158     //
6159     nrow = nresult->Next();
6160     };
6161     };
6162    
6163    
6164    
6165     };
6166     //
6167     if ( !strcmp(fcleanfile.Data(),"") ){
6168     //
6169     // check if there are entries older than "olderthan" seconds from now
6170     //
6171     oss.str("");
6172     oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"
6173     << " INSERT_TIME <= '" << clean_time->AsSQLString() << "';";
6174     //
6175     if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS runs older than %s : query is \n %s \n",clean_time->AsSQLString(),oss.str().c_str());
6176     result = conn->Query(oss.str().c_str());
6177     //
6178     } else {
6179     oss.str("");
6180     oss << " SELECT ID FROM GL_ROOT WHERE NAME='" << fcleanfile.Data() << "';";
6181     if ( IsDebug() ) printf(" Getting ID_ROOT_L0 query %s \n",oss.str().c_str());
6182     result = conn->Query(oss.str().c_str());
6183     //
6184     if ( result ){
6185     //
6186     row = result->Next();
6187     //
6188     if ( row ){
6189     oss.str("");
6190     oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"
6191     << " ID_ROOT_L0=" << row->GetField(0) << ";";
6192     //
6193     if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS for ROOT file query is \n %s \n",oss.str().c_str());
6194     result = conn->Query(oss.str().c_str());
6195     //
6196     };
6197     } else {
6198     return(2);
6199     };
6200     };
6201     //
6202     if ( result ){
6203     //
6204     row = result->Next();
6205     //
6206     while ( row ){
6207     //
6208     oss.str("");
6209     oss << " ID= "<< row->GetField(0);
6210     //
6211     glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);
6212     //
6213     oss.str("");
6214     oss << " SELECT ID,NEVENTS,TRK_CALIB_USED,PKT_COUNTER FROM GL_RUN WHERE "
6215     << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND ("
6216     << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
6217     << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
6218     << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
6219     << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
6220     << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
6221     << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
6222     << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
6223     << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
6224     << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
6225     << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
6226     << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
6227     << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
6228     //
6229     if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
6230     result2 = conn->Query(oss.str().c_str());
6231     //
6232     if ( !result2 ) throw -4;
6233     //
6234     row2 = result2->Next();
6235     //
6236     if ( !row2 ){
6237     //
6238     if ( IsDebug() ) printf(" The run is new \n");
6239     if ( IsDebug() ) printf(" -> fill the DB \n");
6240     //
6241     // glrun->SetID(this->AssignRunID()); we use the old run number!
6242     glrun->SetID_RUN_FRAG(glrun->GetID());
6243     glrun->Fill_GL_RUN(conn);
6244     //
6245 mocchiut 1.2 // oss.str("");
6246     // oss << " SELECT ID FROM GL_RUN WHERE "
6247     // << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "
6248     // << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "
6249     // << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "
6250     // << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "
6251     // << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";
6252     // //
6253     // if ( IsDebug() ) printf(" Look for the ID of the inserted run: query is \n %s \n",oss.str().c_str());
6254     // result2 = conn->Query(oss.str().c_str());
6255     // //
6256     // if ( !result2 ) throw -4;
6257     // //
6258     // row2 = result2->Next();
6259     // //
6260     // if ( !row2 ) throw -25;
6261     // //
6262     // oss.str("");
6263     // oss << " UPDATE GL_RUN SET ID_RUN_FRAG = " << row2->GetField(0) << " WHERE ID = " << row2->GetField(0);
6264     // if ( IsDebug() ) printf(" Update the ID_RUN_FRAG of the inserted run: query is \n %s \n",oss.str().c_str());
6265     // result2 = conn->Query(oss.str().c_str());
6266     // //
6267     // if ( !result2 ) throw -4;
6268 mocchiut 1.1 //
6269     moved++;
6270     //
6271     } else {
6272     if ( IsDebug() ) printf(" The already exist in the GL_RUN table! \n");
6273     if ( PEDANTIC ) throw -83;
6274     };
6275     if ( IsDebug() ) printf(" Delete run %s from the GL_RUN_FRAGMENTS table \n",row->GetField(0));
6276     //
6277     //
6278     glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
6279 mocchiut 1.2 // oss.str("");
6280     // oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);
6281     // if ( IsDebug() ) printf(" Clean the GL_RUN_FRAGMENTS table: query is \n %s \n",oss.str().c_str());
6282     // result2 = conn->Query(oss.str().c_str());
6283     // //
6284     // if ( !result2 ) throw -4;
6285     // //
6286 mocchiut 1.1 row = result->Next();
6287     };
6288     };
6289     if ( IsDebug() ) printf(" Moved %u runs\n",moved);
6290     return(0);
6291     };
6292    
6293     /**
6294     * Check if runs are good, i.e. if the tracker calibration is correctly associated..
6295     */
6296     Int_t PamelaDBOperations::ValidateRuns(){
6297     return(this->ValidateRuns(""));
6298     };
6299    
6300     /**
6301     * Check if runs are good, i.e. if the tracker calibration is correctly associated..
6302     */
6303     Int_t PamelaDBOperations::ValidateRuns(TString valfile){
6304     //
6305     TSQLResult *result = 0;
6306     TSQLRow *row = 0;
6307     //
6308     UInt_t calibtime = 50;
6309     //
6310     stringstream oss;
6311     oss.str("");
6312     //
6313     // =======================================================
6314     // validate runs by checking missing calibrations
6315     // =======================================================
6316     UInt_t t_stop = 0;
6317     UInt_t t_start = 0;
6318     if ( !strcmp(valfile.Data(),"") ) {
6319     // --------------------------------------------------------------
6320     // 1) get the OBT of the last run inserted after clean-time limit
6321     // --------------------------------------------------------------
6322     oss.str("");
6323     oss << " SELECT * FROM GL_RUN WHERE INSERT_TIME <= '" << clean_time->AsSQLString()
6324     << "' ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
6325     if ( IsDebug() ) printf(" Get start validation-time: query is \n %s \n",oss.str().c_str());
6326     result = conn->Query(oss.str().c_str());
6327     if ( !result ) throw -4;
6328     if ( !result->GetRowCount() ) {
6329     printf(" No runs to validate \n");
6330     return(1);
6331     }else{
6332     row = result->Next();
6333     t_start = (UInt_t)atoll(row->GetField(4));
6334     };
6335     // --------------------------------------------------------------
6336     // 2) get the OBT of the last validated run
6337     // --------------------------------------------------------------
6338     oss.str("");
6339     oss << " SELECT * FROM GL_RUN WHERE VALIDATION=1 AND RUNHEADER_TIME<="<< t_start
6340     <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
6341     if ( IsDebug() ) printf(" Get stop validation-time: query is \n %s \n",oss.str().c_str());
6342     result = conn->Query(oss.str().c_str());
6343     if ( !result ) throw -4;
6344     if ( result->GetRowCount() ){
6345     row = result->Next();
6346     t_stop = (UInt_t)atoll(row->GetField(4));
6347     };
6348     if ( IsDebug() ) printf("Validation interval: from time %u - to time %u \n\n",t_stop,t_start);
6349     // --------------------------------------------------------------
6350     // now retrieves runs to be validated
6351     // --------------------------------------------------------------
6352     oss.str("");
6353     oss << " SELECT * FROM GL_RUN WHERE RUNHEADER_TIME <=" << t_start;
6354     oss << " AND RUNHEADER_TIME >="<< t_stop;
6355     oss << " ORDER BY RUNHEADER_TIME DESC;";
6356     if ( IsDebug() )printf(" Check runs for validation: query is \n %s \n",oss.str().c_str());
6357     result = conn->Query(oss.str().c_str());
6358     } else {
6359     //
6360     stringstream myquery;
6361     UInt_t myid = 0;
6362     myquery.str("");
6363     myquery << " SELECT ID FROM GL_ROOT where NAME='"<<valfile.Data() <<"';";
6364     //
6365     result = conn->Query(myquery.str().c_str());
6366     //
6367     row = result->Next();
6368     if( !row ){
6369     if ( strcmp(valfile.Data(),GetRootName().Data()) ){
6370     if ( IsDebug() ) printf(" No file to be validated even if option \"-validate file\" was used!!\n");
6371     return(2);
6372     };
6373     if ( IsDebug() ) printf(" No file to be validated (force mode)! \n");
6374     return(0);
6375     };
6376     myid=(UInt_t)atoll(row->GetField(0));
6377     //
6378     myquery.str("");
6379     myquery << " SELECT MAX(RUNTRAILER_TIME),MIN(RUNHEADER_TIME) FROM GL_RUN WHERE ID_ROOT_L0="<< myid <<";";
6380     //
6381     result = conn->Query(myquery.str().c_str());
6382     //
6383     row = result->Next();
6384     if( !row->GetField(0) || !row->GetField(1)){
6385     //
6386     if ( IsDebug() ) printf(" NO RUN ASSOCIATED TO THIS FILE! \n");
6387     //
6388     return(0);
6389     //
6390     } else {
6391     //
6392     UInt_t runhtime = (UInt_t)atoll(row->GetField(0));
6393     UInt_t runttime = (UInt_t)atoll(row->GetField(1));
6394     UInt_t caltime = 0;
6395     //
6396     myquery.str("");
6397     myquery << " SELECT FROM_TIME FROM GL_TRK_CALIB where FROM_TIME>" <<runhtime;
6398     myquery << " order by FROM_TIME asc limit 1;";
6399     //
6400     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
6401     //
6402     //
6403     result = conn->Query(myquery.str().c_str());
6404     //
6405     row = result->Next();
6406     if( !row ){
6407     caltime = runhtime;
6408     } else {
6409     caltime = (UInt_t)atoll(row->GetField(0));
6410     };
6411     //
6412     myquery.str("");
6413     myquery << " SELECT * from GL_RUN where RUNHEADER_TIME>="<< runttime <<" AND RUNHEADER_TIME<=" ;
6414     myquery << caltime << " order by RUNHEADER_TIME DESC";
6415     //
6416     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
6417     //
6418     result = conn->Query(myquery.str().c_str());
6419     //
6420     };
6421     };
6422     //
6423     if ( !result ) throw -4;
6424     if ( !result->GetRowCount() && IsDebug() ) printf(" No runs to validate \n");
6425     //
6426     Int_t nrow = 0;
6427     GL_RUN* this_run = new GL_RUN();
6428     GL_RUN* next_run = new GL_RUN();
6429     Int_t nseq_max = 1000;
6430 mocchiut 1.2 // UInt_t* sequence = new UInt_t[100];
6431 mocchiut 1.1 vector<UInt_t> sequence(nseq_max);
6432     Int_t nseq = 0;
6433     Bool_t CHECK = false;
6434     Bool_t this_ONLINE = false;
6435     Bool_t next_ONLINE = false;
6436     UInt_t t1=0,t2=0;
6437     // ---------------------------------------------------------------------------------
6438     // - loop over runs, back in time,
6439     // - select sequences of runs close in time (less than calibtime s apart),
6440     // which could be preceeded by a calibration
6441     // - check if there might be a missing calibration
6442     // ---------------------------------------------------------------------------------
6443     while(1){
6444    
6445 mocchiut 1.2 row = result->Next();
6446     if( row == NULL ) break;
6447 mocchiut 1.1
6448 mocchiut 1.2 //------------
6449     //get run info
6450     //------------
6451     this_run->Set_GL_RUN(row);
6452 mocchiut 1.1
6453 mocchiut 1.2 Bool_t this_BAD = false;
6454     if(this_run->GetTRK_CALIB_USED() == 1 || this_run->GetTRK_CALIB_USED() == 2) this_ONLINE = true;
6455     else if (this_run->GetTRK_CALIB_USED() == 104) this_ONLINE = false;
6456     else{
6457     // printf("Missing or corrupted header!! \n");
6458     this_ONLINE = false;
6459     this_BAD = true;
6460     };
6461 mocchiut 1.1
6462 mocchiut 1.2 //-----------------------------------
6463     //compare with previous(next in time)
6464     //-----------------------------------
6465     CHECK = false;
6466     UInt_t interval=0;
6467 mocchiut 1.1
6468 mocchiut 1.2 if( nrow != 0){
6469 mocchiut 1.1
6470    
6471 mocchiut 1.2 t1 = this_run->GetRUNTRAILER_TIME();
6472     t2 = next_run->GetRUNHEADER_TIME();
6473     interval = (t2-t1);
6474 mocchiut 1.1
6475 mocchiut 1.2 if(this_ONLINE && next_ONLINE){ // this: ON-LINE + next: ON-LINE
6476 mocchiut 1.1
6477 mocchiut 1.2 if( this_run->ID == next_run->ID_RUN_FRAG ) interval = 0; //=> run fragments
6478 mocchiut 1.1
6479 mocchiut 1.2 if( interval >= calibtime )CHECK = true; //more than calibtime s => there might be a calibration
6480 mocchiut 1.1
6481 mocchiut 1.2 if( !CHECK && this_run->VALIDATION ){
6482     for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);
6483     nseq=0;
6484     }
6485 mocchiut 1.1
6486 mocchiut 1.2 }else if( !this_ONLINE && next_ONLINE) { // this: DEFAULT + next:ON-LINE
6487 mocchiut 1.1
6488 mocchiut 1.2 CHECK = true;
6489 mocchiut 1.1
6490 mocchiut 1.2 }else if( !next_ONLINE ){ // this:ANY + next:DEFAULT
6491 mocchiut 1.1
6492 mocchiut 1.2 assignVALIDATION(next_run->ID,true);
6493     nseq=0;
6494     }
6495     }
6496 mocchiut 1.1
6497 mocchiut 1.2 //----------------------------
6498     //check run sequence for calib
6499     //----------------------------
6500     if( CHECK ){
6501     // check if calibration exists
6502     if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval);
6503     Bool_t MISSING = MissingTRK_CALIB(t1,t2);
6504     for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],!MISSING);
6505     nseq=0;
6506     };
6507     //--------------
6508     //store run info
6509     //--------------
6510     *next_run = *this_run;
6511     next_ONLINE = this_ONLINE;
6512     if( !this_BAD ){
6513     if(nseq < nseq_max){
6514     sequence[nseq] = this_run->ID;
6515     nseq++;
6516     }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);
6517     };
6518 mocchiut 1.1
6519 mocchiut 1.2 if ( IsDebug() ) printf("%i Run %u \n",nrow,this_run->ID);
6520     nrow++;
6521 mocchiut 1.1
6522     };
6523     delete this_run;
6524     delete next_run;
6525     //
6526     return(0);
6527     };
6528     /**
6529     * Check if there might be a missing tracker calibration in a given time interval
6530     * @param t1 From absolute time
6531     * @param t2 To absolute time
6532     * @return true if there might be a missing calibration
6533     */
6534     Bool_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
6535    
6536 mocchiut 1.2 GL_TRK_CALIB* trkcalib = new GL_TRK_CALIB();
6537 mocchiut 1.1
6538 pam-fi 1.4 // get the closest calibration before the run start (t2)
6539 mocchiut 1.2 if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(true); //>>> missing
6540 mocchiut 1.1
6541 mocchiut 1.2 if ( trkcalib->TO_TIME < t2 ) return(true); //>>> missing
6542 mocchiut 1.1
6543 mocchiut 1.2 //==============================================================
6544     // Check is done first on the basis of time between calibration,
6545     // which should be equal to the time between ascending-nodes.
6546     //==============================================================
6547     if ( t2 - trkcalib->FROM_TIME > 5700) {
6548     if ( IsDebug() )printf("Long time between calib and run start %u :-( ==> there might be a missing calib \n",t2 - trkcalib->FROM_TIME);
6549     //==============================================================
6550     // there might be a missing calibration, due to:
6551     // - MM full
6552     // - corrupted packets
6553     // - loss of data
6554     // There is an exception in case a download was done during ascending node
6555     //==============================================================
6556     Bool_t DOWNLOAD = false;
6557     // check if the calib was skipped becouse of download .... DA FARE!!
6558     if(DOWNLOAD)return(false);
6559 mocchiut 1.1
6560 mocchiut 1.2 return(true); //>>> missing
6561 mocchiut 1.1
6562 mocchiut 1.2 };
6563 mocchiut 1.1
6564 mocchiut 1.2 //==============================================================
6565     // If the last calibration is close to the run less than this time,
6566     // it is enough to say that there are no missing calibrations
6567     //==============================================================
6568     // the long time interval bewteen runs might be due to download
6569     if ( IsDebug() )printf("Short time between calib and run start %u :-) ==> OK! \n",t2 - trkcalib->FROM_TIME);
6570     return(false);
6571 mocchiut 1.1
6572     };
6573     /**
6574     * Assign VALIDATION value to a GL_RUN entry
6575     * @param idrun Run ID
6576     * @param validation true/false
6577     */
6578     Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, Bool_t validation){
6579 mocchiut 1.2 TSQLResult *result = 0;
6580     stringstream oss;
6581     oss.str("");
6582     oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";
6583     //
6584     // if ( IsDebug() )
6585     // printf(" Set VALIDATION = %i for run %i \n",validation,idrun);
6586     if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());
6587     result = conn->Query(oss.str().c_str());
6588     if ( !result ) throw -4;
6589     return(0);
6590 mocchiut 1.1 }
6591    
6592    
6593    
6594     // Insert TLEs from file tlefilename in the table GL_TLE in the db
6595     // opened by conn, sorting them by date from older to newer, if each
6596     // TLE has not been alread inserted.
6597     Int_t PamelaDBOperations::populateTLE()//(TSQLServer *conn, char *tleFile)
6598     {
6599     fstream tlefile(tlefilename, ios::in);
6600    
6601     if ( !tlefile ) throw -7;
6602    
6603     vector<cTle*> ctles;
6604     vector<cTle*>::iterator iter;
6605     int present = 0;
6606    
6607     // Get three lines from tlefile, create a cTle object and put it
6608     // into ctles
6609     while(1) {
6610     cTle *tlef;
6611     string str1, str2, str3;
6612    
6613     getline(tlefile, str1);
6614     if(tlefile.eof()) break;
6615    
6616     getline(tlefile, str2);
6617     if(tlefile.eof()) break;
6618    
6619     getline(tlefile, str3);
6620     if(tlefile.eof()) break;
6621    
6622     // We now have three good lines for a cTle.
6623     tlef = new cTle(str1, str2, str3);
6624     ctles.push_back(tlef);
6625     }
6626    
6627     tlefile.close();
6628    
6629     // Sort by date
6630     sort(ctles.begin(), ctles.end(), compTLE);
6631    
6632     // Now we insert each TLE into the db
6633     for(iter = ctles.begin(); iter != ctles.end(); iter++) {
6634     cTle *tle = *iter;
6635    
6636     // Do nothing if it's already present in the db. Just increase
6637     // the counter present.
6638     if (! isTlePresent(tle))
6639     {
6640     int status = insertTle(tle);
6641    
6642     // Insert query failed. Return 1.
6643     if(status == EXIT_FAILURE) {
6644    
6645     if( IsDebug() ) {
6646     cerr << "Error: inserting TLE:" << endl
6647     << tle->getName() << endl
6648     << tle->getLine1() << endl
6649     << tle->getLine2() << endl;
6650     }
6651    
6652     throw -4;
6653     return 1;
6654     }
6655    
6656     }
6657     else
6658     present++;
6659    
6660     }
6661    
6662     int inserted = ctles.size() - present; // Number of inserted TLE.
6663     if ( IsDebug() )
6664     cout << "\nProcessed TLEs ranging from " << getTleDatetime(ctles[0]) << " to " << getTleDatetime(ctles[ctles.size()-1]) << "." << endl
6665     << inserted << " newly inserted TLEs out of " << ctles.size() << " processed." << endl;
6666    
6667     ctles.clear();
6668    
6669    
6670     // Return 2 if no new TLE has been inserted. 0 otherwise.
6671     if(! inserted ) return 2;
6672     return 0;
6673     }
6674    
6675    
6676     // Insert tle in the table GL_TLE using the connection conn.
6677     Int_t PamelaDBOperations::insertTle(cTle *tle)
6678     {
6679     stringstream oss;
6680     TSQLResult *result = 0;
6681    
6682     oss.str("");
6683     oss << " INSERT INTO GL_TLE (TLE1, TLE2, TLE3, FROM_TIME)"
6684     << " VALUES ( '"
6685     << tle->getName() << "', '"
6686     << tle->getLine1() << "', '"
6687     << tle->getLine2() << "', '"
6688     << getTleDatetime(tle) << "')";
6689    
6690     // cout << oss.str().c_str() << endl;
6691     result = conn->Query(oss.str().c_str());
6692     if (result == NULL)
6693     return EXIT_FAILURE;
6694    
6695     return EXIT_SUCCESS;
6696     }
6697    
6698    
6699     // Return whether tle is already in the db connected by conn.
6700     bool PamelaDBOperations::isTlePresent(cTle *tle)
6701     {
6702     stringstream oss;
6703     TSQLResult *result = 0;
6704    
6705     oss.str("");
6706     oss << "SELECT * FROM GL_TLE WHERE FROM_TIME = '"
6707     << getTleDatetime(tle) << "'";
6708    
6709     result = conn->Query(oss.str().c_str());
6710     if (result == NULL) throw -4;
6711    
6712     if (result->GetRowCount())
6713     return true;
6714     else
6715     return false;
6716     }
6717    
6718    
6719     // Return whether the first TLE is dated early than the second
6720     bool compTLE (cTle *tle1, cTle *tle2)
6721     {
6722     return getTleJulian(tle1) < getTleJulian(tle2);
6723     }
6724    
6725    
6726     // Return the date of the tle using the format (year-2000)*1e3 +
6727     // julian day. e.g. 6365 is the 31th Dec 2006.
6728     // It does *not* return a cJulian date.
6729     float getTleJulian(cTle *tle) {
6730     return tle->getField(cTle::FLD_EPOCHYEAR)*1e3 + tle->getField(cTle::FLD_EPOCHDAY);
6731     }
6732    
6733    
6734     // Return a string like YYYY-MM-DD hh:mm:ss, usable for mysql datetime
6735     // format.
6736     string getTleDatetime(cTle *tle)
6737     {
6738     int year, mon, day, hh, mm, ss;
6739     double dom; // day of month (is double!)
6740     stringstream date; // date in datetime format
6741    
6742     // create a cJulian from the date in tle
6743     cJulian jdate = cJulian( 2000 + (int) tle->getField(cTle::FLD_EPOCHYEAR), tle->getField(cTle::FLD_EPOCHDAY));
6744    
6745     // get year, month, day of month
6746     jdate.getComponent(&year, &mon, &dom);
6747    
6748     // build a datetime YYYY-MM-DD hh:mm:ss
6749     date.str("");
6750     day = (int) floor(dom);
6751     hh = (int) floor( (dom - day) * 24);
6752     mm = (int) floor( ((dom - day) * 24 - hh) * 60);
6753     ss = (int) floor( ((((dom - day) * 24 - hh) * 60 - mm) * 60));
6754     // ms = (int) floor( (((((dom - day) * 24 - hh) * 60 - mm) * 60) - ss) * 1000);
6755    
6756     date << year << "-" << mon << "-" << day << " " << hh << ":" << mm << ":" << ss;
6757    
6758     return date.str();
6759     }
6760    
6761     /**
6762     * Remove a file from the DB, delete on cascade all entries related to that file
6763     * rearrange GL_RUN and GL_XXX_CALIB tables, turn off validation till the following
6764     * calibration
6765     **/
6766     Int_t PamelaDBOperations::removeFile(TString remfile){
6767     //
6768     // Determine ID_ROOT_L0 and ID_RAW
6769     //
6770     TSQLResult *pResult;
6771     TSQLRow *Row;
6772     stringstream myquery;
6773     //
6774     myquery.str("");
6775     myquery << " SELECT ID, ID_RAW FROM GL_ROOT where NAME='"<<remfile.Data() <<"';";
6776     //
6777     pResult = conn->Query(myquery.str().c_str());
6778     //
6779     Row = pResult->Next();
6780     if( !Row ){
6781     if ( strcmp(remfile.Data(),GetRootName().Data()) ){
6782     if ( IsDebug() ) printf(" No file to be removed even if option \"-remove file\" was used!!\n");
6783     return(1);
6784     };
6785     if ( IsDebug() ) printf(" No file to be removed (force mode)! \n");
6786     return(0);
6787     };
6788     //
6789     this->SetID_ROOT((UInt_t)atoll(Row->GetField(0)));
6790     this->SetID_RAW((UInt_t)atoll(Row->GetField(1)));
6791     //
6792     this->ValidationOFF();
6793     //
6794     this->RemoveCALIBS();
6795     //
6796     this->RemoveRUNS();
6797     //
6798     this->RemoveFILES();
6799     //
6800     this->SetID_ROOT(0);
6801     this->SetID_RAW(0);
6802     //
6803     return(0);
6804     };
6805    
6806     /**
6807     *
6808     * Set validation bit to zero for runs following the removing file till
6809     * 1) a run with TRK_CALIB_USED=140
6810     * 2) a run with VALIDATION = 0
6811     * 3) the next calibration
6812     *
6813     **/
6814     void PamelaDBOperations::ValidationOFF(){
6815     TSQLResult *pResult;
6816     TSQLRow *Row;
6817     stringstream myquery;
6818     Int_t unv = 0;
6819     //select ID from GL_RUN where RUNHEADER_TIME>=1152671382 AND (VALIDATION=0 OR TRK_CALIB_USED=104) order by RUNHEADER_TIME asc limit 1;
6820     myquery.str("");
6821     myquery << " SELECT MAX(RUNTRAILER_TIME) FROM GL_RUN WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
6822     //
6823     pResult = conn->Query(myquery.str().c_str());
6824     //
6825     Row = pResult->Next();
6826     if( !Row->GetField(0) ){
6827     //
6828     if ( IsDebug() ) printf(" NO RUN ASSOCIATED TO THIS FILE! \n");
6829     //
6830     } else {
6831     //
6832     UInt_t runhtime = (UInt_t)atoll(Row->GetField(0));
6833     UInt_t caltime = 0;
6834     //
6835     myquery.str("");
6836     myquery << " SELECT FROM_TIME FROM GL_TRK_CALIB where FROM_TIME>" <<runhtime;
6837     myquery << " order by FROM_TIME asc limit 1;";
6838     //
6839     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
6840     //
6841     //
6842     delete pResult;
6843     pResult = conn->Query(myquery.str().c_str());
6844     //
6845     Row = pResult->Next();
6846     if( !Row ){
6847     caltime = runhtime;
6848     } else {
6849     caltime = (UInt_t)atoll(Row->GetField(0));
6850     };
6851     //
6852     myquery.str("");
6853     myquery << " SELECT ID,RUNHEADER_TIME from GL_RUN where RUNHEADER_TIME>="<< runhtime <<" AND (VALIDATION=0 OR TRK_CALIB_USED=104 OR RUNHEADER_TIME>" ;
6854     myquery << caltime << ") order by RUNHEADER_TIME asc LIMIT 1";
6855     //
6856     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
6857     //
6858     pResult = conn->Query(myquery.str().c_str());
6859     //
6860     Row = pResult->Next();
6861     if( !Row ){
6862     //
6863     if ( IsDebug() ) printf(" NO RUN NEED TO BE UNVALIDATED \n");
6864     //
6865     } else {
6866     myquery.str("");
6867     myquery << " SELECT ID from GL_RUN where RUNHEADER_TIME<"<< Row->GetField(1) <<" AND ";
6868     myquery << " RUNHEADER_TIME>=" <<runhtime;
6869     myquery << " order by RUNHEADER_TIME asc;";
6870     //
6871     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
6872     //
6873     pResult = conn->Query(myquery.str().c_str());
6874     //
6875     Row = pResult->Next();
6876     while ( Row ){
6877     //
6878     unv++;
6879     this->assignVALIDATION((UInt_t)atoll(Row->GetField(0)), false);
6880     Row = pResult->Next();
6881     //
6882     };
6883     };
6884     };
6885     if ( IsDebug() ) printf(" %u runs have been unvalidated \n",unv);
6886     };
6887    
6888     /**
6889     *
6890     * Rearrange GL_RUN table and remove runs
6891     *
6892     **/
6893     void PamelaDBOperations::RemoveRUNS(){
6894     TSQLResult *pResult;
6895     TSQLRow *Row;
6896     stringstream myquery;
6897     UInt_t drun = 0;
6898     GL_RUN *delrun = new GL_RUN();
6899     //
6900     myquery.str("");
6901     myquery << " SELECT ID FROM GL_RUN where ID_RUN_FRAG=0 and ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
6902     //
6903     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
6904     //
6905     pResult = conn->Query(myquery.str().c_str());
6906     //
6907     Row = pResult->Next();
6908     //
6909     //
6910     if ( !Row ){
6911     if ( IsDebug() ) printf(" No run with ID_RUN_FRAG=0 belonged to this file \n");
6912     } else {
6913     if ( IsDebug() ) printf(" Deleting run from GL_RUN table \n");
6914     while ( Row ){
6915     delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(0)),"GL_RUN");
6916     if ( IsDebug() ) printf(" del run %u \n",(UInt_t)atoll(Row->GetField(0)));
6917     drun++;
6918     Row = pResult->Next();
6919     };
6920     };
6921     //
6922     //
6923     myquery.str("");
6924     myquery << " SELECT ID,ID_RUN_FRAG FROM GL_RUN where ID_RUN_FRAG!=0 and ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
6925     //
6926     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
6927     //
6928     pResult = conn->Query(myquery.str().c_str());
6929     //
6930     Row = pResult->Next();
6931     //
6932     if ( !Row ){
6933     if ( IsDebug() ) printf(" No run with ID_RUN_FRAG!=0 belonged to this file \n");
6934     } else {
6935     if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN table \n");
6936     while ( Row ){
6937     if ( IsDebug() ) printf(" restore run %u \n",(UInt_t)atoll(Row->GetField(1)));
6938     delrun->RestoreRun(conn,(UInt_t)atoll(Row->GetField(1)),"GL_RUN_FRAGMENTS");
6939     if ( IsDebug() ) printf(" del run %u \n",(UInt_t)atoll(Row->GetField(1)));
6940     delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(1)),"GL_RUN");
6941     if ( (UInt_t)atoll(Row->GetField(1)) != (UInt_t)atoll(Row->GetField(0)) ){
6942     if ( IsDebug() ) printf(" del run %u \n",(UInt_t)atoll(Row->GetField(0)));
6943     delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(0)),"GL_RUN");
6944     };
6945     drun++;
6946     Row = pResult->Next();
6947     };
6948     };
6949     //
6950     if ( IsDebug() ) printf(" Deleted %i run(s) from GL_RUN table \n",drun);
6951     //
6952     //
6953     //
6954     drun = 0;
6955     //
6956     myquery.str("");
6957     myquery << " SELECT ID_TRASH FROM GL_RUN_TRASH where BELONGED_TO='GL_RUN_FRAGMENTS' AND ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
6958     //
6959     pResult = conn->Query(myquery.str().c_str());
6960     //
6961     Row = pResult->Next();
6962     //
6963     if ( !Row ){
6964     if ( IsDebug() ) printf(" No run from GL_RUN_FRAGMENTS table in the trash table for this file \n");
6965     } else {
6966     if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN_TRASH table \n");
6967     while ( Row ){
6968     if ( IsDebug() ) printf(" del run idtrash %u \n",(UInt_t)atoll(Row->GetField(0)));
6969     myquery.str("");
6970     myquery << " DELETE FROM GL_RUN_TRASH where ID_TRASH=" << Row->GetField(0) <<";";
6971     conn->Query(myquery.str().c_str());
6972     drun++;
6973     Row = pResult->Next();
6974     };
6975     };
6976     //
6977     if ( IsDebug() ) printf(" Deleted %u run(s) from GL_RUN_TRASH table \n",drun);
6978     //
6979     //
6980     //
6981     drun = 0;
6982     //
6983     myquery.str("");
6984     myquery << " SELECT ID FROM GL_RUN_FRAGMENTS where ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
6985     //
6986     pResult = conn->Query(myquery.str().c_str());
6987     //
6988     Row = pResult->Next();
6989     //
6990     if ( !Row ){
6991     if ( IsDebug() ) printf(" No run in the GL_RUN_FRAGMENTS table for this file \n");
6992     } else {
6993     if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN_FRAGMENTS table \n");
6994     while ( Row ){
6995     if ( IsDebug() ) printf(" del run %u \n",(UInt_t)atoll(Row->GetField(0)));
6996     myquery.str("");
6997     myquery << " DELETE FROM GL_RUN_FRAGMENTS where ID=" << Row->GetField(0) <<";";
6998     conn->Query(myquery.str().c_str());
6999     drun++;
7000     Row = pResult->Next();
7001     };
7002     };
7003     //
7004     if ( IsDebug() ) printf(" Deleted %u run(s) from GL_RUN_FRAGMENTS table \n",drun);
7005     //
7006     //
7007     //
7008     delete delrun;
7009     //
7010     };
7011    
7012    
7013     /**
7014     *
7015     * Rearrange calibration tables
7016     *
7017     **/
7018     void PamelaDBOperations::RemoveFILES(){
7019     stringstream myquery;
7020     //
7021     myquery.str("");
7022     myquery << " DELETE FROM GL_RAW WHERE ID=" <<this->GetID_RAW() <<";";
7023     //
7024     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
7025     //
7026     conn->Query(myquery.str().c_str());
7027     //
7028     };
7029    
7030     /**
7031     *
7032     * Rearrange calibration tables
7033     *
7034     **/
7035     void PamelaDBOperations::RemoveCALIBS(){
7036     TSQLResult *pResult;
7037     TSQLRow *Row;
7038     stringstream myquery;
7039     //
7040     //
7041     // Calorimeter
7042     //
7043     for (Int_t section = 0; section < 4; section++){
7044     myquery.str("");
7045     myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_CALO_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<" AND ";
7046     myquery << " SECTION=" << section << ";";
7047     //
7048     pResult = conn->Query(myquery.str().c_str());
7049     //
7050     Row = pResult->Next();
7051     if( !Row->GetField(0) || !Row->GetField(1) ){
7052     //
7053     if ( IsDebug() ) printf(" NO CALO CALIBRATION SECTION %i ASSOCIATED TO THIS FILE! \n",section);
7054     //
7055     } else {
7056     //
7057     myquery.str("");
7058     myquery << " UPDATE GL_CALO_CALIB SET TO_TIME=" << Row->GetField(1);
7059     myquery << " WHERE TO_TIME="<< Row->GetField(0) << " AND ";
7060     myquery << " SECTION=" << section << ";";
7061     //
7062     pResult = conn->Query(myquery.str().c_str());
7063     //
7064     if( !pResult ){
7065     //
7066     if ( IsDebug() ) printf(" ERROR DELETING CALO CALIBRATIONS \n");
7067     //
7068     throw -4;
7069     //
7070     };
7071     //
7072     };
7073     };
7074     Bool_t OLDDB = false;
7075     for (Int_t section = 0; section < 4; section++){
7076     myquery.str("");
7077     myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_CALOPULSE_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<" AND ";
7078     myquery << " SECTION=" << section << ";";
7079     //
7080     pResult = conn->Query(myquery.str().c_str());
7081     //
7082     if ( conn->GetErrorCode() ){
7083     printf(" Section %i : warning, old databse structure no GL_CALOPULSE_CALIB table!\n",section);
7084     OLDDB=true;
7085     } else {
7086     Row = pResult->Next();
7087     if( !Row->GetField(0) || !Row->GetField(1) ){
7088     //
7089     if ( IsDebug() ) printf(" NO PULSE CALO CALIBRATION SECTION %i ASSOCIATED TO THIS FILE! \n",section);
7090     //
7091     } else {
7092     //
7093     myquery.str("");
7094     myquery << " UPDATE GL_CALOPULSE_CALIB SET TO_TIME=" << Row->GetField(1);
7095     myquery << " WHERE TO_TIME="<< Row->GetField(0) << " AND ";
7096     myquery << " SECTION=" << section << ";";
7097     //
7098     pResult = conn->Query(myquery.str().c_str());
7099     //
7100     if( !pResult ){
7101     //
7102     if ( IsDebug() ) printf(" ERROR DELETING CALO PULSE CALIBRATIONS \n");
7103     //
7104     throw -4;
7105     //
7106     };
7107     //
7108     };
7109     };
7110     };
7111     myquery.str("");
7112     myquery << " DELETE FROM GL_CALO_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT() << ";";
7113     //
7114     pResult = conn->Query(myquery.str().c_str());
7115     //
7116     if( !pResult ){
7117     //
7118     if ( IsDebug() ) printf(" ERROR DELETING CALO CALIBRATIONS \n");
7119     //
7120     throw -4;
7121     //
7122     };
7123     //
7124     myquery.str("");
7125     myquery << " DELETE FROM GL_CALOPULSE_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT() << ";";
7126     //
7127     pResult = conn->Query(myquery.str().c_str());
7128     if ( IsDebug() ) printf(" Delete from GL_CALOPULSE_CALIB query is %s \n",myquery.str().c_str());
7129     if ( !OLDDB ){
7130     //
7131     if( !pResult ){
7132     //
7133     if ( IsDebug() ) printf(" ERROR DELETING PULSE CALO CALIBRATIONS \n");
7134     //
7135     throw -4;
7136     //
7137     };
7138     };
7139     //
7140     // Tracker
7141     //
7142     myquery.str("");
7143     myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_TRK_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
7144     //
7145     pResult = conn->Query(myquery.str().c_str());
7146     //
7147     Row = pResult->Next();
7148     if( !Row->GetField(0) || !Row->GetField(1) ){
7149     //
7150     if ( IsDebug() ) printf(" NO TRK CALIBRATION ASSOCIATED TO THIS FILE! \n");
7151     //
7152     } else {
7153     //
7154     myquery.str("");
7155     myquery << " UPDATE GL_TRK_CALIB SET TO_TIME=" << Row->GetField(1);
7156     myquery << " WHERE TO_TIME="<< Row->GetField(0) << ";";
7157     //
7158     pResult = conn->Query(myquery.str().c_str());
7159     //
7160     if( !pResult ){
7161     //
7162     if ( IsDebug() ) printf(" ERROR DELETING TRK CALIBRATIONS \n");
7163     //
7164     throw -4;
7165     //
7166     };
7167     //
7168     myquery.str("");
7169     myquery << " DELETE FROM GL_TRK_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT() << ";";
7170     //
7171     pResult = conn->Query(myquery.str().c_str());
7172     //
7173     if( !pResult ){
7174     //
7175     if ( IsDebug() ) printf(" ERROR DELETING TRK CALIBRATIONS \n");
7176     //
7177     throw -4;
7178     //
7179     };
7180     };
7181     //
7182     //
7183     // S4
7184     //
7185     myquery.str("");
7186     myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_S4_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
7187     //
7188     pResult = conn->Query(myquery.str().c_str());
7189     //
7190     Row = pResult->Next();
7191     if( !Row->GetField(0) || !Row->GetField(1) ){
7192     //
7193     if ( IsDebug() ) printf(" NO S4 CALIBRATION ASSOCIATED TO THIS FILE! \n");
7194     //
7195     } else {
7196     //
7197     myquery.str("");
7198     myquery << " UPDATE GL_S4_CALIB SET TO_TIME=" << Row->GetField(1);
7199     myquery << " WHERE TO_TIME="<< Row->GetField(0) << ";";
7200     //
7201     pResult = conn->Query(myquery.str().c_str());
7202     //
7203     if( !pResult ){
7204     //
7205     if ( IsDebug() ) printf(" ERROR DELETING S4 CALIBRATIONS \n");
7206     //
7207     throw -4;
7208     //
7209     };
7210     //
7211     myquery.str("");
7212     myquery << " DELETE FROM GL_S4_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT() << ";";
7213     //
7214     pResult = conn->Query(myquery.str().c_str());
7215     //
7216     if( !pResult ){
7217     //
7218     if ( IsDebug() ) printf(" ERROR DELETING S4 CALIBRATIONS \n");
7219     //
7220     throw -4;
7221     //
7222     };
7223     //
7224     };
7225     };
7226    
7227     /**
7228     *
7229     * Rearrange calibration tables
7230     *
7231     **/
7232 pam-fi 1.4 UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh , TFile *file){
7233    
7234     if(!caltrk) return 0;
7235    
7236     if ( IsDebug() ) cout << "ValidateTrkCalib:"<<endl;
7237    
7238     UInt_t validate = 1;
7239     Int_t vorder[]={5,5,3,3,4,4,2,2,1,1,0,0};
7240     UInt_t timeaftercalib=120000; //2000;
7241     TString classname = caltrk->GetName();
7242    
7243     // ----------------------------------
7244     // Check CRCs and failed calibrations
7245     // ----------------------------------
7246     for(Int_t ipkt=0; ipkt<6; ipkt++){
7247     if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
7248     if( caltrk->crc_hcal[ipkt] ){
7249     // if(IsDebug())cout<<"(CRC Header)";
7250     validate = 0;
7251     if(IsDebug())cout <<endl<<" *** CRC *** (header DSPn "<<caltrk->DSPnumber[ipkt]<<")";
7252    
7253     }
7254     for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] ){
7255     // if(IsDebug())cout<<"(CRC Pkt-"<<ilad<<")";
7256     if(IsDebug())cout <<endl<<" *** CRC *** (data DSPn "<<caltrk->DSPnumber[ipkt]<<" ladder "<<ilad<<")";
7257     validate = 0;
7258     }
7259     if( !(caltrk->ncalib_event[ipkt]==0 && caltrk->cal_flag[ipkt]==0) ){
7260     if(IsDebug())cout <<endl<<" *** FAILURE *** (data DSPn "<<caltrk->DSPnumber[ipkt]<<")";
7261     validate = 0;
7262     }
7263     }else{
7264     // validate=0;
7265     if(IsDebug())cout <<endl<<" *** DSPn *** ("<< caltrk->DSPnumber[ipkt] <<" @pkt "<<ipkt<<")";
7266     }
7267     }
7268    
7269     // -----------------------
7270     // Check missing packets:
7271     // -----------------------
7272     // Readout order:
7273     // ------------------
7274     // DSP packet board
7275     // ------------------
7276     // 12 0 1
7277     // 10 1 1
7278     // 8 2 1
7279     // 4 3 1
7280     // 6 4 1
7281     // 2 5 1
7282     // ------------------
7283     // 11 0 2
7284     // 9 1 2
7285     // 7 2 2
7286     // 3 3 2
7287     // 5 4 2
7288     // 1 5 2
7289     // ------------------
7290     // -------------------------------------------------
7291     // Check if it is first or second calibration packet
7292     // -------------------------------------------------
7293     UInt_t build=0;
7294     UInt_t base=0;
7295     UInt_t mask=0;
7296     if(classname.Contains("CalibTrk1Event")){
7297     base=12;
7298     mask=0x03F000;
7299     }
7300     if(classname.Contains("CalibTrk2Event")){
7301     base=18;
7302     mask=0xFC0000;
7303     }
7304     // ----------------------------------------------------
7305     // Count number of valid packets and set build variable
7306     // ----------------------------------------------------
7307     if(IsDebug())cout <<endl<< " DSP: ";
7308     Int_t npkts=0;
7309     for(Int_t ipkt=0; ipkt<6; ipkt++){
7310     if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
7311     if(IsDebug())cout <<" "<<caltrk->DSPnumber[ipkt];
7312     npkts++;
7313     build = build | ( 1<<(base+vorder[caltrk->DSPnumber[ipkt]-1]) );
7314     // cout << caltrk->DSPnumber[ipkt]
7315     };
7316     }
7317     if(IsDebug())cout << " ==> "<< hex << build << dec;
7318     // ----------------------------------------------------
7319     // If the number of valid packets is 6, ok exit...
7320     // ----------------------------------------------------
7321     if( npkts==6 ){
7322     return validate; // exit
7323     }
7324     ////////////////////////////////////////////////////////
7325     // ...otherwise there might be some missing packets
7326     //
7327     // In this case check the acq configuration
7328     // (some DSPs might be excluded from acquisition)
7329     ////////////////////////////////////////////////////////
7330    
7331     if(!eh || !file || (file&&file->IsZombie()) ){
7332     if ( IsDebug() )cout << " *** MISSING VIEW *** eh="<<eh<<" file="<<file<<" cannot validate"<<endl;
7333     return (0);
7334     }
7335    
7336     // -----------------------------------------------
7337     // retrieve the first run header after calib
7338     // -----------------------------------------------
7339    
7340     PacketType *pctp;
7341     EventCounter *cod;
7342     cod = eh->GetCounter();
7343     Int_t irun = cod->Get(pctp->RunHeader);
7344     TTree *rh=(TTree*)file->Get("RunHeader");
7345     if ( !rh || rh->IsZombie() ) throw -17;
7346     if( rh->GetEntries() <= irun ){
7347     if ( IsDebug() ) cout << " *** MISSING-PKT *** no runs after calib (1) -- cannot validate :-( "<<endl;
7348     return 0; // :-(
7349     }
7350     RunHeaderEvent *run = 0;
7351     EventHeader *hrun = 0;
7352     rh->SetBranchAddress("RunHeader", &run);
7353     rh->SetBranchAddress("Header", &hrun);
7354     rh->GetEntry(irun);
7355     if( OBT(hrun->GetPscuHeader()->GetOrbitalTime()) < OBT(eh->GetPscuHeader()->GetOrbitalTime())){
7356     if ( IsDebug() ) cout << " *** MISSING-PKT *** no runs after calib (2) -- cannot validate :-( "<<endl;
7357     return 0; // :-(
7358     }
7359    
7360     UInt_t dtime = OBT(hrun->GetPscuHeader()->GetOrbitalTime()) - OBT(eh->GetPscuHeader()->GetOrbitalTime());
7361     if( dtime > timeaftercalib ){
7362     if ( IsDebug() ) cout << " *** MISSING-PKT *** run after calib too far ( "<<dtime<<"ms ) -- cannot validate :-( "<<endl;
7363     return 0; // :-(
7364     }
7365    
7366     if ( IsDebug() ) cout <<endl<< " ACQ_BUILD_INFO ==> "<<hex<<(run->ACQ_BUILD_INFO & mask)<<dec;
7367    
7368     if( (run->ACQ_BUILD_INFO & mask) != build ){
7369     validate=0; // :-(
7370     cout <<endl<< " *** MISSING-PKT *** packet mismatch: ACQ_BUILD_INFO="<<hex<<(run->ACQ_BUILD_INFO&mask)<<" != "<<build<<dec;
7371     };
7372    
7373     return validate;
7374 mocchiut 1.1
7375 mocchiut 1.2
7376 pam-fi 1.4 }
7377     // UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh ){
7378 mocchiut 1.1
7379 pam-fi 1.4 // if(!caltrk || !eh) return 0;
7380 mocchiut 1.1
7381 pam-fi 1.4 // Int_t vorder[]={5,5,3,3,4,4,2,2,1,1,0,0};
7382     // UInt_t timeaftercalib=120000; //2000;
7383     // // ----------
7384     // // Check CRCs
7385     // // ----------
7386     // for(Int_t ipkt=0; ipkt<6; ipkt++){
7387     // if( caltrk->crc_hcal[ipkt] )return 0; // :-(
7388     // for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] )return 0; // :-(
7389     // }
7390     // // -----------------------
7391     // // Check missing packets:
7392     // // -----------------------
7393     // // Readout order:
7394     // // ------------------
7395     // // DSP packet board
7396     // // ------------------
7397     // // 12 0 1
7398     // // 10 1 1
7399     // // 8 2 1
7400     // // 4 3 1
7401     // // 6 4 1
7402     // // 2 5 1
7403     // // ------------------
7404     // // 11 0 2
7405     // // 9 1 2
7406     // // 7 2 2
7407     // // 3 3 2
7408     // // 5 4 2
7409     // // 1 5 2
7410     // // ------------------
7411     // // -------------------------------------------------
7412     // // Check if it is first or second calibration packet
7413     // // -------------------------------------------------
7414     // UInt_t build=0;
7415     // TString classname = caltrk->GetName();
7416     // UInt_t base=0;
7417     // UInt_t mask=0;
7418     // if(classname.Contains("CalibTrk1Event")){
7419     // base=12;
7420     // mask=0x03F000;
7421     // }
7422     // if(classname.Contains("CalibTrk2Event")){
7423     // base=18;
7424     // mask=0xFC0000;
7425     // }
7426     // // -------------------------------------------------
7427     // // Count number of packets and set build variable
7428     // // -------------------------------------------------
7429     // Int_t npkts=0;
7430     // for(Int_t ipkt=0; ipkt<6; ipkt++){
7431     // if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
7432     // npkts++;
7433     // build = build | ( 1<<(base+vorder[caltrk->DSPnumber[ipkt]-1]) );
7434     // }
7435     // }
7436     // // if( npkts==6 )return 1; // :-)
7437    
7438     // // cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime()<<endl;
7439    
7440     // // -----------------------------------------------
7441     // // If missing packets: check the acq configuration
7442     // // (some DSPs might be excluded from acquisition)
7443     // // -----------------------------------------------
7444    
7445     // // -----------------------------------------------
7446     // // retrieve the first run header after calib
7447     // // -----------------------------------------------
7448     // PacketType *pctp;
7449     // EventCounter *cod;
7450     // cod = eh->GetCounter();
7451     // Int_t irun = cod->Get(pctp->RunHeader);
7452     // TTree *rh=(TTree*)file->Get("RunHeader");
7453     // if ( !rh || rh->IsZombie() ) throw -17;
7454     // if( rh->GetEntries() == irun ){
7455     // if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (1) -- cannot validate :-( "<<endl;
7456     // return 0; // :-(
7457     // }
7458    
7459     // RunHeaderEvent *run = 0;
7460     // EventHeader *hrun = 0;
7461     // rh->SetBranchAddress("RunHeader", &run);
7462     // rh->SetBranchAddress("Header", &hrun);
7463     // rh->GetEntry(irun);
7464     // // cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime() << " Run " << hrun->GetPscuHeader()->GetOrbitalTime() <<endl;
7465    
7466     // if( OBT(hrun->GetPscuHeader()->GetOrbitalTime()) < OBT(eh->GetPscuHeader()->GetOrbitalTime())){
7467     // if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (2) -- cannot validate :-( "<<endl;
7468     // return 0; // :-(
7469     // }
7470 mocchiut 1.1
7471 pam-fi 1.4 // if( !run->RM_ACQ_AFTER_CALIB ){
7472     // if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) RM_ACQ_AFTER_CALIB=0 -- cannot validate :-( "<<endl;
7473     // return 0; // :-(
7474     // }
7475    
7476     // UInt_t dtime = OBT(hrun->GetPscuHeader()->GetOrbitalTime()) - OBT(eh->GetPscuHeader()->GetOrbitalTime());
7477     // if( dtime > timeaftercalib ){
7478     // if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) run after calib too far ( "<<dtime<<"ms ) -- cannot validate :-( "<<endl;
7479     // return 0; // :-(
7480     // }
7481 mocchiut 1.1
7482    
7483    
7484 pam-fi 1.4 // if( (run->ACQ_BUILD_INFO & mask) != build ){
7485     // if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) ACQ_BUILD_INFO= >>> "<<hex << (run->ACQ_BUILD_INFO&mask) << " != "<< build << dec<<endl;
7486     // return 0; // :-(
7487     // }
7488     // return 1; // :-)
7489 mocchiut 1.1
7490 pam-fi 1.4 // }
7491 mocchiut 1.1
7492     /**
7493     *
7494     * Check the DB (only for overlapping runs at the moment)
7495     *
7496     **/
7497     UInt_t PamelaDBOperations::Check(){
7498 mocchiut 1.2 return(this->Check(0,0));
7499 mocchiut 1.1 }
7500    
7501     UInt_t PamelaDBOperations::Check(UInt_t from, UInt_t to){
7502     //
7503 mocchiut 1.2 if ( IsDebug() ) printf(" from %u to %u \n",from,to);
7504 mocchiut 1.1 //
7505     UInt_t test = 0;
7506     //
7507     UInt_t thisrht = 0;
7508     UInt_t thisrtt = 0;
7509     UInt_t thisid = 0;
7510     UInt_t prevrht = 0;
7511     UInt_t prevrtt = 0;
7512     UInt_t previd = 0;
7513     //
7514     UInt_t prevl0id = 0;
7515     UInt_t thisl0id = 0;
7516     //
7517     stringstream oss;
7518     TSQLResult *result = 0;
7519     TSQLRow *row = 0;
7520     TSQLResult *result2 = 0;
7521     TSQLRow *row2 = 0;
7522     TSQLResult *result3 = 0;
7523     TSQLRow *row3 = 0;
7524     oss.str("");
7525     oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME,NEVENTS FROM GL_RUN order by RUNHEADER_TIME asc;";
7526     // oss << "SELECT ID,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN where ID>10170 and ID<10190 order by RUNHEADER_TIME asc;";
7527     result = conn->Query(oss.str().c_str());
7528     //
7529     if ( !result ) throw -4;;
7530     //
7531     row = result->Next();
7532     UInt_t nid = 0;
7533     //
7534     while ( row ){
7535     nid++;
7536     if ( !(nid%1000) && nid ) printf(" %iK run scanned \n",nid/1000);
7537     thisid = (UInt_t)atoll(row->GetField(0));
7538     thisl0id = (UInt_t)atoll(row->GetField(1));
7539     thisrht = (UInt_t)atoll(row->GetField(2));
7540     thisrtt = (UInt_t)atoll(row->GetField(3));
7541     //
7542     if ( from > 0 && nid <= from ) goto ss;
7543     if ( to > 0 && nid >= to ) goto ss;
7544 mocchiut 1.2 //
7545 mocchiut 1.1 if ( (UInt_t)atoll(row->GetField(4)) > 1 ){
7546     //
7547     //
7548     //
7549     oss.str("");
7550     oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN WHERE ID!="
7551     << thisid << " AND ( RUNHEADER_TIME="
7552     << thisrht << " OR RUNTRAILER_TIME="
7553     << thisrtt << " ) AND NEVENTS!=0 AND NEVENTS!=1 order by RUNHEADER_TIME asc;";
7554     result3 = conn->Query(oss.str().c_str());
7555     if ( IsDebug() ) printf(" query is %s \n",oss.str().c_str());
7556     if ( result3 ){
7557     //
7558     oss.str("");
7559     oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN WHERE ID!="
7560     << thisid << " AND RUNHEADER_TIME="
7561     << thisrht << " AND RUNTRAILER_TIME!="
7562     << thisrtt << " AND NEVENTS!=0 AND NEVENTS!=1 order by RUNHEADER_TIME asc;";
7563     result3 = conn->Query(oss.str().c_str());
7564     if ( IsDebug() ) printf(" query is %s \n",oss.str().c_str());
7565     if ( result3 ){
7566     row3 = result3->Next();
7567     //
7568     while ( row3 ){
7569     //
7570     // 2 runs with same runheader
7571     //
7572     printf(" CHECK n.4 RUNs %u and %u HAVE SAME RUNHEADER \n",thisid,(UInt_t)atoll(row3->GetField(0)));
7573     row3 = result3->Next();
7574     };
7575 mocchiut 1.2 // delete result3;
7576 mocchiut 1.1
7577     };
7578     //
7579     oss.str("");
7580     oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN WHERE ID!="
7581     << thisid << " AND RUNHEADER_TIME!="
7582     << thisrht << " AND RUNTRAILER_TIME="
7583     << thisrtt << " AND NEVENTS!=0 AND NEVENTS!=1 order by RUNHEADER_TIME asc;";
7584     result3 = conn->Query(oss.str().c_str());
7585     if ( IsDebug() ) printf(" query is %s \n",oss.str().c_str());
7586     if ( result3 ){
7587     row3 = result3->Next();
7588     //
7589     while ( row3 ){
7590     //
7591     // 2 runs with same runtrailer
7592     //
7593     printf(" CHECK n.5 RUNs %u and %u HAVE SAME RUNTRAILER \n",thisid,(UInt_t)atoll(row3->GetField(0)));
7594     row3 = result3->Next();
7595     };
7596 mocchiut 1.2 // delete result3;
7597 mocchiut 1.1 };
7598     //
7599     oss.str("");
7600     oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN WHERE ID!="
7601     << thisid << " AND RUNHEADER_TIME="
7602     << thisrht << " AND RUNTRAILER_TIME="
7603     << thisrtt << " AND ID_RUN_FRAG!="
7604     << thisid << " order by RUNHEADER_TIME asc;";
7605     result3 = conn->Query(oss.str().c_str());
7606     if ( result3 ){
7607     row3 = result3->Next();
7608     //
7609     while ( row3 ){
7610     //
7611     // duplicated run
7612     //
7613     printf(" CHECK n.7 RUNs %u and %u HAVE SAME RUNTRAILER AND RUNHEADER (ARE THE SAME?) \n",thisid,(UInt_t)atoll(row3->GetField(0)));
7614     row3 = result3->Next();
7615     };
7616 mocchiut 1.2 // delete result3;
7617 mocchiut 1.1
7618     };
7619     };
7620     //
7621     oss.str("");
7622     oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN WHERE ID!="
7623     << thisid << " AND RUNHEADER_TIME>"
7624     << thisrht << " AND RUNTRAILER_TIME<"
7625     << thisrtt << " order by RUNHEADER_TIME asc;";
7626     result3 = conn->Query(oss.str().c_str());
7627     if ( result3 ){
7628     row3 = result3->Next();
7629     //
7630     while ( row3 ){
7631     //
7632     // run contained in the checked one
7633     //
7634     printf(" CHECK n.6 RUN %u CONTAINS RUN %u \n",thisid,(UInt_t)atoll(row3->GetField(0)));
7635     row3 = result3->Next();
7636     };
7637 mocchiut 1.2 // delete result3;
7638 mocchiut 1.1 };
7639     //
7640     };
7641     //
7642     // if ( thisrht < prevrtt || thisrtt < prevrht || thisrht > thisrtt && !(!prevrht && !prevrtt &&!previd) ){
7643     // if ( (thisrht < prevrtt || thisrtt < prevrht || thisrht > thisrtt) && (thisrht != prevrht) ){
7644     if ( (thisrht < prevrtt) && (thisrht != prevrht) ){
7645     if ( IsDebug() ) printf(" IDprev %u ID %u prevrht %u prevrtt %u thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
7646     printf(" CHECK n.1 TIME SCREW of %i s AROUND RUNs %u and %u \n",(thisrht-prevrtt),previd,thisid);
7647     TString prevf = "";
7648     TString thisf = "";
7649     oss.str("");
7650     oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
7651     result2 = conn->Query(oss.str().c_str());
7652     if ( !result2 ) throw -4;;
7653     row2 = result2->Next();
7654     prevf = (TString)row2->GetField(0);
7655     oss.str("");
7656     oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
7657     result2 = conn->Query(oss.str().c_str());
7658     if ( !result2 ) throw -4;;
7659     row2 = result2->Next();
7660     thisf = (TString)row2->GetField(0);
7661     if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
7662     test = 1;
7663 mocchiut 1.2 // delete result2;
7664 mocchiut 1.1 };
7665     //
7666     if ( (thisrtt < prevrht) && (thisrht != prevrht) ){
7667     if ( IsDebug() ) printf(" IDprev %u ID %u prevrht %u prevrtt %u thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
7668     printf(" CHECK n.2 TIME SCREW of %i s AROUND RUNs %u and %u \n",(thisrtt-prevrht),previd,thisid);
7669     TString prevf = "";
7670     TString thisf = "";
7671     oss.str("");
7672     oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
7673     result2 = conn->Query(oss.str().c_str());
7674     if ( !result2 ) throw -4;
7675     row2 = result2->Next();
7676     prevf = (TString)row2->GetField(0);
7677     oss.str("");
7678     oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
7679     result2 = conn->Query(oss.str().c_str());
7680     if ( !result2 ) throw -4;;
7681     row2 = result2->Next();
7682     thisf = (TString)row2->GetField(0);
7683     if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
7684     test = 1;
7685 mocchiut 1.2 // delete result2;
7686 mocchiut 1.1 };
7687     //
7688     if ( (thisrht > thisrtt) && (thisrht != prevrht) ){
7689     if ( IsDebug() ) printf(" IDprev %u ID %u prevrht %u prevrtt %u thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
7690     printf(" CHECK n.3 TIME SCREW of %i s AROUND RUNs %u and %u \n",(thisrht-thisrtt),previd,thisid);
7691     TString prevf = "";
7692     TString thisf = "";
7693     oss.str("");
7694     oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
7695     result2 = conn->Query(oss.str().c_str());
7696     if ( !result2 ) throw -4;;
7697     row2 = result2->Next();
7698     prevf = (TString)row2->GetField(0);
7699     oss.str("");
7700     oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
7701     result2 = conn->Query(oss.str().c_str());
7702     if ( !result2 ) throw -4;;
7703     row2 = result2->Next();
7704     thisf = (TString)row2->GetField(0);
7705     if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
7706     test = 1;
7707 mocchiut 1.2 // delete result2;
7708 mocchiut 1.1 };
7709 mocchiut 1.2 ss:
7710 mocchiut 1.1 //
7711     prevrht = thisrht;
7712     prevrtt = thisrtt;
7713     previd = thisid;
7714     prevl0id = thisl0id;
7715     row = result->Next();
7716 mocchiut 1.2 // if ( result2 ) delete result2;
7717     // if ( result3 ) delete result3;
7718 mocchiut 1.1 };
7719     //
7720     return(test);
7721     //
7722     };

  ViewVC Help
Powered by ViewVC 1.1.23