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

Annotation of /YodaProfiler/src/PamelaDBOperations.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.23 - (hide annotations) (download)
Mon Dec 4 09:49:34 2006 UTC (18 years ago) by mocchiut
Branch: MAIN
Changes since 1.22: +2 -0 lines
Duplicate entry bug fixed

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

  ViewVC Help
Powered by ViewVC 1.1.23