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

Annotation of /YodaProfiler/src/PamelaDBOperations.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.25 - (hide annotations) (download)
Tue Jan 23 17:04:12 2007 UTC (17 years, 10 months ago) by mocchiut
Branch: MAIN
Changes since 1.24: +1 -0 lines
Updated GL_TLE class

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

  ViewVC Help
Powered by ViewVC 1.1.23