/[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.14 by mocchiut, Fri Oct 20 11:39:37 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 <sgp4.h>
35    
36  #include <PamelaDBOperations.h>  #include <PamelaDBOperations.h>
37  //  //
38  using namespace std;  using namespace std;
39  using namespace pamela;  using namespace pamela;
40  //using namespace yngn::util;  
41    // Some function to work with cTle stuff.
42    bool compTLE(cTle* tle1, cTle *tle2);
43    float getTleJulian(cTle *);
44    string getTleDatetime(cTle*);
45    
46  /**  /**
47   * Constructor.   * Constructor.
# Line 48  using namespace pamela; Line 54  using namespace pamela;
54   * @param obt0         file obt0.   * @param obt0         file obt0.
55   * @param tsync        file timesync.   * @param tsync        file timesync.
56   * @param debug        debug flag.   * @param debug        debug flag.
57     * @param tlefilename  ascii file with TLE 3 line elements.
58   */   */
59  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){
60    //    //
61    //    //
62    SetConnection(host,user,password);    SetConnection(host,user,password);
# Line 63  PamelaDBOperations::PamelaDBOperations(T Line 70  PamelaDBOperations::PamelaDBOperations(T
70    SetTsync(tsync);    SetTsync(tsync);
71    SetObt0(obt0);    SetObt0(obt0);
72    //    //
73      SetTLEPath(tlefilename);
74    //    //
   SetRootName(filerootname);  
   SetRawName(filerawname);  
75    //    //
76    this->OpenFile();    INSERT_RAW =!filerawname.IsNull();
77      if(INSERT_RAW)SetRawName(filerawname);
78      //
79      INSERT_ROOT = !filerootname.IsNull();
80      if( INSERT_ROOT ){
81        this->SetRootName(filerootname);
82        this->SetOrbitNo();
83        file = TFile::Open(this->GetRootName().Data());
84      };
85    //    //
86    this->SetID_RAW(0);    this->SetID_RAW(0);
87    this->SetID_ROOT(0);    this->SetID_ROOT(0);
88    
89      VALIDATE = false;
90      
91    //    //
92  };  };
93    
# Line 79  PamelaDBOperations::PamelaDBOperations(T Line 96  PamelaDBOperations::PamelaDBOperations(T
96   */   */
97  void PamelaDBOperations::Close(){  void PamelaDBOperations::Close(){
98    if( conn && conn->IsConnected() ) conn->Close();    if( conn && conn->IsConnected() ) conn->Close();
99      delete clean_time;
100    delete glrun;    delete glrun;
101    delete this;    delete this;
102  };  };
# Line 87  void PamelaDBOperations::Close(){ Line 105  void PamelaDBOperations::Close(){
105  // SETTERS  // SETTERS
106  //  //
107    
108    //
109    // 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
110    //
111    void PamelaDBOperations::CheckValidate(Long64_t olderthan){
112      clean_time = new TDatime();
113      if(olderthan >= 0){
114        VALIDATE = true;
115        UInt_t timelim = 0;
116        timelim =  (UInt_t)clean_time->Convert() - olderthan;
117        clean_time->Set(timelim,false);
118      };
119    };
120    
121  /**  /**
122   * Open the DB connection   * Open the DB connection
123   * @param host         hostname for the SQL connection.   * @param host         hostname for the SQL connection.
# Line 94  void PamelaDBOperations::Close(){ Line 125  void PamelaDBOperations::Close(){
125   * @param password     password for the SQL connection.   * @param password     password for the SQL connection.
126   */   */
127  void PamelaDBOperations::SetConnection(TString host, TString user, TString password){  void PamelaDBOperations::SetConnection(TString host, TString user, TString password){
128      if ( IsDebug() ) printf(" Connecting using host = %s user = %s password = %s \n",host.Data(),user.Data(),password.Data());
129    conn = TSQLServer::Connect(host.Data(),user.Data(),password.Data());    conn = TSQLServer::Connect(host.Data(),user.Data(),password.Data());
130  };  };
131    
# Line 162  void PamelaDBOperations::SetRootName(TSt Line 194  void PamelaDBOperations::SetRootName(TSt
194  };  };
195    
196  /**  /**
197     * Store the downlink orbit number from filename.
198     */
199    void PamelaDBOperations::SetOrbitNo(){
200      dworbit = 0;
201      TString name = this->GetRootFile();
202      Int_t nlength = name.Length();
203      if ( nlength < 5 ) return;
204      TString dwo = 0;
205      for (Int_t i = 0; i<5; i++){
206        dwo.Append(name[i],1);
207      };
208      if ( dwo.IsDigit() ){
209        dworbit = (UInt_t)dwo.Atoi();
210      } else {
211        dwo="";
212        for (Int_t i = 8; i<13; i++){
213          dwo.Append(name[i],1);
214        };    
215        if ( dwo.IsDigit() ) dworbit = (UInt_t)dwo.Atoi();
216      };
217      if ( IsDebug() ) printf(" Downlink orbit is %i (dwo = %s) \n",dworbit,dwo.Data());
218      return;
219    };
220    
221    
222    
223    /**
224   * Store the NOBOOT flag.   * Store the NOBOOT flag.
225   * @param noboot    true/false.   * @param noboot    true/false.
226   */   */
# Line 170  void PamelaDBOperations::SetNOBOOT(Bool_ Line 229  void PamelaDBOperations::SetNOBOOT(Bool_
229  };  };
230    
231  /**  /**
232     * Store path to the TLE file.
233     */
234    void PamelaDBOperations::SetTLEPath(TString str){
235      tlefilename = str;
236    };
237    
238    /**
239     * Store the olderthan variable
240     * @param olderthan
241     */
242    // void PamelaDBOperations::SetOlderThan(Long64_t oldthan){
243    //   olderthan = oldthan;
244    // };
245    
246    /**
247   * Retrieve the ID_RAW, if exists, returns NULL if does not exist.   * Retrieve the ID_RAW, if exists, returns NULL if does not exist.
248   */   */
249  Bool_t PamelaDBOperations::SetID_RAW(){  Bool_t PamelaDBOperations::SetID_RAW(){
# Line 181  Bool_t PamelaDBOperations::SetID_RAW(){ Line 255  Bool_t PamelaDBOperations::SetID_RAW(){
255        << " PATH = '" << this->GetRawPath().Data() << "' AND "        << " PATH = '" << this->GetRawPath().Data() << "' AND "
256        << " NAME = '" << this->GetRawFile().Data() << "' ";        << " NAME = '" << this->GetRawFile().Data() << "' ";
257    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
258    if (result == NULL) throw -4;    if ( result == NULL ) throw -4;
259    row = result->Next();    row = result->Next();
260    if (row == NULL) return false;    if ( !row ) return(false);
261    delete result;    delete result;
262    id = (UInt_t)atoll(row->GetField(0));    id = (UInt_t)atoll(row->GetField(0));
263    return(true);    return(true);
# Line 216  Int_t PamelaDBOperations::SetUpperLimits Line 290  Int_t PamelaDBOperations::SetUpperLimits
290    ULong64_t upperobt2 = 0;    ULong64_t upperobt2 = 0;
291    UInt_t zomp = 0;    UInt_t zomp = 0;
292    UInt_t jump = 50000; // was 5000    UInt_t jump = 50000; // was 5000
293      EventCounter *code=0;
294      //
295      UInt_t deltapkt = 5000;
296      ULong64_t deltaobt = 50000;
297      //
298      //   pcksList packetsNames;
299      //   pcksList::iterator Iter;
300      //   getPacketsNames(packetsNames);
301    //    //
302    pktfirst = 0;    pktfirst = 0;
303    obtfirst = 0;    obtfirst = 0;
# Line 233  Int_t PamelaDBOperations::SetUpperLimits Line 315  Int_t PamelaDBOperations::SetUpperLimits
315    pktfirst = ph->GetCounter();    pktfirst = ph->GetCounter();
316    obtfirst = ph->GetOrbitalTime();      obtfirst = ph->GetOrbitalTime();  
317    //    //
318      //   code = eh->GetCounter();
319      //   UInt_t en = 0;
320      //   for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
321      //     en = code->Get(GetPacketType(*Iter));
322      //     if ( en ) printf(" Packet type is %s, entries: %i \n",*Iter,en);
323      //};  
324      //
325    T->GetEntry(nevent-1);    T->GetEntry(nevent-1);
326    ph = eh->GetPscuHeader();    ph = eh->GetPscuHeader();
327    pktlast = ph->GetCounter();    pktlast = ph->GetCounter();
# Line 252  Int_t PamelaDBOperations::SetUpperLimits Line 341  Int_t PamelaDBOperations::SetUpperLimits
341    //    //
342    if ( nevent < 2 ) return(4);    if ( nevent < 2 ) return(4);
343    //    //
344    if ( PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst) ){    if ( (PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) || (labs(PKT(pktlast)-PKT(pktfirst))<deltapkt && labs(OBT(obtlast)-OBT(obtfirst))<deltaobt) ){
345        //
346      // go back      // go back
347      zomp = nevent - 2;      zomp = nevent - 2;
348      //      //
# Line 301  Int_t PamelaDBOperations::SetUpperLimits Line 391  Int_t PamelaDBOperations::SetUpperLimits
391    // 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)
392    //    //
393    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);  
394    TTree *rh=(TTree*)file->Get("RunHeader");    TTree *rh=(TTree*)file->Get("RunHeader");
395    if ( !rh || rh->IsZombie() ) throw -17;    if ( !rh || rh->IsZombie() ) throw -17;
396    TTree *rt=(TTree*)file->Get("RunTrailer");    TTree *rt=(TTree*)file->Get("RunTrailer");
# Line 319  Int_t PamelaDBOperations::SetUpperLimits Line 404  Int_t PamelaDBOperations::SetUpperLimits
404    //    //
405    rhev = rh->GetEntries();    rhev = rh->GetEntries();
406    rtev = rt->GetEntries();    rtev = rt->GetEntries();
407      UInt_t sobtt = 0;
408      UInt_t sobth = 0;
409      UInt_t spktt = 0;
410      UInt_t spkth = 0;
411    UInt_t pktt = 0;    UInt_t pktt = 0;
412    ULong64_t obtt = 0;    ULong64_t obtt = 0;
413    UInt_t pkth = 0;    UInt_t pkth = 0;
414    ULong64_t obth = 0;    ULong64_t obth = 0;
415    //    //
416      T->GetEntry(upperentry);
417      code = eh->GetCounter();
418      Int_t lasttrail = code->Get(pctp->RunTrailer);
419      Int_t lasthead = code->Get(pctp->RunHeader);
420    if ( lasttrail < rtev ){    if ( lasttrail < rtev ){
421      rt->GetEntry(lasttrail);      rt->GetEntry(lasttrail);
422      pht = eht->GetPscuHeader();      pht = eht->GetPscuHeader();
# Line 331  Int_t PamelaDBOperations::SetUpperLimits Line 424  Int_t PamelaDBOperations::SetUpperLimits
424      obtt = OBT(pht->GetOrbitalTime());      obtt = OBT(pht->GetOrbitalTime());
425    };    };
426    //    //
427      if ( lasthead < rhev ){
428        rh->GetEntry(lasthead);
429        phh = ehh->GetPscuHeader();
430        pkth = PKT(phh->GetCounter());
431        obth = OBT(phh->GetOrbitalTime());
432      };
433      //
434      if ( IsDebug() ) printf(" rhev before %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);
435      if ( pkth > upperpkt && obth > upperobt ){
436        if ( IsDebug() ) printf(" Upper limits extended to include last header: ph %i upperp %i oh %llu uppero %llu \n",pkth,upperpkt,obth,upperobt);
437        upperpkt = pkth;
438        upperobt = obth;
439        rhev = lasthead+1;
440      } else {
441        rhev = lasthead;
442      };
443      if ( IsDebug() ) printf(" rhev after %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);
444      //
445    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);
446    if ( pktt > upperpkt && obtt > upperobt ){    if ( pktt > upperpkt && obtt > upperobt ){
447      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 452  Int_t PamelaDBOperations::SetUpperLimits
452      rtev = lasttrail;      rtev = lasttrail;
453    };    };
454    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);
455      //  goto kikko;
456      //
457      //
458      // Check if runtrailer/runheader are within lower limits
459      //
460      //
461      pkth = 0;
462      obth = 0;
463      spkth = 0;
464      sobth = 0;
465      for (Int_t k=0; k<rhev; k++){
466        if ( k > 0 ){
467          spkth = pkth;
468          sobth = obth;
469        };
470        rh->GetEntry(k);
471        phh = ehh->GetPscuHeader();
472        pkth = PKT(phh->GetCounter());
473        obth = OBT(phh->GetOrbitalTime());
474        //
475    //    if ( IsDebug() ) printf(" k %i rhev before %i ph %u upperp %u oh %u uppero %u \n",k,rhev,pkth,spkth,obth,sobth);
476        //
477        if ( pkth < spkth && obth < sobth ){
478          if ( IsDebug() ) printf(" RH PROBLEMS determining the event repetition at the end of the file lasthead %i  \n",rhev);
479          //
480          rhev = k-1;
481          rh->GetEntry(rhev);
482          pkth = spkth;
483          obth = sobth;
484          //
485          UInt_t evbefh = 0;
486          code = ehh->GetCounter();
487          evbefh = code->Get(pctp->Physics);    
488          if ( evbefh >= 0 ){
489            T->GetEntry(evbefh);
490            ph = eh->GetPscuHeader();
491            t_pktlast = PKT(ph->GetCounter());
492            t_obtlast = OBT(ph->GetOrbitalTime());
493            if ( t_pktlast <= spkth && t_obtlast <= sobth ){ // jump
494              upperpkt = pkth;
495              upperobt = obth;
496              upperentry = evbefh-1;
497            } else {
498              while ( t_pktlast > spkth && t_obtlast > sobth && evbefh < nevent ){
499                evbefh++;  
500                T->GetEntry(evbefh);
501                ph = eh->GetPscuHeader();
502                t_pktlast = PKT(ph->GetCounter());
503                t_obtlast = OBT(ph->GetOrbitalTime());
504              };
505              T->GetEntry(evbefh-1);
506              ph = eh->GetPscuHeader();
507              upperpkt = PKT(ph->GetCounter());
508              upperobt = OBT(ph->GetOrbitalTime());
509              upperentry = evbefh-1;
510            };    
511          };
512          if ( IsDebug() ) printf(" rhev after %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);
513          goto kikko0;
514        };
515      };
516     kikko0:
517      //
518      //
519      //
520      pktt = 0;
521      obtt = 0;
522      spktt = 0;
523      sobtt = 0;
524      for (Int_t k=0; k<rtev; k++){
525        if ( k > 0 ){
526          spktt = pktt;
527          sobtt = obtt;
528        };
529        rt->GetEntry(k);
530        pht = eht->GetPscuHeader();
531        pktt = PKT(pht->GetCounter());
532        obtt = OBT(pht->GetOrbitalTime());
533        //
534    //    if ( IsDebug() ) printf(" k %i rtev beforev %i  pt %i upperp %i ot %llu uppero %llu \n",k,rtev,pktt,spktt,obtt,sobtt);
535        //
536        if ( pktt < spktt && obtt < sobtt ){
537          if ( IsDebug() ) printf(" RT PROBLEMS determining the event repetition at the end of the file lasttrail %i \n",rtev);
538          //
539          rtev = k-1;
540          rt->GetEntry(rtev);
541          pktt = spktt;
542          obtt = sobtt;
543          if ( IsDebug() ) printf(" lasttrail %i pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);
544          //
545          UInt_t evbeft = 0;
546          code = eht->GetCounter();
547          evbeft = code->Get(pctp->Physics);    
548          if ( evbeft >= 0 ){
549            T->GetEntry(evbeft);
550            ph = eh->GetPscuHeader();
551            t_pktlast = PKT(ph->GetCounter());
552            t_obtlast = OBT(ph->GetOrbitalTime());
553            if ( t_pktlast <= spktt && t_obtlast <= sobtt ){ // jump
554              upperpkt = pktt;
555              upperobt = obtt;
556              upperentry = evbeft-1;
557            } else {
558              while ( t_pktlast > spktt && t_obtlast > sobtt && evbeft < nevent ){
559                evbeft++;  
560                T->GetEntry(evbeft);
561                ph = eh->GetPscuHeader();
562                t_pktlast = PKT(ph->GetCounter());
563                t_obtlast = OBT(ph->GetOrbitalTime());
564              };
565              T->GetEntry(evbeft-1);
566              ph = eh->GetPscuHeader();
567              upperpkt = PKT(ph->GetCounter());
568              upperobt = OBT(ph->GetOrbitalTime());
569              upperentry = evbeft-1;
570            };
571          };
572          if ( IsDebug() ) printf(" rtev after %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);
573          goto kikko;
574          //      break;
575          //
576        };
577        //  
578      };
579      //
580     kikko:
581      //
582      T->GetEntry(upperentry);
583      code = eh->GetCounter();
584      lasttrail = code->Get(pctp->RunTrailer);
585      lasthead = code->Get(pctp->RunHeader);
586      if ( lasttrail < rtev ){
587        rt->GetEntry(lasttrail);
588        pht = eht->GetPscuHeader();
589        pktt = PKT(pht->GetCounter());
590        obtt = OBT(pht->GetOrbitalTime());
591      };
592    //    //
593    if ( lasthead < rhev ){    if ( lasthead < rhev ){
594      rh->GetEntry(lasthead);      rh->GetEntry(lasthead);
595      phh = ehh->GetPscuHeader();      phh = ehh->GetPscuHeader();
596      pkth = PKT(pht->GetCounter());      pkth = PKT(phh->GetCounter());
597      obth = OBT(pht->GetOrbitalTime());      obth = OBT(phh->GetOrbitalTime());
598    };    };
599    //    //
600    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 608  Int_t PamelaDBOperations::SetUpperLimits
608    };    };
609    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);
610    //    //
611      if ( IsDebug() ) printf(" rtev beforev %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);
612      if ( pktt > upperpkt && obtt > upperobt ){
613        if ( IsDebug() ) printf(" Upper limits extended to include last trailer: pt %i upperp %i ot %llu uppero %llu \n",pktt,upperpkt,obtt,upperobt);
614        upperpkt = pktt;
615        upperobt = obtt;
616        rtev = lasttrail+1;
617      } else {
618        rtev = lasttrail;
619      };
620      if ( IsDebug() ) printf(" rtev after %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);
621      //
622    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);
623    //    //
624    return(0);    return(0);
625  }  }
626    
627    /**
628     *
629     * Trick to have unique RUN ID numbers even when runs are deleted and mysql deamon restarted.
630     * Entries in the _RUNID_GEN table are never deleted.
631     *
632     **/
633    UInt_t PamelaDBOperations::AssignRunID(){
634      //
635      TSQLResult *result = 0;
636      TSQLRow *row = 0;
637      UInt_t runid = 0;
638      //
639      stringstream   oss;
640      //  
641      oss.str("");
642      oss << "INSERT INTO _RUNID_GEN VALUES (NULL);";
643      result = conn->Query(oss.str().c_str());
644      if ( !result ) throw -10;
645      oss.str("");
646      oss << "SELECT ID FROM _RUNID_GEN ORDER BY ID DESC LIMIT 1;";
647      result = conn->Query(oss.str().c_str());
648      if ( !result ) throw -10;
649      //
650      row = result->Next();
651      //
652      if ( !row ) throw -28;
653      //
654      runid = (UInt_t)atoll(row->GetField(0));
655      //
656      return(runid);
657    };
658    
659  //  //
660  // GETTERS  // GETTERS
661  //  //
# Line 440  const PacketType* PamelaDBOperations::Ge Line 731  const PacketType* PamelaDBOperations::Ge
731  // PRIVATE FUNCTIONS  // PRIVATE FUNCTIONS
732  //  //
733    
734  /**  // /**
735   * Open the ROOT filename for reading  // * Open the ROOT filename for reading
736   */  // */
737  void PamelaDBOperations::OpenFile(){  // void PamelaDBOperations::OpenFile(){
738    file = TFile::Open(this->GetRootName().Data());  //   file = TFile::Open(this->GetRootName().Data());
739    //   //
740    
741    void PamelaDBOperations::CheckFile(){  
742      if ( !file ) throw -12;
743  };  };
744    
745    
746  /**  /**
747   * Check if LEVEL0 file and DB connection have really be opened   * Check if LEVEL0 file and DB connection have really be opened
748   */   */
749  void PamelaDBOperations::CheckFile(){    void PamelaDBOperations::CheckConnection(){  
   //  
   if ( !file ) throw -12;  
750    //    //
751    // check connection    // check connection
752    //    //
753    if( !conn ) throw -1;        if( !conn ) throw -1;
754    bool connect = conn->IsConnected();    bool connect = conn->IsConnected();
755    if( !connect ) throw -1;        if( !connect ) throw -1;
756      if ( !dworbit ) throw -27;
757  };  };
758    
759  /**  /**
# Line 550  void PamelaDBOperations::FillClass(Bool_ Line 844  void PamelaDBOperations::FillClass(Bool_
844      lastPkt = glrun->GetRUNTRAILER_PKT();      lastPkt = glrun->GetRUNTRAILER_PKT();
845    };    };
846    //    //
847    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
848    //    //
849    if ( mishead ) {    if ( mishead ) {
850      glrun->Set_GL_RUNH0();      glrun->Set_GL_RUNH0();
# Line 639  Int_t PamelaDBOperations::insertPamelaGL Line 933  Int_t PamelaDBOperations::insertPamelaGL
933    if ( this->GetID_RAW() == 0 )  throw -11;    if ( this->GetID_RAW() == 0 )  throw -11;
934    //    //
935    oss.str("");    oss.str("");
936    oss << "SELECT OFFSET_DATE FROM GL_RESURS_OFFSET WHERE FROM_ID_RAW<= "    oss << "SELECT OFFSET_DATE FROM GL_RESURS_OFFSET WHERE SPECIAL_FILE='"
937        << id << " AND TO_ID_RAW >= "        << this->GetRawFile().Data() << "';";
       << id << ";";  
938    if ( IsDebug() ) printf(" %s \n",oss.str().c_str());    if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
939    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
940    if ( !result ) throw -10;    if ( !result ) throw -10;
941    row = result->Next();    row = result->Next();
942    if ( !row ) throw -10;    //
943      if ( !row ){
944        oss.str("");
945        oss << "SELECT OFFSET_DATE FROM GL_RESURS_OFFSET WHERE FROM_ORBIT< "
946            << dworbit << " order by FROM_ORBIT desc limit 1;";
947        if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
948        result = conn->Query(oss.str().c_str());
949        if ( !result ) throw -10;
950        row = result->Next();
951        if ( !row ) throw -10;
952      };
953    //    //
954    t0 = (UInt_t)TDatime(row->GetField(0)).Convert();    t0 = (UInt_t)TDatime(row->GetField(0)).Convert();
955    /*    /*
# Line 668  Int_t PamelaDBOperations::insertPamelaGL Line 971  Int_t PamelaDBOperations::insertPamelaGL
971    };    };
972    //    //
973    TTree *T = 0;    TTree *T = 0;
974      Int_t signal = 0;
975    //    //
976    UInt_t nevent = 0;    UInt_t nevent = 0;
977    UInt_t recEntries = 0;    UInt_t recEntries = 0;
# Line 719  Int_t PamelaDBOperations::insertPamelaGL Line 1023  Int_t PamelaDBOperations::insertPamelaGL
1023          //          //
1024          TYPE = 55;//224;          TYPE = 55;//224;
1025          //          //
1026            if ( IsDebug() ) printf("mcmd tsync %i tsync %u obt %u \n",i,TSYNC,OBT);
1027            //
1028          if ( TSYNC && OBT ){          if ( TSYNC && OBT ){
1029            existsts = true;            existsts = true;
1030            goto out;            goto eout;
1031          };          };
1032          //          //
1033        };        };
# Line 729  Int_t PamelaDBOperations::insertPamelaGL Line 1035  Int_t PamelaDBOperations::insertPamelaGL
1035    };    };
1036    if ( !existsts ) { // try with runheader and runtrailer    if ( !existsts ) { // try with runheader and runtrailer
1037      //      //
1038        if ( IsDebug() ) printf(" No ts mcmd \n");
1039        signal = 2;
1040        //
1041      TTree *rh=(TTree*)file->Get("RunHeader");      TTree *rh=(TTree*)file->Get("RunHeader");
1042      if ( !rh || rh->IsZombie() ) throw -17;      if ( !rh || rh->IsZombie() ) throw -17;
1043      TTree *rt=(TTree*)file->Get("RunTrailer");      TTree *rt=(TTree*)file->Get("RunTrailer");
# Line 738  Int_t PamelaDBOperations::insertPamelaGL Line 1047  Int_t PamelaDBOperations::insertPamelaGL
1047      //      //
1048      rt->SetBranchAddress("RunTrailer", &runt);      rt->SetBranchAddress("RunTrailer", &runt);
1049      //      //
1050      //    Int_t rhev = rh->GetEntries();      Int_t nrhev = rh->GetEntries();
1051      //    Int_t rtev = rt->GetEntries();      Int_t nrtev = rt->GetEntries();
1052        if ( IsDebug() ) printf(" ou nevent %i rhev %i rtev %i \n",nevent,nrhev,nrtev);
1053      //      //
1054      if ( rhev > 0 ){      if ( nrhev > 0 ){
1055        rh->GetEntry(0);        for (Int_t i=0; i<nrhev; i++){
1056        //          //
1057        TSYNC = runh->LAST_TIME_SYNC_INFO;          rh->GetEntry(i);
1058        OBT = runh->OBT_TIME_SYNC * 1000;          //
1059        //          TSYNC = runh->LAST_TIME_SYNC_INFO;
1060        TYPE = 20;          OBT = runh->OBT_TIME_SYNC * 1000;
1061        //          //
1062        if ( TSYNC && OBT ){          TYPE = 20;
1063          existsts = true;          //
1064          goto out;          if ( IsDebug() ) printf("runheader %i tsync %u obt %u \n",i,TSYNC,OBT);
1065            //
1066            if ( TSYNC && OBT ){
1067              existsts = true;
1068              goto eout;
1069            };
1070        };        };
1071        //        //
1072      };      };
1073      if ( rtev > 0 ){      if ( nrtev > 0 ){
       rt->GetEntry(0);  
1074        //        //
1075        TSYNC = runt->LAST_TYME_SYNC_INFO;        if ( IsDebug() ) printf(" No runheader \n");
1076        OBT = runt->OBT_TYME_SYNC * 1000;        signal = 6;
1077        //        //
1078        TYPE = 21;        for (Int_t i=0; i<nrtev; i++){
1079        //          //
1080        if ( TSYNC && OBT ){          rt->GetEntry(i);
1081          existsts = true;          //
1082          goto out;          TSYNC = runt->LAST_TYME_SYNC_INFO;
1083            OBT = runt->OBT_TYME_SYNC * 1000;
1084            //
1085            TYPE = 21;
1086            //
1087            if ( IsDebug() ) printf("runtrailer %i tsync %u obt %u \n",i,TSYNC,OBT);
1088            //
1089            if ( TSYNC && OBT ){
1090              existsts = true;
1091              goto eout;
1092            };
1093        };        };
1094        //        //
1095        } else {
1096          if ( IsDebug() ) printf(" No runheader \n");
1097      };      };
1098    };    };
1099    //    //
1100    if ( !existsts ){ // try with inclination mcmd    if ( !existsts ){ // try with inclination mcmd
1101        //
1102        if ( IsDebug() ) printf(" No runtrailer \n");
1103        signal = 14;
1104        //
1105      Double_t timesync = 0.;      Double_t timesync = 0.;
1106      for (UInt_t i=0; i<nevent;i++){      for (UInt_t i=0; i<nevent;i++){
1107        //        //
# Line 800  Int_t PamelaDBOperations::insertPamelaGL Line 1130  Int_t PamelaDBOperations::insertPamelaGL
1130        TYPE = 666;        TYPE = 666;
1131        if ( TSYNC && OBT ){        if ( TSYNC && OBT ){
1132          existsts = true;          existsts = true;
1133          goto out;          goto eout;
1134        };        };
1135      };      };
1136    };    };
1137    //    //
1138    if ( !existsts && obt0 ){ // insert timesync by hand    if ( !existsts && obt0 ){ // insert timesync by hand
1139        //
1140        if ( IsDebug() ) printf(" No incl mcmd \n");
1141        signal = 30;
1142        //
1143      OBT = obt0;      OBT = obt0;
1144      TSYNC = tsync;      TSYNC = tsync;
1145      TYPE = 999;      TYPE = 999;
1146      existsts = true;      existsts = true;
1147      goto out;      goto eout;
1148    };    };
1149    //    //
1150   out:   eout:
1151    //    //
1152    if ( !existsts ) throw -3;    if ( !existsts ) throw -3;
1153    //    //
# Line 829  Int_t PamelaDBOperations::insertPamelaGL Line 1163  Int_t PamelaDBOperations::insertPamelaGL
1163    toffset = (UInt_t)TSYNC - (UInt_t)(this->OBT(OBT)/1000) + t0;    toffset = (UInt_t)TSYNC - (UInt_t)(this->OBT(OBT)/1000) + t0;
1164    //    //
1165    delete result;    delete result;
1166    return(0);    return(signal);
1167  }  }
1168    
1169  /**  /**
# Line 907  Int_t PamelaDBOperations::assignBOOT_NUM Line 1241  Int_t PamelaDBOperations::assignBOOT_NUM
1241        << " NAME = '" << this->GetRawFile().Data() << "' ";        << " NAME = '" << this->GetRawFile().Data() << "' ";
1242    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1243    //    //
1244    if ( !result ) return(8);    if ( !result ) throw -4;;
1245    row = result->Next();    row = result->Next();
1246    if ( !row ) return(16);    if ( !row ) return(16);
1247    if ( row->GetField(1) ){    if ( row->GetField(1) ){
1248      this->SetBOOTnumber((UInt_t)atoll(row->GetField(1)));      this->SetBOOTnumber((UInt_t)atoll(row->GetField(1)));
1249      return(1);      return(1);
1250    };    };
1251    if ( !row->GetField(0) ) return(8);    if ( !row->GetField(0) ) throw -26;
1252    //    //
1253    UInt_t idRaw = (UInt_t)atoll(row->GetField(0));    UInt_t idRaw = (UInt_t)atoll(row->GetField(0));
1254    //    //
# Line 924  Int_t PamelaDBOperations::assignBOOT_NUM Line 1258  Int_t PamelaDBOperations::assignBOOT_NUM
1258    trDumpEv = (TTree*)file->Get("VarDump");    trDumpEv = (TTree*)file->Get("VarDump");
1259    if ( !trDumpEv || trDumpEv->IsZombie() ) throw -20;    if ( !trDumpEv || trDumpEv->IsZombie() ) throw -20;
1260    //    //
   if (trDumpEv == NULL) return(2);  
   //      
1261    VarDumpEvent  *vde = 0;    VarDumpEvent  *vde = 0;
1262    VarDumpRecord *vdr = 0;    VarDumpRecord *vdr = 0;
1263    //    //
1264    trDumpEv->SetBranchAddress("VarDump", &vde);    trDumpEv->SetBranchAddress("VarDump", &vde);
1265    if (trDumpEv->GetEntries() > 0){    if ( trDumpEv->GetEntries() > 0 ){
1266      trDumpEv->GetEntry(0);      Bool_t found = false;
1267      vde->Records->GetEntries();      for ( Int_t i = 0; i < trDumpEv->GetEntries(); i++){
1268      if ( !vde->Records->GetEntries() ){        trDumpEv->GetEntry(i);
1269        if ( !this->GetBOOTnumber() ) return(4);        vde->Records->GetEntries();
1270      } else {        if ( vde->Records->GetEntries()>0 ){
1271            found = true;
1272            goto fill;
1273          };
1274        };
1275      fill:
1276        if ( found ){
1277          //
1278        vdr = (VarDumpRecord*)vde->Records->At(6);        vdr = (VarDumpRecord*)vde->Records->At(6);
1279          //
1280        this->SetBOOTnumber((Int_t)vdr->VAR_VALUE);        this->SetBOOTnumber((Int_t)vdr->VAR_VALUE);
1281          //
1282        } else {
1283          if ( !this->GetBOOTnumber() ) return(4);
1284      };      };
1285    } else {    } else {
1286      if ( !this->GetBOOTnumber() ) return(2);      if ( !this->GetBOOTnumber() ) return(2);
# Line 1023  Int_t PamelaDBOperations::insertPamelaRU Line 1366  Int_t PamelaDBOperations::insertPamelaRU
1366          //          //
1367          if ( IsDebug() ) printf(" Missing header %i %i %i\n",ptht,pth,ptt);          if ( IsDebug() ) printf(" Missing header %i %i %i\n",ptht,pth,ptt);
1368          //          //
1369          if ( (ptt-1) < 0 ) throw -15;          if ( (ptt-1) < 0 ) throw -15; // should never arrive here!
1370          rt->GetEntry(ptt-1);          rt->GetEntry(ptt-1);
1371          cod = eht->GetCounter();          cod = eht->GetCounter();
1372          evbefh = cod->Get(pctp->Physics);          evbefh = cod->Get(pctp->Physics);
# Line 1129  Int_t PamelaDBOperations::insertPamelaRU Line 1472  Int_t PamelaDBOperations::insertPamelaRU
1472            if ( (UInt_t)evbeft < upperentry-1 ){            if ( (UInt_t)evbeft < upperentry-1 ){
1473              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");
1474              //              //
1475              if ( (ptt-1) < 0 ) throw -15;              if ( (ptt-1) < 0 ) throw -15; // should never arrive here!
1476              rt->GetEntry(ptt-1);              rt->GetEntry(ptt-1);
1477              cod = eht->GetCounter();              cod = eht->GetCounter();
1478              evbefh = cod->Get(pctp->Physics);              evbefh = cod->Get(pctp->Physics);
# Line 1286  void PamelaDBOperations::HandleRun(){   Line 1629  void PamelaDBOperations::HandleRun(){  
1629      //      //
1630      this->FillClass();      this->FillClass();
1631      //      //
1632      if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);      if ( !IsRunAlreadyInserted() ){
1633          glrun->SetID(this->AssignRunID());
1634          glrun->SetID_RUN_FRAG(0);
1635          glrun->Fill_GL_RUN(conn);
1636        };
1637    } else {    } else {
1638      //      //
1639      if ( IsDebug() ) printf(" oh no! the distance between runheader and runtrailer seems wrong: check %llu pktt %llu \n",chkpkt,pktt);      if ( IsDebug() ) printf(" oh no! the distance between runheader and runtrailer seems wrong: check %llu pktt %llu \n",chkpkt,pktt);
# Line 1458  void PamelaDBOperations::HandleRunFragme Line 1805  void PamelaDBOperations::HandleRunFragme
1805        };        };
1806        if ( IsDebug() ) printf(" Check overlapping events done: %i %i %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);        if ( IsDebug() ) printf(" Check overlapping events done: %i %i %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
1807        //        //
       glrun1->SetID(0);  
1808        glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());        glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
1809        glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());        glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
1810        glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());        glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
# Line 1486  void PamelaDBOperations::HandleRunFragme Line 1832  void PamelaDBOperations::HandleRunFragme
1832        //        //
1833        if ( !IsRunAlreadyInserted() ){        if ( !IsRunAlreadyInserted() ){
1834          //          //
1835            glrun->SetID(this->AssignRunID());
1836            glrun->SetID_RUN_FRAG(glrun1->GetID());
1837          glrun->Fill_GL_RUN(conn);          glrun->Fill_GL_RUN(conn);
1838          //          //
1839          // get id number          // get id number
1840          //          //
1841          oss.str("");  //      oss.str("");
1842          oss << " SELECT ID FROM GL_RUN WHERE BOOT_NUMBER="<<this->GetBOOTnumber()<<" AND "  //      oss << " SELECT ID FROM GL_RUN WHERE BOOT_NUMBER="<<this->GetBOOTnumber()<<" AND "
1843              << " RUNHEADER_OBT="<<glrun->GetRUNHEADER_OBT()<<" AND "  //          << " RUNHEADER_OBT="<<glrun->GetRUNHEADER_OBT()<<" AND "
1844              << " RUNTRAILER_OBT="<<glrun->GetRUNTRAILER_OBT()<<";";  //          << " RUNTRAILER_OBT="<<glrun->GetRUNTRAILER_OBT()<<";";
1845          //  //      //
1846          if ( IsDebug() ) printf(" search for idrun0 , query is : \n%s\n",oss.str().c_str());  //      if ( IsDebug() ) printf(" search for idrun0 , query is : \n%s\n",oss.str().c_str());
1847          //  //      //
1848          result =  conn->Query(oss.str().c_str());  //      result =  conn->Query(oss.str().c_str());
1849          if ( !result ) throw -4;  //      if ( !result ) throw -4;
1850          row = result->Next();  //      row = result->Next();
1851          //  //      //
1852          UInt_t idrun0 = 0;  //      UInt_t idrun0 = 0;
1853          if ( !row ){  //      if ( !row ){
1854            throw -10;  //        throw -10;
1855          } else {  //      } else {
1856            idrun0 = (UInt_t)atoll(row->GetField(0));  //        idrun0 = (UInt_t)atoll(row->GetField(0));
1857          };  //      };
         //  
         glrun1->SetID_RUN_FRAG(idrun0);  
1858          //          //
1859            //      glrun1->SetID_RUN_FRAG(idrun0);
1860            glrun1->SetID_RUN_FRAG(glrun->GetID());
1861          glrun1->Fill_GL_RUN(conn);          glrun1->Fill_GL_RUN(conn);
1862          //          //
1863          oss.str("");  //      oss.str("");
1864          oss << " SELECT ID FROM GL_RUN WHERE ID_RUN_FRAG="<<idrun0<<" ;";  //      oss << " SELECT ID FROM GL_RUN WHERE ID_RUN_FRAG="<<idrun0<<" ;";
1865          //  //      //
1866          if ( IsDebug() ) printf(" search for idrun1 , query is : \n%s\n",oss.str().c_str());  //      if ( IsDebug() ) printf(" search for idrun1 , query is : \n%s\n",oss.str().c_str());
1867          //  //      //
1868          result =  conn->Query(oss.str().c_str());  //      result =  conn->Query(oss.str().c_str());
1869          if ( !result ) throw -4;  //      if ( !result ) throw -4;
1870          row = result->Next();  //      row = result->Next();
1871          //  //      //
1872          UInt_t idrun1 = 0;  //      UInt_t idrun1 = 0;
1873          if ( !row ){  //      if ( !row ){
1874            throw -10;  //        throw -10;
1875          } else {  //      } else {
1876            idrun1 = (UInt_t)atoll(row->GetField(0));  //        idrun1 = (UInt_t)atoll(row->GetField(0));
1877          };  //      };
1878          //  //      //
1879          oss.str("");  //      oss.str("");
1880          oss << " UPDATE GL_RUN SET ID_RUN_FRAG="<<idrun1<<" WHERE ID="<<idrun0<<" ;";  //      oss << " UPDATE GL_RUN SET ID_RUN_FRAG="<<idrun1<<" WHERE ID="<<idrun0<<" ;";
1881          //  //      //
1882          result =  conn->Query(oss.str().c_str());  //      result =  conn->Query(oss.str().c_str());
1883          if ( !result ) throw -4;  //      if ( !result ) throw -4;
1884          //          //
1885        };        };
1886        //        //
# Line 1682  void PamelaDBOperations::HandleRunFragme Line 2030  void PamelaDBOperations::HandleRunFragme
2030        glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());        glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());
2031        glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());        glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());
2032        //        //
       glrun1->SetID(0);  
2033        glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());        glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());
2034        glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());        glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());
2035        glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());        glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());
# Line 1702  void PamelaDBOperations::HandleRunFragme Line 2049  void PamelaDBOperations::HandleRunFragme
2049        //        //
2050        if ( !IsRunAlreadyInserted() ){        if ( !IsRunAlreadyInserted() ){
2051          //          //
2052            glrun->SetID(this->AssignRunID());
2053            //
2054            glrun->SetID_RUN_FRAG(glrun1->GetID());
2055          glrun->Fill_GL_RUN(conn);          glrun->Fill_GL_RUN(conn);
2056          //          //
2057          // get id number          // get id number
2058          //          //
2059          oss.str("");  //      oss.str("");
2060          oss << " SELECT ID FROM GL_RUN WHERE BOOT_NUMBER="<<this->GetBOOTnumber()<<" AND "  //      oss << " SELECT ID FROM GL_RUN WHERE BOOT_NUMBER="<<this->GetBOOTnumber()<<" AND "
2061              << " RUNHEADER_OBT="<<glrun->GetRUNHEADER_OBT()<<" AND "  //          << " RUNHEADER_OBT="<<glrun->GetRUNHEADER_OBT()<<" AND "
2062              << " RUNTRAILER_OBT="<<glrun->GetRUNTRAILER_OBT()<<";";  //          << " RUNTRAILER_OBT="<<glrun->GetRUNTRAILER_OBT()<<";";
2063          //  //      //
2064          if ( IsDebug() ) printf(" search for idrun0 , query is : \n%s\n",oss.str().c_str());  //      if ( IsDebug() ) printf(" search for idrun0 , query is : \n%s\n",oss.str().c_str());
2065          //  //      //
2066          result =  conn->Query(oss.str().c_str());  //      result =  conn->Query(oss.str().c_str());
2067          if ( !result ) throw -4;  //      if ( !result ) throw -4;
2068          row = result->Next();  //      row = result->Next();
2069          //  //      //
2070          UInt_t idrun0 = 0;  //      UInt_t idrun0 = 0;
2071          if ( !row ){  //      if ( !row ){
2072            throw -10;  //        throw -10;
2073          } else {  //      } else {
2074            idrun0 = (UInt_t)atoll(row->GetField(0));  //        idrun0 = (UInt_t)atoll(row->GetField(0));
2075          };  //      };
2076          //  //      //
2077          glrun1->SetID_RUN_FRAG(idrun0);  //      glrun1->SetID_RUN_FRAG(idrun0);
2078          //  //
2079            glrun1->SetID_RUN_FRAG(glrun->GetID());
2080          glrun1->Fill_GL_RUN(conn);          glrun1->Fill_GL_RUN(conn);
2081          //          //
2082          oss.str("");  //      oss.str("");
2083          oss << " SELECT ID FROM GL_RUN WHERE ID_RUN_FRAG="<<idrun0<<" ;";  //      oss << " SELECT ID FROM GL_RUN WHERE ID_RUN_FRAG="<<idrun0<<" ;";
2084          //  //      //
2085          if ( IsDebug() ) printf(" search for idrun1 , query is : \n%s\n",oss.str().c_str());  //      if ( IsDebug() ) printf(" search for idrun1 , query is : \n%s\n",oss.str().c_str());
2086          //  //      //
2087          result =  conn->Query(oss.str().c_str());  //      result =  conn->Query(oss.str().c_str());
2088          if ( !result ) throw -4;  //      if ( !result ) throw -4;
2089          row = result->Next();  //      row = result->Next();
2090          //  //      //
2091          UInt_t idrun1 = 0;  //      UInt_t idrun1 = 0;
2092          if ( !row ){  //      if ( !row ){
2093            throw -10;  //        throw -10;
2094          } else {  //      } else {
2095            idrun1 = (UInt_t)atoll(row->GetField(0));  //        idrun1 = (UInt_t)atoll(row->GetField(0));
2096          };  //      };
2097          //  //      //
2098          oss.str("");  //      oss.str("");
2099          oss << " UPDATE GL_RUN SET ID_RUN_FRAG="<<idrun1<<" WHERE ID="<<idrun0<<" ;";  //      oss << " UPDATE GL_RUN SET ID_RUN_FRAG="<<idrun1<<" WHERE ID="<<idrun0<<" ;";
2100          //  //      //
2101          result =  conn->Query(oss.str().c_str());  //      result =  conn->Query(oss.str().c_str());
2102          if ( !result ) throw -4;  //      if ( !result ) throw -4;
2103          //          //
2104        };        };
2105        //        //
# Line 1832  void PamelaDBOperations::HandleRunFragme Line 2183  void PamelaDBOperations::HandleRunFragme
2183          if ( IsDebug() ) printf(" The run is new \n");          if ( IsDebug() ) printf(" The run is new \n");
2184          if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");          if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
2185          //          //
2186            glrun->SetID(this->AssignRunID());
2187            glrun->SetID_RUN_FRAG(0);
2188          glrun->Fill_GL_RUN_FRAGMENTS(conn);          glrun->Fill_GL_RUN_FRAGMENTS(conn);
2189          //          //
2190        } else {        } else {
# Line 1864  void PamelaDBOperations::HandleMissingHo Line 2217  void PamelaDBOperations::HandleMissingHo
2217      //      //
2218      this->FillClass(mishead,mistrail,firstev,lastev);      this->FillClass(mishead,mistrail,firstev,lastev);
2219      //      //
2220      if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);          if ( !IsRunAlreadyInserted() ){
2221          glrun->SetID(this->AssignRunID());
2222          glrun->SetID_RUN_FRAG(0);
2223          glrun->Fill_GL_RUN(conn);    
2224        };
2225      //      //
2226    };    };
2227    //    //
# Line 2031  Bool_t PamelaDBOperations::IsRunConsiste Line 2388  Bool_t PamelaDBOperations::IsRunConsiste
2388            //                  //      
2389            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
2390            //            //
2391            if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                  if ( !IsRunAlreadyInserted() ){
2392                glrun->SetID(this->AssignRunID());
2393                glrun->SetID_RUN_FRAG(0);
2394                glrun->Fill_GL_RUN(conn);      
2395              };
2396            //            //
2397            firstevno = lastentry + 1;            firstevno = lastentry + 1;
2398            //            //
# Line 2106  void PamelaDBOperations::HandleSuspiciou Line 2467  void PamelaDBOperations::HandleSuspiciou
2467    if ( firstev == lastev+1 ) { // no events inside the run!    if ( firstev == lastev+1 ) { // no events inside the run!
2468      if ( IsDebug() ) printf(" Checking but no events in the run! \n");      if ( IsDebug() ) printf(" Checking but no events in the run! \n");
2469      //      //
     //    if ( IsDebug() ) printf(" -> fill the DB \n");  
     //  
2470      this->FillClass();      this->FillClass();
2471      if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);          if ( !IsRunAlreadyInserted() ){
2472          glrun->SetID(this->AssignRunID());
2473          glrun->SetID_RUN_FRAG(0);
2474          glrun->Fill_GL_RUN(conn);    
2475        };
2476      //      //
2477    } else {    } else {
2478      //      //
# Line 2137  void PamelaDBOperations::HandleSuspiciou Line 2500  void PamelaDBOperations::HandleSuspiciou
2500        if ( IsDebug() ) printf(" No packets but physics inside the run, I will consider it as good\n");        if ( IsDebug() ) printf(" No packets but physics inside the run, I will consider it as good\n");
2501        //        //
2502        this->FillClass();        this->FillClass();
2503        if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                if ( !IsRunAlreadyInserted() ){
2504            glrun->SetID(this->AssignRunID());
2505            glrun->SetID_RUN_FRAG(0);
2506            glrun->Fill_GL_RUN(conn);        
2507          };
2508        //        //
2509      } else {      } else {
2510        //        //
# Line 2235  void PamelaDBOperations::HandleSuspiciou Line 2602  void PamelaDBOperations::HandleSuspiciou
2602            //                  //      
2603            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
2604            //            //
2605            if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                  if ( !IsRunAlreadyInserted() ){
2606                glrun->SetID(this->AssignRunID());
2607                glrun->SetID_RUN_FRAG(0);
2608                glrun->Fill_GL_RUN(conn);      
2609              };
2610            //            //
2611            if ( i == lastev && checkfirst < check ){ // if the last event gives a wrong check...            if ( i == lastev && checkfirst < check ){ // if the last event gives a wrong check...
2612              //              //
# Line 2270  void PamelaDBOperations::HandleSuspiciou Line 2641  void PamelaDBOperations::HandleSuspiciou
2641              //                  //    
2642              this->SetCommonGLRUN(firstTime,lastTime);              this->SetCommonGLRUN(firstTime,lastTime);
2643              //              //
2644              if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                    if ( !IsRunAlreadyInserted() ){
2645                  glrun->SetID(this->AssignRunID());
2646                  glrun->SetID_RUN_FRAG(0);
2647                  glrun->Fill_GL_RUN(conn);      
2648                };
2649            };            };
2650            //            //
2651            firstevno = lastentry + 1;            firstevno = lastentry + 1;
# Line 2318  Int_t PamelaDBOperations::insertCALO_CAL Line 2693  Int_t PamelaDBOperations::insertCALO_CAL
2693    tr->SetBranchAddress("Header", &eh);    tr->SetBranchAddress("Header", &eh);
2694    nevents = tr->GetEntries();    nevents = tr->GetEntries();
2695    //    //
2696    if ( !nevents ) return(0);    if ( !nevents ) return(1);
2697    //    //
2698    for (UInt_t i=0; i < nevents; i++){    for (UInt_t i=0; i < nevents; i++){
2699      tr->GetEntry(i);      tr->GetEntry(i);
# Line 2635  Int_t PamelaDBOperations::insertTRK_CALI Line 3010  Int_t PamelaDBOperations::insertTRK_CALI
3010    tr2->SetBranchAddress("Header", &eh2);    tr2->SetBranchAddress("Header", &eh2);
3011    nevents2 = tr2->GetEntries();    nevents2 = tr2->GetEntries();
3012    //    //
3013    if ( !nevents1 && !nevents2 ) return(0);    if ( !nevents1 && !nevents2 ) return(1);
3014    //    //
3015    t2 = -1;    t2 = -1;
3016    Int_t pret2 = 0;    Int_t pret2 = 0;
# Line 2807  Int_t PamelaDBOperations::insertS4_CALIB Line 3182  Int_t PamelaDBOperations::insertS4_CALIB
3182    stringstream oss;    stringstream oss;
3183    oss.str("");    oss.str("");
3184    //    //
   CalibS4Event *calibS4    = new  CalibS4Event();  
3185    TTree *tr = 0;    TTree *tr = 0;
3186    EventHeader *eh = 0;    EventHeader *eh = 0;
3187    PscuHeader *ph = 0;    PscuHeader *ph = 0;
# Line 2821  Int_t PamelaDBOperations::insertS4_CALIB Line 3195  Int_t PamelaDBOperations::insertS4_CALIB
3195    tr = (TTree*)file->Get("CalibS4");    tr = (TTree*)file->Get("CalibS4");
3196    if ( !tr || tr->IsZombie() ) throw -24;    if ( !tr || tr->IsZombie() ) throw -24;
3197    //    //
   tr->SetBranchAddress("CalibS4", &calibS4);  
3198    tr->SetBranchAddress("Header", &eh);    tr->SetBranchAddress("Header", &eh);
3199    //    //
3200    nevents = tr->GetEntries();    nevents = tr->GetEntries();
3201    //    //
3202    if ( !nevents ) return(0);    if ( !nevents ) return(1);
3203    //    //
3204    for (UInt_t i = 0; i < nevents; i++){    for (UInt_t i = 0; i < nevents; i++){
3205      //      //
3206      tr->GetEntry(i);      tr->GetEntry(i);
     TArrayD params = S4_paramfit(calibS4);  
3207      //      //
3208      ph = eh->GetPscuHeader();      ph = eh->GetPscuHeader();
3209      obt = ph->GetOrbitalTime();        obt = ph->GetOrbitalTime();  
# Line 2921  Int_t PamelaDBOperations::insertS4_CALIB Line 3293  Int_t PamelaDBOperations::insertS4_CALIB
3293          };          };
3294          //          //
3295          oss.str("");          oss.str("");
3296          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) "
3297              << " VALUES (NULL,' "              << " VALUES (NULL,' "
3298              << idroot << "','"              << idroot << "','"
3299              << i << "','"              << i << "','"
3300              << fromtime << "','"              << fromtime << "','"
3301              << totime << "','"              << totime << "','"
             << dec << params.At(0) << "','"  
             << dec << params.At(1) << "','"        
3302              << obt << "','"              << obt << "','"
3303              << pkt << "','"              << pkt << "','"
3304              << this->GetBOOTnumber() << "','"              << this->GetBOOTnumber() << "');";
             << valid << "');";  
3305          //          //
3306          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());
3307          //          //
# Line 2953  Int_t PamelaDBOperations::insertS4_CALIB Line 3322  Int_t PamelaDBOperations::insertS4_CALIB
3322    return(0);    return(0);
3323  };  };
3324    
3325    /**
3326     * Scan the fragment table and move old fragments to the GL_RUN table
3327     */
3328    Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(){
3329      //
3330      TSQLResult *result = 0;
3331      TSQLRow    *row    = 0;
3332      TSQLResult *result2 = 0;
3333      TSQLRow    *row2   = 0;
3334      //
3335      UInt_t moved = 0;
3336    //  UInt_t timelim = 0;
3337    //  TDatime *time = new TDatime();
3338      //
3339      stringstream oss;
3340      oss.str("");
3341      //
3342      //
3343      // check if there are entries older than "olderthan" seconds from now
3344      //
3345      oss.str("");
3346      oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"
3347          << " INSERT_TIME <= '" << clean_time->AsSQLString() << "';";
3348      //
3349      if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS runs older than %s : query is \n %s \n",clean_time->AsSQLString(),oss.str().c_str());
3350      result = conn->Query(oss.str().c_str());
3351      //
3352      if ( result ){
3353        //
3354        row = result->Next();
3355        //
3356        while ( row ){
3357          //
3358          oss.str("");
3359          oss << " ID= "<< row->GetField(0);
3360          //
3361          glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);  
3362          //
3363          oss.str("");
3364          oss << " SELECT ID,NEVENTS,TRK_CALIB_USED,PKT_COUNTER FROM GL_RUN WHERE "
3365              << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND ("
3366              << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3367              << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3368              << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3369              << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3370              << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3371              << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3372              << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3373              << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3374              << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3375              << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3376              << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3377              << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3378          //
3379          if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3380          result2 = conn->Query(oss.str().c_str());
3381          //
3382          if ( !result2 ) throw -4;
3383          //
3384          row2 = result2->Next();
3385          //
3386          if ( !row2 ){
3387            //
3388            if ( IsDebug() ) printf(" The run is new \n");
3389            if ( IsDebug() ) printf(" -> fill the DB \n");      
3390            //
3391            //      glrun->SetID(this->AssignRunID()); we use the old run number!
3392            glrun->SetID_RUN_FRAG(glrun->GetID());
3393            glrun->Fill_GL_RUN(conn);  
3394            //
3395    //      oss.str("");
3396    //      oss << " SELECT ID FROM GL_RUN WHERE "
3397    //          << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "
3398    //          << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "
3399    //          << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "
3400    //          << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "
3401    //          << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";
3402    //      //
3403    //      if ( IsDebug() ) printf(" Look for the ID of the inserted run: query is \n %s \n",oss.str().c_str());
3404    //      result2 = conn->Query(oss.str().c_str());
3405    //      //
3406    //      if ( !result2 ) throw -4;
3407    //      //
3408    //      row2 = result2->Next();
3409    //      //
3410    //      if ( !row2 ) throw -25;
3411    //      //
3412    //      oss.str("");
3413    //      oss << " UPDATE GL_RUN SET ID_RUN_FRAG = " << row2->GetField(0) << " WHERE ID = " << row2->GetField(0);
3414    //      if ( IsDebug() ) printf(" Update the ID_RUN_FRAG of the inserted run: query is \n %s \n",oss.str().c_str());
3415    //      result2 = conn->Query(oss.str().c_str());
3416    //      //
3417    //      if ( !result2 ) throw -4;
3418            //
3419            moved++;
3420            //
3421          } else {
3422            if ( IsDebug() ) printf(" The already exist in the GL_RUN table! \n");
3423          };
3424          if ( IsDebug() ) printf(" Delete run %s from the GL_RUN_FRAGMENTS table \n",row->GetField(0));      
3425          //
3426          //
3427          oss.str("");
3428          oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);
3429          if ( IsDebug() ) printf(" Clean the GL_RUN_FRAGMENTS table: query is \n %s \n",oss.str().c_str());
3430          result2 = conn->Query(oss.str().c_str());
3431          //
3432          if ( !result2 ) throw -4;
3433          //
3434          row = result->Next();
3435        };
3436      };
3437      if ( IsDebug() ) printf(" Moved %u runs\n",moved);
3438      return(0);
3439    };
3440    
3441  /*  /**
3442   * Fit function Received from Valeria Malvezzi 06/02/2006   * Check if runs are good, i.e. if the tracker calibration is correctly associated..
3443   */   */
3444  Double_t fitf(Double_t *x, Double_t *par){    Int_t PamelaDBOperations::ValidateRuns(){
3445    Double_t fitval =(par[0]*x[0])+par[1];    //
3446    return fitval;    TSQLResult *result = 0;
3447      TSQLRow    *row    = 0;
3448      //
3449      stringstream oss;
3450      oss.str("");
3451      //
3452      // =======================================================
3453      // validate runs by checking missing calibrations
3454      // =======================================================
3455      UInt_t t_stop  = 0;
3456      UInt_t t_start = 0;
3457      // --------------------------------------------------------------
3458      // 1) get the OBT of the last run inserted after clean-time limit
3459      // --------------------------------------------------------------
3460      oss.str("");
3461      oss << " SELECT * FROM GL_RUN  WHERE INSERT_TIME <= '" << clean_time->AsSQLString()
3462              << "' ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
3463      if ( IsDebug() ) printf(" Get start validation-time: query is \n %s \n",oss.str().c_str());
3464      result = conn->Query(oss.str().c_str());
3465      if ( !result ) throw -4;
3466      if ( !result->GetRowCount() ) {
3467              printf(" No runs to validate \n");
3468              return(1);
3469      }else{
3470            row = result->Next();
3471            t_start = (UInt_t)atoll(row->GetField(4));
3472      };  
3473      // --------------------------------------------------------------
3474      // 2) get the OBT of the last validated run
3475      // --------------------------------------------------------------
3476      oss.str("");
3477      oss << " SELECT * FROM GL_RUN  WHERE VALIDATION=1 AND RUNHEADER_TIME<="<< t_start
3478          <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
3479      if ( IsDebug() ) printf(" Get stop validation-time: query is \n %s \n",oss.str().c_str());
3480      result = conn->Query(oss.str().c_str());
3481      if ( !result ) throw -4;
3482      if ( result->GetRowCount() ){
3483              row = result->Next();
3484              t_stop = (UInt_t)atoll(row->GetField(4));
3485      };
3486      if ( IsDebug() ) printf("Validation interval: from time %i - to time %i \n\n",t_stop,t_start);
3487      // --------------------------------------------------------------
3488      // now retrieves runs to be validated
3489      // --------------------------------------------------------------
3490      oss.str("");
3491      oss << " SELECT * FROM GL_RUN  WHERE  RUNHEADER_TIME <=" << t_start;
3492      oss << " AND RUNHEADER_TIME >="<< t_stop;
3493      oss << " ORDER BY RUNHEADER_TIME DESC;";
3494    //  if ( IsDebug() )
3495      if ( IsDebug() )printf(" Check runs for validation: query is \n %s \n",oss.str().c_str());
3496      result = conn->Query(oss.str().c_str());
3497      if ( !result ) throw -4;
3498      if ( !result->GetRowCount() ) printf(" No runs to validate \n");
3499    //  printf("------------------------------------------------------------------------------- \n");
3500      
3501      Int_t nrow = 0;
3502      GL_RUN* this_run = new GL_RUN();
3503      GL_RUN* next_run = new GL_RUN();
3504      Int_t   nseq_max = 1000;
3505    //  UInt_t* sequence = new UInt_t[100];
3506      vector<UInt_t> sequence(nseq_max);
3507      Int_t   nseq = 0;
3508      Bool_t CHECK = false;
3509      Bool_t this_ONLINE = false;
3510      Bool_t next_ONLINE = false;
3511      UInt_t t1=0,t2=0;
3512      // ---------------------------------------------------------------------------------
3513      // - loop over runs, back in time,
3514      // - select sequences of runs close in time (less than 60 s apart),
3515      //   which could be preceeded by a calibration
3516      // - check if there might be a missing calibration
3517      // ---------------------------------------------------------------------------------
3518      while(1){
3519              
3520              row = result->Next();
3521              if( row == NULL ) break;
3522              
3523              //------------
3524              //get run info
3525              //------------
3526              this_run->Set_GL_RUN(row);
3527                      
3528              Bool_t this_BAD = false;
3529              if(this_run->GetTRK_CALIB_USED() == 1 || this_run->GetTRK_CALIB_USED() == 2) this_ONLINE = true;
3530              else if (this_run->GetTRK_CALIB_USED() == 104)                          this_ONLINE = false;
3531              else{
3532    //                printf("Missing or corrupted header!! \n");
3533                      this_ONLINE = false;
3534                      this_BAD = true;
3535              };
3536    
3537              //-----------------------------------
3538              //compare with previous(next in time)
3539              //-----------------------------------
3540              CHECK = false;
3541              UInt_t interval=0;
3542              
3543              if( nrow != 0){
3544            
3545                      
3546                      t1 = this_run->GetRUNTRAILER_TIME();
3547                      t2 = next_run->GetRUNHEADER_TIME();
3548                      interval = (t2-t1);
3549                      
3550                      if(this_ONLINE && next_ONLINE){                               // this: ON-LINE + next: ON-LINE
3551                              
3552                              if( this_run->ID == next_run->ID_RUN_FRAG ) interval = 0;     //=> run fragments
3553                              
3554                              if( interval >= 60 )CHECK = true;                     //more than 60 s => there might be a calibration
3555                              
3556                              if( !CHECK && this_run->VALIDATION ){
3557                                      for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);
3558                                      nseq=0;
3559                              }
3560                      
3561                      }else if( !this_ONLINE && next_ONLINE) {              // this: DEFAULT + next:ON-LINE
3562                              
3563                              CHECK = true;
3564    
3565                      }else if( !next_ONLINE ){                                             // this:ANY + next:DEFAULT
3566                              
3567                              assignVALIDATION(next_run->ID,true);
3568                              nseq=0;
3569                      }
3570              }
3571    
3572              //----------------------------
3573              //check run sequence for calib
3574              //----------------------------
3575              if( CHECK ){
3576                      // check if calibration exists
3577                      if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval);
3578                      Bool_t MISSING = MissingTRK_CALIB(t1,t2);
3579                      for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],!MISSING);
3580                      nseq=0;
3581              };
3582              //--------------
3583              //store run info
3584              //--------------
3585              *next_run   = *this_run;
3586              next_ONLINE = this_ONLINE;
3587              if( !this_BAD ){
3588                      if(nseq < nseq_max){
3589                              sequence[nseq] = this_run->ID;
3590                              nseq++;
3591                      }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);
3592              };
3593              
3594              if ( IsDebug() ) printf("%i Run %i \n",nrow,this_run->ID);
3595              nrow++;
3596              
3597      };
3598      delete this_run;
3599      delete next_run;
3600      //
3601      return(0);
3602    };
3603    /**
3604     * Check if there might be a missing tracker calibration in a given time interval
3605     * @param t1 From absolute time
3606     * @param t2 To absolute time
3607     * @return true if there might be a missing calibration
3608     */
3609    Bool_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
3610            
3611            GL_TRK_CALIB* trkcalib = new GL_TRK_CALIB();
3612            
3613            // get the closest VALIDATED calibration before the run start (t2)
3614            if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(true);      //>>> missing
3615            
3616            if ( trkcalib->TO_TIME  < t2 ) return(true);                                    //>>> missing
3617            
3618            //==============================================================
3619            // Check is done first on the basis of time between calibration,
3620            // which should be equal to the time between ascending-nodes.
3621            //==============================================================
3622            if ( t2 - trkcalib->FROM_TIME > 5700) {
3623                    if ( IsDebug() )printf("Long time between calib and run start %i :-( ==> there might be a missing calib \n",t2 - trkcalib->FROM_TIME);
3624            //==============================================================
3625            // there might be a missing calibration, due to:
3626            // - MM full
3627            // - corrupted packets
3628            // - loss of data
3629            // There is an exception in case a download was done during ascending node
3630            //==============================================================
3631                    Bool_t DOWNLOAD = false;
3632                    // check if the calib was skipped becouse of download .... DA FARE!!
3633                    if(DOWNLOAD)return(false);
3634                    
3635                    return(true);                                   //>>> missing
3636                    
3637            };
3638            
3639            //==============================================================
3640            // If the last calibration is close to the run less than this time,
3641            // it is enough to say that there are no missing calibrations
3642            //==============================================================
3643            // the long time interval bewteen runs might be due to download
3644            if ( IsDebug() )printf("Short time between calib and run start %i :-) ==> OK! \n",t2 - trkcalib->FROM_TIME);
3645            return(false);
3646            
3647    };
3648    /**
3649     * Assign VALIDATION value to a GL_RUN entry
3650     * @param idrun Run ID
3651     * @param validation true/false
3652     */
3653    Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, Bool_t validation){
3654            TSQLResult *result = 0;
3655            stringstream oss;
3656            oss.str("");
3657            oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";
3658            //
3659    //      if ( IsDebug() )
3660    //      printf(" Set VALIDATION = %i for run %i \n",validation,idrun);
3661            if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());
3662            result = conn->Query(oss.str().c_str());
3663            if ( !result ) throw -4;
3664            return(0);
3665  }  }
3666    
 /*  
  * Fit the S4 calibration with a straight line - Received from Valeria Malvezzi 06/02/2006  
  */  
 TArrayD PamelaDBOperations::S4_paramfit(pamela::CalibS4Event *S4CalibEvent){        
3667    
   //----------- variable initialization -------------------------------------------------  
3668    
3669    Double_t mip[3]={1, 30, 300};  // Insert TLEs from file tlefilename in the table GL_TLE in the db
3670    Double_t adc[3] = {0.,0.,0.};  // opened by conn, sorting them by date from older to newer, if each
3671      // TLE has not been alread inserted.
3672    TArrayD parametri(2);  Int_t PamelaDBOperations::populateTLE()//(TSQLServer *conn, char *tleFile)
3673    {
3674    valid = 1;    fstream tlefile(tlefilename, ios::in);
3675    
3676      if ( !tlefile ) throw -7;
3677    
3678      vector<cTle*> ctles;
3679      vector<cTle*>::iterator iter;
3680      int present = 0;
3681    
3682      // Get three lines from tlefile, create a cTle object and put it
3683      // into ctles
3684      while(1) {
3685        cTle *tlef;
3686        string str1, str2, str3;
3687    
3688        getline(tlefile, str1);
3689        if(tlefile.eof()) break;
3690    
3691        getline(tlefile, str2);
3692        if(tlefile.eof()) break;
3693    
3694        getline(tlefile, str3);
3695        if(tlefile.eof()) break;
3696    
3697        // We now have three good lines for a cTle.
3698        tlef = new cTle(str1, str2, str3);
3699        ctles.push_back(tlef);
3700      }
3701    
3702      tlefile.close();
3703    
3704      // Sort by date
3705      sort(ctles.begin(), ctles.end(), compTLE);
3706    
3707      // Now we insert each TLE into the db
3708      for(iter = ctles.begin(); iter != ctles.end(); iter++) {
3709        cTle *tle = *iter;
3710    
3711        // Do nothing if it's already present in the db.  Just increase
3712        // the counter present.
3713        if (! isTlePresent(tle))
3714          {
3715            int status = insertTle(tle);
3716    
3717            // Insert query failed.  Return 1.
3718            if(status == EXIT_FAILURE) {
3719              
3720              if( IsDebug() ) {
3721                cerr << "Error: inserting TLE:" << endl
3722                     << tle->getName() << endl
3723                     << tle->getLine1() << endl
3724                     << tle->getLine2() << endl;
3725              }
3726    
3727              throw -4;
3728              return 1;
3729            }
3730    
3731          }
3732        else
3733          present++;
3734    
3735      }
3736    
3737      int inserted = ctles.size() - present;  // Number of inserted TLE.
3738      if ( IsDebug() )
3739        cout << "\nProcessed TLEs ranging from " << getTleDatetime(ctles[0]) << " to " << getTleDatetime(ctles[ctles.size()-1]) << "." << endl
3740             << inserted << " newly inserted TLEs out of " << ctles.size() << " processed." << endl;
3741    
3742      ctles.clear();
3743    
3744    
3745      // Return 2 if no new TLE has been inserted.  0 otherwise.
3746      if(! inserted ) return 2;
3747      return 0;
3748    }
3749    
   //------------ Fit calibrations and find parameters to calibrate data ------------------  
   pamela::S4::S4Event  *s4Record;  
3750    
3751    for (Int_t j = 0; j < 4; j++){  // Insert tle in the table GL_TLE using the connection conn.
3752      for (Int_t i = 0; i < 128; i++){  int PamelaDBOperations::insertTle(cTle *tle)
3753        s4Record = (pamela::S4::S4Event*)S4CalibEvent->Records->At((j*128 + i));  {
3754        switch (j) {    stringstream oss;
3755        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);  
3756    
3757    if ( parametri[0] < 0. || parametri[0] > 0.5 || parametri[1] < 0.8 || parametri[1] > 1. ) valid = 0;    oss.str("");
3758      oss << " INSERT INTO GL_TLE (TLE1, TLE2, TLE3, FROM_TIME)"
3759          << " VALUES ( '"
3760          << tle->getName() << "', '"
3761          << tle->getLine1() << "', '"
3762          << tle->getLine2() << "', '"
3763          << getTleDatetime(tle) << "')";
3764    
3765    if ( IsDebug() ) printf(" par1 = %g par2 = %g\n",parametri[0],parametri[1]);    //  cout << oss.str().c_str() << endl;
3766      result = conn->Query(oss.str().c_str());
3767    return parametri;    if (result == NULL)
3768  };      return EXIT_FAILURE;
3769    
3770      return EXIT_SUCCESS;
3771    }
3772    
3773    
3774    // Return whether tle is already in the db connected by conn.
3775    bool PamelaDBOperations::isTlePresent(cTle *tle)
3776    {
3777      stringstream oss;
3778      TSQLResult *result = 0;
3779    
3780      oss.str("");
3781      oss << "SELECT * FROM GL_TLE WHERE FROM_TIME = '"
3782          << getTleDatetime(tle) << "'";
3783    
3784      result = conn->Query(oss.str().c_str());
3785      if (result == NULL) throw -4;
3786    
3787      if (result->GetRowCount())
3788        return true;
3789      else
3790        return false;
3791    }
3792    
3793    
3794    // Return whether the first TLE is dated early than the second
3795    bool compTLE (cTle *tle1, cTle *tle2)
3796    {
3797      return getTleJulian(tle1) < getTleJulian(tle2);
3798    }
3799    
3800    
3801    // Return the date of the tle using the format (year-2000)*1e3 +
3802    // julian day.  e.g. 6365 is the 31th Dec 2006.
3803    // It does *not* return a cJulian date.
3804    float getTleJulian(cTle *tle) {
3805      return tle->getField(cTle::FLD_EPOCHYEAR)*1e3 + tle->getField(cTle::FLD_EPOCHDAY);
3806    }
3807    
3808    
3809    // Return a string like YYYY-MM-DD hh:mm:ss, usable for mysql datetime
3810    // format.
3811    string getTleDatetime(cTle *tle)
3812    {
3813      int year, mon, day, hh, mm, ss;
3814      double dom; // day of month (is double!)
3815      stringstream date; // date in datetime format
3816    
3817      // create a cJulian from the date in tle
3818      cJulian jdate = cJulian( 2000 + (int) tle->getField(cTle::FLD_EPOCHYEAR), tle->getField(cTle::FLD_EPOCHDAY));
3819    
3820      // get year, month, day of month
3821      jdate.getComponent(&year, &mon, &dom);
3822    
3823      // build a datetime YYYY-MM-DD hh:mm:ss
3824      date.str("");
3825      day = (int) floor(dom);
3826      hh = (int) floor( (dom - day) * 24);
3827      mm = (int) floor( ((dom - day) * 24 - hh) * 60);
3828      ss = (int) floor( ((((dom - day) * 24 - hh) * 60 - mm) * 60));
3829      //  ms = (int) floor( (((((dom - day) * 24 - hh) * 60 - mm) * 60) - ss) * 1000);
3830    
3831      date << year << "-" << mon << "-" << day << " " << hh << ":" << mm << ":" << ss;
3832    
3833      return date.str();
3834    }

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

  ViewVC Help
Powered by ViewVC 1.1.23