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

Annotation of /YodaProfiler/src/PamelaDBOperations.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.27 - (hide annotations) (download)
Mon Feb 12 13:32:18 2007 UTC (17 years, 9 months ago) by mocchiut
Branch: MAIN
Changes since 1.26: +23 -5 lines
-boot bug fixed, introduced -dworbit option, small bugs fixed

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

  ViewVC Help
Powered by ViewVC 1.1.23