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

Annotation of /YodaProfiler/src/PamelaDBOperations.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.30 - (hide annotations) (download)
Mon Apr 30 08:09:50 2007 UTC (17 years, 7 months ago) by mocchiut
Branch: MAIN
Changes since 1.29: +2 -0 lines
Obt bug fixed

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

  ViewVC Help
Powered by ViewVC 1.1.23