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

Diff of /YodaProfiler/src/PamelaDBOperations.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.1 by mocchiut, Wed Aug 30 11:18:13 2006 UTC revision 1.12 by mocchiut, Tue Oct 17 15:20:04 2006 UTC
# Line 8  Line 8 
8  #include <list>  #include <list>
9  #include <errno.h>  #include <errno.h>
10  //  //
11    #include <TFile.h>
12    #include <TSystem.h>
13  #include <TSQLResult.h>  #include <TSQLResult.h>
 #include <TRFIOFile.h>  
14  #include <TSQLRow.h>  #include <TSQLRow.h>
15  #include <TTree.h>  #include <TTree.h>
16  #include <TGraph.h>  #include <TGraph.h>
# Line 29  Line 30 
30  #include <varDump/VarDumpEvent.h>  #include <varDump/VarDumpEvent.h>
31  #include <varDump/VarDumpRecord.h>  #include <varDump/VarDumpRecord.h>
32  #include <physics/S4/S4Event.h>  #include <physics/S4/S4Event.h>
   
33  //  //
34    #include <cTle.h>
35    #include <cEci.h>
36    #include <cJulian.h>
37    
38  #include <PamelaDBOperations.h>  #include <PamelaDBOperations.h>
39  //  //
40  using namespace std;  using namespace std;
41  using namespace pamela;  using namespace pamela;
42  //using namespace yngn::util;  
43    // Some function to work with cTle stuff.
44    bool compTLE(cTle* tle1, cTle *tle2);
45    float getTleJulian(cTle *);
46    string getTleDatetime(cTle*);
47    
48  /**  /**
49   * Constructor.   * Constructor.
# Line 48  using namespace pamela; Line 56  using namespace pamela;
56   * @param obt0         file obt0.   * @param obt0         file obt0.
57   * @param tsync        file timesync.   * @param tsync        file timesync.
58   * @param debug        debug flag.   * @param debug        debug flag.
59     * @param tlefilename  ascii file with TLE 3 line elements.
60   */   */
61  PamelaDBOperations::PamelaDBOperations(TString host, TString user, TString password, TString filerawname, TString filerootname, UInt_t boot, UInt_t tsync, UInt_t obt0, Bool_t debug){  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){
62    //    //
63    //    //
64    SetConnection(host,user,password);    SetConnection(host,user,password);
# Line 63  PamelaDBOperations::PamelaDBOperations(T Line 72  PamelaDBOperations::PamelaDBOperations(T
72    SetTsync(tsync);    SetTsync(tsync);
73    SetObt0(obt0);    SetObt0(obt0);
74    //    //
75      SetTLEPath(tlefilename);
76    //    //
   SetRootName(filerootname);  
   SetRawName(filerawname);  
77    //    //
78    this->OpenFile();    INSERT_RAW =!filerawname.IsNull();
79      if(INSERT_RAW)SetRawName(filerawname);
80      //
81      INSERT_ROOT = !filerootname.IsNull();
82      if( INSERT_ROOT ){
83        this->SetRootName(filerootname);
84        file = TFile::Open(this->GetRootName().Data());
85      };
86    //    //
87    this->SetID_RAW(0);    this->SetID_RAW(0);
88    this->SetID_ROOT(0);    this->SetID_ROOT(0);
89    
90      VALIDATE = false;
91      
92    //    //
93  };  };
94    
# Line 79  PamelaDBOperations::PamelaDBOperations(T Line 97  PamelaDBOperations::PamelaDBOperations(T
97   */   */
98  void PamelaDBOperations::Close(){  void PamelaDBOperations::Close(){
99    if( conn && conn->IsConnected() ) conn->Close();    if( conn && conn->IsConnected() ) conn->Close();
100      delete clean_time;
101    delete glrun;    delete glrun;
102    delete this;    delete this;
103  };  };
# Line 87  void PamelaDBOperations::Close(){ Line 106  void PamelaDBOperations::Close(){
106  // SETTERS  // SETTERS
107  //  //
108    
109    //
110    // 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
111    //
112    void PamelaDBOperations::CheckValidate(Long64_t olderthan){
113      clean_time = new TDatime();
114      if(olderthan >= 0){
115        VALIDATE = true;
116        UInt_t timelim = 0;
117        timelim =  (UInt_t)clean_time->Convert() - olderthan;
118        clean_time->Set(timelim,false);
119      };
120    };
121    
122  /**  /**
123   * Open the DB connection   * Open the DB connection
124   * @param host         hostname for the SQL connection.   * @param host         hostname for the SQL connection.
# Line 170  void PamelaDBOperations::SetNOBOOT(Bool_ Line 202  void PamelaDBOperations::SetNOBOOT(Bool_
202  };  };
203    
204  /**  /**
205     * Store path to the TLE file.
206     */
207    void PamelaDBOperations::SetTLEPath(TString str){
208      tlefilename = str;
209    };
210    
211    /**
212     * Store the olderthan variable
213     * @param olderthan
214     */
215    // void PamelaDBOperations::SetOlderThan(Long64_t oldthan){
216    //   olderthan = oldthan;
217    // };
218    
219    /**
220   * Retrieve the ID_RAW, if exists, returns NULL if does not exist.   * Retrieve the ID_RAW, if exists, returns NULL if does not exist.
221   */   */
222  Bool_t PamelaDBOperations::SetID_RAW(){  Bool_t PamelaDBOperations::SetID_RAW(){
# Line 181  Bool_t PamelaDBOperations::SetID_RAW(){ Line 228  Bool_t PamelaDBOperations::SetID_RAW(){
228        << " PATH = '" << this->GetRawPath().Data() << "' AND "        << " PATH = '" << this->GetRawPath().Data() << "' AND "
229        << " NAME = '" << this->GetRawFile().Data() << "' ";        << " NAME = '" << this->GetRawFile().Data() << "' ";
230    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
231    if (result == NULL) throw -4;    if ( result == NULL ) throw -4;
232    row = result->Next();    row = result->Next();
233    if (row == NULL) return false;    if ( !row ) return(false);
234    delete result;    delete result;
235    id = (UInt_t)atoll(row->GetField(0));    id = (UInt_t)atoll(row->GetField(0));
236    return(true);    return(true);
# Line 216  Int_t PamelaDBOperations::SetUpperLimits Line 263  Int_t PamelaDBOperations::SetUpperLimits
263    ULong64_t upperobt2 = 0;    ULong64_t upperobt2 = 0;
264    UInt_t zomp = 0;    UInt_t zomp = 0;
265    UInt_t jump = 50000; // was 5000    UInt_t jump = 50000; // was 5000
266      EventCounter *code=0;
267      //
268      //   pcksList packetsNames;
269      //   pcksList::iterator Iter;
270      //   getPacketsNames(packetsNames);
271    //    //
272    pktfirst = 0;    pktfirst = 0;
273    obtfirst = 0;    obtfirst = 0;
# Line 233  Int_t PamelaDBOperations::SetUpperLimits Line 285  Int_t PamelaDBOperations::SetUpperLimits
285    pktfirst = ph->GetCounter();    pktfirst = ph->GetCounter();
286    obtfirst = ph->GetOrbitalTime();      obtfirst = ph->GetOrbitalTime();  
287    //    //
288      //   code = eh->GetCounter();
289      //   UInt_t en = 0;
290      //   for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
291      //     en = code->Get(GetPacketType(*Iter));
292      //     if ( en ) printf(" Packet type is %s, entries: %i \n",*Iter,en);
293      //};  
294      //
295    T->GetEntry(nevent-1);    T->GetEntry(nevent-1);
296    ph = eh->GetPscuHeader();    ph = eh->GetPscuHeader();
297    pktlast = ph->GetCounter();    pktlast = ph->GetCounter();
# Line 301  Int_t PamelaDBOperations::SetUpperLimits Line 360  Int_t PamelaDBOperations::SetUpperLimits
360    // check if last runtrailer is within limits, if not extend limits (one should check for all packets but we need only runtrailer)    // check if last runtrailer is within limits, if not extend limits (one should check for all packets but we need only runtrailer)
361    //    //
362    PacketType *pctp=0;    PacketType *pctp=0;
   EventCounter *code=0;  
   T->GetEntry(upperentry);  
   code = eh->GetCounter();  
   Int_t lasttrail = code->Get(pctp->RunTrailer);  
   Int_t lasthead = code->Get(pctp->RunHeader);  
363    TTree *rh=(TTree*)file->Get("RunHeader");    TTree *rh=(TTree*)file->Get("RunHeader");
364    if ( !rh || rh->IsZombie() ) throw -17;    if ( !rh || rh->IsZombie() ) throw -17;
365    TTree *rt=(TTree*)file->Get("RunTrailer");    TTree *rt=(TTree*)file->Get("RunTrailer");
# Line 319  Int_t PamelaDBOperations::SetUpperLimits Line 373  Int_t PamelaDBOperations::SetUpperLimits
373    //    //
374    rhev = rh->GetEntries();    rhev = rh->GetEntries();
375    rtev = rt->GetEntries();    rtev = rt->GetEntries();
376      UInt_t sobtt = 0;
377      UInt_t sobth = 0;
378      UInt_t spktt = 0;
379      UInt_t spkth = 0;
380    UInt_t pktt = 0;    UInt_t pktt = 0;
381    ULong64_t obtt = 0;    ULong64_t obtt = 0;
382    UInt_t pkth = 0;    UInt_t pkth = 0;
383    ULong64_t obth = 0;    ULong64_t obth = 0;
384    //    //
385      T->GetEntry(upperentry);
386      code = eh->GetCounter();
387      Int_t lasttrail = code->Get(pctp->RunTrailer);
388      Int_t lasthead = code->Get(pctp->RunHeader);
389    if ( lasttrail < rtev ){    if ( lasttrail < rtev ){
390      rt->GetEntry(lasttrail);      rt->GetEntry(lasttrail);
391      pht = eht->GetPscuHeader();      pht = eht->GetPscuHeader();
# Line 331  Int_t PamelaDBOperations::SetUpperLimits Line 393  Int_t PamelaDBOperations::SetUpperLimits
393      obtt = OBT(pht->GetOrbitalTime());      obtt = OBT(pht->GetOrbitalTime());
394    };    };
395    //    //
396      if ( lasthead < rhev ){
397        rh->GetEntry(lasthead);
398        phh = ehh->GetPscuHeader();
399        pkth = PKT(phh->GetCounter());
400        obth = OBT(phh->GetOrbitalTime());
401      };
402      //
403      if ( IsDebug() ) printf(" rhev before %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);
404      if ( pkth > upperpkt && obth > upperobt ){
405        if ( IsDebug() ) printf(" Upper limits extended to include last header: ph %i upperp %i oh %llu uppero %llu \n",pkth,upperpkt,obth,upperobt);
406        upperpkt = pkth;
407        upperobt = obth;
408        rhev = lasthead+1;
409      } else {
410        rhev = lasthead;
411      };
412      if ( IsDebug() ) printf(" rhev after %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);
413      //
414    if ( IsDebug() ) printf(" rtev beforev %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);    if ( IsDebug() ) printf(" rtev beforev %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);
415    if ( pktt > upperpkt && obtt > upperobt ){    if ( pktt > upperpkt && obtt > upperobt ){
416      if ( IsDebug() ) printf(" Upper limits extended to include last trailer: pt %i upperp %i ot %llu uppero %llu \n",pktt,upperpkt,obtt,upperobt);      if ( IsDebug() ) printf(" Upper limits extended to include last trailer: pt %i upperp %i ot %llu uppero %llu \n",pktt,upperpkt,obtt,upperobt);
# Line 341  Int_t PamelaDBOperations::SetUpperLimits Line 421  Int_t PamelaDBOperations::SetUpperLimits
421      rtev = lasttrail;      rtev = lasttrail;
422    };    };
423    if ( IsDebug() ) printf(" rtev after %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);    if ( IsDebug() ) printf(" rtev after %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);
424      //  goto kikko;
425      //
426      //
427      // Check if runtrailer/runheader are within lower limits
428      //
429      //
430      pkth = 0;
431      obth = 0;
432      spkth = 0;
433      sobth = 0;
434      for (Int_t k=0; k<rhev; k++){
435        if ( k > 0 ){
436          spkth = pkth;
437          sobth = obth;
438        };
439        rh->GetEntry(k);
440        phh = ehh->GetPscuHeader();
441        pkth = PKT(phh->GetCounter());
442        obth = OBT(phh->GetOrbitalTime());
443        //
444    //    if ( IsDebug() ) printf(" k %i rhev before %i ph %u upperp %u oh %u uppero %u \n",k,rhev,pkth,spkth,obth,sobth);
445        //
446        if ( pkth < spkth && obth < sobth ){
447          if ( IsDebug() ) printf(" RH PROBLEMS determining the event repetition at the end of the file lasthead %i  \n",rhev);
448          //
449          rhev = k-1;
450          rh->GetEntry(rhev);
451          pkth = spkth;
452          obth = sobth;
453          //
454          UInt_t evbefh = 0;
455          code = ehh->GetCounter();
456          evbefh = code->Get(pctp->Physics);    
457          if ( evbefh >= 0 ){
458            T->GetEntry(evbefh);
459            ph = eh->GetPscuHeader();
460            t_pktlast = PKT(ph->GetCounter());
461            t_obtlast = OBT(ph->GetOrbitalTime());
462            if ( t_pktlast <= spkth && t_obtlast <= sobth ){ // jump
463              upperpkt = pkth;
464              upperobt = obth;
465              upperentry = evbefh-1;
466            } else {
467              while ( t_pktlast > spkth && t_obtlast > sobth && evbefh < nevent ){
468                evbefh++;  
469                T->GetEntry(evbefh);
470                ph = eh->GetPscuHeader();
471                t_pktlast = PKT(ph->GetCounter());
472                t_obtlast = OBT(ph->GetOrbitalTime());
473              };
474              T->GetEntry(evbefh-1);
475              ph = eh->GetPscuHeader();
476              upperpkt = PKT(ph->GetCounter());
477              upperobt = OBT(ph->GetOrbitalTime());
478              upperentry = evbefh-1;
479            };    
480          };
481          if ( IsDebug() ) printf(" rhev after %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);
482          goto kikko0;
483        };
484      };
485     kikko0:
486      //
487      //
488      //
489      pktt = 0;
490      obtt = 0;
491      spktt = 0;
492      sobtt = 0;
493      for (Int_t k=0; k<rtev; k++){
494        if ( k > 0 ){
495          spktt = pktt;
496          sobtt = obtt;
497        };
498        rt->GetEntry(k);
499        pht = eht->GetPscuHeader();
500        pktt = PKT(pht->GetCounter());
501        obtt = OBT(pht->GetOrbitalTime());
502        //
503    //    if ( IsDebug() ) printf(" k %i rtev beforev %i  pt %i upperp %i ot %llu uppero %llu \n",k,rtev,pktt,spktt,obtt,sobtt);
504        //
505        if ( pktt < spktt && obtt < sobtt ){
506          if ( IsDebug() ) printf(" RT PROBLEMS determining the event repetition at the end of the file lasttrail %i \n",rtev);
507          //
508          rtev = k-1;
509          rt->GetEntry(rtev);
510          pktt = spktt;
511          obtt = sobtt;
512          if ( IsDebug() ) printf(" lasttrail %i pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);
513          //
514          UInt_t evbeft = 0;
515          code = eht->GetCounter();
516          evbeft = code->Get(pctp->Physics);    
517          if ( evbeft >= 0 ){
518            T->GetEntry(evbeft);
519            ph = eh->GetPscuHeader();
520            t_pktlast = PKT(ph->GetCounter());
521            t_obtlast = OBT(ph->GetOrbitalTime());
522            if ( t_pktlast <= spktt && t_obtlast <= sobtt ){ // jump
523              upperpkt = pktt;
524              upperobt = obtt;
525              upperentry = evbeft-1;
526            } else {
527              while ( t_pktlast > spktt && t_obtlast > sobtt && evbeft < nevent ){
528                evbeft++;  
529                T->GetEntry(evbeft);
530                ph = eh->GetPscuHeader();
531                t_pktlast = PKT(ph->GetCounter());
532                t_obtlast = OBT(ph->GetOrbitalTime());
533              };
534              T->GetEntry(evbeft-1);
535              ph = eh->GetPscuHeader();
536              upperpkt = PKT(ph->GetCounter());
537              upperobt = OBT(ph->GetOrbitalTime());
538              upperentry = evbeft-1;
539            };
540          };
541          if ( IsDebug() ) printf(" rtev after %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);
542          goto kikko;
543          //      break;
544          //
545        };
546        //  
547      };
548      //
549     kikko:
550      //
551      T->GetEntry(upperentry);
552      code = eh->GetCounter();
553      lasttrail = code->Get(pctp->RunTrailer);
554      lasthead = code->Get(pctp->RunHeader);
555      if ( lasttrail < rtev ){
556        rt->GetEntry(lasttrail);
557        pht = eht->GetPscuHeader();
558        pktt = PKT(pht->GetCounter());
559        obtt = OBT(pht->GetOrbitalTime());
560      };
561    //    //
562    if ( lasthead < rhev ){    if ( lasthead < rhev ){
563      rh->GetEntry(lasthead);      rh->GetEntry(lasthead);
564      phh = ehh->GetPscuHeader();      phh = ehh->GetPscuHeader();
565      pkth = PKT(pht->GetCounter());      pkth = PKT(phh->GetCounter());
566      obth = OBT(pht->GetOrbitalTime());      obth = OBT(phh->GetOrbitalTime());
567    };    };
568    //    //
569    if ( IsDebug() ) printf(" rhev before %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);    if ( IsDebug() ) printf(" rhev before %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);
# Line 360  Int_t PamelaDBOperations::SetUpperLimits Line 577  Int_t PamelaDBOperations::SetUpperLimits
577    };    };
578    if ( IsDebug() ) printf(" rhev after %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);    if ( IsDebug() ) printf(" rhev after %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);
579    //    //
580      if ( IsDebug() ) printf(" rtev beforev %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);
581      if ( pktt > upperpkt && obtt > upperobt ){
582        if ( IsDebug() ) printf(" Upper limits extended to include last trailer: pt %i upperp %i ot %llu uppero %llu \n",pktt,upperpkt,obtt,upperobt);
583        upperpkt = pktt;
584        upperobt = obtt;
585        rtev = lasttrail+1;
586      } else {
587        rtev = lasttrail;
588      };
589      if ( IsDebug() ) printf(" rtev after %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);
590      //
591    if ( IsDebug() ) printf(" Upper limits are: OBT %llu pkt_num %i upper entry %i \n",upperobt,upperpkt,upperentry);    if ( IsDebug() ) printf(" Upper limits are: OBT %llu pkt_num %i upper entry %i \n",upperobt,upperpkt,upperentry);
592    //    //
593    return(0);    return(0);
# Line 440  const PacketType* PamelaDBOperations::Ge Line 668  const PacketType* PamelaDBOperations::Ge
668  // PRIVATE FUNCTIONS  // PRIVATE FUNCTIONS
669  //  //
670    
671  /**  // /**
672   * Open the ROOT filename for reading  // * Open the ROOT filename for reading
673   */  // */
674  void PamelaDBOperations::OpenFile(){  // void PamelaDBOperations::OpenFile(){
675    file = TFile::Open(this->GetRootName().Data());  //   file = TFile::Open(this->GetRootName().Data());
676    //   //
677    
678    void PamelaDBOperations::CheckFile(){  
679      if ( !file ) throw -12;
680  };  };
681    
682    
683  /**  /**
684   * Check if LEVEL0 file and DB connection have really be opened   * Check if LEVEL0 file and DB connection have really be opened
685   */   */
686  void PamelaDBOperations::CheckFile(){    void PamelaDBOperations::CheckConnection(){  
   //  
   if ( !file ) throw -12;  
687    //    //
688    // check connection    // check connection
689    //    //
690    if( !conn ) throw -1;        if( !conn ) throw -1;
691    bool connect = conn->IsConnected();    bool connect = conn->IsConnected();
692    if( !connect ) throw -1;        if( !connect ) throw -1;
693  };  };
694    
695  /**  /**
# Line 550  void PamelaDBOperations::FillClass(Bool_ Line 780  void PamelaDBOperations::FillClass(Bool_
780      lastPkt = glrun->GetRUNTRAILER_PKT();      lastPkt = glrun->GetRUNTRAILER_PKT();
781    };    };
782    //    //
783    if ( mishead && mistrail && lastev+1 == firstev ) throw -14; // run with no events, no runtrailer, no runheader... unsupported    if ( mishead && mistrail && lastev+1 == firstev ) throw -14; // run with no events, no runtrailer, no runheader... unsupported should never arrive here
784    //    //
785    if ( mishead ) {    if ( mishead ) {
786      glrun->Set_GL_RUNH0();      glrun->Set_GL_RUNH0();
# Line 668  Int_t PamelaDBOperations::insertPamelaGL Line 898  Int_t PamelaDBOperations::insertPamelaGL
898    };    };
899    //    //
900    TTree *T = 0;    TTree *T = 0;
901      Int_t signal = 0;
902    //    //
903    UInt_t nevent = 0;    UInt_t nevent = 0;
904    UInt_t recEntries = 0;    UInt_t recEntries = 0;
# Line 719  Int_t PamelaDBOperations::insertPamelaGL Line 950  Int_t PamelaDBOperations::insertPamelaGL
950          //          //
951          TYPE = 55;//224;          TYPE = 55;//224;
952          //          //
953            if ( IsDebug() ) printf("mcmd tsync %i tsync %u obt %u \n",i,TSYNC,OBT);
954            //
955          if ( TSYNC && OBT ){          if ( TSYNC && OBT ){
956            existsts = true;            existsts = true;
957            goto out;            goto eout;
958          };          };
959          //          //
960        };        };
# Line 729  Int_t PamelaDBOperations::insertPamelaGL Line 962  Int_t PamelaDBOperations::insertPamelaGL
962    };    };
963    if ( !existsts ) { // try with runheader and runtrailer    if ( !existsts ) { // try with runheader and runtrailer
964      //      //
965        if ( IsDebug() ) printf(" No ts mcmd \n");
966        signal = 2;
967        //
968      TTree *rh=(TTree*)file->Get("RunHeader");      TTree *rh=(TTree*)file->Get("RunHeader");
969      if ( !rh || rh->IsZombie() ) throw -17;      if ( !rh || rh->IsZombie() ) throw -17;
970      TTree *rt=(TTree*)file->Get("RunTrailer");      TTree *rt=(TTree*)file->Get("RunTrailer");
# Line 738  Int_t PamelaDBOperations::insertPamelaGL Line 974  Int_t PamelaDBOperations::insertPamelaGL
974      //      //
975      rt->SetBranchAddress("RunTrailer", &runt);      rt->SetBranchAddress("RunTrailer", &runt);
976      //      //
977      //    Int_t rhev = rh->GetEntries();      Int_t nrhev = rh->GetEntries();
978      //    Int_t rtev = rt->GetEntries();      Int_t nrtev = rt->GetEntries();
979        if ( IsDebug() ) printf(" ou nevent %i rhev %i rtev %i \n",nevent,nrhev,nrtev);
980      //      //
981      if ( rhev > 0 ){      if ( nrhev > 0 ){
982        rh->GetEntry(0);        for (Int_t i=0; i<nrhev; i++){
983        //          //
984        TSYNC = runh->LAST_TIME_SYNC_INFO;          rh->GetEntry(i);
985        OBT = runh->OBT_TIME_SYNC * 1000;          //
986        //          TSYNC = runh->LAST_TIME_SYNC_INFO;
987        TYPE = 20;          OBT = runh->OBT_TIME_SYNC * 1000;
988        //          //
989        if ( TSYNC && OBT ){          TYPE = 20;
990          existsts = true;          //
991          goto out;          if ( IsDebug() ) printf("runheader %i tsync %u obt %u \n",i,TSYNC,OBT);
992            //
993            if ( TSYNC && OBT ){
994              existsts = true;
995              goto eout;
996            };
997        };        };
998        //        //
999      };      };
1000      if ( rtev > 0 ){      if ( nrtev > 0 ){
       rt->GetEntry(0);  
1001        //        //
1002        TSYNC = runt->LAST_TYME_SYNC_INFO;        if ( IsDebug() ) printf(" No runheader \n");
1003        OBT = runt->OBT_TYME_SYNC * 1000;        signal = 6;
1004        //        //
1005        TYPE = 21;        for (Int_t i=0; i<nrtev; i++){
1006        //          //
1007        if ( TSYNC && OBT ){          rt->GetEntry(i);
1008          existsts = true;          //
1009          goto out;          TSYNC = runt->LAST_TYME_SYNC_INFO;
1010            OBT = runt->OBT_TYME_SYNC * 1000;
1011            //
1012            TYPE = 21;
1013            //
1014            if ( IsDebug() ) printf("runtrailer %i tsync %u obt %u \n",i,TSYNC,OBT);
1015            //
1016            if ( TSYNC && OBT ){
1017              existsts = true;
1018              goto eout;
1019            };
1020        };        };
1021        //        //
1022        } else {
1023          if ( IsDebug() ) printf(" No runheader \n");
1024      };      };
1025    };    };
1026    //    //
1027    if ( !existsts ){ // try with inclination mcmd    if ( !existsts ){ // try with inclination mcmd
1028        //
1029        if ( IsDebug() ) printf(" No runtrailer \n");
1030        signal = 14;
1031        //
1032      Double_t timesync = 0.;      Double_t timesync = 0.;
1033      for (UInt_t i=0; i<nevent;i++){      for (UInt_t i=0; i<nevent;i++){
1034        //        //
# Line 800  Int_t PamelaDBOperations::insertPamelaGL Line 1057  Int_t PamelaDBOperations::insertPamelaGL
1057        TYPE = 666;        TYPE = 666;
1058        if ( TSYNC && OBT ){        if ( TSYNC && OBT ){
1059          existsts = true;          existsts = true;
1060          goto out;          goto eout;
1061        };        };
1062      };      };
1063    };    };
1064    //    //
1065    if ( !existsts && obt0 ){ // insert timesync by hand    if ( !existsts && obt0 ){ // insert timesync by hand
1066        //
1067        if ( IsDebug() ) printf(" No incl mcmd \n");
1068        signal = 30;
1069        //
1070      OBT = obt0;      OBT = obt0;
1071      TSYNC = tsync;      TSYNC = tsync;
1072      TYPE = 999;      TYPE = 999;
1073      existsts = true;      existsts = true;
1074      goto out;      goto eout;
1075    };    };
1076    //    //
1077   out:   eout:
1078    //    //
1079    if ( !existsts ) throw -3;    if ( !existsts ) throw -3;
1080    //    //
# Line 829  Int_t PamelaDBOperations::insertPamelaGL Line 1090  Int_t PamelaDBOperations::insertPamelaGL
1090    toffset = (UInt_t)TSYNC - (UInt_t)(this->OBT(OBT)/1000) + t0;    toffset = (UInt_t)TSYNC - (UInt_t)(this->OBT(OBT)/1000) + t0;
1091    //    //
1092    delete result;    delete result;
1093    return(0);    return(signal);
1094  }  }
1095    
1096  /**  /**
# Line 907  Int_t PamelaDBOperations::assignBOOT_NUM Line 1168  Int_t PamelaDBOperations::assignBOOT_NUM
1168        << " NAME = '" << this->GetRawFile().Data() << "' ";        << " NAME = '" << this->GetRawFile().Data() << "' ";
1169    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1170    //    //
1171    if ( !result ) return(8);    if ( !result ) throw -4;;
1172    row = result->Next();    row = result->Next();
1173    if ( !row ) return(16);    if ( !row ) return(16);
1174    if ( row->GetField(1) ){    if ( row->GetField(1) ){
1175      this->SetBOOTnumber((UInt_t)atoll(row->GetField(1)));      this->SetBOOTnumber((UInt_t)atoll(row->GetField(1)));
1176      return(1);      return(1);
1177    };    };
1178    if ( !row->GetField(0) ) return(8);    if ( !row->GetField(0) ) throw -26;
1179    //    //
1180    UInt_t idRaw = (UInt_t)atoll(row->GetField(0));    UInt_t idRaw = (UInt_t)atoll(row->GetField(0));
1181    //    //
# Line 924  Int_t PamelaDBOperations::assignBOOT_NUM Line 1185  Int_t PamelaDBOperations::assignBOOT_NUM
1185    trDumpEv = (TTree*)file->Get("VarDump");    trDumpEv = (TTree*)file->Get("VarDump");
1186    if ( !trDumpEv || trDumpEv->IsZombie() ) throw -20;    if ( !trDumpEv || trDumpEv->IsZombie() ) throw -20;
1187    //    //
   if (trDumpEv == NULL) return(2);  
   //      
1188    VarDumpEvent  *vde = 0;    VarDumpEvent  *vde = 0;
1189    VarDumpRecord *vdr = 0;    VarDumpRecord *vdr = 0;
1190    //    //
1191    trDumpEv->SetBranchAddress("VarDump", &vde);    trDumpEv->SetBranchAddress("VarDump", &vde);
1192    if (trDumpEv->GetEntries() > 0){    if ( trDumpEv->GetEntries() > 0 ){
1193      trDumpEv->GetEntry(0);      Bool_t found = false;
1194      vde->Records->GetEntries();      for ( Int_t i = 0; i < trDumpEv->GetEntries(); i++){
1195      if ( !vde->Records->GetEntries() ){        trDumpEv->GetEntry(i);
1196        if ( !this->GetBOOTnumber() ) return(4);        vde->Records->GetEntries();
1197      } else {        if ( vde->Records->GetEntries()>0 ){
1198            found = true;
1199            goto fill;
1200          };
1201        };
1202      fill:
1203        if ( found ){
1204          //
1205        vdr = (VarDumpRecord*)vde->Records->At(6);        vdr = (VarDumpRecord*)vde->Records->At(6);
1206          //
1207        this->SetBOOTnumber((Int_t)vdr->VAR_VALUE);        this->SetBOOTnumber((Int_t)vdr->VAR_VALUE);
1208          //
1209        } else {
1210          if ( !this->GetBOOTnumber() ) return(4);
1211      };      };
1212    } else {    } else {
1213      if ( !this->GetBOOTnumber() ) return(2);      if ( !this->GetBOOTnumber() ) return(2);
# Line 1023  Int_t PamelaDBOperations::insertPamelaRU Line 1293  Int_t PamelaDBOperations::insertPamelaRU
1293          //          //
1294          if ( IsDebug() ) printf(" Missing header %i %i %i\n",ptht,pth,ptt);          if ( IsDebug() ) printf(" Missing header %i %i %i\n",ptht,pth,ptt);
1295          //          //
1296          if ( (ptt-1) < 0 ) throw -15;          if ( (ptt-1) < 0 ) throw -15; // should never arrive here!
1297          rt->GetEntry(ptt-1);          rt->GetEntry(ptt-1);
1298          cod = eht->GetCounter();          cod = eht->GetCounter();
1299          evbefh = cod->Get(pctp->Physics);          evbefh = cod->Get(pctp->Physics);
# Line 1129  Int_t PamelaDBOperations::insertPamelaRU Line 1399  Int_t PamelaDBOperations::insertPamelaRU
1399            if ( (UInt_t)evbeft < upperentry-1 ){            if ( (UInt_t)evbeft < upperentry-1 ){
1400              if ( IsDebug() ) printf(" Piece of run at the end of the file with NO RUNHEADER!\n");              if ( IsDebug() ) printf(" Piece of run at the end of the file with NO RUNHEADER!\n");
1401              //              //
1402              if ( (ptt-1) < 0 ) throw -15;              if ( (ptt-1) < 0 ) throw -15; // should never arrive here!
1403              rt->GetEntry(ptt-1);              rt->GetEntry(ptt-1);
1404              cod = eht->GetCounter();              cod = eht->GetCounter();
1405              evbefh = cod->Get(pctp->Physics);              evbefh = cod->Get(pctp->Physics);
# Line 2106  void PamelaDBOperations::HandleSuspiciou Line 2376  void PamelaDBOperations::HandleSuspiciou
2376    if ( firstev == lastev+1 ) { // no events inside the run!    if ( firstev == lastev+1 ) { // no events inside the run!
2377      if ( IsDebug() ) printf(" Checking but no events in the run! \n");      if ( IsDebug() ) printf(" Checking but no events in the run! \n");
2378      //      //
     //    if ( IsDebug() ) printf(" -> fill the DB \n");  
     //  
2379      this->FillClass();      this->FillClass();
2380      if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);          if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);    
2381      //      //
# Line 2318  Int_t PamelaDBOperations::insertCALO_CAL Line 2586  Int_t PamelaDBOperations::insertCALO_CAL
2586    tr->SetBranchAddress("Header", &eh);    tr->SetBranchAddress("Header", &eh);
2587    nevents = tr->GetEntries();    nevents = tr->GetEntries();
2588    //    //
2589    if ( !nevents ) return(0);    if ( !nevents ) return(1);
2590    //    //
2591    for (UInt_t i=0; i < nevents; i++){    for (UInt_t i=0; i < nevents; i++){
2592      tr->GetEntry(i);      tr->GetEntry(i);
# Line 2635  Int_t PamelaDBOperations::insertTRK_CALI Line 2903  Int_t PamelaDBOperations::insertTRK_CALI
2903    tr2->SetBranchAddress("Header", &eh2);    tr2->SetBranchAddress("Header", &eh2);
2904    nevents2 = tr2->GetEntries();    nevents2 = tr2->GetEntries();
2905    //    //
2906    if ( !nevents1 && !nevents2 ) return(0);    if ( !nevents1 && !nevents2 ) return(1);
2907    //    //
2908    t2 = -1;    t2 = -1;
2909    Int_t pret2 = 0;    Int_t pret2 = 0;
# Line 2807  Int_t PamelaDBOperations::insertS4_CALIB Line 3075  Int_t PamelaDBOperations::insertS4_CALIB
3075    stringstream oss;    stringstream oss;
3076    oss.str("");    oss.str("");
3077    //    //
   CalibS4Event *calibS4    = new  CalibS4Event();  
3078    TTree *tr = 0;    TTree *tr = 0;
3079    EventHeader *eh = 0;    EventHeader *eh = 0;
3080    PscuHeader *ph = 0;    PscuHeader *ph = 0;
# Line 2821  Int_t PamelaDBOperations::insertS4_CALIB Line 3088  Int_t PamelaDBOperations::insertS4_CALIB
3088    tr = (TTree*)file->Get("CalibS4");    tr = (TTree*)file->Get("CalibS4");
3089    if ( !tr || tr->IsZombie() ) throw -24;    if ( !tr || tr->IsZombie() ) throw -24;
3090    //    //
   tr->SetBranchAddress("CalibS4", &calibS4);  
3091    tr->SetBranchAddress("Header", &eh);    tr->SetBranchAddress("Header", &eh);
3092    //    //
3093    nevents = tr->GetEntries();    nevents = tr->GetEntries();
3094    //    //
3095    if ( !nevents ) return(0);    if ( !nevents ) return(1);
3096    //    //
3097    for (UInt_t i = 0; i < nevents; i++){    for (UInt_t i = 0; i < nevents; i++){
3098      //      //
3099      tr->GetEntry(i);      tr->GetEntry(i);
     TArrayD params = S4_paramfit(calibS4);  
3100      //      //
3101      ph = eh->GetPscuHeader();      ph = eh->GetPscuHeader();
3102      obt = ph->GetOrbitalTime();        obt = ph->GetOrbitalTime();  
# Line 2921  Int_t PamelaDBOperations::insertS4_CALIB Line 3186  Int_t PamelaDBOperations::insertS4_CALIB
3186          };          };
3187          //          //
3188          oss.str("");          oss.str("");
3189          oss << " INSERT INTO GL_S4_CALIB (ID,ID_ROOT_L0,EV_ROOT,FROM_TIME,TO_TIME,PARAM_FIT0,PARAM_FIT1,OBT,PKT,BOOT_NUMBER,VALIDATION) "          oss << " INSERT INTO GL_S4_CALIB (ID,ID_ROOT_L0,EV_ROOT,FROM_TIME,TO_TIME,OBT,PKT,BOOT_NUMBER) "
3190              << " VALUES (NULL,' "              << " VALUES (NULL,' "
3191              << idroot << "','"              << idroot << "','"
3192              << i << "','"              << i << "','"
3193              << fromtime << "','"              << fromtime << "','"
3194              << totime << "','"              << totime << "','"
             << dec << params.At(0) << "','"  
             << dec << params.At(1) << "','"        
3195              << obt << "','"              << obt << "','"
3196              << pkt << "','"              << pkt << "','"
3197              << this->GetBOOTnumber() << "','"              << this->GetBOOTnumber() << "');";
             << valid << "');";  
3198          //          //
3199          if ( IsDebug() ) printf(" Insert the new calibration: query is \n %s \n",oss.str().c_str());          if ( IsDebug() ) printf(" Insert the new calibration: query is \n %s \n",oss.str().c_str());
3200          //          //
# Line 2953  Int_t PamelaDBOperations::insertS4_CALIB Line 3215  Int_t PamelaDBOperations::insertS4_CALIB
3215    return(0);    return(0);
3216  };  };
3217    
3218    /**
3219     * Scan the fragment table and move old fragments to the GL_RUN table
3220     */
3221    Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(){
3222      //
3223      TSQLResult *result = 0;
3224      TSQLRow    *row    = 0;
3225      TSQLResult *result2 = 0;
3226      TSQLRow    *row2   = 0;
3227      //
3228      UInt_t moved = 0;
3229    //  UInt_t timelim = 0;
3230    //  TDatime *time = new TDatime();
3231      //
3232      stringstream oss;
3233      oss.str("");
3234      //
3235      //
3236      // check if there are entries older than "olderthan" seconds from now
3237      //
3238      oss.str("");
3239      oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"
3240          << " INSERT_TIME <= '" << clean_time->AsSQLString() << "';";
3241      //
3242      if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS runs older than %s : query is \n %s \n",clean_time->AsSQLString(),oss.str().c_str());
3243      result = conn->Query(oss.str().c_str());
3244      //
3245      if ( result ){
3246        //
3247        row = result->Next();
3248        //
3249        while ( row ){
3250          //
3251          oss.str("");
3252          oss << " ID= "<< row->GetField(0);
3253          //
3254          glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);  
3255          //
3256          oss.str("");
3257          oss << " SELECT ID,NEVENTS,TRK_CALIB_USED,PKT_COUNTER FROM GL_RUN WHERE "
3258              << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND ("
3259              << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3260              << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3261              << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3262              << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3263              << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3264              << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3265              << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3266              << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3267              << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3268              << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3269              << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3270              << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3271          //
3272          if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3273          result2 = conn->Query(oss.str().c_str());
3274          //
3275          if ( !result2 ) throw -4;
3276          //
3277          row2 = result2->Next();
3278          //
3279          if ( !row2 ){
3280            //
3281            if ( IsDebug() ) printf(" The run is new \n");
3282            if ( IsDebug() ) printf(" -> fill the DB \n");      
3283            //
3284            glrun->SetID(0);
3285            glrun->Fill_GL_RUN(conn);  
3286            //
3287            oss.str("");
3288            oss << " SELECT ID FROM GL_RUN WHERE "
3289                << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "
3290                << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "
3291                << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "
3292                << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "
3293                << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";
3294            //
3295            if ( IsDebug() ) printf(" Look for the ID of the inserted run: query is \n %s \n",oss.str().c_str());
3296            result2 = conn->Query(oss.str().c_str());
3297            //
3298            if ( !result2 ) throw -4;
3299            //
3300            row2 = result2->Next();
3301            //
3302            if ( !row2 ) throw -25;
3303            //
3304            oss.str("");
3305            oss << " UPDATE GL_RUN SET ID_RUN_FRAG = " << row2->GetField(0) << " WHERE ID = " << row2->GetField(0);
3306            if ( IsDebug() ) printf(" Update the ID_RUN_FRAG of the inserted run: query is \n %s \n",oss.str().c_str());
3307            result2 = conn->Query(oss.str().c_str());
3308            //
3309            if ( !result2 ) throw -4;
3310            //
3311            moved++;
3312            //
3313          } else {
3314            if ( IsDebug() ) printf(" The already exist in the GL_RUN table! \n");
3315          };
3316          if ( IsDebug() ) printf(" Delete run %s from the GL_RUN_FRAGMENTS table \n",row->GetField(0));      
3317          //
3318          //
3319          oss.str("");
3320          oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);
3321          if ( IsDebug() ) printf(" Clean the GL_RUN_FRAGMENTS table: query is \n %s \n",oss.str().c_str());
3322          result2 = conn->Query(oss.str().c_str());
3323          //
3324          if ( !result2 ) throw -4;
3325          //
3326          row = result->Next();
3327        };
3328      };
3329      if ( IsDebug() ) printf(" Moved %u runs\n",moved);
3330      return(0);
3331    };
3332    
3333  /*  /**
3334   * Fit function Received from Valeria Malvezzi 06/02/2006   * Check if runs are good, i.e. if the tracker calibration is correctly associated..
3335   */   */
3336  Double_t fitf(Double_t *x, Double_t *par){    Int_t PamelaDBOperations::ValidateRuns(){
3337    Double_t fitval =(par[0]*x[0])+par[1];    //
3338    return fitval;    TSQLResult *result = 0;
3339      TSQLRow    *row    = 0;
3340      //
3341      stringstream oss;
3342      oss.str("");
3343      //
3344      // =======================================================
3345      // validate runs by checking missing calibrations
3346      // =======================================================
3347      UInt_t t_stop  = 0;
3348      UInt_t t_start = 0;
3349      // --------------------------------------------------------------
3350      // 1) get the OBT of the last run inserted after clean-time limit
3351      // --------------------------------------------------------------
3352      oss.str("");
3353      oss << " SELECT * FROM GL_RUN  WHERE INSERT_TIME <= '" << clean_time->AsSQLString()
3354              << "' ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
3355      if ( IsDebug() ) printf(" Get start validation-time: query is \n %s \n",oss.str().c_str());
3356      result = conn->Query(oss.str().c_str());
3357      if ( !result ) throw -4;
3358      if ( !result->GetRowCount() ) {
3359              printf(" No runs to validate \n");
3360              return(1);
3361      }else{
3362            row = result->Next();
3363            t_start = (UInt_t)atoll(row->GetField(4));
3364      };  
3365      // --------------------------------------------------------------
3366      // 2) get the OBT of the last validated run
3367      // --------------------------------------------------------------
3368      oss.str("");
3369      oss << " SELECT * FROM GL_RUN  WHERE VALIDATION=1 AND RUNHEADER_TIME<="<< t_start
3370          <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
3371      if ( IsDebug() ) printf(" Get stop validation-time: query is \n %s \n",oss.str().c_str());
3372      result = conn->Query(oss.str().c_str());
3373      if ( !result ) throw -4;
3374      if ( result->GetRowCount() ){
3375              row = result->Next();
3376              t_stop = (UInt_t)atoll(row->GetField(4));
3377      };
3378      if ( IsDebug() ) printf("Validation interval: from time %i - to time %i \n\n",t_stop,t_start);
3379      // --------------------------------------------------------------
3380      // now retrieves runs to be validated
3381      // --------------------------------------------------------------
3382      oss.str("");
3383      oss << " SELECT * FROM GL_RUN  WHERE  RUNHEADER_TIME <=" << t_start;
3384      oss << " AND RUNHEADER_TIME >="<< t_stop;
3385      oss << " ORDER BY RUNHEADER_TIME DESC;";
3386    //  if ( IsDebug() )
3387      if ( IsDebug() )printf(" Check runs for validation: query is \n %s \n",oss.str().c_str());
3388      result = conn->Query(oss.str().c_str());
3389      if ( !result ) throw -4;
3390      if ( !result->GetRowCount() ) printf(" No runs to validate \n");
3391    //  printf("------------------------------------------------------------------------------- \n");
3392      
3393      Int_t nrow = 0;
3394      GL_RUN* this_run = new GL_RUN();
3395      GL_RUN* next_run = new GL_RUN();
3396      Int_t   nseq_max = 1000;
3397    //  UInt_t* sequence = new UInt_t[100];
3398      vector<UInt_t> sequence(nseq_max);
3399      Int_t   nseq = 0;
3400      Bool_t CHECK = false;
3401      Bool_t this_ONLINE = false;
3402      Bool_t next_ONLINE = false;
3403      UInt_t t1=0,t2=0;
3404      // ---------------------------------------------------------------------------------
3405      // - loop over runs, back in time,
3406      // - select sequences of runs close in time (less than 60 s apart),
3407      //   which could be preceeded by a calibration
3408      // - check if there might be a missing calibration
3409      // ---------------------------------------------------------------------------------
3410      while(1){
3411              
3412              row = result->Next();
3413              if( row == NULL ) break;
3414              
3415              //------------
3416              //get run info
3417              //------------
3418              this_run->Set_GL_RUN(row);
3419                      
3420              Bool_t this_BAD = false;
3421              if(this_run->GetTRK_CALIB_USED() == 1 || this_run->GetTRK_CALIB_USED() == 2) this_ONLINE = true;
3422              else if (this_run->GetTRK_CALIB_USED() == 104)                          this_ONLINE = false;
3423              else{
3424    //                printf("Missing or corrupted header!! \n");
3425                      this_ONLINE = false;
3426                      this_BAD = true;
3427              };
3428    
3429              //-----------------------------------
3430              //compare with previous(next in time)
3431              //-----------------------------------
3432              CHECK = false;
3433              UInt_t interval=0;
3434              
3435              if( nrow != 0){
3436            
3437                      
3438                      t1 = this_run->GetRUNTRAILER_TIME();
3439                      t2 = next_run->GetRUNHEADER_TIME();
3440                      interval = (t2-t1);
3441                      
3442                      if(this_ONLINE && next_ONLINE){                               // this: ON-LINE + next: ON-LINE
3443                              
3444                              if( this_run->ID == next_run->ID_RUN_FRAG ) interval = 0;     //=> run fragments
3445                              
3446                              if( interval >= 60 )CHECK = true;                     //more than 60 s => there might be a calibration
3447                              
3448                              if( !CHECK && this_run->VALIDATION ){
3449                                      for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);
3450                                      nseq=0;
3451                              }
3452                      
3453                      }else if( !this_ONLINE && next_ONLINE) {              // this: DEFAULT + next:ON-LINE
3454                              
3455                              CHECK = true;
3456    
3457                      }else if( !next_ONLINE ){                                             // this:ANY + next:DEFAULT
3458                              
3459                              assignVALIDATION(next_run->ID,true);
3460                              nseq=0;
3461                      }
3462              }
3463    
3464              //----------------------------
3465              //check run sequence for calib
3466              //----------------------------
3467              if( CHECK ){
3468                      // check if calibration exists
3469                      if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval);
3470                      Bool_t MISSING = MissingTRK_CALIB(t1,t2);
3471                      for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],!MISSING);
3472                      nseq=0;
3473              };
3474              //--------------
3475              //store run info
3476              //--------------
3477              *next_run   = *this_run;
3478              next_ONLINE = this_ONLINE;
3479              if( !this_BAD ){
3480                      if(nseq < nseq_max){
3481                              sequence[nseq] = this_run->ID;
3482                              nseq++;
3483                      }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);
3484              };
3485              
3486              if ( IsDebug() ) printf("%i Run %i \n",nrow,this_run->ID);
3487              nrow++;
3488              
3489      };
3490      delete this_run;
3491      delete next_run;
3492      //
3493      return(0);
3494    };
3495    /**
3496     * Check if there might be a missing tracker calibration in a given time interval
3497     * @param t1 From absolute time
3498     * @param t2 To absolute time
3499     * @return true if there might be a missing calibration
3500     */
3501    Bool_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
3502            
3503            GL_TRK_CALIB* trkcalib = new GL_TRK_CALIB();
3504            
3505            // get the closest VALIDATED calibration before the run start (t2)
3506            if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(true);      //>>> missing
3507            
3508            if ( trkcalib->TO_TIME  < t2 ) return(true);                                    //>>> missing
3509            
3510            //==============================================================
3511            // Check is done first on the basis of time between calibration,
3512            // which should be equal to the time between ascending-nodes.
3513            //==============================================================
3514            if ( t2 - trkcalib->FROM_TIME > 5700) {
3515                    if ( IsDebug() )printf("Long time between calib and run start %i :-( ==> there might be a missing calib \n",t2 - trkcalib->FROM_TIME);
3516            //==============================================================
3517            // there might be a missing calibration, due to:
3518            // - MM full
3519            // - corrupted packets
3520            // - loss of data
3521            // There is an exception in case a download was done during ascending node
3522            //==============================================================
3523                    Bool_t DOWNLOAD = false;
3524                    // check if the calib was skipped becouse of download .... DA FARE!!
3525                    if(DOWNLOAD)return(false);
3526                    
3527                    return(true);                                   //>>> missing
3528                    
3529            };
3530            
3531            //==============================================================
3532            // If the last calibration is close to the run less than this time,
3533            // it is enough to say that there are no missing calibrations
3534            //==============================================================
3535            // the long time interval bewteen runs might be due to download
3536            if ( IsDebug() )printf("Short time between calib and run start %i :-) ==> OK! \n",t2 - trkcalib->FROM_TIME);
3537            return(false);
3538            
3539    };
3540    /**
3541     * Assign VALIDATION value to a GL_RUN entry
3542     * @param idrun Run ID
3543     * @param validation true/false
3544     */
3545    Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, Bool_t validation){
3546            TSQLResult *result = 0;
3547            stringstream oss;
3548            oss.str("");
3549            oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";
3550            //
3551    //      if ( IsDebug() )
3552    //      printf(" Set VALIDATION = %i for run %i \n",validation,idrun);
3553            if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());
3554            result = conn->Query(oss.str().c_str());
3555            if ( !result ) throw -4;
3556            return(0);
3557  }  }
3558    
 /*  
  * Fit the S4 calibration with a straight line - Received from Valeria Malvezzi 06/02/2006  
  */  
 TArrayD PamelaDBOperations::S4_paramfit(pamela::CalibS4Event *S4CalibEvent){        
3559    
   //----------- variable initialization -------------------------------------------------  
3560    
3561    Double_t mip[3]={1, 30, 300};  // Insert TLEs from file tlefilename in the table GL_TLE in the db
3562    Double_t adc[3] = {0.,0.,0.};  // opened by conn, sorting them by date from older to newer, if each
3563      // TLE has not been alread inserted.
3564    TArrayD parametri(2);  Int_t PamelaDBOperations::populateTLE()//(TSQLServer *conn, char *tleFile)
3565    {
3566    valid = 1;    fstream tlefile(tlefilename, ios::in);
3567    
3568      if ( !tlefile ) throw -7;
3569    
3570      vector<cTle*> ctles;
3571      vector<cTle*>::iterator iter;
3572      int present = 0;
3573    
3574      // Get three lines from tlefile, create a cTle object and put it
3575      // into ctles
3576      while(1) {
3577        cTle *tlef;
3578        string str1, str2, str3;
3579    
3580        getline(tlefile, str1);
3581        if(tlefile.eof()) break;
3582    
3583        getline(tlefile, str2);
3584        if(tlefile.eof()) break;
3585    
3586        getline(tlefile, str3);
3587        if(tlefile.eof()) break;
3588    
3589        // We now have three good lines for a cTle.
3590        tlef = new cTle(str1, str2, str3);
3591        ctles.push_back(tlef);
3592      }
3593    
3594      tlefile.close();
3595    
3596      // Sort by date
3597      sort(ctles.begin(), ctles.end(), compTLE);
3598    
3599      // Now we insert each TLE into the db
3600      for(iter = ctles.begin(); iter != ctles.end(); iter++) {
3601        cTle *tle = *iter;
3602    
3603        // Do nothing if it's already present in the db.  Just increase
3604        // the counter present.
3605        if (! isTlePresent(tle))
3606          {
3607            int status = insertTle(tle);
3608    
3609            // Insert query failed.  Return 1.
3610            if(status == EXIT_FAILURE) {
3611              
3612              if( IsDebug() ) {
3613                cerr << "Error: inserting TLE:" << endl
3614                     << tle->getName() << endl
3615                     << tle->getLine1() << endl
3616                     << tle->getLine2() << endl;
3617              }
3618    
3619              throw -4;
3620              return 1;
3621            }
3622    
3623          }
3624        else
3625          present++;
3626    
3627      }
3628    
3629      int inserted = ctles.size() - present;  // Number of inserted TLE.
3630      if ( IsDebug() )
3631        cout << "\nProcessed TLEs ranging from " << getTleDatetime(ctles[0]) << " to " << getTleDatetime(ctles[ctles.size()-1]) << "." << endl
3632             << inserted << " newly inserted TLEs out of " << ctles.size() << " processed." << endl;
3633    
3634      ctles.clear();
3635    
3636    
3637      // Return 2 if no new TLE has been inserted.  0 otherwise.
3638      if(! inserted ) return 2;
3639      return 0;
3640    }
3641    
   //------------ Fit calibrations and find parameters to calibrate data ------------------  
   pamela::S4::S4Event  *s4Record;  
3642    
3643    for (Int_t j = 0; j < 4; j++){  // Insert tle in the table GL_TLE using the connection conn.
3644      for (Int_t i = 0; i < 128; i++){  int PamelaDBOperations::insertTle(cTle *tle)
3645        s4Record = (pamela::S4::S4Event*)S4CalibEvent->Records->At((j*128 + i));  {
3646        switch (j) {    stringstream oss;
3647        case 0 :{    TSQLResult *result = 0;
         adc[0]=adc[0]+((s4Record->S4_DATA)-32);  
         break;  
       };  
       case 1 :{  
         adc[1]=adc[1]+((s4Record->S4_DATA)-32);  
         break;  
       };  
       case 3 :{  
         adc[2]=adc[2]+((s4Record->S4_DATA)-32);  
         break;  
       };  
       };  
     };  
   };  
     
   adc[0]=adc[0]/128;  
   adc[1]=adc[1]/128;  
   adc[2]=adc[2]/128;  
     
   TGraph *fitpar = new TGraph (3, adc, mip);  
   TF1 *func = new TF1("fitf", fitf, -0., 1000., 2); // definizione della funzione, 2 = num. parametri  
     
   func->SetParameters(0.3,1.);        //inizializzazione dei parametri a 1  
   func->SetParNames("m","q");      //definisce il nome dei parametri  
   fitpar->Fit(func,"qr");          //fitta fitpar con la funzione func nel range definito nella funzione  
   //fitpar->Fit(func,"r");          //fitta fitpar con la funzione func nel range definito nella funzione  
       
   parametri[0] = func -> GetParameter(0);  
   parametri[1] = func -> GetParameter(1);  
3648    
3649    if ( parametri[0] < 0. || parametri[0] > 0.5 || parametri[1] < 0.8 || parametri[1] > 1. ) valid = 0;    oss.str("");
3650      oss << " INSERT INTO GL_TLE (TLE1, TLE2, TLE3, FROM_TIME)"
3651          << " VALUES ( '"
3652          << tle->getName() << "', '"
3653          << tle->getLine1() << "', '"
3654          << tle->getLine2() << "', '"
3655          << getTleDatetime(tle) << "')";
3656    
3657    if ( IsDebug() ) printf(" par1 = %g par2 = %g\n",parametri[0],parametri[1]);    //  cout << oss.str().c_str() << endl;
3658      result = conn->Query(oss.str().c_str());
3659    return parametri;    if (result == NULL)
3660  };      return EXIT_FAILURE;
3661    
3662      return EXIT_SUCCESS;
3663    }
3664    
3665    
3666    // Return whether tle is already in the db connected by conn.
3667    bool PamelaDBOperations::isTlePresent(cTle *tle)
3668    {
3669      stringstream oss;
3670      TSQLResult *result = 0;
3671    
3672      oss.str("");
3673      oss << "SELECT * FROM GL_TLE WHERE FROM_TIME = '"
3674          << getTleDatetime(tle) << "'";
3675    
3676      result = conn->Query(oss.str().c_str());
3677      if (result == NULL) throw -4;
3678    
3679      if (result->GetRowCount())
3680        return true;
3681      else
3682        return false;
3683    }
3684    
3685    
3686    // Return whether the first TLE is dated early than the second
3687    bool compTLE (cTle *tle1, cTle *tle2)
3688    {
3689      return getTleJulian(tle1) < getTleJulian(tle2);
3690    }
3691    
3692    
3693    // Return the date of the tle using the format (year-2000)*1e3 +
3694    // julian day.  e.g. 6365 is the 31th Dec 2006.
3695    // It does *not* return a cJulian date.
3696    float getTleJulian(cTle *tle) {
3697      return tle->getField(cTle::FLD_EPOCHYEAR)*1e3 + tle->getField(cTle::FLD_EPOCHDAY);
3698    }
3699    
3700    
3701    // Return a string like YYYY-MM-DD hh:mm:ss, usable for mysql datetime
3702    // format.
3703    string getTleDatetime(cTle *tle)
3704    {
3705      int year, mon, day, hh, mm, ss;
3706      double dom; // day of month (is double!)
3707      stringstream date; // date in datetime format
3708    
3709      // create a cJulian from the date in tle
3710      cJulian jdate = cJulian( 2000 + (int) tle->getField(cTle::FLD_EPOCHYEAR), tle->getField(cTle::FLD_EPOCHDAY));
3711    
3712      // get year, month, day of month
3713      jdate.getComponent(&year, &mon, &dom);
3714    
3715      // build a datetime YYYY-MM-DD hh:mm:ss
3716      date.str("");
3717      day = (int) floor(dom);
3718      hh = (int) floor( (dom - day) * 24);
3719      mm = (int) floor( ((dom - day) * 24 - hh) * 60);
3720      ss = (int) floor( ((((dom - day) * 24 - hh) * 60 - mm) * 60));
3721      //  ms = (int) floor( (((((dom - day) * 24 - hh) * 60 - mm) * 60) - ss) * 1000);
3722    
3723      date << year << "-" << mon << "-" << day << " " << hh << ":" << mm << ":" << ss;
3724    
3725      return date.str();
3726    }

Legend:
Removed from v.1.1  
changed lines
  Added in v.1.12

  ViewVC Help
Powered by ViewVC 1.1.23