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

Annotation of /YodaProfiler/src/PamelaDBOperations.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.16 - (hide annotations) (download)
Tue Oct 31 15:36:04 2006 UTC (18 years, 1 month ago) by mocchiut
Branch: MAIN
CVS Tags: v2r01, v2r00
Changes since 1.15: +701 -210 lines
Force mode introduced together with other features, R2-D2 moved here, manual added

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

  ViewVC Help
Powered by ViewVC 1.1.23