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

Annotation of /YodaProfiler/src/PamelaDBOperations.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.19 - (hide annotations) (download)
Thu Nov 9 16:47:47 2006 UTC (18 years ago) by mocchiut
Branch: MAIN
CVS Tags: v2r04, v2r03
Changes since 1.18: +13 -11 lines
Time screw bug in install_DB.sh fixed + get rid completely of TDatime

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 mocchiut 1.3 #include <TFile.h>
12     #include <TSystem.h>
13 mocchiut 1.1 #include <TSQLResult.h>
14     #include <TSQLRow.h>
15     #include <TTree.h>
16     #include <TGraph.h>
17 mocchiut 1.17 #include <TTimeStamp.h>
18 mocchiut 1.1 #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 <CalibS4Event.h>
28     #include <CalibTrk1Event.h>
29     #include <CalibTrk2Event.h>
30     #include <varDump/VarDumpEvent.h>
31     #include <varDump/VarDumpRecord.h>
32     #include <physics/S4/S4Event.h>
33     //
34 mocchiut 1.14 #include <sgp4.h>
35 mocchiut 1.12
36 mocchiut 1.1 #include <PamelaDBOperations.h>
37     //
38     using namespace std;
39     using namespace pamela;
40    
41 mocchiut 1.12 // Some function to work with cTle stuff.
42     bool compTLE(cTle* tle1, cTle *tle2);
43     float getTleJulian(cTle *);
44     string getTleDatetime(cTle*);
45    
46 mocchiut 1.1 /**
47     * Constructor.
48     * @param host hostname for the SQL connection.
49     * @param user username for the SQL connection.
50     * @param password password for the SQL connection.
51     * @param filerawname The path and name to the raw file.
52     * @param filerootname The path and name of the raw file.
53     * @param boot file BOOT number.
54     * @param obt0 file obt0.
55     * @param tsync file timesync.
56     * @param debug debug flag.
57 mocchiut 1.12 * @param tlefilename ascii file with TLE 3 line elements.
58 mocchiut 1.1 */
59 mocchiut 1.12 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){
60 mocchiut 1.1 //
61     //
62     SetConnection(host,user,password);
63     //
64     SetDebugFlag(debug);
65     //
66     glrun = new GL_RUN();
67     //
68     if ( !boot ) SetNOBOOT(false);
69     SetBOOTnumber(boot);
70     SetTsync(tsync);
71     SetObt0(obt0);
72     //
73 mocchiut 1.12 SetTLEPath(tlefilename);
74     //
75 mocchiut 1.1 //
76 pam-fi 1.8 INSERT_RAW =!filerawname.IsNull();
77     if(INSERT_RAW)SetRawName(filerawname);
78 mocchiut 1.1 //
79 pam-fi 1.8 INSERT_ROOT = !filerootname.IsNull();
80 mocchiut 1.9 if( INSERT_ROOT ){
81 mocchiut 1.10 this->SetRootName(filerootname);
82 mocchiut 1.13 this->SetOrbitNo();
83 mocchiut 1.9 file = TFile::Open(this->GetRootName().Data());
84 mocchiut 1.16 } else {
85     this->SetRootName("");
86 pam-fi 1.8 };
87 mocchiut 1.1 //
88     this->SetID_RAW(0);
89     this->SetID_ROOT(0);
90 pam-fi 1.8
91     VALIDATE = false;
92    
93 mocchiut 1.9 //
94 mocchiut 1.1 };
95    
96     /**
97     * Destructor
98     */
99     void PamelaDBOperations::Close(){
100     if( conn && conn->IsConnected() ) conn->Close();
101 pam-fi 1.8 delete clean_time;
102 mocchiut 1.1 delete glrun;
103     delete this;
104     };
105    
106     //
107     // SETTERS
108     //
109    
110 mocchiut 1.9 //
111     // 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
112     //
113     void PamelaDBOperations::CheckValidate(Long64_t olderthan){
114     clean_time = new TDatime();
115 mocchiut 1.17 //
116 mocchiut 1.9 if(olderthan >= 0){
117     VALIDATE = true;
118     UInt_t timelim = 0;
119 mocchiut 1.17 timelim = (UInt_t)clean_time->Convert(true) - olderthan;
120 mocchiut 1.9 clean_time->Set(timelim,false);
121     };
122     };
123    
124 mocchiut 1.1 /**
125     * Open the DB connection
126     * @param host hostname for the SQL connection.
127     * @param user username for the SQL connection.
128     * @param password password for the SQL connection.
129     */
130     void PamelaDBOperations::SetConnection(TString host, TString user, TString password){
131 mocchiut 1.13 if ( IsDebug() ) printf(" Connecting using host = %s user = %s password = %s \n",host.Data(),user.Data(),password.Data());
132 mocchiut 1.1 conn = TSQLServer::Connect(host.Data(),user.Data(),password.Data());
133     };
134    
135     /**
136     * Store the ID of the ROOT file.
137     * @param idr ID of the ROOT file
138     */
139     void PamelaDBOperations::SetID_ROOT(UInt_t idr){
140     idroot=idr;
141     };
142    
143     /**
144     * Store the ID of the RAW file.
145     * @param idr ID of the RAW file
146     */
147     void PamelaDBOperations::SetID_RAW(UInt_t idr){
148     id=idr;
149     };
150    
151     /**
152     * Set the debug flag
153     *
154     */
155     void PamelaDBOperations::SetDebugFlag(Bool_t dbg){
156     debug = dbg;
157     };
158    
159     /**
160 mocchiut 1.16 * Set the nofrag flag
161     *
162     */
163     void PamelaDBOperations::SetNoFrag(Bool_t nf){
164     NOFRAG = nf;
165     };
166    
167     /**
168 mocchiut 1.1 * Store the BOOT number of the RAW file.
169     * @param boot BOOT number of the RAW file
170     */
171     void PamelaDBOperations::SetBOOTnumber(UInt_t boot){
172     BOOTNO=boot;
173     };
174    
175     /**
176     * Store the time sync of the RAW file.
177     * @param boot time sync
178     */
179     void PamelaDBOperations::SetTsync(UInt_t ts){
180     tsync=ts;
181     };
182    
183     /**
184     * Store the time sync of the RAW file.
185     * @param boot time sync
186     */
187     void PamelaDBOperations::SetObt0(UInt_t ts){
188     obt0=ts;
189     };
190    
191     /**
192     * Store the RAW filename.
193     * @param str the RAW filename.
194     */
195     void PamelaDBOperations::SetRawName(TString str){
196     filerawname=str;
197     };
198    
199     /**
200     * Store the ROOT filename.
201     * @param str the ROOT filename.
202     */
203     void PamelaDBOperations::SetRootName(TString str){
204     filerootname=str;
205     };
206    
207     /**
208 mocchiut 1.13 * Store the downlink orbit number from filename.
209     */
210     void PamelaDBOperations::SetOrbitNo(){
211     dworbit = 0;
212     TString name = this->GetRootFile();
213     Int_t nlength = name.Length();
214     if ( nlength < 5 ) return;
215     TString dwo = 0;
216     for (Int_t i = 0; i<5; i++){
217     dwo.Append(name[i],1);
218     };
219     if ( dwo.IsDigit() ){
220     dworbit = (UInt_t)dwo.Atoi();
221     } else {
222     dwo="";
223     for (Int_t i = 8; i<13; i++){
224     dwo.Append(name[i],1);
225     };
226     if ( dwo.IsDigit() ) dworbit = (UInt_t)dwo.Atoi();
227     };
228     if ( IsDebug() ) printf(" Downlink orbit is %i (dwo = %s) \n",dworbit,dwo.Data());
229     return;
230     };
231    
232    
233    
234     /**
235 mocchiut 1.1 * Store the NOBOOT flag.
236     * @param noboot true/false.
237     */
238     void PamelaDBOperations::SetNOBOOT(Bool_t noboot){
239     NOBOOT = noboot;
240     };
241    
242     /**
243 mocchiut 1.12 * Store path to the TLE file.
244     */
245     void PamelaDBOperations::SetTLEPath(TString str){
246     tlefilename = str;
247     };
248    
249     /**
250 mocchiut 1.2 * Store the olderthan variable
251     * @param olderthan
252     */
253 pam-fi 1.8 // void PamelaDBOperations::SetOlderThan(Long64_t oldthan){
254     // olderthan = oldthan;
255     // };
256 mocchiut 1.2
257     /**
258 mocchiut 1.1 * Retrieve the ID_RAW, if exists, returns NULL if does not exist.
259     */
260     Bool_t PamelaDBOperations::SetID_RAW(){
261     stringstream oss;
262     TSQLResult *result = 0;
263     TSQLRow *row = 0;
264     oss.str("");
265     oss << "SELECT ID FROM GL_RAW WHERE "
266     << " PATH = '" << this->GetRawPath().Data() << "' AND "
267     << " NAME = '" << this->GetRawFile().Data() << "' ";
268     result = conn->Query(oss.str().c_str());
269 mocchiut 1.2 if ( result == NULL ) throw -4;
270 mocchiut 1.1 row = result->Next();
271 mocchiut 1.2 if ( !row ) return(false);
272 mocchiut 1.1 delete result;
273     id = (UInt_t)atoll(row->GetField(0));
274     return(true);
275     }
276    
277     /**
278     *
279     * Set the variables which have to be stored in the GL_RUN table and that do not depend on the RUN
280     *
281     */
282     void PamelaDBOperations::SetCommonGLRUN(UInt_t absth, UInt_t abstt){
283     glrun->SetBOOTNUMBER(BOOTNO);
284     glrun->SetRUNHEADER_TIME(absth);
285     glrun->SetRUNTRAILER_TIME(abstt);
286     glrun->SetID_ROOT_L2(0);
287     glrun->SetID_ROOT_L0(idroot);
288     glrun->SetVALIDATION(0);
289     };
290    
291     /**
292     * Patch, look for upper limits to avoid processing retransmitted data
293     */
294     Int_t PamelaDBOperations::SetUpperLimits(){
295     UInt_t nevent = 0;
296     UInt_t pktlast = 0;
297     UInt_t obtlast = 0;
298     UInt_t t_pktlast = 0;
299     UInt_t t_obtlast = 0;
300     UInt_t upperpkt2 = 0;
301     ULong64_t upperobt2 = 0;
302     UInt_t zomp = 0;
303     UInt_t jump = 50000; // was 5000
304 mocchiut 1.4 EventCounter *code=0;
305     //
306 mocchiut 1.13 UInt_t deltapkt = 5000;
307     ULong64_t deltaobt = 50000;
308     //
309 mocchiut 1.4 // pcksList packetsNames;
310     // pcksList::iterator Iter;
311     // getPacketsNames(packetsNames);
312 mocchiut 1.1 //
313     pktfirst = 0;
314     obtfirst = 0;
315     //
316     TTree *T = 0;
317     T = (TTree*)file->Get("Physics");
318     if ( !T || T->IsZombie() ) throw -16;
319     EventHeader *eh = 0;
320     PscuHeader *ph = 0;
321     T->SetBranchAddress("Header", &eh);
322     nevent = T->GetEntries();
323     //
324     T->GetEntry(0);
325     ph = eh->GetPscuHeader();
326     pktfirst = ph->GetCounter();
327     obtfirst = ph->GetOrbitalTime();
328     //
329 mocchiut 1.4 // code = eh->GetCounter();
330     // UInt_t en = 0;
331     // for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
332     // en = code->Get(GetPacketType(*Iter));
333     // if ( en ) printf(" Packet type is %s, entries: %i \n",*Iter,en);
334     //};
335     //
336 mocchiut 1.1 T->GetEntry(nevent-1);
337     ph = eh->GetPscuHeader();
338     pktlast = ph->GetCounter();
339     obtlast = ph->GetOrbitalTime();
340     //
341     upperpkt = PKT(pktlast);
342     upperobt = OBT(obtlast);
343     upperentry = nevent-1;
344     //
345     if ( IsDebug() ) printf(" First entries are: OBT %llu pkt_num %i \n",obtfirst,pktfirst);
346     //
347     if ( IsDebug() ) printf(" Last entries are: OBT %llu pkt_num %i entry %i\n",upperobt,upperpkt,upperentry);
348     //
349     if ( (PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) > OBT(obtfirst)) || (PKT(pktlast) > PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) ) return(1);
350     //
351     if ( !nevent ) return(2);
352     //
353     if ( nevent < 2 ) return(4);
354     //
355 mocchiut 1.13 if ( (PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) || (labs(PKT(pktlast)-PKT(pktfirst))<deltapkt && labs(OBT(obtlast)-OBT(obtfirst))<deltaobt) ){
356     //
357 mocchiut 1.1 // go back
358     zomp = nevent - 2;
359     //
360     while ( jump > 0 ){
361     //
362     t_pktlast = PKT(pktlast);
363     t_obtlast = OBT(obtlast);
364     //
365     for (UInt_t i = zomp; i>1; i-=jump){
366     //
367     if ( i >= 0 ) T->GetEntry(i);
368     ph = eh->GetPscuHeader();
369     upperpkt = PKT(ph->GetCounter());
370     upperobt = OBT(ph->GetOrbitalTime());
371     upperentry = i;
372     //
373     if ( (i-1) >= 0 ) T->GetEntry(i-1);
374     ph = eh->GetPscuHeader();
375     upperpkt2 = PKT(ph->GetCounter());
376     upperobt2 = OBT(ph->GetOrbitalTime());
377     //
378     if ( (t_pktlast < upperpkt && t_obtlast > upperobt) || (t_pktlast < upperpkt2 && t_obtlast > upperobt2) ) throw -13;
379     //
380     if ( t_pktlast < upperpkt && t_obtlast < upperobt && t_pktlast < upperpkt2 && t_obtlast < upperobt2 ){
381     zomp = i + jump + 1;
382     if ( zomp > nevent-2 ) zomp = nevent - 2;
383     if ( IsDebug() ) printf(" .-. jump %i zomp %i upperpkt %i pktlast %i upperobt %llu obtlast %u last entry is %i \n",jump,zomp,upperpkt,pktlast,upperobt,obtlast,i);
384     break;
385     };
386     //
387     t_pktlast = upperpkt;
388     t_obtlast = upperobt;
389     };
390     //
391     if ( jump == 1 ) jump = 0;
392     if ( jump == 10 ) jump = 1;
393     if ( jump == 100 ) jump = 10;
394     if ( jump == 1000 ) jump = 100;
395     if ( jump == 5000 ) jump = 1000;
396     if ( jump == 50000 ) jump = 5000;
397     //
398     };
399     //
400     };
401     //
402     // check if last runtrailer is within limits, if not extend limits (one should check for all packets but we need only runtrailer)
403     //
404     PacketType *pctp=0;
405     TTree *rh=(TTree*)file->Get("RunHeader");
406     if ( !rh || rh->IsZombie() ) throw -17;
407     TTree *rt=(TTree*)file->Get("RunTrailer");
408     if ( !rt || rt->IsZombie() ) throw -18;
409     //
410     rh->SetBranchAddress("RunHeader", &runh);
411     rh->SetBranchAddress("Header", &ehh);
412     //
413     rt->SetBranchAddress("RunTrailer", &runt);
414     rt->SetBranchAddress("Header", &eht);
415     //
416     rhev = rh->GetEntries();
417     rtev = rt->GetEntries();
418 mocchiut 1.4 UInt_t sobtt = 0;
419     UInt_t sobth = 0;
420     UInt_t spktt = 0;
421     UInt_t spkth = 0;
422 mocchiut 1.1 UInt_t pktt = 0;
423     ULong64_t obtt = 0;
424     UInt_t pkth = 0;
425     ULong64_t obth = 0;
426     //
427 mocchiut 1.6 T->GetEntry(upperentry);
428     code = eh->GetCounter();
429     Int_t lasttrail = code->Get(pctp->RunTrailer);
430     Int_t lasthead = code->Get(pctp->RunHeader);
431 mocchiut 1.1 if ( lasttrail < rtev ){
432     rt->GetEntry(lasttrail);
433     pht = eht->GetPscuHeader();
434     pktt = PKT(pht->GetCounter());
435     obtt = OBT(pht->GetOrbitalTime());
436     };
437     //
438     if ( lasthead < rhev ){
439     rh->GetEntry(lasthead);
440     phh = ehh->GetPscuHeader();
441 mocchiut 1.6 pkth = PKT(phh->GetCounter());
442     obth = OBT(phh->GetOrbitalTime());
443 mocchiut 1.1 };
444     //
445     if ( IsDebug() ) printf(" rhev before %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);
446     if ( pkth > upperpkt && obth > upperobt ){
447     if ( IsDebug() ) printf(" Upper limits extended to include last header: ph %i upperp %i oh %llu uppero %llu \n",pkth,upperpkt,obth,upperobt);
448     upperpkt = pkth;
449     upperobt = obth;
450     rhev = lasthead+1;
451     } else {
452     rhev = lasthead;
453     };
454     if ( IsDebug() ) printf(" rhev after %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);
455     //
456 mocchiut 1.4 if ( IsDebug() ) printf(" rtev beforev %i pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);
457     if ( pktt > upperpkt && obtt > upperobt ){
458     if ( IsDebug() ) printf(" Upper limits extended to include last trailer: pt %i upperp %i ot %llu uppero %llu \n",pktt,upperpkt,obtt,upperobt);
459     upperpkt = pktt;
460     upperobt = obtt;
461     rtev = lasttrail+1;
462     } else {
463     rtev = lasttrail;
464     };
465     if ( IsDebug() ) printf(" rtev after %i pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);
466     // goto kikko;
467     //
468     //
469     // Check if runtrailer/runheader are within lower limits
470     //
471     //
472     pkth = 0;
473     obth = 0;
474     spkth = 0;
475     sobth = 0;
476     for (Int_t k=0; k<rhev; k++){
477     if ( k > 0 ){
478     spkth = pkth;
479     sobth = obth;
480     };
481     rh->GetEntry(k);
482     phh = ehh->GetPscuHeader();
483     pkth = PKT(phh->GetCounter());
484     obth = OBT(phh->GetOrbitalTime());
485     //
486 mocchiut 1.7 // if ( IsDebug() ) printf(" k %i rhev before %i ph %u upperp %u oh %u uppero %u \n",k,rhev,pkth,spkth,obth,sobth);
487 mocchiut 1.6 //
488 mocchiut 1.4 if ( pkth < spkth && obth < sobth ){
489     if ( IsDebug() ) printf(" RH PROBLEMS determining the event repetition at the end of the file lasthead %i \n",rhev);
490     //
491 mocchiut 1.6 rhev = k-1;
492 mocchiut 1.4 rh->GetEntry(rhev);
493     pkth = spkth;
494     obth = sobth;
495     //
496     UInt_t evbefh = 0;
497     code = ehh->GetCounter();
498     evbefh = code->Get(pctp->Physics);
499     if ( evbefh >= 0 ){
500     T->GetEntry(evbefh);
501     ph = eh->GetPscuHeader();
502     t_pktlast = PKT(ph->GetCounter());
503     t_obtlast = OBT(ph->GetOrbitalTime());
504 mocchiut 1.7 if ( t_pktlast <= spkth && t_obtlast <= sobth ){ // jump
505 mocchiut 1.4 upperpkt = pkth;
506     upperobt = obth;
507     upperentry = evbefh-1;
508     } else {
509     while ( t_pktlast > spkth && t_obtlast > sobth && evbefh < nevent ){
510     evbefh++;
511     T->GetEntry(evbefh);
512     ph = eh->GetPscuHeader();
513     t_pktlast = PKT(ph->GetCounter());
514     t_obtlast = OBT(ph->GetOrbitalTime());
515     };
516     T->GetEntry(evbefh-1);
517     ph = eh->GetPscuHeader();
518     upperpkt = PKT(ph->GetCounter());
519     upperobt = OBT(ph->GetOrbitalTime());
520     upperentry = evbefh-1;
521     };
522     };
523     if ( IsDebug() ) printf(" rhev after %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);
524 mocchiut 1.6 goto kikko0;
525 mocchiut 1.4 };
526     };
527 mocchiut 1.6 kikko0:
528 mocchiut 1.4 //
529     //
530     //
531     pktt = 0;
532     obtt = 0;
533     spktt = 0;
534     sobtt = 0;
535     for (Int_t k=0; k<rtev; k++){
536     if ( k > 0 ){
537     spktt = pktt;
538     sobtt = obtt;
539     };
540     rt->GetEntry(k);
541     pht = eht->GetPscuHeader();
542     pktt = PKT(pht->GetCounter());
543     obtt = OBT(pht->GetOrbitalTime());
544     //
545 mocchiut 1.7 // if ( IsDebug() ) printf(" k %i rtev beforev %i pt %i upperp %i ot %llu uppero %llu \n",k,rtev,pktt,spktt,obtt,sobtt);
546 mocchiut 1.6 //
547 mocchiut 1.4 if ( pktt < spktt && obtt < sobtt ){
548     if ( IsDebug() ) printf(" RT PROBLEMS determining the event repetition at the end of the file lasttrail %i \n",rtev);
549     //
550 mocchiut 1.6 rtev = k-1;
551 mocchiut 1.4 rt->GetEntry(rtev);
552     pktt = spktt;
553     obtt = sobtt;
554     if ( IsDebug() ) printf(" lasttrail %i pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);
555     //
556     UInt_t evbeft = 0;
557     code = eht->GetCounter();
558     evbeft = code->Get(pctp->Physics);
559     if ( evbeft >= 0 ){
560     T->GetEntry(evbeft);
561     ph = eh->GetPscuHeader();
562     t_pktlast = PKT(ph->GetCounter());
563     t_obtlast = OBT(ph->GetOrbitalTime());
564 mocchiut 1.7 if ( t_pktlast <= spktt && t_obtlast <= sobtt ){ // jump
565 mocchiut 1.4 upperpkt = pktt;
566     upperobt = obtt;
567     upperentry = evbeft-1;
568     } else {
569     while ( t_pktlast > spktt && t_obtlast > sobtt && evbeft < nevent ){
570     evbeft++;
571     T->GetEntry(evbeft);
572     ph = eh->GetPscuHeader();
573     t_pktlast = PKT(ph->GetCounter());
574     t_obtlast = OBT(ph->GetOrbitalTime());
575     };
576     T->GetEntry(evbeft-1);
577     ph = eh->GetPscuHeader();
578     upperpkt = PKT(ph->GetCounter());
579     upperobt = OBT(ph->GetOrbitalTime());
580     upperentry = evbeft-1;
581     };
582     };
583     if ( IsDebug() ) printf(" rtev after %i pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);
584 mocchiut 1.6 goto kikko;
585     // break;
586 mocchiut 1.4 //
587     };
588     //
589     };
590     //
591 mocchiut 1.6 kikko:
592     //
593     T->GetEntry(upperentry);
594     code = eh->GetCounter();
595     lasttrail = code->Get(pctp->RunTrailer);
596     lasthead = code->Get(pctp->RunHeader);
597     if ( lasttrail < rtev ){
598     rt->GetEntry(lasttrail);
599     pht = eht->GetPscuHeader();
600     pktt = PKT(pht->GetCounter());
601     obtt = OBT(pht->GetOrbitalTime());
602     };
603     //
604     if ( lasthead < rhev ){
605     rh->GetEntry(lasthead);
606     phh = ehh->GetPscuHeader();
607     pkth = PKT(phh->GetCounter());
608     obth = OBT(phh->GetOrbitalTime());
609     };
610     //
611     if ( IsDebug() ) printf(" rhev before %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);
612     if ( pkth > upperpkt && obth > upperobt ){
613     if ( IsDebug() ) printf(" Upper limits extended to include last header: ph %i upperp %i oh %llu uppero %llu \n",pkth,upperpkt,obth,upperobt);
614     upperpkt = pkth;
615     upperobt = obth;
616     rhev = lasthead+1;
617     } else {
618     rhev = lasthead;
619     };
620     if ( IsDebug() ) printf(" rhev after %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);
621     //
622     if ( IsDebug() ) printf(" rtev beforev %i pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);
623     if ( pktt > upperpkt && obtt > upperobt ){
624     if ( IsDebug() ) printf(" Upper limits extended to include last trailer: pt %i upperp %i ot %llu uppero %llu \n",pktt,upperpkt,obtt,upperobt);
625     upperpkt = pktt;
626     upperobt = obtt;
627     rtev = lasttrail+1;
628     } else {
629     rtev = lasttrail;
630     };
631     if ( IsDebug() ) printf(" rtev after %i pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);
632 mocchiut 1.4 //
633 mocchiut 1.1 if ( IsDebug() ) printf(" Upper limits are: OBT %llu pkt_num %i upper entry %i \n",upperobt,upperpkt,upperentry);
634     //
635     return(0);
636     }
637    
638 mocchiut 1.13 /**
639     *
640     * Trick to have unique RUN ID numbers even when runs are deleted and mysql deamon restarted.
641     * Entries in the _RUNID_GEN table are never deleted.
642     *
643     **/
644     UInt_t PamelaDBOperations::AssignRunID(){
645     //
646     TSQLResult *result = 0;
647     TSQLRow *row = 0;
648     UInt_t runid = 0;
649     //
650     stringstream oss;
651     //
652     oss.str("");
653     oss << "INSERT INTO _RUNID_GEN VALUES (NULL);";
654     result = conn->Query(oss.str().c_str());
655     if ( !result ) throw -10;
656     oss.str("");
657     oss << "SELECT ID FROM _RUNID_GEN ORDER BY ID DESC LIMIT 1;";
658     result = conn->Query(oss.str().c_str());
659     if ( !result ) throw -10;
660     //
661     row = result->Next();
662     //
663     if ( !row ) throw -28;
664     //
665     runid = (UInt_t)atoll(row->GetField(0));
666     //
667     return(runid);
668     };
669    
670 mocchiut 1.1 //
671     // GETTERS
672     //
673    
674     /**
675     *
676     * Returns the DB absolute time needed to associate calibrations to data
677     *
678     */
679     UInt_t PamelaDBOperations::GetAbsTime(UInt_t obt){
680     //
681     return(((UInt_t)(OBT(obt)/1000)+toffset));
682     //
683     };
684    
685     /**
686     *
687     * List of packet types (just to make easily the loops)
688     *
689     */
690     const PacketType* PamelaDBOperations::GetPacketType(const char* type){
691     if ( !strcmp(type,"Pscu") ) return(PacketType::Pscu);
692     if ( !strcmp(type,"PhysEndRun") ) return(PacketType::PhysEndRun);
693     if ( !strcmp(type,"CalibCalPulse1") ) return(PacketType::CalibCalPulse1);
694     if ( !strcmp(type,"CalibCalPulse2") ) return(PacketType::CalibCalPulse2);
695     if ( !strcmp(type,"Physics") ) return(PacketType::Physics);
696     if ( !strcmp(type,"CalibTrkBoth") ) return(PacketType::CalibTrkBoth);
697     if ( !strcmp(type,"CalibTrk1") ) return(PacketType::CalibTrk1);
698     if ( !strcmp(type,"CalibTrk2") ) return(PacketType::CalibTrk2);
699     if ( !strcmp(type,"CalibTof") ) return(PacketType::CalibTof);
700     if ( !strcmp(type,"CalibS4") ) return(PacketType::CalibS4);
701     if ( !strcmp(type,"CalibCalPed") ) return(PacketType::CalibCalPed);
702     if ( !strcmp(type,"Calib1_Ac1") ) return(PacketType::Calib1_Ac1);
703     if ( !strcmp(type,"Calib2_Ac1") ) return(PacketType::Calib2_Ac1);
704     if ( !strcmp(type,"Calib1_Ac2") ) return(PacketType::Calib1_Ac2);
705     if ( !strcmp(type,"Calib2_Ac2") ) return(PacketType::Calib2_Ac2);
706     if ( !strcmp(type,"CalibCal") ) return(PacketType::CalibCal);
707     if ( !strcmp(type,"RunHeader") ) return(PacketType::RunHeader);
708     if ( !strcmp(type,"RunTrailer") ) return(PacketType::RunTrailer);
709     if ( !strcmp(type,"CalibHeader") ) return(PacketType::CalibHeader);
710     if ( !strcmp(type,"CalibTrailer") ) return(PacketType::CalibTrailer);
711     if ( !strcmp(type,"InitHeader") ) return(PacketType::InitHeader);
712     if ( !strcmp(type,"InitTrailer") ) return(PacketType::InitTrailer);
713     if ( !strcmp(type,"EventTrk") ) return(PacketType::EventTrk);
714     if ( !strcmp(type,"Log") ) return(PacketType::Log);
715     if ( !strcmp(type,"VarDump") ) return(PacketType::VarDump);
716     if ( !strcmp(type,"ArrDump") ) return(PacketType::ArrDump);
717     if ( !strcmp(type,"TabDump") ) return(PacketType::TabDump);
718     if ( !strcmp(type,"Tmtc") ) return(PacketType::Tmtc);
719     if ( !strcmp(type,"Mcmd") ) return(PacketType::Mcmd);
720     if ( !strcmp(type,"ForcedFECmd") ) return(PacketType::ForcedFECmd);
721     if ( !strcmp(type,"Ac1Init") ) return(PacketType::Ac1Init);
722     if ( !strcmp(type,"CalInit") ) return(PacketType::CalInit);
723     if ( !strcmp(type,"TrkInit") ) return(PacketType::TrkInit);
724     if ( !strcmp(type,"TofInit") ) return(PacketType::TofInit);
725     if ( !strcmp(type,"TrgInit") ) return(PacketType::TrgInit);
726     if ( !strcmp(type,"NdInit") ) return(PacketType::NdInit);
727     if ( !strcmp(type,"S4Init") ) return(PacketType::S4Init);
728     if ( !strcmp(type,"Ac2Init") ) return(PacketType::Ac2Init);
729     if ( !strcmp(type,"CalAlarm") ) return(PacketType::CalAlarm);
730     if ( !strcmp(type,"Ac1Alarm") ) return(PacketType::Ac1Alarm);
731     if ( !strcmp(type,"TrkAlarm") ) return(PacketType::TrkAlarm);
732     if ( !strcmp(type,"TrgAlarm") ) return(PacketType::TrgAlarm);
733     if ( !strcmp(type,"TofAlarm") ) return(PacketType::TofAlarm);
734     if ( !strcmp(type,"S4Alarm") ) return(PacketType::S4Alarm);
735     if ( !strcmp(type,"Ac2Alarm") ) return(PacketType::Ac2Alarm);
736     if ( !strcmp(type,"TsbT") ) return(PacketType::TsbT);
737     if ( !strcmp(type,"TsbB") ) return(PacketType::TsbB);
738     return(PacketType::Invalid);
739     };
740    
741     //
742     // PRIVATE FUNCTIONS
743     //
744    
745 pam-fi 1.8 // /**
746     // * Open the ROOT filename for reading
747     // */
748     // void PamelaDBOperations::OpenFile(){
749     // file = TFile::Open(this->GetRootName().Data());
750     // //
751 mocchiut 1.9
752     void PamelaDBOperations::CheckFile(){
753     if ( !file ) throw -12;
754     };
755 mocchiut 1.1
756    
757     /**
758     * Check if LEVEL0 file and DB connection have really be opened
759     */
760 pam-fi 1.8 void PamelaDBOperations::CheckConnection(){
761 mocchiut 1.1 //
762     // check connection
763     //
764 pam-fi 1.8 if( !conn ) throw -1;
765 mocchiut 1.1 bool connect = conn->IsConnected();
766 pam-fi 1.8 if( !connect ) throw -1;
767 mocchiut 1.16 if ( !dworbit && strcmp(this->GetRootName().Data(),"") ) throw -27;
768 mocchiut 1.17 //
769     // set DB timezone to UTC
770     //
771 mocchiut 1.19 stringstream oss;
772 mocchiut 1.17 //
773     oss.str("");
774     oss << "SET time_zone='+0:00';";
775 mocchiut 1.19 TSQLResult *result = 0;
776     result = conn->Query(oss.str().c_str());
777     if ( !result ) throw -10;
778 mocchiut 1.17 //
779 mocchiut 1.1 };
780    
781     /**
782     * Return the correct packet number if we went back to zero
783     */
784     UInt_t PamelaDBOperations::PKT(UInt_t pkt_num){
785     //
786     // if ( IsDebug() ) printf(" pkt conversion: pkt_num is %u pktfirst is %u (pktfirst - (UInt_t)(16777212/2)) is %u \n",pkt_num,pktfirst,(pktfirst - (UInt_t)(16777212/2)));
787     //
788     if ( pkt_num < (pktfirst/2) && pktfirst > (16777214/2) ) return((pkt_num+16777215));
789     //
790     if ( pkt_num > pktfirst*2 && pkt_num > (16777214/2) ){
791     if ( (pkt_num-16777215) < 0 ){
792     return((16777215-pkt_num));
793     } else {
794     return((pkt_num-16777215));
795     };
796     };
797     //
798     return(pkt_num);
799     //
800     };
801    
802     /**
803     * Return the correct On Board Time if we went back to zero
804     */
805     ULong64_t PamelaDBOperations::OBT(UInt_t obt){
806     //
807     if ( obt < (obtfirst/2) && obtfirst > (numeric_limits<UInt_t>::max()/2) ) return((ULong64_t)(obt+numeric_limits<UInt_t>::max()));
808     //
809     if ( obt > (obtfirst*2) && obt > (numeric_limits<UInt_t>::max()/2) ){
810     if ( (obt-numeric_limits<UInt_t>::max()) < 0 ){
811     return((ULong64_t)(numeric_limits<UInt_t>::max()-obt));
812     } else {
813     return((ULong64_t)(obt-numeric_limits<UInt_t>::max()));
814     };
815     };
816     //
817     return((ULong64_t)obt);
818     };
819    
820     /**
821     *
822     * Fill the glrun class with infos about the run when we have both runtrailer and runheader
823     *
824     */
825     void PamelaDBOperations::FillClass(){
826     this->FillClass(false,false,0,0);
827     };
828    
829     /**
830     *
831     * Fill the glrun class with infos about the run when we have both runtrailer and runheader
832     *
833     */
834     void PamelaDBOperations::FillClass(Bool_t mishead, Bool_t mistrail, UInt_t firstev, UInt_t lastev){
835     //
836     TTree *T = 0;
837     T = (TTree*)file->Get("Physics");
838     if ( !T || T->IsZombie() ) throw -16;
839     //
840     EventHeader *eh = 0;
841     PscuHeader *ph = 0;
842     T->SetBranchAddress("Header", &eh);
843     PacketType *pctp=0;
844     EventCounter *codt=0;
845     EventCounter *codh=0;
846     UInt_t firstObt = 0;
847     UInt_t lastObt = 0;
848     UInt_t firstPkt = 0;
849     UInt_t lastPkt = 0;
850     UInt_t rhtime = 0;
851     UInt_t rttime = 0;
852     if ( !mishead ){
853     codh = ehh->GetCounter();
854     firstev = codh->Get(pctp->Physics);
855     rhtime = this->GetAbsTime(phh->GetOrbitalTime());
856     glrun->Set_GL_RUNH(runh,phh);
857     firstObt = glrun->GetRUNHEADER_OBT();
858     firstPkt = glrun->GetRUNHEADER_PKT();
859     };
860     if ( !mistrail ){
861     codt = eht->GetCounter();
862     lastev = codt->Get(pctp->Physics)-1;
863     rttime = this->GetAbsTime(pht->GetOrbitalTime());
864     glrun->Set_GL_RUNT(runt,pht);
865     lastObt = glrun->GetRUNTRAILER_OBT();
866     lastPkt = glrun->GetRUNTRAILER_PKT();
867     };
868     //
869 mocchiut 1.2 if ( mishead && mistrail && lastev+1 == firstev ) throw -14; // run with no events, no runtrailer, no runheader... unsupported should never arrive here
870 mocchiut 1.1 //
871     if ( mishead ) {
872     glrun->Set_GL_RUNH0();
873     //
874     if ( lastev+1 == firstev ){
875     firstObt = lastObt;
876     firstPkt = lastPkt;
877     rhtime = rttime;
878     } else {
879     T->GetEntry(firstev);
880     ph = eh->GetPscuHeader();
881     firstObt = ph->GetOrbitalTime();
882     rhtime = this->GetAbsTime(firstObt);
883     firstPkt = ph->GetCounter();
884     };
885     //
886     glrun->SetRUNHEADER_PKT(firstPkt);
887     glrun->SetRUNHEADER_OBT(firstObt);
888     //
889     };
890     if ( mistrail ){
891     glrun->Set_GL_RUNT0();
892     //
893     if ( lastev+1 == firstev ){
894     lastObt = firstObt;
895     lastPkt = firstPkt;
896     rttime = rhtime;
897     } else {
898     T->GetEntry(lastev);
899     ph = eh->GetPscuHeader();
900     lastObt = ph->GetOrbitalTime();
901     rttime = this->GetAbsTime(lastObt);
902     lastPkt = ph->GetCounter();
903     };
904     //
905     glrun->SetRUNTRAILER_OBT(lastObt);
906     glrun->SetRUNTRAILER_PKT(lastPkt);
907     //
908     };
909     glrun->SetEV_FROM(firstev);
910     glrun->SetEV_TO(lastev);
911     glrun->SetNEVENTS(lastev-firstev+1);
912     //
913     this->SetCommonGLRUN(rhtime,rttime);
914     //
915     };
916    
917     //
918     // PUBLIC FUNCTIONS
919     //
920    
921     /**
922     * Insert a new row into GL_RAW table.
923     */
924     Int_t PamelaDBOperations::insertPamelaRawFile(){
925     //
926     stringstream oss;
927     //
928     Bool_t idr = this->SetID_RAW();
929     if ( idr ) return(1);
930     //
931     oss.str("");
932     oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('"
933     << this->GetRawPath().Data() << "', '" << this->GetRawFile().Data() << "')";
934     if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;
935     //
936     idr = this->SetID_RAW();
937     if ( !idr ) throw -11;
938     //
939     return(0);
940     }
941    
942    
943     /**
944     * Look for one timesync information in the file and
945     * 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
946     */
947     Int_t PamelaDBOperations::insertPamelaGL_TIMESYNC(){
948     //
949     TSQLResult *result = 0;
950     TSQLRow *row = 0;
951     UInt_t t0 = 0;
952     //
953     stringstream oss;
954     //
955     if ( this->GetID_RAW() == 0 ) throw -11;
956     //
957     oss.str("");
958 mocchiut 1.19 oss << "SELECT YEAR(OFFSET_DATE),MONTH(OFFSET_DATE),DAY(OFFSET_DATE),HOUR(OFFSET_DATE),MINUTE(OFFSET_DATE),SECOND(OFFSET_DATE) FROM GL_RESURS_OFFSET WHERE SPECIAL_FILE='"
959 mocchiut 1.13 << this->GetRawFile().Data() << "';";
960 mocchiut 1.1 if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
961     result = conn->Query(oss.str().c_str());
962     if ( !result ) throw -10;
963     row = result->Next();
964 mocchiut 1.13 //
965     if ( !row ){
966     oss.str("");
967 mocchiut 1.19 oss << "SELECT YEAR(OFFSET_DATE),MONTH(OFFSET_DATE),DAY(OFFSET_DATE),HOUR(OFFSET_DATE),MINUTE(OFFSET_DATE),SECOND(OFFSET_DATE) FROM GL_RESURS_OFFSET WHERE FROM_ORBIT< "
968 mocchiut 1.13 << dworbit << " order by FROM_ORBIT desc limit 1;";
969     if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
970     result = conn->Query(oss.str().c_str());
971     if ( !result ) throw -10;
972     row = result->Next();
973     if ( !row ) throw -10;
974     };
975 mocchiut 1.1 //
976 mocchiut 1.19 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);
977 mocchiut 1.17 t0 = (UInt_t)tu.GetSec();
978 mocchiut 1.19 if ( IsDebug() ) printf(" t0 is %u ti is %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));
979 mocchiut 1.17 //
980 mocchiut 1.1 /*
981     * Verify that the TIMESYNC have been not already processed
982     */
983     oss.str("");
984     oss << " SELECT COUNT(GL_TIMESYNC.ID),GL_TIMESYNC.OBT0,GL_TIMESYNC.TIMESYNC FROM GL_TIMESYNC "
985     << " LEFT JOIN GL_RAW "
986     << " ON GL_RAW.ID = GL_TIMESYNC.ID_RAW "
987     << " WHERE GL_TIMESYNC.ID_RAW = " << this->GetID_RAW()
988     << " GROUP BY GL_TIMESYNC.OBT0;";
989     if ( IsDebug() ) printf(" check for old timesync: query is \n %s \n",oss.str().c_str());
990     result = conn->Query(oss.str().c_str());
991     if (result == NULL) throw -10;
992     row = result->Next();
993     if ((row != NULL) && ((UInt_t)atoll(row->GetField(0)) > 0)){
994 mocchiut 1.19 if ( IsDebug() ) printf(" found a timesync t0 is %u \n",t0);
995 mocchiut 1.1 toffset = (UInt_t)atoll(row->GetField(2)) - (UInt_t)(this->OBT((UInt_t)atoll(row->GetField(1)))/1000) + t0;
996     return(1);
997     };
998     //
999     TTree *T = 0;
1000 mocchiut 1.2 Int_t signal = 0;
1001 mocchiut 1.1 //
1002     UInt_t nevent = 0;
1003     UInt_t recEntries = 0;
1004     //
1005     UInt_t OBT = 0;
1006     UInt_t TYPE = 0;
1007     //
1008     Double_t minimum = 0.;
1009     Double_t maximum = 0.;
1010     Double_t minimum2 = 0.;
1011     Double_t maximum2 = 0.;
1012     //
1013     UInt_t TSYNC = 0;
1014     //
1015     pamela::McmdEvent *mc = 0;
1016     pamela::McmdRecord *mcrc = 0;
1017     TArrayC *mcmddata = 0;
1018     //
1019     minimum = numeric_limits<Double_t>::max();
1020     maximum = numeric_limits<Double_t>::min();
1021     minimum2 = numeric_limits<Double_t>::max();
1022     maximum2 = numeric_limits<Double_t>::min();
1023     //
1024     T = (TTree*)file->Get("Mcmd");
1025     if ( !T || T->IsZombie() ) throw -19;
1026     T->SetBranchAddress("Mcmd",&mc);
1027     //
1028     nevent = T->GetEntries();
1029     //
1030     // loop over events
1031     //
1032     Bool_t existsts = false;
1033     //
1034     for (UInt_t i=0; i<nevent;i++){
1035     //
1036     T->GetEntry(i);
1037     //
1038     recEntries = mc->Records->GetEntries();
1039     //
1040     for (UInt_t j = 0; j < recEntries; j++){
1041     mcrc = (pamela::McmdRecord*)mc->Records->At(j);
1042     mcmddata = mcrc->McmdData;
1043     //
1044     if (mcrc->ID1 == 0xE0){ // mcmd timesync
1045     //
1046     OBT = (Int_t)(mcrc->MCMD_RECORD_OBT);
1047     //
1048     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);
1049     //
1050     TYPE = 55;//224;
1051     //
1052 mocchiut 1.11 if ( IsDebug() ) printf("mcmd tsync %i tsync %u obt %u \n",i,TSYNC,OBT);
1053     //
1054 mocchiut 1.1 if ( TSYNC && OBT ){
1055     existsts = true;
1056 mocchiut 1.2 goto eout;
1057 mocchiut 1.1 };
1058     //
1059     };
1060     };
1061     };
1062     if ( !existsts ) { // try with runheader and runtrailer
1063     //
1064 mocchiut 1.2 if ( IsDebug() ) printf(" No ts mcmd \n");
1065     signal = 2;
1066     //
1067 mocchiut 1.1 TTree *rh=(TTree*)file->Get("RunHeader");
1068     if ( !rh || rh->IsZombie() ) throw -17;
1069     TTree *rt=(TTree*)file->Get("RunTrailer");
1070     if ( !rt || rt->IsZombie() ) throw -18;
1071     //
1072     rh->SetBranchAddress("RunHeader", &runh);
1073     //
1074     rt->SetBranchAddress("RunTrailer", &runt);
1075     //
1076 mocchiut 1.11 Int_t nrhev = rh->GetEntries();
1077     Int_t nrtev = rt->GetEntries();
1078     if ( IsDebug() ) printf(" ou nevent %i rhev %i rtev %i \n",nevent,nrhev,nrtev);
1079     //
1080     if ( nrhev > 0 ){
1081     for (Int_t i=0; i<nrhev; i++){
1082     //
1083     rh->GetEntry(i);
1084     //
1085     TSYNC = runh->LAST_TIME_SYNC_INFO;
1086     OBT = runh->OBT_TIME_SYNC * 1000;
1087     //
1088     TYPE = 20;
1089     //
1090     if ( IsDebug() ) printf("runheader %i tsync %u obt %u \n",i,TSYNC,OBT);
1091     //
1092     if ( TSYNC && OBT ){
1093     existsts = true;
1094     goto eout;
1095     };
1096 mocchiut 1.1 };
1097     //
1098     };
1099 mocchiut 1.11 if ( nrtev > 0 ){
1100 mocchiut 1.2 //
1101     if ( IsDebug() ) printf(" No runheader \n");
1102     signal = 6;
1103     //
1104 mocchiut 1.11 for (Int_t i=0; i<nrtev; i++){
1105     //
1106     rt->GetEntry(i);
1107     //
1108     TSYNC = runt->LAST_TYME_SYNC_INFO;
1109     OBT = runt->OBT_TYME_SYNC * 1000;
1110     //
1111     TYPE = 21;
1112     //
1113     if ( IsDebug() ) printf("runtrailer %i tsync %u obt %u \n",i,TSYNC,OBT);
1114     //
1115     if ( TSYNC && OBT ){
1116     existsts = true;
1117     goto eout;
1118     };
1119 mocchiut 1.1 };
1120     //
1121 mocchiut 1.2 } else {
1122     if ( IsDebug() ) printf(" No runheader \n");
1123 mocchiut 1.1 };
1124     };
1125     //
1126     if ( !existsts ){ // try with inclination mcmd
1127 mocchiut 1.2 //
1128     if ( IsDebug() ) printf(" No runtrailer \n");
1129     signal = 14;
1130     //
1131 mocchiut 1.1 Double_t timesync = 0.;
1132     for (UInt_t i=0; i<nevent;i++){
1133     //
1134     T->GetEntry(i);
1135     //
1136     recEntries = mc->Records->GetEntries();
1137     // //
1138     for (UInt_t j = 0; j < recEntries; j++){
1139     mcrc = (pamela::McmdRecord*)mc->Records->At(j);
1140     mcmddata = mcrc->McmdData;
1141     //
1142     if (mcrc->ID1 == 0xE2){ // mcmd inclination
1143     timesync = 0.;
1144     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);
1145     //
1146     if ( timesync > maximum2){
1147     maximum2 = timesync;
1148     OBT = (Int_t)(mcrc->MCMD_RECORD_OBT);
1149     };
1150     };
1151     //
1152     };
1153     };
1154     if ( maximum2 > numeric_limits<Double_t>::min() ){
1155     TSYNC = (UInt_t)(maximum2 + 0.5);
1156     TYPE = 666;
1157     if ( TSYNC && OBT ){
1158     existsts = true;
1159 mocchiut 1.2 goto eout;
1160 mocchiut 1.1 };
1161     };
1162     };
1163     //
1164     if ( !existsts && obt0 ){ // insert timesync by hand
1165 mocchiut 1.2 //
1166     if ( IsDebug() ) printf(" No incl mcmd \n");
1167     signal = 30;
1168     //
1169 mocchiut 1.1 OBT = obt0;
1170     TSYNC = tsync;
1171     TYPE = 999;
1172     existsts = true;
1173 mocchiut 1.2 goto eout;
1174 mocchiut 1.1 };
1175     //
1176 mocchiut 1.2 eout:
1177 mocchiut 1.1 //
1178     if ( !existsts ) throw -3;
1179     //
1180     oss.str("");
1181     oss << "INSERT INTO GL_TIMESYNC (ID_RAW,TYPE,OBT0,TIMESYNC) VALUES ('"
1182     << this->GetID_RAW() << "','"//224'"
1183     << dec << (UInt_t)TYPE << "','"
1184     << dec << (UInt_t)OBT << "','"
1185     << dec << (UInt_t)TSYNC << "');";
1186     conn->Query(oss.str().c_str());
1187     if ( IsDebug() ) printf(" Query the GL_TIMESYNC table to fill it:\n %s \n",oss.str().c_str());
1188     //
1189 mocchiut 1.19 if ( IsDebug() ) printf(" found a timesync t0 is %u \n",t0);
1190 mocchiut 1.1 toffset = (UInt_t)TSYNC - (UInt_t)(this->OBT(OBT)/1000) + t0;
1191     //
1192     delete result;
1193 mocchiut 1.2 return(signal);
1194 mocchiut 1.1 }
1195    
1196     /**
1197     * Insert all the new rows into GL_ROOT.
1198     * The raw file indicates in the parameters should be already been stored in the database.
1199     */
1200     Int_t PamelaDBOperations::insertPamelaRootFile(){
1201     stringstream oss;
1202     TSQLResult *result = 0;
1203     TSQLRow *row = 0;
1204     UInt_t idtimesync = 0;
1205     //
1206     oss.str("");
1207     oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
1208     << " LEFT JOIN GL_ROOT "
1209     << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
1210     << " WHERE GL_RAW.PATH = '" << this->GetRawPath().Data() << "' AND "
1211     << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
1212     result = conn->Query(oss.str().c_str());
1213     //
1214     if ( !result ) throw -12;
1215     //
1216     row = result->Next();
1217     //
1218     if ( !row ) throw -10;
1219     if ( row != NULL && (UInt_t)atoll(row->GetField(0))>0 ){
1220     idroot = (UInt_t)atoll(row->GetField(2));
1221     return(1);
1222     };
1223     //
1224     // determine which timesync has to be used
1225     //
1226     oss.str("");
1227     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;";
1228     result = conn->Query(oss.str().c_str());
1229     //
1230     if ( !result ) throw -3;
1231     //
1232     row = result->Next();
1233     //
1234     if ( !row ) throw -3;
1235     idtimesync = (UInt_t)atoll(row->GetField(0));
1236     //
1237     oss.str("");
1238     oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"
1239     << this->GetID_RAW() << "', '" << idtimesync << "', '" << this->GetRootPath().Data() << "', '" << this->GetRootFile().Data() << "')";
1240     //
1241     if (conn->Query(oss.str().c_str()) == 0) throw -4;
1242     //
1243     delete result;
1244     //
1245     oss.str("");
1246     oss << "SELECT ID FROM GL_ROOT WHERE ID_RAW=" << this->GetID_RAW() << ";";
1247     //
1248     result = conn->Query(oss.str().c_str());
1249     if ( !result ) throw -12;
1250     row = result->Next();
1251     this->SetID_ROOT((UInt_t)atoll(row->GetField(0)));
1252     //
1253     delete result;
1254     //
1255     return(0);
1256     }
1257    
1258     /**
1259     * Assign the BOOT_NUMBER to the raw file.
1260     */
1261     Int_t PamelaDBOperations::assignBOOT_NUMBER(){
1262     stringstream oss;
1263     TSQLResult *result = 0;
1264     TSQLRow *row = 0;
1265     oss.str("");
1266     oss << "SELECT ID, BOOT_NUMBER FROM GL_RAW WHERE "
1267     << " PATH = '" << this->GetRawPath().Data() << "' AND "
1268     << " NAME = '" << this->GetRawFile().Data() << "' ";
1269     result = conn->Query(oss.str().c_str());
1270     //
1271 mocchiut 1.2 if ( !result ) throw -4;;
1272 mocchiut 1.1 row = result->Next();
1273     if ( !row ) return(16);
1274     if ( row->GetField(1) ){
1275     this->SetBOOTnumber((UInt_t)atoll(row->GetField(1)));
1276     return(1);
1277     };
1278 mocchiut 1.2 if ( !row->GetField(0) ) throw -26;
1279 mocchiut 1.1 //
1280     UInt_t idRaw = (UInt_t)atoll(row->GetField(0));
1281     //
1282     //
1283     //
1284     TTree *trDumpEv = 0;
1285     trDumpEv = (TTree*)file->Get("VarDump");
1286     if ( !trDumpEv || trDumpEv->IsZombie() ) throw -20;
1287     //
1288     VarDumpEvent *vde = 0;
1289     VarDumpRecord *vdr = 0;
1290     //
1291     trDumpEv->SetBranchAddress("VarDump", &vde);
1292 mocchiut 1.2 if ( trDumpEv->GetEntries() > 0 ){
1293     Bool_t found = false;
1294     for ( Int_t i = 0; i < trDumpEv->GetEntries(); i++){
1295     trDumpEv->GetEntry(i);
1296     vde->Records->GetEntries();
1297     if ( vde->Records->GetEntries()>0 ){
1298     found = true;
1299     goto fill;
1300     };
1301     };
1302     fill:
1303     if ( found ){
1304     //
1305 mocchiut 1.1 vdr = (VarDumpRecord*)vde->Records->At(6);
1306 mocchiut 1.2 //
1307 mocchiut 1.1 this->SetBOOTnumber((Int_t)vdr->VAR_VALUE);
1308 mocchiut 1.2 //
1309     } else {
1310     if ( !this->GetBOOTnumber() ) return(4);
1311 mocchiut 1.1 };
1312     } else {
1313     if ( !this->GetBOOTnumber() ) return(2);
1314     };
1315     //
1316     oss.str("");
1317     oss << " UPDATE GL_RAW "
1318     << " SET GL_RAW.BOOT_NUMBER = '" << dec << this->GetBOOTnumber() << "'"
1319     << " WHERE GL_RAW.ID = '" << idRaw << "'";
1320     conn->Query(oss.str().c_str());
1321     //
1322     delete result;
1323     return(0);
1324     };
1325    
1326     /**
1327     * Scan runtrailer packet, fill the GL_RUN table and
1328     * check for missing and truncated runs
1329     */
1330     Int_t PamelaDBOperations::insertPamelaRUN(){
1331     Int_t signal = 0;
1332     //
1333     stringstream oss;
1334     oss.str("");
1335     //
1336     signal = this->SetUpperLimits();
1337     //
1338     // loop on runheader and runtrailer events
1339     //
1340     TTree *rh=(TTree*)file->Get("RunHeader");
1341     if ( !rh || rh->IsZombie() ) throw -17;
1342     TTree *rt=(TTree*)file->Get("RunTrailer");
1343     if ( !rt || rt->IsZombie() ) throw -18;
1344     //
1345     PacketType *pctp=0;
1346     EventCounter *cod=0;
1347     //
1348     rh->SetBranchAddress("RunHeader", &runh);
1349     rh->SetBranchAddress("Header", &ehh);
1350     //
1351     rt->SetBranchAddress("RunTrailer", &runt);
1352     rt->SetBranchAddress("Header", &eht);
1353     //
1354     UInt_t obtt = 0;
1355     UInt_t obth = 0;
1356     UInt_t pktt = 0;
1357     UInt_t pkth = 0;
1358     Int_t pth = -1;
1359     Int_t ptht = -1;
1360     Int_t evbeft = 0;
1361     Int_t evbefh = 0;
1362     //
1363     // no runtrailers in the file!
1364     //
1365     if ( !rtev ){
1366     if ( !upperentry ){
1367     if ( IsDebug() ) printf(" No physics events nor runs in the file \n");
1368     throw -8;
1369     } else {
1370     this->HandleRunFragments(true,true,0,upperentry);
1371     };
1372     } else {
1373     //
1374     for (Int_t ptt=0; ptt<rtev; ptt++){
1375     //
1376     rt->GetEntry(ptt);
1377     pht = eht->GetPscuHeader();
1378     pktt = pht->GetCounter();
1379     obtt = pht->GetOrbitalTime();
1380     //
1381     cod = eht->GetCounter();
1382     ptht = cod->Get(pctp->RunHeader) - 1;
1383     evbeft = cod->Get(pctp->Physics);
1384     //
1385     if ( !ptt && !(ptht+1) ){
1386     //
1387     if ( IsDebug() ) printf(" Piece of run at the beginning of the file %i %i %i \n",ptht,pth,ptt);
1388     //
1389     this->HandleRunFragments(true,false,0,(evbeft-1));
1390     //
1391     //
1392     } else if ( pth == ptht ){
1393     //
1394     if ( IsDebug() ) printf(" Missing header %i %i %i\n",ptht,pth,ptt);
1395     //
1396 mocchiut 1.2 if ( (ptt-1) < 0 ) throw -15; // should never arrive here!
1397 mocchiut 1.1 rt->GetEntry(ptt-1);
1398     cod = eht->GetCounter();
1399     evbefh = cod->Get(pctp->Physics);
1400     rt->GetEntry(ptt);
1401     pht = eht->GetPscuHeader();
1402     //
1403     if ( IsDebug() ) printf(" Try to find the beginning of a run which has only the runtrailer %i %i %i \n",ptht,pth,ptt);
1404     if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' %i %i %i \n",pkth,obth,obtt);
1405     //
1406     this->HandleMissingHoT(true,false,evbefh,evbeft-1);
1407     //
1408     } else {
1409     //
1410     if ( IsDebug() ) printf(" Could be a good run, we have a runheader followed by a runtrailer %i %i %i\n",ptht,pth,ptt);
1411     //
1412     rh->GetEntry(ptht);
1413     phh = ehh->GetPscuHeader();
1414     pkth = phh->GetCounter();
1415     obth = phh->GetOrbitalTime();
1416     cod = ehh->GetCounter();
1417     evbefh = cod->Get(pctp->Physics);
1418     if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' %i %i %i \n",pkth,obth,obtt);
1419     //
1420     // handle this run
1421     //
1422     this->HandleRun();
1423     //
1424     //
1425     //
1426     if ( PKT(pkth)>PKT(pktfirst) && OBT(obth)>OBT(obtfirst) && !ptt ){
1427     //
1428     if ( IsDebug() ) printf(" Piece of run at the beginning of the file WITH NO RUNTRAILER \n");
1429     //
1430     this->HandleRunFragments(true,true,0,(evbefh-1));
1431     //
1432     };
1433     //
1434     //
1435     if ( (ptht - pth) > 1 ){
1436     //
1437     if ( IsDebug() ) printf(" Missing runtrailers! \n");
1438     if ( IsDebug() ) printf(" Attention there is a jump in the runheader counter %i %i %i \n",ptht,pth,ptt);
1439     // is not the consecutive header
1440     while ( pth != ptht ){
1441     //
1442     // treat the header(s) in the middle and then go to the next header, repeat until you reach the correct header.
1443     //
1444     pth++;
1445     //
1446     rh->GetEntry(pth+1);
1447     phh = ehh->GetPscuHeader();
1448     pktt = phh->GetCounter();
1449     obtt = phh->GetOrbitalTime();
1450     cod = ehh->GetCounter();
1451     evbeft = cod->Get(pctp->Physics);
1452     rh->GetEntry(pth);
1453     phh = ehh->GetPscuHeader();
1454     cod = ehh->GetCounter();
1455     pkth = phh->GetCounter();
1456     obth = phh->GetOrbitalTime();
1457     evbefh = cod->Get(pctp->Physics);
1458     //
1459     if ( IsDebug() ) printf(" Try to find the end of a run which has only the runheader %i %i %i \n",ptht,pth,ptt);
1460     if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' %i %i %i \n",pkth,obth,obtt);
1461     //
1462     this->HandleMissingHoT(false,true,evbefh,evbeft-1);
1463     //
1464     };
1465     //
1466     } else if ( !(ptht - pth) ){
1467     //
1468     if ( IsDebug() ) printf(" Missing runheader! \n");
1469     if ( IsDebug() ) printf(" Attention! the runheader counter did not changed %i %i %i \n",ptht,pth,ptt);
1470     if ( IsDebug() ) printf(" The run should have already been handled by HandleRun() \n");
1471     //
1472     } else {
1473     //
1474     // go on with next header
1475     //
1476     pth = ptht;
1477     };
1478     //
1479     };
1480     //
1481     if ( ptt+1 == rtev){
1482     ptht++;
1483     if ( ptht < rhev ){
1484     rh->GetEntry(ptht);
1485     phh = ehh->GetPscuHeader();
1486     pkth = phh->GetCounter();
1487     obth = phh->GetOrbitalTime();
1488     cod = ehh->GetCounter();
1489     evbefh = cod->Get(pctp->Physics);
1490     if ( IsDebug() ) printf(" Piece of run at the end of file %i %i %i \n",pkth,obth,obtt);
1491     if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''' %i %i %i \n",ptht,pth,ptt);
1492     if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''' %i \n",rhev);
1493     //
1494     this->HandleRunFragments(false,true,evbefh,upperentry);
1495     } else {
1496     //
1497     // check if we have a fragment with no header
1498     //
1499     if ( (UInt_t)evbeft < upperentry-1 ){
1500     if ( IsDebug() ) printf(" Piece of run at the end of the file with NO RUNHEADER!\n");
1501     //
1502 mocchiut 1.2 if ( (ptt-1) < 0 ) throw -15; // should never arrive here!
1503 mocchiut 1.1 rt->GetEntry(ptt-1);
1504     cod = eht->GetCounter();
1505     evbefh = cod->Get(pctp->Physics);
1506     rt->GetEntry(ptt);
1507     pht = eht->GetPscuHeader();
1508     this->HandleRunFragments(true,true,evbefh,upperentry);
1509     };
1510     };
1511     };
1512     //
1513     };
1514     };
1515     //
1516     return(signal);
1517     };
1518    
1519     /**
1520     *
1521     * Check if the run has already been inserted
1522     *
1523     */
1524     Bool_t PamelaDBOperations::IsRunAlreadyInserted(){
1525     //
1526     TSQLResult *result = 0;
1527     TSQLRow *row = 0;
1528     //
1529     stringstream oss;
1530     oss.str("");
1531     //
1532     // the where clause is of the type: boot_number = _our_boot && (
1533     // ( runhead_time >= (_our_runhead_time-10) && runtrail_time <= (_our_runtrail_time+10) &&
1534     // ( runhead_obt >= _our_runheadobt || runhead_pkt >= _our_runheadpkt ) &&
1535     // ( runtrail_obt >= _our_runtrailobt || runtrail_pkt >= _our_runtrailpkt ) )
1536     // ||
1537     // ( runhead_time <= _our_runhead_time && runtrail_time >= _our_runtrail_time) &&
1538     // ( runhead_obt <= _our_runheadobt || runhead_pkt <= _our_runheadpkt ) &&
1539     // ( runtrail_obt <= _our_runtrailobt || runtrail_pkt <= _our_runtrailpkt ) )
1540     // )
1541     //
1542     oss << " SELECT ID,NEVENTS,TRK_CALIB_USED,PKT_COUNTER FROM GL_RUN WHERE "
1543     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
1544     << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
1545     << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
1546     << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
1547     << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
1548     << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
1549     << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
1550     << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
1551     << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
1552     << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
1553     << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
1554     << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
1555     << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
1556     //
1557     if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
1558     result = conn->Query(oss.str().c_str());
1559     //
1560     if ( !result ) throw -4;
1561     //
1562     row = result->Next();
1563     //
1564     if ( !row ){
1565     if ( IsDebug() ) printf(" The run is new \n");
1566     if ( IsDebug() ) printf(" -> fill the DB \n");
1567     return(false); // the file has not been inserted in the DB, go on.
1568     };
1569     //
1570     Bool_t signal = true;
1571     //
1572     while ( row != NULL ){
1573     if ( IsDebug() ) printf(" A run exists with runheader and runtrailer time and packets compatible with this one \n");
1574     //
1575     // the run has already been inserted
1576     //
1577     // return(true); //<<<<<<<<<<<<<<<<<<<<<<<< patch follows, uncomment here
1578     //
1579     // PATCH!
1580     // 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
1581     // while the old run doesn't have it 3) we have more events than the old run
1582     //
1583     if ( glrun->GetNEVENTS() > (UInt_t)atoll(row->GetField(1)) ){
1584     //
1585     if ( IsDebug() ) printf(" The new run has more events than the old one \n");
1586 mocchiut 1.15 glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1587     // oss.str("");
1588     // oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
1589     // if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());
1590     // conn->Query(oss.str().c_str());
1591 mocchiut 1.1 if ( signal ) signal = false;
1592     goto gonext;
1593     //
1594     } else if ( glrun->GetNEVENTS() < (UInt_t)atoll(row->GetField(1)) ){
1595     if ( IsDebug() ) printf(" The new run has less events than the old one \n");
1596     if ( IsDebug() ) printf(" The run is already inserted \n");
1597     goto gonext;
1598     };
1599     //
1600     if ( glrun->GetTRK_CALIB() && !(UInt_t)atoll(row->GetField(2)) ){
1601     //
1602     if ( IsDebug() ) printf(" The new run has the same number of events and the runheader the old one miss the runheader \n");
1603     //
1604 mocchiut 1.15 glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1605     // oss.str("");
1606     // oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
1607     // if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());
1608     // conn->Query(oss.str().c_str());
1609 mocchiut 1.1 //
1610     if ( signal ) signal = false;
1611     goto gonext;
1612     } else if ( !glrun->GetTRK_CALIB() && (UInt_t)atoll(row->GetField(2)) ){
1613     if ( IsDebug() ) printf(" The new run has the same number of events but miss the runheader the old has the runheader \n");
1614     if ( IsDebug() ) printf(" The run is already inserted \n");
1615     goto gonext;
1616     };
1617     //
1618     if ( glrun->GetPKT_COUNTER() && !(UInt_t)atoll(row->GetField(3)) ){
1619     //
1620     if ( IsDebug() ) printf(" The new run has the same number of events, the runheader and the runtrailer the old one miss the runtrailer \n");
1621     //
1622 mocchiut 1.15 glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1623     // oss.str("");
1624     // oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
1625     // if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());
1626     // conn->Query(oss.str().c_str());
1627 mocchiut 1.1 if ( signal ) signal = false;
1628     //
1629     };
1630     //
1631     gonext:
1632     // END PATCH!
1633     //
1634     row = result->Next();
1635     //
1636     };
1637     //
1638     delete result;
1639     //
1640     if ( signal && IsDebug() ) printf(" The run has already been inserted \n");
1641     return(signal);
1642     };
1643    
1644     /**
1645     * Handle runs which seems to be good ones.
1646     **/
1647     void PamelaDBOperations::HandleRun(){
1648     ULong64_t chkpkt = 0;
1649     ULong64_t pktt = (ULong64_t)PKT(pht->GetCounter());
1650     ULong64_t pkth = (ULong64_t)PKT(phh->GetCounter());
1651     //
1652     chkpkt = pkth + (ULong64_t)runt->PKT_COUNTER + 1ULL + 1ULL;
1653     //
1654     if ( labs(chkpkt-pktt)<2 ){
1655     //
1656     if ( IsDebug() ) printf(" check %llu pktt %llu \n",chkpkt,pktt);
1657     //
1658     // it must be a good run, fill the db
1659     //
1660     this->FillClass();
1661     //
1662 mocchiut 1.13 if ( !IsRunAlreadyInserted() ){
1663     glrun->SetID(this->AssignRunID());
1664     glrun->SetID_RUN_FRAG(0);
1665     glrun->Fill_GL_RUN(conn);
1666     };
1667 mocchiut 1.1 } else {
1668     //
1669     if ( IsDebug() ) printf(" oh no! the distance between runheader and runtrailer seems wrong: check %llu pktt %llu \n",chkpkt,pktt);
1670     if ( IsDebug() ) printf(" try to recover run(s) without runheader and runtrailer between runheader and runtrailer\n");
1671     //
1672     this->HandleSuspiciousRun();
1673     //
1674     };
1675     //
1676     //
1677     return;
1678     };
1679    
1680    
1681     /**
1682     * Handle run fragments at the beginning or at the end of the file
1683     **/
1684     void PamelaDBOperations::HandleRunFragments(Bool_t mishead, Bool_t mistrail, UInt_t firstev, UInt_t lastev){
1685     //
1686     UInt_t rhfirstev = firstev;
1687     UInt_t rtlastev = lastev;
1688     Bool_t found = false;
1689 mocchiut 1.16 Bool_t foundinrun = false;
1690 mocchiut 1.1 //
1691     TSQLResult *result = 0;
1692     TSQLRow *row = 0;
1693     //
1694     stringstream oss;
1695     oss.str("");
1696     //
1697     // is the piece of run good (no other packets inside)?
1698     //
1699     if ( !this->IsRunConsistent(mishead,mistrail,firstev,lastev)){
1700     //
1701     // if not, handle other pieces and continue with the first one
1702     //
1703     if ( IsDebug() ) printf("The run is not consistent, it contains non-physics packets! The run has been handled \n");
1704     //
1705     };
1706     //
1707     // we have now the good first piece of a run, fill the glrun object
1708     //
1709     if ( rhfirstev != firstev && !mishead ) mishead = true;
1710     if ( rtlastev != lastev && !mistrail ) mistrail = true;
1711     //
1712     this->FillClass(mishead,mistrail,firstev,lastev);
1713     //
1714     if ( IsDebug() ) printf("The run is good, is it the other piece in the GL_RUN_FRAGMENTS table?\n");
1715     //
1716 mocchiut 1.16 // First of all insert the run in the fragment table...
1717     //
1718     oss.str("");
1719     oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE "
1720     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
1721     << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
1722     << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
1723     << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
1724     << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
1725     << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
1726     << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
1727     << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
1728     << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
1729     << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
1730     << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
1731     << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
1732     << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
1733     //
1734     if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
1735     result = conn->Query(oss.str().c_str());
1736     //
1737     if ( !result ) throw -4;
1738     //
1739     row = result->Next();
1740     //
1741     if ( !row ){
1742     //
1743     // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
1744     //
1745     if ( IsDebug() ) printf(" The run is new \n");
1746     if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
1747     //
1748     glrun->SetID(this->AssignRunID());
1749     glrun->SetID_RUN_FRAG(0);
1750     glrun->Fill_GL_RUN_FRAGMENTS(conn);
1751     //
1752     } else {
1753     if ( IsDebug() ) printf(" The run is already present in the fragment table \n");
1754     };
1755     //
1756     //
1757 mocchiut 1.1 // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?
1758     //
1759     if ( mishead && rhfirstev == firstev ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is
1760     // missing it no way we can found a piece in the frag table
1761     //
1762     oss.str("");
1763     oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN_FRAGMENTS WHERE "
1764     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
1765 mocchiut 1.16 << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
1766     << " ID != " << glrun->ID
1767 mocchiut 1.1 << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
1768     //
1769     if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());
1770     result = conn->Query(oss.str().c_str());
1771     //
1772     if ( !result ) throw -4;
1773     //
1774     row = result->Next();
1775     //
1776 mocchiut 1.16 if ( !row && NoFrag() ){
1777     //
1778     oss.str("");
1779     oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "
1780     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
1781     << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
1782     << " ID != " << glrun->ID
1783     << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
1784     //
1785     if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
1786     result = conn->Query(oss.str().c_str());
1787     //
1788     if ( !result ) throw -4;
1789     //
1790     foundinrun = true;
1791     //
1792     row = result->Next();
1793     //
1794     };
1795     //
1796 mocchiut 1.1 if ( !row ){
1797     if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
1798     found = false;
1799     } else {
1800     //
1801     found = false; // default value
1802     //
1803     if ( IsDebug() ) printf(" Found a possible candidate, checking if it is the good one... \n");
1804     //
1805     // if we have both runheader and runtrailer we can check with pkt_counter:
1806     //
1807     if ( !mistrail && (UInt_t)atoll(row->GetField(1)) != 0 ){
1808     ULong64_t chkpkt = 0;
1809     ULong64_t pktt = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
1810     ULong64_t pkth = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
1811     //
1812     chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;
1813     //
1814     if ( labs(chkpkt-pktt)<2 ){
1815     //
1816     if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
1817     //
1818     found = true;
1819     //
1820     } else {
1821     //
1822     if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);
1823     //
1824     found = false;
1825     //
1826     };
1827     };
1828     if ( !found ){
1829     //
1830     // 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
1831     //
1832     ULong64_t chkpkt1 = 0;
1833     ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
1834     ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
1835     chkpkt1 = labs(orunh1-dbrunt1);
1836     //
1837     ULong64_t chkpkt2 = 0;
1838     ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNHEADER_OBT());
1839     ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
1840     chkpkt2 = labs(orunh2-dbrunt2);
1841     //
1842     ULong64_t chkpkt3 = 0;
1843     ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNHEADER_TIME());
1844     ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
1845     chkpkt3 = labs(orunh3-dbrunt3);
1846     //
1847     if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
1848     // if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){
1849     //
1850     if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
1851     //
1852     found = true;
1853     //
1854     } else {
1855     //
1856     if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
1857     //
1858     found = false;
1859     //
1860     };
1861     };
1862     };
1863     //
1864     if ( found ){
1865     //
1866     // 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
1867     //
1868     if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
1869     //
1870 mocchiut 1.16 if ( foundinrun ){
1871     glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
1872     glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1873     };
1874     //
1875 mocchiut 1.1 GL_RUN *glrun1 = new GL_RUN();
1876     //
1877 mocchiut 1.16 // UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
1878 mocchiut 1.1 //
1879     oss.str("");
1880     oss << " ID="<<row->GetField(0)<<";";
1881     //
1882     glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runheader infos
1883     //
1884     // merge infos
1885     //
1886     UInt_t apkt = PKT(glrun1->GetRUNTRAILER_PKT());
1887     ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());
1888     UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());
1889     ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());
1890     if ( IsDebug() ) printf(" Check overlapping events: %i %i %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
1891     TTree *T= 0;
1892     T = (TTree*)file->Get("Physics");
1893     if ( !T || T->IsZombie() ) throw -16;
1894     EventHeader *eh = 0;
1895     PscuHeader *ph = 0;
1896     T->SetBranchAddress("Header", &eh);
1897     while ( apkt > bpkt && aobt > bobt && firstev < lastev ){
1898     T->GetEntry(firstev);
1899     ph = eh->GetPscuHeader();
1900     bpkt = PKT(ph->GetCounter());
1901     bobt = OBT(ph->GetOrbitalTime());
1902     firstev++;
1903     };
1904     if ( IsDebug() ) printf(" Check overlapping events done: %i %i %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
1905     //
1906     glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
1907     glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
1908     glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
1909     glrun1->SetRUNTRAILER_OBT(glrun->GetRUNTRAILER_OBT());
1910     glrun1->SetRUNTRAILER_PKT(glrun->GetRUNTRAILER_PKT());
1911     //
1912     glrun->SetEV_FROM(firstev);
1913     glrun->SetNEVENTS(lastev-firstev+1);
1914 mocchiut 1.16 //
1915 mocchiut 1.1 glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
1916     glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
1917     glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
1918     glrun->SetCOMPILATIONTIMESTAMP(glrun1->GetCOMPILATIONTIMESTAMP());
1919     glrun->SetFAV_WRK_SCHEDULE(glrun1->GetFAV_WRK_SCHEDULE());
1920     glrun->SetEFF_WRK_SCHEDULE(glrun1->GetEFF_WRK_SCHEDULE());
1921     glrun->SetPRH_VAR_TRG_MODE_A(glrun1->GetPRH_VAR_TRG_MODE_A());
1922     glrun->SetPRH_VAR_TRG_MODE_B(glrun1->GetPRH_VAR_TRG_MODE_B());
1923     glrun->SetACQ_BUILD_INFO(glrun1->GetACQ_BUILD_INFO());
1924     glrun->SetACQ_VAR_INFO(glrun1->GetACQ_VAR_INFO());
1925     glrun->SetRM_ACQ_AFTER_CALIB(glrun1->GetRM_ACQ_AFTER_CALIB());
1926     glrun->SetRM_ACQ_SETTING_MODE(glrun1->GetRM_ACQ_SETTING_MODE());
1927     glrun->SetTRK_CALIB_USED(glrun1->GetTRK_CALIB_USED());
1928     glrun->SetCAL_DSP_MASK(glrun1->GetCAL_DSP_MASK());
1929     glrun->SetLAST_TIMESYNC(glrun1->GetLAST_TIMESYNC());
1930     glrun->SetOBT_TIMESYNC(glrun1->GetOBT_TIMESYNC());
1931     //
1932     if ( !IsRunAlreadyInserted() ){
1933     //
1934 mocchiut 1.16 // glrun->SetID(this->AssignRunID());
1935 mocchiut 1.13 glrun->SetID_RUN_FRAG(glrun1->GetID());
1936 mocchiut 1.1 glrun->Fill_GL_RUN(conn);
1937     //
1938 mocchiut 1.16 // set id number
1939 mocchiut 1.1 //
1940 mocchiut 1.13 glrun1->SetID_RUN_FRAG(glrun->GetID());
1941 mocchiut 1.1 glrun1->Fill_GL_RUN(conn);
1942     //
1943     };
1944 mocchiut 1.16 // delete old entry in fragment table
1945     //
1946     glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
1947     glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
1948 mocchiut 1.1 //
1949     delete glrun1;
1950     //
1951     //
1952     return;
1953     //
1954     };
1955     //
1956     };
1957     //
1958     if ( mistrail && rtlastev == lastev ) { // look for runtrailer (only when at the end of the file, if at the beginning and the runh is
1959 mocchiut 1.16 // missing it no way we can found a piece in the frag table
1960 mocchiut 1.1 //
1961     oss.str("");
1962     oss << " SELECT ID,PKT_COUNTER,RUNHEADER_TIME,RUNHEADER_OBT,RUNTRAILER_PKT,RUNHEADER_PKT FROM GL_RUN_FRAGMENTS WHERE "
1963     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
1964 mocchiut 1.16 << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
1965     << " ID != " << glrun->ID
1966 mocchiut 1.1 << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
1967     //
1968     if ( IsDebug() ) printf(" look for runtrailer in the fragments table: query is \n %s \n",oss.str().c_str());
1969     result = conn->Query(oss.str().c_str());
1970     //
1971     if ( !result ) throw -4;
1972     //
1973     row = result->Next();
1974     //
1975 mocchiut 1.16 if ( !row && NoFrag() ){
1976     //
1977     oss.str("");
1978     oss << " SELECT ID,PKT_COUNTER,RUNHEADER_TIME,RUNHEADER_OBT,RUNTRAILER_PKT,RUNHEADER_PKT FROM GL_RUN WHERE "
1979     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
1980     << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
1981     << " ID != " << glrun->ID
1982     << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
1983     //
1984     if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
1985     result = conn->Query(oss.str().c_str());
1986     //
1987     if ( !result ) throw -4;
1988     //
1989     foundinrun = true;
1990     row = result->Next();
1991     //
1992     };
1993     //
1994 mocchiut 1.1 if ( !row ){
1995     if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
1996     found = false;
1997     } else {
1998     //
1999     found = false; // default value
2000     //
2001     if ( IsDebug() ) printf(" Found a possible candidate, checking if it is the good one... \n");
2002     //
2003     // if we have both runheader and runtrailer we can check with pkt_counter:
2004     //
2005     if ( !mishead && (UInt_t)atoll(row->GetField(1)) != 0 ){
2006     ULong64_t chkpkt = 0;
2007     ULong64_t pktt = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
2008     ULong64_t pkth = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
2009     //
2010     chkpkt = pkth + (ULong64_t)((UInt_t)atoll(row->GetField(1))) + 1ULL + 1ULL;
2011     //
2012     if ( labs(chkpkt-pktt)<2 ){
2013     //
2014     if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
2015     //
2016     found = true;
2017     //
2018     } else {
2019     //
2020     if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);
2021     //
2022     found = false;
2023     //
2024     };
2025     };
2026     if ( !found ){
2027     //
2028     // 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
2029     //
2030     ULong64_t chkpkt1 = 0;
2031     ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
2032     ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
2033     chkpkt1 = labs(orunh1-dbrunt1);
2034     //
2035     ULong64_t chkpkt2 = 0;
2036     ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNTRAILER_OBT());
2037     ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
2038     chkpkt2 = labs(orunh2-dbrunt2);
2039     //
2040     ULong64_t chkpkt3 = 0;
2041     ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNTRAILER_TIME());
2042     ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
2043     chkpkt3 = labs(orunh3-dbrunt3);
2044     //
2045     if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
2046     //
2047     if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
2048     //
2049     found = true;
2050     //
2051     } else {
2052     //
2053     if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
2054     //
2055     found = false;
2056     //
2057     };
2058     };
2059     };
2060     //
2061     if ( found ){
2062     //
2063     // 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
2064     //
2065     if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
2066     //
2067 mocchiut 1.16 if ( foundinrun ){
2068     glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
2069     glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2070     };
2071     //
2072 mocchiut 1.1 GL_RUN *glrun1 = new GL_RUN();
2073     //
2074 mocchiut 1.16 // UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
2075 mocchiut 1.1 //
2076     oss.str("");
2077     oss << " ID="<<row->GetField(0)<<";";
2078     //
2079     glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runtrailer infos
2080     //
2081     // merge infos
2082     //
2083     UInt_t apkt = PKT(glrun->GetRUNTRAILER_PKT());
2084     ULong64_t aobt = OBT(glrun->GetRUNTRAILER_OBT());
2085     UInt_t bpkt = PKT(glrun1->GetRUNHEADER_PKT());
2086     ULong64_t bobt = OBT(glrun1->GetRUNHEADER_OBT());
2087     if ( IsDebug() ) printf(" Check overlapping events: %i %i %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);
2088     TTree *T= 0;
2089     T = (TTree*)file->Get("Physics");
2090     if ( !T || T->IsZombie() ) throw -16;
2091     EventHeader *eh = 0;
2092     PscuHeader *ph = 0;
2093     T->SetBranchAddress("Header", &eh);
2094     while ( apkt > bpkt && aobt > bobt && lastev > 0 ){
2095     T->GetEntry(lastev);
2096     ph = eh->GetPscuHeader();
2097     apkt = PKT(ph->GetCounter());
2098     aobt = OBT(ph->GetOrbitalTime());
2099     lastev--;
2100     };
2101     if ( IsDebug() ) printf(" Check overlapping events done: %i %i %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);
2102     //
2103     glrun->SetEV_TO(lastev);
2104     glrun->SetNEVENTS(lastev-firstev+1);
2105     glrun->SetPKT_COUNTER(glrun1->GetPKT_COUNTER());
2106     glrun->SetPKT_READY_COUNTER(glrun1->GetPKT_READY_COUNTER());
2107     glrun->SetRUNTRAILER_TIME(glrun1->GetRUNTRAILER_TIME());
2108     glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());
2109     glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());
2110     //
2111     glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());
2112     glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());
2113     glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());
2114     glrun1->SetCOMPILATIONTIMESTAMP(glrun->GetCOMPILATIONTIMESTAMP());
2115     glrun1->SetFAV_WRK_SCHEDULE(glrun->GetFAV_WRK_SCHEDULE());
2116     glrun1->SetEFF_WRK_SCHEDULE(glrun->GetEFF_WRK_SCHEDULE());
2117     glrun1->SetPRH_VAR_TRG_MODE_A(glrun->GetPRH_VAR_TRG_MODE_A());
2118     glrun1->SetPRH_VAR_TRG_MODE_B(glrun->GetPRH_VAR_TRG_MODE_B());
2119     glrun1->SetACQ_BUILD_INFO(glrun->GetACQ_BUILD_INFO());
2120     glrun1->SetACQ_VAR_INFO(glrun->GetACQ_VAR_INFO());
2121     glrun1->SetRM_ACQ_AFTER_CALIB(glrun->GetRM_ACQ_AFTER_CALIB());
2122     glrun1->SetRM_ACQ_SETTING_MODE(glrun->GetRM_ACQ_SETTING_MODE());
2123     glrun1->SetTRK_CALIB_USED(glrun->GetTRK_CALIB_USED());
2124     glrun1->SetCAL_DSP_MASK(glrun->GetCAL_DSP_MASK());
2125     glrun1->SetLAST_TIMESYNC(glrun->GetLAST_TIMESYNC());
2126     glrun1->SetOBT_TIMESYNC(glrun->GetOBT_TIMESYNC());
2127     //
2128     if ( !IsRunAlreadyInserted() ){
2129     //
2130 mocchiut 1.16 // glrun->SetID(this->AssignRunID());
2131 mocchiut 1.13 //
2132     glrun->SetID_RUN_FRAG(glrun1->GetID());
2133 mocchiut 1.1 glrun->Fill_GL_RUN(conn);
2134     //
2135 mocchiut 1.16 // set id number
2136 mocchiut 1.1 //
2137 mocchiut 1.13 glrun1->SetID_RUN_FRAG(glrun->GetID());
2138 mocchiut 1.1 glrun1->Fill_GL_RUN(conn);
2139     //
2140     };
2141     //
2142 mocchiut 1.16 // delete old entries in fragment table
2143 mocchiut 1.1 //
2144 mocchiut 1.16 glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2145     glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2146 mocchiut 1.1 //
2147 mocchiut 1.16 delete glrun1;
2148 mocchiut 1.1 //
2149     return;
2150     //
2151     };
2152     //
2153     };
2154     //
2155     if ( !found ){
2156     //
2157     if ( IsDebug() ) printf(" not found, check if we have already processed the file \n ");
2158     //
2159     // not found, has this run already inserted in the GL_RUN or in the GL_RUN_FRAGMENTS table?
2160     //
2161     oss.str("");
2162     oss << " SELECT ID FROM GL_RUN WHERE "
2163     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
2164     << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
2165     << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
2166     << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
2167     << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2168     << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
2169     << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
2170     << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2171     << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
2172     << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
2173     << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2174     << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
2175     << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
2176     //
2177     if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
2178     result = conn->Query(oss.str().c_str());
2179     //
2180     if ( !result ) throw -4;
2181     //
2182     row = result->Next();
2183     //
2184 mocchiut 1.16 if ( row ){
2185     if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");
2186 mocchiut 1.1 } else {
2187 mocchiut 1.16 if ( NoFrag() ){
2188     glrun->SetID_RUN_FRAG(glrun->GetID());
2189     glrun->Fill_GL_RUN(conn);
2190     glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2191     };
2192 mocchiut 1.1 };
2193     };
2194     //
2195     return;
2196     };
2197    
2198    
2199     /**
2200     * Handle run without header or trailer
2201     **/
2202     void PamelaDBOperations::HandleMissingHoT(Bool_t mishead, Bool_t mistrail, UInt_t firstev, UInt_t lastev){
2203     //
2204     //
2205     // is the piece of run good (no other packets inside)?
2206     //
2207     if ( !this->IsRunConsistent(mishead,mistrail,firstev,lastev)){
2208     //
2209     // if not, handle other pieces and continue with the first one
2210     //
2211     if ( IsDebug() ) printf("The run is not consistent, it contains non-physics packets! The run has been handled \n");
2212     //
2213     } else {
2214     //
2215     this->FillClass(mishead,mistrail,firstev,lastev);
2216     //
2217 mocchiut 1.13 if ( !IsRunAlreadyInserted() ){
2218     glrun->SetID(this->AssignRunID());
2219     glrun->SetID_RUN_FRAG(0);
2220     glrun->Fill_GL_RUN(conn);
2221     };
2222 mocchiut 1.1 //
2223     };
2224     //
2225     return;
2226     };
2227    
2228     /**
2229     *
2230     * check if we have non-physics packets inside the run
2231     *
2232     */
2233     Bool_t PamelaDBOperations::IsRunConsistent(Bool_t mishead, Bool_t mistrail, UInt_t &firstev, UInt_t &lastev){
2234     //
2235     EventCounter *code=0;
2236     //
2237     UInt_t nevent = 0;
2238     UInt_t checkfirst = 0;
2239     UInt_t checklast = 0;
2240     UInt_t firstentry = 0;
2241     UInt_t lastentry = 0;
2242     UInt_t firstTime = 0;
2243     UInt_t lastTime = 0;
2244     UInt_t firstPkt = 0;
2245     UInt_t lastPkt = 0;
2246     UInt_t firstObt = 0;
2247     UInt_t lastObt = 0;
2248     //
2249     pcksList packetsNames;
2250     pcksList::iterator Iter;
2251     getPacketsNames(packetsNames);
2252     //
2253     TTree *T= 0;
2254     T =(TTree*)file->Get("Physics");
2255     if ( !T || T->IsZombie() ) throw -16;
2256     EventHeader *eh = 0;
2257     PscuHeader *ph = 0;
2258     T->SetBranchAddress("Header", &eh);
2259     nevent = T->GetEntries();
2260     //
2261     //
2262     if ( firstev == lastev+1 ) { // no events inside the run!
2263     if ( IsDebug() ) printf(" Checking but no events in the run! \n");
2264     // return true is correct
2265     return(true);
2266     //
2267     } else {
2268     //
2269     T->GetEntry(firstev);
2270     code = eh->GetCounter();
2271     checkfirst = 0;
2272     for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
2273     if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));
2274     };
2275     if ( IsDebug() ) printf(" Check first is %i firstev is %i\n",checkfirst,firstev);
2276     //
2277     T->GetEntry(lastev);
2278     code = eh->GetCounter();
2279     checklast = 0;
2280     for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
2281     if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));
2282     };
2283     if ( IsDebug() ) printf(" Check last is %i lastev is %i\n",checklast,lastev);
2284     //
2285     if ( checkfirst == checklast ){
2286     //
2287     if ( IsDebug() ) printf(" No packets but physics inside the run, I will consider it as good\n");
2288     //
2289     return(true);
2290     //
2291     } else {
2292     //
2293     if ( IsDebug() ) printf(" There are no-phyics packets inside the run!\n");
2294     //
2295     // HERE WE MUST HANDLE THAT RUNS AND GO BACK
2296     //
2297     if ( IsDebug() ) printf(" Never seen this case, try to handle it anyway, it was throw -95\n");
2298     //
2299     Bool_t emptyruns = false;
2300     UInt_t check = 0;
2301     UInt_t lastevtemp = lastev;
2302     UInt_t firstevno = firstev;
2303     //
2304     for (UInt_t i=firstev; i<=lastev; i++){
2305     //
2306     T->GetEntry(i);
2307     code = eh->GetCounter();
2308     //
2309     check = 0;
2310     //
2311     for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
2312     if ( strcmp(*Iter,"Physics") ) check += code->Get(GetPacketType(*Iter));
2313     };
2314     //
2315     if ( checkfirst < check || i == lastev ){
2316     //
2317     firstentry = firstevno;
2318     //
2319     if ( checkfirst < check ){
2320     lastentry = i-1;
2321     } else {
2322     lastentry = i;
2323     };
2324     //
2325     if ( IsDebug() ) printf(" Run between %i and %i entries\n",firstentry,lastentry);
2326     //
2327     glrun->SetEV_FROM(firstentry);
2328     glrun->SetEV_TO(lastentry);
2329     if ( lastentry == (firstentry-1) ){ // no physics packets inside physics run with no runheader no runtrailer
2330     if ( IsDebug() ) printf(" no physics packets inside physics run with no runheader no runtrailer\n");
2331     lastentry--;
2332     };
2333     glrun->SetNEVENTS(lastentry-firstentry+1);
2334     //
2335     glrun->Set_GL_RUNH0();
2336     glrun->Set_GL_RUNT0();
2337     //
2338     glrun->SetLAST_TIMESYNC(0);
2339     glrun->SetOBT_TIMESYNC(0);
2340     //
2341     T->GetEntry(firstentry);
2342     ph = eh->GetPscuHeader();
2343     firstObt = ph->GetOrbitalTime();
2344     firstTime = this->GetAbsTime(firstObt);
2345     firstPkt = ph->GetCounter();
2346     //
2347     T->GetEntry(lastentry);
2348     ph = eh->GetPscuHeader();
2349     lastObt = ph->GetOrbitalTime();
2350     lastTime = this->GetAbsTime(lastObt);
2351     lastPkt = ph->GetCounter();
2352     //
2353     glrun->SetRUNHEADER_PKT(firstPkt);
2354     glrun->SetRUNTRAILER_PKT(lastPkt);
2355     //
2356     glrun->SetRUNHEADER_OBT(firstObt);
2357     glrun->SetRUNTRAILER_OBT(lastObt);
2358     //
2359     if ( firstev == firstentry && !emptyruns && !mishead ){
2360     glrun->Set_GL_RUNH(runh,phh);
2361     firstTime = this->GetAbsTime(phh->GetOrbitalTime());
2362     if ( IsDebug() ) printf(" We have the runheader \n");
2363     };
2364     if ( lastev == i && !mistrail ){
2365     glrun->Set_GL_RUNT(runt,pht);
2366     lastTime = this->GetAbsTime(pht->GetOrbitalTime());
2367     if ( IsDebug() ) printf(" We have the runtrailer \n");
2368     };
2369     //
2370     if ( lastentry == (firstentry-2) ){ // no events in the run
2371     emptyruns = true;
2372     if ( IsDebug() ) printf(" No events in the run \n");
2373     lastTime = firstTime;
2374     if ( (UInt_t)firstTime == this->GetAbsTime(phh->GetOrbitalTime()) ){
2375     lastObt = glrun->RUNHEADER_OBT;
2376     lastPkt = glrun->RUNHEADER_PKT;
2377     } else {
2378     lastObt = firstObt;
2379     lastPkt = firstPkt;
2380     };
2381     glrun->SetRUNTRAILER_PKT(lastPkt);
2382     glrun->SetRUNTRAILER_OBT(lastObt);
2383     lastentry++;
2384     };
2385     //
2386     this->SetCommonGLRUN(firstTime,lastTime);
2387     //
2388 mocchiut 1.13 if ( !IsRunAlreadyInserted() ){
2389     glrun->SetID(this->AssignRunID());
2390     glrun->SetID_RUN_FRAG(0);
2391     glrun->Fill_GL_RUN(conn);
2392     };
2393 mocchiut 1.1 //
2394     firstevno = lastentry + 1;
2395     //
2396     checkfirst = check;
2397     //
2398     };
2399     //
2400     if ( check == checklast && i != lastev ){
2401     lastevtemp = i - 1;
2402     i = lastev - 1;
2403     };
2404     //
2405     };
2406     //
2407     lastev = lastevtemp;
2408     //
2409     return(false);
2410     //
2411     };
2412     };
2413     //
2414     return(false); // should never arrive here
2415     };
2416    
2417     /**
2418     *
2419     * 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
2420     * 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
2421     * looking for non-physics packets inside.
2422     *
2423     */
2424     void PamelaDBOperations::HandleSuspiciousRun(){
2425     //
2426     PacketType *pctp=0;
2427     EventCounter *codt=0;
2428     EventCounter *codh=0;
2429     EventCounter *code=0;
2430     UInt_t firstev = 0;
2431     UInt_t lastev = 0;
2432     UInt_t nevent = 0;
2433     UInt_t checkfirst = 0;
2434     UInt_t checklast = 0;
2435     UInt_t firstentry = 0;
2436     UInt_t lastentry = 0;
2437     UInt_t firstTime = 0;
2438     UInt_t lastTime = 0;
2439     UInt_t firstPkt = 0;
2440     UInt_t lastPkt = 0;
2441     UInt_t firstObt = 0;
2442     UInt_t lastObt = 0;
2443     //
2444     pcksList packetsNames;
2445     pcksList::iterator Iter;
2446     getPacketsNames(packetsNames);
2447     //
2448     TTree *rh=0;
2449     rh = (TTree*)file->Get("RunHeader");
2450     if ( !rh || rh->IsZombie() ) throw -17;
2451     TTree *T=0;
2452     T =(TTree*)file->Get("Physics");
2453     if ( !T || T->IsZombie() ) throw -16;
2454     EventHeader *eh = 0;
2455     PscuHeader *ph = 0;
2456     T->SetBranchAddress("Header", &eh);
2457     nevent = T->GetEntries();
2458     //
2459     codt = eht->GetCounter();
2460     codh = ehh->GetCounter();
2461     firstev = codh->Get(pctp->Physics);
2462     lastev = codt->Get(pctp->Physics)-1;
2463     //
2464     if ( firstev == lastev+1 ) { // no events inside the run!
2465     if ( IsDebug() ) printf(" Checking but no events in the run! \n");
2466     //
2467     this->FillClass();
2468 mocchiut 1.13 if ( !IsRunAlreadyInserted() ){
2469     glrun->SetID(this->AssignRunID());
2470     glrun->SetID_RUN_FRAG(0);
2471     glrun->Fill_GL_RUN(conn);
2472     };
2473 mocchiut 1.1 //
2474     } else {
2475     //
2476     UInt_t nrunh = 0;
2477     UInt_t nrunh1 = 0;
2478     T->GetEntry(firstev);
2479     code = eh->GetCounter();
2480     checkfirst = 0;
2481     for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
2482     if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));
2483     if ( !strcmp(*Iter,"RunHeader") ) nrunh1++;
2484     };
2485     if ( IsDebug() ) printf(" Check first is %i \n",checkfirst);
2486     //
2487     T->GetEntry(lastev);
2488     code = eh->GetCounter();
2489     checklast = 0;
2490     for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
2491     if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));
2492     };
2493     if ( IsDebug() ) printf(" Check last is %i \n",checklast);
2494     //
2495     if ( checkfirst == checklast ){
2496     //
2497     if ( IsDebug() ) printf(" No packets but physics inside the run, I will consider it as good\n");
2498     //
2499     this->FillClass();
2500 mocchiut 1.13 if ( !IsRunAlreadyInserted() ){
2501     glrun->SetID(this->AssignRunID());
2502     glrun->SetID_RUN_FRAG(0);
2503     glrun->Fill_GL_RUN(conn);
2504     };
2505 mocchiut 1.1 //
2506     } else {
2507     //
2508     if ( IsDebug() ) printf(" There are no-physics packets inside the run, try to separate runs \n");
2509     //
2510     Bool_t emptyruns = false;
2511     UInt_t check = 0;
2512     UInt_t firstevno = firstev;
2513     //
2514     for (UInt_t i=firstev; i<=lastev; i++){
2515     //
2516     T->GetEntry(i);
2517     code = eh->GetCounter();
2518     //
2519     check = 0;
2520     //
2521     for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
2522     if ( strcmp(*Iter,"Physics") ) check += code->Get(GetPacketType(*Iter));
2523     if ( !strcmp(*Iter,"RunHeader") ) nrunh++;
2524     };
2525     //
2526     if ( checkfirst < check || i == lastev ){
2527     //
2528     firstentry = firstevno;
2529     //
2530     if ( checkfirst < check ){
2531     lastentry = i-1;
2532     } else {
2533     lastentry = i;
2534     };
2535     //
2536     if ( IsDebug() ) printf(" Run between %i and %i entries\n",firstentry,lastentry);
2537     //
2538     glrun->SetEV_FROM(firstentry);
2539     glrun->SetEV_TO(lastentry);
2540     if ( lastentry == (firstentry-1) ){ // no physics packets inside physics run with no runheader no runtrailer
2541     if ( IsDebug() ) printf(" no physics packets inside physics run with no runheader no runtrailer\n");
2542     lastentry--;
2543     };
2544     glrun->SetNEVENTS(lastentry-firstentry+1);
2545     //
2546     glrun->Set_GL_RUNH0();
2547     glrun->Set_GL_RUNT0();
2548     //
2549     glrun->SetLAST_TIMESYNC(0);
2550     glrun->SetOBT_TIMESYNC(0);
2551     //
2552     T->GetEntry(firstentry);
2553     ph = eh->GetPscuHeader();
2554     firstObt = ph->GetOrbitalTime();
2555     firstTime = this->GetAbsTime(firstObt);
2556     firstPkt = ph->GetCounter();
2557     //
2558     T->GetEntry(lastentry);
2559     ph = eh->GetPscuHeader();
2560     lastObt = ph->GetOrbitalTime();
2561     lastTime = this->GetAbsTime(lastObt);
2562     lastPkt = ph->GetCounter();
2563     //
2564     glrun->SetRUNHEADER_PKT(firstPkt);
2565     glrun->SetRUNTRAILER_PKT(lastPkt);
2566     //
2567     glrun->SetRUNHEADER_OBT(firstObt);
2568     glrun->SetRUNTRAILER_OBT(lastObt);
2569     //
2570     if ( (firstev == firstentry && !emptyruns) || nrunh == (nrunh1 + 1) ){
2571     rh->GetEntry(nrunh1-1);
2572     phh = ehh->GetPscuHeader();
2573     nrunh1++;
2574     glrun->Set_GL_RUNH(runh,phh);
2575     firstTime = this->GetAbsTime(phh->GetOrbitalTime());
2576     if ( IsDebug() ) printf(" We have the runheader \n");
2577     };
2578     if ( lastev == i && checkfirst == check ){
2579     glrun->Set_GL_RUNT(runt,pht);
2580     lastTime = this->GetAbsTime(pht->GetOrbitalTime());
2581     if ( IsDebug() ) printf(" We have the runtrailer \n");
2582     };
2583     //
2584     if ( lastentry == (firstentry-2) ){ // no events in the run
2585     emptyruns = true;
2586     if ( IsDebug() ) printf(" No events in the run \n");
2587     lastTime = firstTime;
2588     if ( (UInt_t)firstTime == this->GetAbsTime(phh->GetOrbitalTime()) ){
2589     lastObt = glrun->RUNHEADER_OBT;
2590     lastPkt = glrun->RUNHEADER_PKT;
2591     } else {
2592     lastObt = firstObt;
2593     lastPkt = firstPkt;
2594     };
2595     glrun->SetRUNTRAILER_PKT(lastPkt);
2596     glrun->SetRUNTRAILER_OBT(lastObt);
2597     lastentry++;
2598     };
2599     //
2600     this->SetCommonGLRUN(firstTime,lastTime);
2601     //
2602 mocchiut 1.13 if ( !IsRunAlreadyInserted() ){
2603     glrun->SetID(this->AssignRunID());
2604     glrun->SetID_RUN_FRAG(0);
2605     glrun->Fill_GL_RUN(conn);
2606     };
2607 mocchiut 1.1 //
2608     if ( i == lastev && checkfirst < check ){ // if the last event gives a wrong check...
2609     //
2610     firstentry = i;
2611     //
2612     lastentry = i;
2613     //
2614     if ( IsDebug() ) printf(" Run between %i and %i entries\n",firstentry,lastentry);
2615     //
2616     glrun->SetEV_FROM(firstentry);
2617     glrun->SetEV_TO(lastentry);
2618     glrun->SetNEVENTS(lastentry-firstentry+1);
2619     //
2620     glrun->Set_GL_RUNH0();
2621     //
2622     glrun->SetLAST_TIMESYNC(0);
2623     glrun->SetOBT_TIMESYNC(0);
2624     //
2625     T->GetEntry(firstentry);
2626     ph = eh->GetPscuHeader();
2627     firstObt = ph->GetOrbitalTime();
2628     firstTime = this->GetAbsTime(firstObt);
2629     firstPkt = ph->GetCounter();
2630     //
2631     glrun->SetRUNHEADER_PKT(firstPkt);
2632     //
2633     glrun->SetRUNHEADER_OBT(firstObt);
2634     //
2635     glrun->Set_GL_RUNT(runt,pht);
2636     lastTime = this->GetAbsTime(pht->GetOrbitalTime());
2637     if ( IsDebug() ) printf(" We have the runtrailer \n");
2638     //
2639     this->SetCommonGLRUN(firstTime,lastTime);
2640     //
2641 mocchiut 1.13 if ( !IsRunAlreadyInserted() ){
2642     glrun->SetID(this->AssignRunID());
2643     glrun->SetID_RUN_FRAG(0);
2644     glrun->Fill_GL_RUN(conn);
2645     };
2646 mocchiut 1.1 };
2647     //
2648     firstevno = lastentry + 1;
2649     //
2650     checkfirst = check;
2651     //
2652     };
2653     //
2654     if ( check == checklast && i != lastev ) i = lastev - 1; // >>>>>>>>>>>>>>>>>>>>>>
2655     //
2656     };
2657     };
2658     };
2659     //
2660     return;
2661     };
2662    
2663    
2664     /**
2665     * Scan calorimeter calibrations packets, fill the GL_CALO_CALIB table
2666     */
2667     Int_t PamelaDBOperations::insertCALO_CALIB(){
2668     //
2669     TSQLResult *result = 0;
2670     TSQLRow *row = 0;
2671     //
2672     stringstream oss;
2673     oss.str("");
2674     //
2675     CalibCalPedEvent *calibCalPed = 0;
2676     TTree *tr = 0;
2677     EventHeader *eh = 0;
2678     PscuHeader *ph = 0;
2679     //
2680     UInt_t nevents = 0;
2681     UInt_t fromtime = 0;
2682     UInt_t totime = 0;
2683     UInt_t obt = 0;
2684     UInt_t pkt = 0;
2685     //
2686     tr = (TTree*)file->Get("CalibCalPed");
2687     if ( !tr || tr->IsZombie() ) throw -21;
2688     //
2689     tr->SetBranchAddress("CalibCalPed", &calibCalPed);
2690     tr->SetBranchAddress("Header", &eh);
2691     nevents = tr->GetEntries();
2692     //
2693 mocchiut 1.2 if ( !nevents ) return(1);
2694 mocchiut 1.1 //
2695     for (UInt_t i=0; i < nevents; i++){
2696     tr->GetEntry(i);
2697     for (UInt_t section = 0; section < 4; section++){
2698     //
2699     if ( calibCalPed->cstwerr[section] ){
2700     valid = 1;
2701     if ( calibCalPed->cperror[section] ) valid = 0;
2702     ph = eh->GetPscuHeader();
2703     obt = ph->GetOrbitalTime();
2704     pkt = ph->GetCounter();
2705     fromtime = this->GetAbsTime(ph->GetOrbitalTime());
2706     if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->OBT(obt) >= this->OBT(obtfirst) ){
2707     //
2708     if ( IsDebug() ) printf(" Calo calibration for section %i at time %i obt %i pkt %i \n",section,fromtime,obt,pkt);
2709     //
2710     // check if the calibration has already been inserted
2711     //
2712     oss.str("");
2713     oss << " SELECT ID FROM GL_CALO_CALIB WHERE "
2714     << " SECTION = "<< section << " AND "
2715     << " BOOT_NUMBER = "<< this->GetBOOTnumber() << " AND "
2716     << " OBT = "<< obt << " AND "
2717     << " PKT = "<< pkt << ";";
2718     //
2719     if ( IsDebug() ) printf(" Check if the calo calibration has already been inserted: query is \n %s \n",oss.str().c_str());
2720     result = conn->Query(oss.str().c_str());
2721     //
2722     if ( !result ) throw -4;
2723     //
2724     row = result->Next();
2725     //
2726     if ( row ){
2727     //
2728     if ( IsDebug() ) printf(" Calo calibration already inserted in the DB\n");
2729     //
2730     } else {
2731     //
2732     // we have to insert a new calibration, check where to place it
2733     //
2734     oss.str("");
2735     oss << " SELECT ID,TO_TIME FROM GL_CALO_CALIB WHERE "
2736     << " SECTION = "<< section << " AND "
2737     << " FROM_TIME < "<< fromtime << " AND "
2738     << " TO_TIME > "<< fromtime << ";";
2739     //
2740     if ( IsDebug() ) printf(" Check where to place the calo calibration: query is \n %s \n",oss.str().c_str());
2741     result = conn->Query(oss.str().c_str());
2742     //
2743     if ( !result ) throw -4;
2744     //
2745     row = result->Next();
2746     //
2747     if ( !row ){
2748     //
2749     // no calibrations in the db contain our calibration
2750     //
2751     if ( IsDebug() ) printf(" Calibration with fromtime lower than others to be inserted in the DB for section %i \n",section);
2752 mocchiut 1.19 if ( fromtime < 1150871000 ){ //1150866904
2753 mocchiut 1.1 if ( IsDebug() ) printf(" First PAMELA flight calibration at time %i \n",fromtime);
2754     fromtime = 0;// the first flight calibration was taken at about 1156429100 s, this line allow to analyze first runs in raw mode
2755     };
2756     //
2757     oss.str("");
2758     oss << " SELECT FROM_TIME FROM GL_CALO_CALIB WHERE "
2759     << " SECTION = "<< section << " AND "
2760     << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";
2761     //
2762     if ( IsDebug() ) printf(" Check the upper limit for calibration: query is \n %s \n",oss.str().c_str());
2763     result = conn->Query(oss.str().c_str());
2764     //
2765     if ( !result ) throw -4;
2766     //
2767     row = result->Next();
2768     if ( !row ){
2769     totime = numeric_limits<UInt_t>::max();
2770     } else {
2771     totime = (UInt_t)atoll(row->GetField(0));
2772     };
2773     //
2774     } else {
2775     //
2776     // determine upper and lower limits and make space for the new calibration
2777     //
2778     totime = (UInt_t)atoll(row->GetField(1));
2779     //
2780     oss.str("");
2781     oss << " UPDATE GL_CALO_CALIB SET "
2782     << " TO_TIME = "<< fromtime << " WHERE " // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[
2783     << " ID = "<< row->GetField(0) << ";";
2784     //
2785     if ( IsDebug() ) printf(" Make space for the new calibration: query is \n %s \n",oss.str().c_str());
2786     result = conn->Query(oss.str().c_str());
2787     //
2788     if ( !result ) throw -4;
2789     //
2790     };
2791     //
2792     oss.str("");
2793     oss << " INSERT INTO GL_CALO_CALIB (ID,ID_ROOT_L0,EV_ROOT,FROM_TIME,TO_TIME,SECTION,OBT,PKT,BOOT_NUMBER,VALIDATION) "
2794     << " VALUES (NULL,' "
2795     << idroot << "','"
2796     << i << "','"
2797     << fromtime << "','"
2798     << totime << "','"
2799     << section << "','"
2800     << obt << "','"
2801     << pkt << "','"
2802     << this->GetBOOTnumber() << "','"
2803     << valid << "');";
2804     //
2805     if ( IsDebug() ) printf(" Insert the new calibration: query is \n %s \n",oss.str().c_str());
2806     //
2807     result = conn->Query(oss.str().c_str());
2808     //
2809     if ( !result ) throw -4;
2810     //
2811     };
2812     //
2813     } else {
2814     //
2815     if ( IsDebug() ) printf(" Repetead calo calibration for section %i at time %i obt %i pkt %i \n",section,fromtime,obt,pkt);
2816     //
2817     };
2818     //
2819     };
2820     };
2821     };
2822     //
2823     return(0);
2824     };
2825    
2826     /**
2827     * Fill the GL_TRK_CALIB table
2828     */
2829     void PamelaDBOperations::HandleTRK_CALIB(Bool_t pk1, Bool_t pk2){
2830     //
2831     TSQLResult *result = 0;
2832     TSQLRow *row = 0;
2833     //
2834     stringstream oss;
2835     oss.str("");
2836     //
2837     UInt_t totime = 0;
2838     //
2839     if ( !pk1 && !pk2 ){
2840     if ( IsDebug() ) printf(" Cannot handle trk calibration with both packet missing!\n");
2841     };
2842     //
2843     // check if the calibration has already been inserted
2844     //
2845     oss.str("");
2846     oss << " SELECT ID FROM GL_TRK_CALIB WHERE "
2847     << " BOOT_NUMBER = "<< this->GetBOOTnumber(); //
2848     oss << " AND ( ( ";
2849     if ( pk1 ){
2850     oss << " OBT1 = "<< obt1 << " AND "
2851     << " PKT1 = "<< pkt1
2852     << " ) OR ( ";
2853     } else {
2854     oss << " PKT1 = "<< pkt2-1
2855     << " ) OR ( ";
2856     };
2857     if ( pk2 ){
2858     oss << " OBT2 = "<< obt2 << " AND "
2859     << " PKT2 = "<< pkt2;
2860     } else {
2861     oss << " PKT2 = "<< pkt1+1;
2862     };
2863     oss << " ) );";
2864     //
2865     if ( IsDebug() ) printf(" Check if the trk calibration has already been inserted: query is \n %s \n",oss.str().c_str());
2866     result = conn->Query(oss.str().c_str());
2867     //
2868     if ( !result ) throw -4;
2869     //
2870     row = result->Next();
2871     //
2872     if ( row ){
2873     //
2874     if ( IsDebug() ) printf(" Trk calibration already inserted in the DB\n");
2875     //
2876     } else {
2877     //
2878     // we have to insert a new calibration, check where to place it
2879     //
2880     oss.str("");
2881     oss << " SELECT ID,TO_TIME FROM GL_TRK_CALIB WHERE "
2882     << " FROM_TIME < "<< fromtime << " AND "
2883     << " TO_TIME > "<< fromtime << ";";
2884     //
2885     if ( IsDebug() ) printf(" Check where to place the trk calibration: query is \n %s \n",oss.str().c_str());
2886     result = conn->Query(oss.str().c_str());
2887     //
2888     if ( !result ) throw -4;
2889     //
2890     row = result->Next();
2891     //
2892     if ( !row ){
2893     //
2894     // no calibrations in the db contain our calibration
2895     //
2896     if ( IsDebug() ) printf(" Calibration with fromtime lower than others to be inserted in the DB\n");
2897 mocchiut 1.19 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
2898 mocchiut 1.1 //
2899     oss.str("");
2900     oss << " SELECT FROM_TIME FROM GL_TRK_CALIB WHERE "
2901     << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";
2902     //
2903     if ( IsDebug() ) printf(" Check the upper limit for calibration: query is \n %s \n",oss.str().c_str());
2904     result = conn->Query(oss.str().c_str());
2905     //
2906     if ( !result ) throw -4;
2907     //
2908     row = result->Next();
2909     if ( !row ){
2910     totime = numeric_limits<UInt_t>::max();
2911     } else {
2912     totime = (UInt_t)atoll(row->GetField(0));
2913     };
2914     //
2915     } else {
2916     //
2917     // determine upper and lower limits and make space for the new calibration
2918     //
2919     totime = (UInt_t)atoll(row->GetField(1));
2920     //
2921     oss.str("");
2922     oss << " UPDATE GL_TRK_CALIB SET "
2923     << " TO_TIME = "<< fromtime << " WHERE " // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[
2924     << " ID = "<< row->GetField(0) << ";";
2925     //
2926     if ( IsDebug() ) printf(" Make space for the new trk calibration: query is \n %s \n",oss.str().c_str());
2927     result = conn->Query(oss.str().c_str());
2928     //
2929     if ( !result ) throw -4;
2930     //
2931     };
2932     //
2933     oss.str("");
2934     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) "
2935     << " VALUES (NULL,' "
2936     << idroot << "',";
2937     //
2938     if ( !pk1 ){
2939     oss << "NULL,";
2940     } else {
2941     oss << "'"
2942     << t1 << "',";
2943     };
2944     //
2945     if ( !pk2 ){
2946     oss << "NULL,'";
2947     } else {
2948     oss << "'"
2949     << t2 << "','";
2950     };
2951     //
2952     oss << fromtime << "','"
2953     << totime << "','"
2954     << obt1 << "','"
2955     << pkt1 << "','"
2956     << obt2 << "','"
2957     << pkt2 << "','"
2958     << this->GetBOOTnumber() << "','"
2959     << valid << "');";
2960     //
2961     if ( IsDebug() ) printf(" Insert the new trk calibration: query is \n %s \n",oss.str().c_str());
2962     //
2963     result = conn->Query(oss.str().c_str());
2964     //
2965     if ( !result ) throw -4;
2966     //
2967     };
2968     //
2969     };
2970    
2971     /**
2972     * Scan tracker calibrations packets, fill the GL_TRK_CALIB table
2973     */
2974     Int_t PamelaDBOperations::insertTRK_CALIB(){
2975     //
2976     CalibTrk1Event *caltrk1 = 0;
2977     CalibTrk2Event *caltrk2 = 0;
2978     TTree *tr1 = 0;
2979     TTree *tr2 = 0;
2980     EventHeader *eh1 = 0;
2981     PscuHeader *ph1 = 0;
2982     EventHeader *eh2 = 0;
2983     PscuHeader *ph2 = 0;
2984     //
2985     PacketType *pctp=0;
2986     EventCounter *codt2=0;
2987     //
2988     Int_t nevents1 = 0;
2989     Int_t nevents2 = 0;
2990     //
2991     fromtime = 0;
2992     //
2993     obt1 = 0;
2994     pkt1 = 0;
2995     obt2 = 0;
2996     pkt2 = 0;
2997     //
2998     tr1 = (TTree*)file->Get("CalibTrk1");
2999     if ( !tr1 || tr1->IsZombie() ) throw -22;
3000     tr2 = (TTree*)file->Get("CalibTrk2");
3001     if ( !tr2 || tr2->IsZombie() ) throw -23;
3002     //
3003     tr1->SetBranchAddress("CalibTrk1", &caltrk1);
3004     tr1->SetBranchAddress("Header", &eh1);
3005     nevents1 = tr1->GetEntries();
3006     tr2->SetBranchAddress("CalibTrk2", &caltrk2);
3007     tr2->SetBranchAddress("Header", &eh2);
3008     nevents2 = tr2->GetEntries();
3009     //
3010 mocchiut 1.2 if ( !nevents1 && !nevents2 ) return(1);
3011 mocchiut 1.1 //
3012     t2 = -1;
3013     Int_t pret2 = 0;
3014     Int_t t2t1cal = 0;
3015     //
3016     for (t1=0; t1 < nevents1; t1++){
3017     //
3018     pret2 = t2;
3019     tr1->GetEntry(t1);
3020     //
3021     ph1 = eh1->GetPscuHeader();
3022     obt1 = ph1->GetOrbitalTime();
3023     pkt1 = ph1->GetCounter();
3024     fromtime = this->GetAbsTime(ph1->GetOrbitalTime());
3025     //
3026     valid = 1;
3027     //
3028     if ( caltrk1->unpackError != 0 && caltrk1->good0 == 0 ) valid = 0;// CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT1
3029     //
3030     //
3031     if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->OBT(obt1) >= this->OBT(obtfirst) ){
3032     //
3033     if ( IsDebug() ) printf(" Trk calibration1 at time %i obt %i pkt %i \n",fromtime,obt1,pkt1);
3034     //
3035     // Do we have the second calibration packet?
3036     //
3037     while ( t2t1cal < t1+1 ){ // get the calibration packet2 that follows the packet1
3038     //
3039     t2++;
3040     //
3041     if ( t2 < nevents2 ){
3042     tr2->GetEntry(t2);
3043     codt2 = eh2->GetCounter();
3044     t2t1cal = codt2->Get(pctp->CalibTrk1);
3045     //
3046     ph2 = eh2->GetPscuHeader();
3047     obt2 = ph2->GetOrbitalTime();
3048     pkt2 = ph2->GetCounter();
3049     //
3050     if ( caltrk2->unpackError != 0 || caltrk2->good0 == 0 ) valid = 0; // CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT2
3051     //
3052     } else {
3053     //
3054     // running out of vector without finding the corresponding calibration, sig
3055     //
3056     pret2 = t2;
3057     obt2 = 0;
3058     pkt2 = pkt1+2;
3059     t2t1cal = t1+1;
3060     };
3061     if ( this->PKT(pkt2) < this->PKT(pktfirst) && this->OBT(obt2) < this->OBT(obtfirst) ){
3062     //
3063     // running out of vector without finding the corresponding calibration, sig
3064     //
3065     pret2 = t2;
3066     obt2 = 0;
3067     pkt2 = pkt1+2;
3068     t2t1cal = t1+1;
3069     };
3070     //
3071     };
3072     //
3073     if ( IsDebug() ) printf(" Found trk calibration2 at obt %i pkt %i t2 is %i \n",obt2,pkt2,t2);
3074     //
3075     // The calibration is good
3076     //
3077     if ( this->PKT(pkt2) == this->PKT(pkt1)+1 ){
3078     //
3079     if ( IsDebug() ) printf(" The trk calibration2 at obt %i pkt %i t2 is %i is good \n",obt2,pkt2,t2);
3080     //
3081     // Handle good calib
3082     //
3083     this->HandleTRK_CALIB(true,true);
3084     //
3085     // Check for missing calibtrk1
3086     //
3087     if ( t2 != pret2+1 ){
3088     //
3089     if ( IsDebug() ) printf(" Missing the trk calibration1! Next one at obt %i pkt %i t2 is %i pret2 is %i \n",obt2,pkt2,t2,pret2);
3090     //
3091     while ( t2 > pret2+1 ){
3092     //
3093     // handle missing calib1
3094     //
3095     pret2++;
3096     //
3097     obt1 = 0;
3098     pkt1 = 0;
3099     //
3100     tr2->GetEntry(pret2);
3101     ph2 = eh2->GetPscuHeader();
3102     obt2 = ph2->GetOrbitalTime();
3103     pkt2 = ph2->GetCounter();
3104     //
3105     fromtime = this->GetAbsTime(ph2->GetOrbitalTime());
3106     //
3107     valid = 0;
3108     this->HandleTRK_CALIB(false,true);
3109     //
3110     };
3111     //
3112     };
3113     //
3114     } else if ( this->PKT(pkt2) > this->PKT(pkt1)+1 ){
3115     //
3116     // Check for missing calibtrk2
3117     //
3118     if ( IsDebug() ) printf(" Missing the trk calibration2! Next one at obt %i pkt %i t2 is %i\n",obt2,pkt2,t2);
3119     t2 = pret2;
3120     //
3121     // handle missing calib2
3122     //
3123     obt2 = 0;
3124     pkt2 = 0;
3125     valid = 0;
3126     this->HandleTRK_CALIB(true,false);
3127     //
3128     };
3129     //
3130     } else {
3131     //
3132     if ( IsDebug() ) printf(" Repetead trk calibration1 at time %i obt %i pkt %i \n",fromtime,obt1,pkt1);
3133     //
3134     };
3135     //
3136     };
3137     //
3138     // we have one more calib pkt2 !
3139     //
3140     t2++;
3141     while ( t2 < nevents2 ){
3142     //
3143     // handle missing calib1
3144     //
3145     obt1 = 0;
3146     pkt1 = 0;
3147     //
3148     tr2->GetEntry(t2);
3149     ph2 = eh2->GetPscuHeader();
3150     obt2 = ph2->GetOrbitalTime();
3151     pkt2 = ph2->GetCounter();
3152     //
3153     fromtime = this->GetAbsTime(ph2->GetOrbitalTime());
3154     valid = 0;
3155     if ( this->PKT(pkt2) > this->PKT(pktfirst) || this->OBT(obt2) > this->OBT(obtfirst) ){
3156     //
3157     if ( IsDebug() ) printf(" Missing the trk calibration1! Next one at obt %i pkt %i t2 is %i\n",obt2,pkt2,t2);
3158     //
3159     this->HandleTRK_CALIB(false,true);
3160     //
3161     };
3162     //
3163     t2++;
3164     //
3165     };
3166     //
3167     return(0);
3168     };
3169    
3170    
3171     /**
3172     * Scan S4 calibrations packets, fill the GL_S4_CALIB table
3173     */
3174     Int_t PamelaDBOperations::insertS4_CALIB(){
3175     //
3176     TSQLResult *result = 0;
3177     TSQLRow *row = 0;
3178     //
3179     stringstream oss;
3180     oss.str("");
3181     //
3182     TTree *tr = 0;
3183     EventHeader *eh = 0;
3184     PscuHeader *ph = 0;
3185     //
3186     UInt_t nevents = 0;
3187     UInt_t fromtime = 0;
3188     UInt_t totime = 0;
3189     UInt_t obt = 0;
3190     UInt_t pkt = 0;
3191     //
3192     tr = (TTree*)file->Get("CalibS4");
3193     if ( !tr || tr->IsZombie() ) throw -24;
3194     //
3195     tr->SetBranchAddress("Header", &eh);
3196     //
3197     nevents = tr->GetEntries();
3198     //
3199 mocchiut 1.2 if ( !nevents ) return(1);
3200 mocchiut 1.1 //
3201     for (UInt_t i = 0; i < nevents; i++){
3202     //
3203     tr->GetEntry(i);
3204     //
3205     ph = eh->GetPscuHeader();
3206     obt = ph->GetOrbitalTime();
3207     pkt = ph->GetCounter();
3208     fromtime = this->GetAbsTime(ph->GetOrbitalTime());
3209     if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->OBT(obt) >= this->OBT(obtfirst) ){
3210     //
3211     if ( IsDebug() ) printf(" S4 calibration at time %i obt %i pkt %i \n",fromtime,obt,pkt);
3212     //
3213     // check if the calibration has already been inserted
3214     //
3215     oss.str("");
3216     oss << " SELECT ID FROM GL_S4_CALIB WHERE "
3217     << " BOOT_NUMBER = "<< this->GetBOOTnumber() << " AND "
3218     << " OBT = "<< obt << " AND "
3219     << " PKT = "<< pkt << ";";
3220     //
3221     if ( IsDebug() ) printf(" Check if the S4 calibration has already been inserted: query is \n %s \n",oss.str().c_str());
3222     result = conn->Query(oss.str().c_str());
3223     //
3224     if ( !result ) throw -4;
3225     //
3226     row = result->Next();
3227     //
3228     if ( row ){
3229     //
3230     if ( IsDebug() ) printf(" S4 calibration already inserted in the DB\n");
3231     //
3232     } else {
3233     //
3234     // we have to insert a new calibration, check where to place it
3235     //
3236     oss.str("");
3237     oss << " SELECT ID,TO_TIME FROM GL_S4_CALIB WHERE "
3238     << " FROM_TIME < "<< fromtime << " AND "
3239     << " TO_TIME > "<< fromtime << ";";
3240     //
3241     if ( IsDebug() ) printf(" Check where to place the S4 calibration: query is \n %s \n",oss.str().c_str());
3242     result = conn->Query(oss.str().c_str());
3243     //
3244     if ( !result ) throw -4;
3245     //
3246     row = result->Next();
3247     //
3248     if ( !row ){
3249     //
3250     // no calibrations in the db contain our calibration
3251     //
3252     if ( IsDebug() ) printf(" Calibration with fromtime lower than others to be inserted in the DB \n");
3253 mocchiut 1.19 if ( fromtime < 1150871000 ){
3254 mocchiut 1.1 if ( IsDebug() ) printf(" First PAMELA flight calibration at time %i \n",fromtime);
3255     fromtime = 0;// the first flight calibration was taken at about 1156429100 s, this line allow to analyze first runs in raw mode
3256     };
3257     //
3258     oss.str("");
3259     oss << " SELECT FROM_TIME FROM GL_S4_CALIB WHERE "
3260     << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";
3261     //
3262     if ( IsDebug() ) printf(" Check the upper limit for calibration: query is \n %s \n",oss.str().c_str());
3263     result = conn->Query(oss.str().c_str());
3264     //
3265     if ( !result ) throw -4;
3266     //
3267     row = result->Next();
3268     if ( !row ){
3269     totime = numeric_limits<UInt_t>::max();
3270     } else {
3271     totime = (UInt_t)atoll(row->GetField(0));
3272     };
3273     //
3274     } else {
3275     //
3276     // determine upper and lower limits and make space for the new calibration
3277     //
3278     totime = (UInt_t)atoll(row->GetField(1));
3279     //
3280     oss.str("");
3281     oss << " UPDATE GL_S4_CALIB SET "
3282     << " TO_TIME = "<< fromtime << " WHERE " // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[
3283     << " ID = "<< row->GetField(0) << ";";
3284     //
3285     if ( IsDebug() ) printf(" Make space for the new calibration: query is \n %s \n",oss.str().c_str());
3286     result = conn->Query(oss.str().c_str());
3287     //
3288     if ( !result ) throw -4;
3289     //
3290     };
3291     //
3292     oss.str("");
3293 mocchiut 1.2 oss << " INSERT INTO GL_S4_CALIB (ID,ID_ROOT_L0,EV_ROOT,FROM_TIME,TO_TIME,OBT,PKT,BOOT_NUMBER) "
3294 mocchiut 1.1 << " VALUES (NULL,' "
3295     << idroot << "','"
3296     << i << "','"
3297     << fromtime << "','"
3298     << totime << "','"
3299     << obt << "','"
3300     << pkt << "','"
3301 mocchiut 1.2 << this->GetBOOTnumber() << "');";
3302 mocchiut 1.1 //
3303     if ( IsDebug() ) printf(" Insert the new calibration: query is \n %s \n",oss.str().c_str());
3304     //
3305     result = conn->Query(oss.str().c_str());
3306     //
3307     if ( !result ) throw -4;
3308     //
3309     };
3310     //
3311     } else {
3312     //
3313     if ( IsDebug() ) printf(" Repetead S4 calibration at time %i obt %i pkt %i \n",fromtime,obt,pkt);
3314     //
3315     };
3316     //
3317     };
3318     //
3319     return(0);
3320     };
3321    
3322 mocchiut 1.2 /**
3323     * Scan the fragment table and move old fragments to the GL_RUN table
3324 mocchiut 1.1 */
3325 mocchiut 1.2 Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(){
3326 mocchiut 1.16 return(this->CleanGL_RUN_FRAGMENTS(""));
3327     };
3328    
3329     /**
3330     * Scan the fragment table and move old fragments to the GL_RUN table
3331     */
3332     Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(TString fcleanfile){
3333 mocchiut 1.2 //
3334     TSQLResult *result = 0;
3335     TSQLRow *row = 0;
3336     TSQLResult *result2 = 0;
3337     TSQLRow *row2 = 0;
3338     //
3339     UInt_t moved = 0;
3340     //
3341     stringstream oss;
3342     oss.str("");
3343     //
3344 mocchiut 1.16 if ( !strcmp(fcleanfile.Data(),"") ){
3345     //
3346     // check if there are entries older than "olderthan" seconds from now
3347     //
3348     oss.str("");
3349     oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"
3350     << " INSERT_TIME <= '" << clean_time->AsSQLString() << "';";
3351     //
3352     if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS runs older than %s : query is \n %s \n",clean_time->AsSQLString(),oss.str().c_str());
3353     result = conn->Query(oss.str().c_str());
3354     //
3355     } else {
3356     oss.str("");
3357     oss << " SELECT ID FROM GL_ROOT WHERE NAME='" << fcleanfile.Data() << "';";
3358     if ( IsDebug() ) printf(" Getting ID_ROOT_L0 query %s \n",oss.str().c_str());
3359     result = conn->Query(oss.str().c_str());
3360     //
3361     if ( result ){
3362     //
3363     row = result->Next();
3364     //
3365     if ( row ){
3366     oss.str("");
3367     oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"
3368     << " ID_ROOT_L0=" << row->GetField(0) << ";";
3369     //
3370     if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS for ROOT file query is \n %s \n",oss.str().c_str());
3371     result = conn->Query(oss.str().c_str());
3372     //
3373     };
3374     } else {
3375     return(2);
3376     };
3377     };
3378 mocchiut 1.2 //
3379     if ( result ){
3380     //
3381     row = result->Next();
3382     //
3383 mocchiut 1.12 while ( row ){
3384 mocchiut 1.2 //
3385     oss.str("");
3386     oss << " ID= "<< row->GetField(0);
3387     //
3388     glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);
3389     //
3390     oss.str("");
3391     oss << " SELECT ID,NEVENTS,TRK_CALIB_USED,PKT_COUNTER FROM GL_RUN WHERE "
3392     << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND ("
3393     << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3394     << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3395     << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3396     << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3397     << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3398     << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3399     << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3400     << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3401     << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3402     << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3403     << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3404     << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3405     //
3406     if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3407     result2 = conn->Query(oss.str().c_str());
3408     //
3409     if ( !result2 ) throw -4;
3410     //
3411     row2 = result2->Next();
3412     //
3413     if ( !row2 ){
3414     //
3415     if ( IsDebug() ) printf(" The run is new \n");
3416     if ( IsDebug() ) printf(" -> fill the DB \n");
3417     //
3418 mocchiut 1.13 // glrun->SetID(this->AssignRunID()); we use the old run number!
3419     glrun->SetID_RUN_FRAG(glrun->GetID());
3420 mocchiut 1.2 glrun->Fill_GL_RUN(conn);
3421     //
3422 mocchiut 1.13 // oss.str("");
3423     // oss << " SELECT ID FROM GL_RUN WHERE "
3424     // << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "
3425     // << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "
3426     // << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "
3427     // << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "
3428     // << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";
3429     // //
3430     // if ( IsDebug() ) printf(" Look for the ID of the inserted run: query is \n %s \n",oss.str().c_str());
3431     // result2 = conn->Query(oss.str().c_str());
3432     // //
3433     // if ( !result2 ) throw -4;
3434     // //
3435     // row2 = result2->Next();
3436     // //
3437     // if ( !row2 ) throw -25;
3438     // //
3439     // oss.str("");
3440     // oss << " UPDATE GL_RUN SET ID_RUN_FRAG = " << row2->GetField(0) << " WHERE ID = " << row2->GetField(0);
3441     // if ( IsDebug() ) printf(" Update the ID_RUN_FRAG of the inserted run: query is \n %s \n",oss.str().c_str());
3442     // result2 = conn->Query(oss.str().c_str());
3443     // //
3444     // if ( !result2 ) throw -4;
3445 mocchiut 1.2 //
3446     moved++;
3447     //
3448     } else {
3449     if ( IsDebug() ) printf(" The already exist in the GL_RUN table! \n");
3450 mocchiut 1.1 };
3451 mocchiut 1.2 if ( IsDebug() ) printf(" Delete run %s from the GL_RUN_FRAGMENTS table \n",row->GetField(0));
3452     //
3453     //
3454 mocchiut 1.15 glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3455     // oss.str("");
3456     // oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);
3457     // if ( IsDebug() ) printf(" Clean the GL_RUN_FRAGMENTS table: query is \n %s \n",oss.str().c_str());
3458     // result2 = conn->Query(oss.str().c_str());
3459     // //
3460     // if ( !result2 ) throw -4;
3461     // //
3462 mocchiut 1.12 row = result->Next();
3463 mocchiut 1.1 };
3464     };
3465 mocchiut 1.2 if ( IsDebug() ) printf(" Moved %u runs\n",moved);
3466     return(0);
3467     };
3468 mocchiut 1.1
3469 mocchiut 1.2 /**
3470     * Check if runs are good, i.e. if the tracker calibration is correctly associated..
3471     */
3472     Int_t PamelaDBOperations::ValidateRuns(){
3473 mocchiut 1.16 return(this->ValidateRuns(""));
3474     };
3475    
3476     /**
3477     * Check if runs are good, i.e. if the tracker calibration is correctly associated..
3478     */
3479     Int_t PamelaDBOperations::ValidateRuns(TString valfile){
3480 mocchiut 1.2 //
3481     TSQLResult *result = 0;
3482 pam-fi 1.5 TSQLRow *row = 0;
3483 mocchiut 1.2 //
3484 mocchiut 1.16 UInt_t calibtime = 50;
3485     //
3486 mocchiut 1.2 stringstream oss;
3487     oss.str("");
3488     //
3489 pam-fi 1.5 // =======================================================
3490     // validate runs by checking missing calibrations
3491     // =======================================================
3492     UInt_t t_stop = 0;
3493     UInt_t t_start = 0;
3494 mocchiut 1.16 if ( !strcmp(valfile.Data(),"") ) {
3495     // --------------------------------------------------------------
3496     // 1) get the OBT of the last run inserted after clean-time limit
3497     // --------------------------------------------------------------
3498     oss.str("");
3499     oss << " SELECT * FROM GL_RUN WHERE INSERT_TIME <= '" << clean_time->AsSQLString()
3500     << "' ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
3501     if ( IsDebug() ) printf(" Get start validation-time: query is \n %s \n",oss.str().c_str());
3502     result = conn->Query(oss.str().c_str());
3503     if ( !result ) throw -4;
3504     if ( !result->GetRowCount() ) {
3505     printf(" No runs to validate \n");
3506     return(1);
3507     }else{
3508     row = result->Next();
3509     t_start = (UInt_t)atoll(row->GetField(4));
3510     };
3511     // --------------------------------------------------------------
3512     // 2) get the OBT of the last validated run
3513     // --------------------------------------------------------------
3514     oss.str("");
3515     oss << " SELECT * FROM GL_RUN WHERE VALIDATION=1 AND RUNHEADER_TIME<="<< t_start
3516     <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
3517     if ( IsDebug() ) printf(" Get stop validation-time: query is \n %s \n",oss.str().c_str());
3518     result = conn->Query(oss.str().c_str());
3519     if ( !result ) throw -4;
3520     if ( result->GetRowCount() ){
3521     row = result->Next();
3522     t_stop = (UInt_t)atoll(row->GetField(4));
3523     };
3524     if ( IsDebug() ) printf("Validation interval: from time %i - to time %i \n\n",t_stop,t_start);
3525     // --------------------------------------------------------------
3526     // now retrieves runs to be validated
3527     // --------------------------------------------------------------
3528     oss.str("");
3529     oss << " SELECT * FROM GL_RUN WHERE RUNHEADER_TIME <=" << t_start;
3530     oss << " AND RUNHEADER_TIME >="<< t_stop;
3531     oss << " ORDER BY RUNHEADER_TIME DESC;";
3532     if ( IsDebug() )printf(" Check runs for validation: query is \n %s \n",oss.str().c_str());
3533     result = conn->Query(oss.str().c_str());
3534     } else {
3535     //
3536     stringstream myquery;
3537     UInt_t myid = 0;
3538     myquery.str("");
3539     myquery << " SELECT ID FROM GL_ROOT where NAME='"<<valfile.Data() <<"';";
3540     //
3541     result = conn->Query(myquery.str().c_str());
3542     //
3543     row = result->Next();
3544     if( !row ){
3545     if ( strcmp(valfile.Data(),GetRootName().Data()) ){
3546     if ( IsDebug() ) printf(" No file to be validated even if option \"-validate file\" was used!!\n");
3547     return(2);
3548     };
3549     if ( IsDebug() ) printf(" No file to be validated (force mode)! \n");
3550     return(0);
3551     };
3552     myid=(UInt_t)atoll(row->GetField(0));
3553     //
3554     myquery.str("");
3555     myquery << " SELECT MAX(RUNTRAILER_TIME),MIN(RUNHEADER_TIME) FROM GL_RUN WHERE ID_ROOT_L0="<< myid <<";";
3556     //
3557     result = conn->Query(myquery.str().c_str());
3558     //
3559     row = result->Next();
3560     if( !row->GetField(0) || !row->GetField(1)){
3561     //
3562     if ( IsDebug() ) printf(" NO RUN ASSOCIATED TO THIS FILE! \n");
3563     //
3564     return(0);
3565     //
3566     } else {
3567     //
3568     UInt_t runhtime = (UInt_t)atoll(row->GetField(0));
3569     UInt_t runttime = (UInt_t)atoll(row->GetField(1));
3570     UInt_t caltime = 0;
3571     //
3572     myquery.str("");
3573     myquery << " SELECT FROM_TIME FROM GL_TRK_CALIB where FROM_TIME>" <<runhtime;
3574     myquery << " order by FROM_TIME asc limit 1;";
3575     //
3576     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
3577     //
3578     //
3579     result = conn->Query(myquery.str().c_str());
3580     //
3581     row = result->Next();
3582     if( !row ){
3583     caltime = runhtime;
3584     } else {
3585     caltime = (UInt_t)atoll(row->GetField(0));
3586     };
3587     //
3588     myquery.str("");
3589     myquery << " SELECT * from GL_RUN where RUNHEADER_TIME>="<< runttime <<" AND RUNHEADER_TIME<=" ;
3590     myquery << caltime << " order by RUNHEADER_TIME DESC";
3591     //
3592     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
3593     //
3594     result = conn->Query(myquery.str().c_str());
3595     //
3596     };
3597 pam-fi 1.5 };
3598 mocchiut 1.16 //
3599 mocchiut 1.2 if ( !result ) throw -4;
3600 mocchiut 1.16 if ( !result->GetRowCount() && IsDebug() ) printf(" No runs to validate \n");
3601     //
3602 pam-fi 1.5 Int_t nrow = 0;
3603     GL_RUN* this_run = new GL_RUN();
3604     GL_RUN* next_run = new GL_RUN();
3605 pam-fi 1.8 Int_t nseq_max = 1000;
3606 pam-fi 1.5 // UInt_t* sequence = new UInt_t[100];
3607     vector<UInt_t> sequence(nseq_max);
3608     Int_t nseq = 0;
3609     Bool_t CHECK = false;
3610     Bool_t this_ONLINE = false;
3611     Bool_t next_ONLINE = false;
3612     UInt_t t1=0,t2=0;
3613     // ---------------------------------------------------------------------------------
3614     // - loop over runs, back in time,
3615 mocchiut 1.16 // - select sequences of runs close in time (less than calibtime s apart),
3616 pam-fi 1.5 // which could be preceeded by a calibration
3617     // - check if there might be a missing calibration
3618     // ---------------------------------------------------------------------------------
3619     while(1){
3620    
3621     row = result->Next();
3622     if( row == NULL ) break;
3623    
3624     //------------
3625     //get run info
3626     //------------
3627     this_run->Set_GL_RUN(row);
3628 pam-fi 1.8
3629 pam-fi 1.5 Bool_t this_BAD = false;
3630     if(this_run->GetTRK_CALIB_USED() == 1 || this_run->GetTRK_CALIB_USED() == 2) this_ONLINE = true;
3631     else if (this_run->GetTRK_CALIB_USED() == 104) this_ONLINE = false;
3632     else{
3633 pam-fi 1.8 // printf("Missing or corrupted header!! \n");
3634 pam-fi 1.5 this_ONLINE = false;
3635     this_BAD = true;
3636     };
3637    
3638     //-----------------------------------
3639     //compare with previous(next in time)
3640     //-----------------------------------
3641     CHECK = false;
3642     UInt_t interval=0;
3643    
3644     if( nrow != 0){
3645    
3646    
3647     t1 = this_run->GetRUNTRAILER_TIME();
3648     t2 = next_run->GetRUNHEADER_TIME();
3649     interval = (t2-t1);
3650    
3651     if(this_ONLINE && next_ONLINE){ // this: ON-LINE + next: ON-LINE
3652    
3653     if( this_run->ID == next_run->ID_RUN_FRAG ) interval = 0; //=> run fragments
3654    
3655 mocchiut 1.16 if( interval >= calibtime )CHECK = true; //more than calibtime s => there might be a calibration
3656 pam-fi 1.5
3657     if( !CHECK && this_run->VALIDATION ){
3658     for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);
3659     nseq=0;
3660     }
3661    
3662     }else if( !this_ONLINE && next_ONLINE) { // this: DEFAULT + next:ON-LINE
3663    
3664     CHECK = true;
3665    
3666     }else if( !next_ONLINE ){ // this:ANY + next:DEFAULT
3667    
3668     assignVALIDATION(next_run->ID,true);
3669     nseq=0;
3670     }
3671     }
3672    
3673     //----------------------------
3674     //check run sequence for calib
3675     //----------------------------
3676     if( CHECK ){
3677     // check if calibration exists
3678 pam-fi 1.8 if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval);
3679 pam-fi 1.5 Bool_t MISSING = MissingTRK_CALIB(t1,t2);
3680     for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],!MISSING);
3681     nseq=0;
3682 pam-fi 1.8 };
3683 pam-fi 1.5 //--------------
3684     //store run info
3685     //--------------
3686     *next_run = *this_run;
3687     next_ONLINE = this_ONLINE;
3688     if( !this_BAD ){
3689     if(nseq < nseq_max){
3690     sequence[nseq] = this_run->ID;
3691     nseq++;
3692     }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);
3693     };
3694    
3695 pam-fi 1.8 if ( IsDebug() ) printf("%i Run %i \n",nrow,this_run->ID);
3696 pam-fi 1.5 nrow++;
3697    
3698     };
3699     delete this_run;
3700     delete next_run;
3701 mocchiut 1.2 //
3702     return(0);
3703 mocchiut 1.1 };
3704 pam-fi 1.5 /**
3705     * Check if there might be a missing tracker calibration in a given time interval
3706     * @param t1 From absolute time
3707     * @param t2 To absolute time
3708     * @return true if there might be a missing calibration
3709     */
3710     Bool_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
3711    
3712     GL_TRK_CALIB* trkcalib = new GL_TRK_CALIB();
3713    
3714     // get the closest VALIDATED calibration before the run start (t2)
3715     if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(true); //>>> missing
3716    
3717     if ( trkcalib->TO_TIME < t2 ) return(true); //>>> missing
3718    
3719     //==============================================================
3720     // Check is done first on the basis of time between calibration,
3721     // which should be equal to the time between ascending-nodes.
3722     //==============================================================
3723     if ( t2 - trkcalib->FROM_TIME > 5700) {
3724 pam-fi 1.8 if ( IsDebug() )printf("Long time between calib and run start %i :-( ==> there might be a missing calib \n",t2 - trkcalib->FROM_TIME);
3725 pam-fi 1.5 //==============================================================
3726     // there might be a missing calibration, due to:
3727     // - MM full
3728     // - corrupted packets
3729     // - loss of data
3730     // There is an exception in case a download was done during ascending node
3731     //==============================================================
3732     Bool_t DOWNLOAD = false;
3733     // check if the calib was skipped becouse of download .... DA FARE!!
3734     if(DOWNLOAD)return(false);
3735    
3736     return(true); //>>> missing
3737    
3738     };
3739    
3740     //==============================================================
3741     // If the last calibration is close to the run less than this time,
3742     // it is enough to say that there are no missing calibrations
3743     //==============================================================
3744     // the long time interval bewteen runs might be due to download
3745 pam-fi 1.8 if ( IsDebug() )printf("Short time between calib and run start %i :-) ==> OK! \n",t2 - trkcalib->FROM_TIME);
3746 pam-fi 1.5 return(false);
3747    
3748     };
3749     /**
3750     * Assign VALIDATION value to a GL_RUN entry
3751     * @param idrun Run ID
3752     * @param validation true/false
3753     */
3754     Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, Bool_t validation){
3755     TSQLResult *result = 0;
3756     stringstream oss;
3757     oss.str("");
3758 pam-fi 1.8 oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";
3759 pam-fi 1.5 //
3760     // if ( IsDebug() )
3761 pam-fi 1.8 // printf(" Set VALIDATION = %i for run %i \n",validation,idrun);
3762     if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());
3763     result = conn->Query(oss.str().c_str());
3764     if ( !result ) throw -4;
3765 pam-fi 1.5 return(0);
3766     }
3767    
3768    
3769    
3770 mocchiut 1.12 // Insert TLEs from file tlefilename in the table GL_TLE in the db
3771     // opened by conn, sorting them by date from older to newer, if each
3772     // TLE has not been alread inserted.
3773     Int_t PamelaDBOperations::populateTLE()//(TSQLServer *conn, char *tleFile)
3774     {
3775     fstream tlefile(tlefilename, ios::in);
3776    
3777     if ( !tlefile ) throw -7;
3778    
3779     vector<cTle*> ctles;
3780     vector<cTle*>::iterator iter;
3781     int present = 0;
3782    
3783     // Get three lines from tlefile, create a cTle object and put it
3784     // into ctles
3785     while(1) {
3786     cTle *tlef;
3787     string str1, str2, str3;
3788    
3789     getline(tlefile, str1);
3790     if(tlefile.eof()) break;
3791    
3792     getline(tlefile, str2);
3793     if(tlefile.eof()) break;
3794    
3795     getline(tlefile, str3);
3796     if(tlefile.eof()) break;
3797    
3798     // We now have three good lines for a cTle.
3799     tlef = new cTle(str1, str2, str3);
3800     ctles.push_back(tlef);
3801     }
3802    
3803     tlefile.close();
3804    
3805     // Sort by date
3806     sort(ctles.begin(), ctles.end(), compTLE);
3807    
3808     // Now we insert each TLE into the db
3809     for(iter = ctles.begin(); iter != ctles.end(); iter++) {
3810     cTle *tle = *iter;
3811    
3812     // Do nothing if it's already present in the db. Just increase
3813     // the counter present.
3814     if (! isTlePresent(tle))
3815     {
3816     int status = insertTle(tle);
3817    
3818     // Insert query failed. Return 1.
3819     if(status == EXIT_FAILURE) {
3820    
3821     if( IsDebug() ) {
3822     cerr << "Error: inserting TLE:" << endl
3823     << tle->getName() << endl
3824     << tle->getLine1() << endl
3825     << tle->getLine2() << endl;
3826     }
3827    
3828     throw -4;
3829     return 1;
3830     }
3831    
3832     }
3833     else
3834     present++;
3835    
3836     }
3837    
3838     int inserted = ctles.size() - present; // Number of inserted TLE.
3839     if ( IsDebug() )
3840     cout << "\nProcessed TLEs ranging from " << getTleDatetime(ctles[0]) << " to " << getTleDatetime(ctles[ctles.size()-1]) << "." << endl
3841     << inserted << " newly inserted TLEs out of " << ctles.size() << " processed." << endl;
3842    
3843     ctles.clear();
3844    
3845    
3846     // Return 2 if no new TLE has been inserted. 0 otherwise.
3847     if(! inserted ) return 2;
3848     return 0;
3849     }
3850    
3851    
3852     // Insert tle in the table GL_TLE using the connection conn.
3853 mocchiut 1.16 Int_t PamelaDBOperations::insertTle(cTle *tle)
3854 mocchiut 1.12 {
3855     stringstream oss;
3856     TSQLResult *result = 0;
3857    
3858     oss.str("");
3859     oss << " INSERT INTO GL_TLE (TLE1, TLE2, TLE3, FROM_TIME)"
3860     << " VALUES ( '"
3861     << tle->getName() << "', '"
3862     << tle->getLine1() << "', '"
3863     << tle->getLine2() << "', '"
3864     << getTleDatetime(tle) << "')";
3865    
3866     // cout << oss.str().c_str() << endl;
3867     result = conn->Query(oss.str().c_str());
3868     if (result == NULL)
3869     return EXIT_FAILURE;
3870    
3871     return EXIT_SUCCESS;
3872     }
3873    
3874    
3875     // Return whether tle is already in the db connected by conn.
3876     bool PamelaDBOperations::isTlePresent(cTle *tle)
3877     {
3878     stringstream oss;
3879     TSQLResult *result = 0;
3880    
3881     oss.str("");
3882     oss << "SELECT * FROM GL_TLE WHERE FROM_TIME = '"
3883     << getTleDatetime(tle) << "'";
3884    
3885     result = conn->Query(oss.str().c_str());
3886     if (result == NULL) throw -4;
3887    
3888     if (result->GetRowCount())
3889     return true;
3890     else
3891     return false;
3892     }
3893    
3894    
3895     // Return whether the first TLE is dated early than the second
3896     bool compTLE (cTle *tle1, cTle *tle2)
3897     {
3898     return getTleJulian(tle1) < getTleJulian(tle2);
3899     }
3900    
3901    
3902     // Return the date of the tle using the format (year-2000)*1e3 +
3903     // julian day. e.g. 6365 is the 31th Dec 2006.
3904     // It does *not* return a cJulian date.
3905     float getTleJulian(cTle *tle) {
3906     return tle->getField(cTle::FLD_EPOCHYEAR)*1e3 + tle->getField(cTle::FLD_EPOCHDAY);
3907     }
3908    
3909    
3910     // Return a string like YYYY-MM-DD hh:mm:ss, usable for mysql datetime
3911     // format.
3912     string getTleDatetime(cTle *tle)
3913     {
3914     int year, mon, day, hh, mm, ss;
3915     double dom; // day of month (is double!)
3916     stringstream date; // date in datetime format
3917    
3918     // create a cJulian from the date in tle
3919     cJulian jdate = cJulian( 2000 + (int) tle->getField(cTle::FLD_EPOCHYEAR), tle->getField(cTle::FLD_EPOCHDAY));
3920    
3921     // get year, month, day of month
3922     jdate.getComponent(&year, &mon, &dom);
3923    
3924     // build a datetime YYYY-MM-DD hh:mm:ss
3925     date.str("");
3926     day = (int) floor(dom);
3927     hh = (int) floor( (dom - day) * 24);
3928     mm = (int) floor( ((dom - day) * 24 - hh) * 60);
3929     ss = (int) floor( ((((dom - day) * 24 - hh) * 60 - mm) * 60));
3930     // ms = (int) floor( (((((dom - day) * 24 - hh) * 60 - mm) * 60) - ss) * 1000);
3931    
3932     date << year << "-" << mon << "-" << day << " " << hh << ":" << mm << ":" << ss;
3933    
3934     return date.str();
3935     }
3936 mocchiut 1.16
3937     /**
3938     * Remove a file from the DB, delete on cascade all entries related to that file
3939     * rearrange GL_RUN and GL_XXX_CALIB tables, turn off validation till the following
3940     * calibration
3941     **/
3942     Int_t PamelaDBOperations::removeFile(TString remfile){
3943     //
3944     // Determine ID_ROOT_L0 and ID_RAW
3945     //
3946     TSQLResult *pResult;
3947     TSQLRow *Row;
3948     stringstream myquery;
3949     //
3950     myquery.str("");
3951     myquery << " SELECT ID, ID_RAW FROM GL_ROOT where NAME='"<<remfile.Data() <<"';";
3952     //
3953     pResult = conn->Query(myquery.str().c_str());
3954     //
3955     Row = pResult->Next();
3956     if( !Row ){
3957     if ( strcmp(remfile.Data(),GetRootName().Data()) ){
3958     if ( IsDebug() ) printf(" No file to be removed even if option \"-remove file\" was used!!\n");
3959     return(1);
3960     };
3961     if ( IsDebug() ) printf(" No file to be removed (force mode)! \n");
3962     return(0);
3963     };
3964     //
3965     this->SetID_ROOT((UInt_t)atoll(Row->GetField(0)));
3966     this->SetID_RAW((UInt_t)atoll(Row->GetField(1)));
3967     //
3968     this->ValidationOFF();
3969     //
3970     this->RemoveCALIBS();
3971     //
3972     this->RemoveRUNS();
3973     //
3974     this->RemoveFILES();
3975     //
3976     this->SetID_ROOT(0);
3977     this->SetID_RAW(0);
3978     //
3979     return(0);
3980     };
3981    
3982     /**
3983     *
3984     * Set validation bit to zero for runs following the removing file till
3985     * 1) a run with TRK_CALIB_USED=140
3986     * 2) a run with VALIDATION = 0
3987     * 3) the next calibration
3988     *
3989     **/
3990     void PamelaDBOperations::ValidationOFF(){
3991     TSQLResult *pResult;
3992     TSQLRow *Row;
3993     stringstream myquery;
3994     Int_t unv = 0;
3995     //select ID from GL_RUN where RUNHEADER_TIME>=1152671382 AND (VALIDATION=0 OR TRK_CALIB_USED=104) order by RUNHEADER_TIME asc limit 1;
3996     myquery.str("");
3997     myquery << " SELECT MAX(RUNTRAILER_TIME) FROM GL_RUN WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
3998     //
3999     pResult = conn->Query(myquery.str().c_str());
4000     //
4001     Row = pResult->Next();
4002     if( !Row->GetField(0) ){
4003     //
4004     if ( IsDebug() ) printf(" NO RUN ASSOCIATED TO THIS FILE! \n");
4005     //
4006     } else {
4007     //
4008     UInt_t runhtime = (UInt_t)atoll(Row->GetField(0));
4009     UInt_t caltime = 0;
4010     //
4011     myquery.str("");
4012     myquery << " SELECT FROM_TIME FROM GL_TRK_CALIB where FROM_TIME>" <<runhtime;
4013     myquery << " order by FROM_TIME asc limit 1;";
4014     //
4015     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
4016     //
4017     //
4018     delete pResult;
4019     pResult = conn->Query(myquery.str().c_str());
4020     //
4021     Row = pResult->Next();
4022     if( !Row ){
4023     caltime = runhtime;
4024     } else {
4025     caltime = (UInt_t)atoll(Row->GetField(0));
4026     };
4027     //
4028     myquery.str("");
4029     myquery << " SELECT ID,RUNHEADER_TIME from GL_RUN where RUNHEADER_TIME>="<< runhtime <<" AND (VALIDATION=0 OR TRK_CALIB_USED=104 OR RUNHEADER_TIME>" ;
4030     myquery << caltime << ") order by RUNHEADER_TIME asc LIMIT 1";
4031     //
4032     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
4033     //
4034     pResult = conn->Query(myquery.str().c_str());
4035     //
4036     Row = pResult->Next();
4037     if( !Row ){
4038     //
4039     if ( IsDebug() ) printf(" NO RUN NEED TO BE UNVALIDATED \n");
4040     //
4041     } else {
4042     myquery.str("");
4043     myquery << " SELECT ID from GL_RUN where RUNHEADER_TIME<"<< Row->GetField(1) <<" AND ";
4044     myquery << " RUNHEADER_TIME>=" <<runhtime;
4045     myquery << " order by RUNHEADER_TIME asc;";
4046     //
4047     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
4048     //
4049     pResult = conn->Query(myquery.str().c_str());
4050     //
4051     Row = pResult->Next();
4052     while ( Row ){
4053     //
4054     unv++;
4055     this->assignVALIDATION((UInt_t)atoll(Row->GetField(0)), false);
4056     Row = pResult->Next();
4057     //
4058     };
4059     };
4060     };
4061     if ( IsDebug() ) printf(" %i runs have been unvalidated \n",unv);
4062     };
4063    
4064     /**
4065     *
4066     * Rearrange GL_RUN table and remove runs
4067     *
4068     **/
4069     void PamelaDBOperations::RemoveRUNS(){
4070     TSQLResult *pResult;
4071     TSQLRow *Row;
4072     stringstream myquery;
4073     UInt_t drun = 0;
4074     GL_RUN *delrun = new GL_RUN();
4075     //
4076     myquery.str("");
4077     myquery << " SELECT ID FROM GL_RUN where ID_RUN_FRAG=0 and ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4078     //
4079     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
4080     //
4081     pResult = conn->Query(myquery.str().c_str());
4082     //
4083     Row = pResult->Next();
4084     //
4085     //
4086     if ( !Row ){
4087     if ( IsDebug() ) printf(" No run with ID_RUN_FRAG=0 belonged to this file \n");
4088     } else {
4089     if ( IsDebug() ) printf(" Deleting run from GL_RUN table \n");
4090     while ( Row ){
4091     delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(0)),"GL_RUN");
4092     if ( IsDebug() ) printf(" del run %i \n",(UInt_t)atoll(Row->GetField(0)));
4093     drun++;
4094     Row = pResult->Next();
4095     };
4096     };
4097     //
4098     //
4099     myquery.str("");
4100     myquery << " SELECT ID,ID_RUN_FRAG FROM GL_RUN where ID_RUN_FRAG!=0 and ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4101     //
4102     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
4103     //
4104     pResult = conn->Query(myquery.str().c_str());
4105     //
4106     Row = pResult->Next();
4107     //
4108     if ( !Row ){
4109     if ( IsDebug() ) printf(" No run with ID_RUN_FRAG!=0 belonged to this file \n");
4110     } else {
4111     if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN table \n");
4112     while ( Row ){
4113     if ( IsDebug() ) printf(" restore run %i \n",(UInt_t)atoll(Row->GetField(1)));
4114     delrun->RestoreRun(conn,(UInt_t)atoll(Row->GetField(1)),"GL_RUN_FRAGMENTS");
4115     if ( IsDebug() ) printf(" del run %i \n",(UInt_t)atoll(Row->GetField(1)));
4116     delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(1)),"GL_RUN");
4117     if ( (UInt_t)atoll(Row->GetField(1)) != (UInt_t)atoll(Row->GetField(0)) ){
4118     if ( IsDebug() ) printf(" del run %i \n",(UInt_t)atoll(Row->GetField(0)));
4119     delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(0)),"GL_RUN");
4120     };
4121     drun++;
4122     Row = pResult->Next();
4123     };
4124     };
4125     //
4126     if ( IsDebug() ) printf(" Deleted %i run(s) from GL_RUN table \n",drun);
4127     //
4128     //
4129     //
4130     drun = 0;
4131     //
4132     myquery.str("");
4133     myquery << " SELECT ID_TRASH FROM GL_RUN_TRASH where BELONGED_TO='GL_RUN_FRAGMENTS' AND ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4134     //
4135     pResult = conn->Query(myquery.str().c_str());
4136     //
4137     Row = pResult->Next();
4138     //
4139     if ( !Row ){
4140     if ( IsDebug() ) printf(" No run from GL_RUN_FRAGMENTS table in the trash table for this file \n");
4141     } else {
4142     if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN_TRASH table \n");
4143     while ( Row ){
4144     if ( IsDebug() ) printf(" del run idtrash %i \n",(UInt_t)atoll(Row->GetField(0)));
4145     myquery.str("");
4146     myquery << " DELETE FROM GL_RUN_TRASH where ID_TRASH=" << Row->GetField(0) <<";";
4147     conn->Query(myquery.str().c_str());
4148     drun++;
4149     Row = pResult->Next();
4150     };
4151     };
4152     //
4153     if ( IsDebug() ) printf(" Deleted %i run(s) from GL_RUN_TRASH table \n",drun);
4154     //
4155     //
4156     //
4157     drun = 0;
4158     //
4159     myquery.str("");
4160     myquery << " SELECT ID FROM GL_RUN_FRAGMENTS where ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4161     //
4162     pResult = conn->Query(myquery.str().c_str());
4163     //
4164     Row = pResult->Next();
4165     //
4166     if ( !Row ){
4167     if ( IsDebug() ) printf(" No run in the GL_RUN_FRAGMENTS table for this file \n");
4168     } else {
4169     if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN_FRAGMENTS table \n");
4170     while ( Row ){
4171     if ( IsDebug() ) printf(" del run %i \n",(UInt_t)atoll(Row->GetField(0)));
4172     myquery.str("");
4173     myquery << " DELETE FROM GL_RUN_FRAGMENTS where ID=" << Row->GetField(0) <<";";
4174     conn->Query(myquery.str().c_str());
4175     drun++;
4176     Row = pResult->Next();
4177     };
4178     };
4179     //
4180     if ( IsDebug() ) printf(" Deleted %i run(s) from GL_RUN_FRAGMENTS table \n",drun);
4181     //
4182     //
4183     //
4184     delete delrun;
4185     //
4186     };
4187    
4188    
4189     /**
4190     *
4191     * Rearrange calibration tables
4192     *
4193     **/
4194     void PamelaDBOperations::RemoveFILES(){
4195     stringstream myquery;
4196     //
4197     myquery.str("");
4198     myquery << " DELETE FROM GL_RAW WHERE ID=" <<this->GetID_RAW() <<";";
4199     //
4200     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
4201     //
4202     conn->Query(myquery.str().c_str());
4203     //
4204     };
4205    
4206     /**
4207     *
4208     * Rearrange calibration tables
4209     *
4210     **/
4211     void PamelaDBOperations::RemoveCALIBS(){
4212     TSQLResult *pResult;
4213     TSQLRow *Row;
4214     stringstream myquery;
4215     //
4216     //
4217     // Calorimeter
4218     //
4219     for (Int_t section = 0; section < 4; section++){
4220     myquery.str("");
4221     myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_CALO_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<" AND ";
4222     myquery << " SECTION=" << section << ";";
4223     //
4224     pResult = conn->Query(myquery.str().c_str());
4225     //
4226     Row = pResult->Next();
4227     if( !Row->GetField(0) || !Row->GetField(1) ){
4228     //
4229     if ( IsDebug() ) printf(" NO CALO CALIBRATION SECTION %i ASSOCIATED TO THIS FILE! \n",section);
4230     //
4231     } else {
4232     //
4233     myquery.str("");
4234     myquery << " UPDATE GL_CALO_CALIB SET TO_TIME=" << Row->GetField(1);
4235     myquery << " WHERE TO_TIME="<< Row->GetField(0) << " AND ";
4236     myquery << " SECTION=" << section << ";";
4237     //
4238     pResult = conn->Query(myquery.str().c_str());
4239     //
4240     if( !pResult ){
4241     //
4242     if ( IsDebug() ) printf(" ERROR DELETING CALO CALIBRATIONS \n");
4243     //
4244     throw -4;
4245     //
4246     };
4247     //
4248     };
4249     };
4250     myquery.str("");
4251     myquery << " DELETE FROM GL_CALO_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT();
4252     //
4253     pResult = conn->Query(myquery.str().c_str());
4254     //
4255     if( !pResult ){
4256     //
4257     if ( IsDebug() ) printf(" ERROR DELETING CALO CALIBRATIONS \n");
4258     //
4259     throw -4;
4260     //
4261     };
4262     //
4263     // Tracker
4264     //
4265     myquery.str("");
4266     myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_TRK_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
4267     //
4268     pResult = conn->Query(myquery.str().c_str());
4269     //
4270     Row = pResult->Next();
4271     if( !Row->GetField(0) || !Row->GetField(1) ){
4272     //
4273     if ( IsDebug() ) printf(" NO TRK CALIBRATION ASSOCIATED TO THIS FILE! \n");
4274     //
4275     } else {
4276     //
4277     myquery.str("");
4278     myquery << " UPDATE GL_TRK_CALIB SET TO_TIME=" << Row->GetField(1);
4279     myquery << " WHERE TO_TIME="<< Row->GetField(0) << ";";
4280     //
4281     pResult = conn->Query(myquery.str().c_str());
4282     //
4283     if( !pResult ){
4284     //
4285     if ( IsDebug() ) printf(" ERROR DELETING TRK CALIBRATIONS \n");
4286     //
4287     throw -4;
4288     //
4289     };
4290     //
4291     myquery.str("");
4292     myquery << " DELETE FROM GL_TRK_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT();
4293     //
4294     pResult = conn->Query(myquery.str().c_str());
4295     //
4296     if( !pResult ){
4297     //
4298     if ( IsDebug() ) printf(" ERROR DELETING TRK CALIBRATIONS \n");
4299     //
4300     throw -4;
4301     //
4302     };
4303     };
4304     //
4305     //
4306     // S4
4307     //
4308     myquery.str("");
4309     myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_S4_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
4310     //
4311     pResult = conn->Query(myquery.str().c_str());
4312     //
4313     Row = pResult->Next();
4314     if( !Row->GetField(0) || !Row->GetField(1) ){
4315     //
4316     if ( IsDebug() ) printf(" NO S4 CALIBRATION ASSOCIATED TO THIS FILE! \n");
4317     //
4318     } else {
4319     //
4320     myquery.str("");
4321     myquery << " UPDATE GL_S4_CALIB SET TO_TIME=" << Row->GetField(1);
4322     myquery << " WHERE TO_TIME="<< Row->GetField(0) << ";";
4323     //
4324     pResult = conn->Query(myquery.str().c_str());
4325     //
4326     if( !pResult ){
4327     //
4328     if ( IsDebug() ) printf(" ERROR DELETING S4 CALIBRATIONS \n");
4329     //
4330     throw -4;
4331     //
4332     };
4333     //
4334     myquery.str("");
4335     myquery << " DELETE FROM GL_S4_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT();
4336     //
4337     pResult = conn->Query(myquery.str().c_str());
4338     //
4339     if( !pResult ){
4340     //
4341     if ( IsDebug() ) printf(" ERROR DELETING S4 CALIBRATIONS \n");
4342     //
4343     throw -4;
4344     //
4345     };
4346     //
4347     };
4348     };

  ViewVC Help
Powered by ViewVC 1.1.23