/[PAMELA software]/DarthVader/OrbitalInfo/src/OrbitalInfoCore.cpp
ViewVC logotype

Diff of /DarthVader/OrbitalInfo/src/OrbitalInfoCore.cpp

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

revision 1.45 by mocchiut, Fri Jan 29 20:45:52 2010 UTC revision 1.82 by malakhov, Tue Mar 3 10:58:13 2015 UTC
# Line 9  Line 9 
9  // ROOT headers  // ROOT headers
10  //  //
11  //#include <TCanvas.h>  //#include <TCanvas.h>
12  //#include <TH2F.h> //for test only. Vitaly.  #include <TH2F.h> //for test only. Vitaly.
13    #include <TVector3.h>
14  //#include <TF1.h>  //#include <TF1.h>
15    
16  #include <TTree.h>  #include <TTree.h>
# Line 25  Line 26 
26  #include <TSQLServer.h>  #include <TSQLServer.h>
27  #include <TSQLRow.h>  #include <TSQLRow.h>
28  #include <TSQLResult.h>  #include <TSQLResult.h>
29    #include <TObjectTable.h>
30  //  //
31  // RunInfo header  // RunInfo header
32  //  //
# Line 47  Line 49 
49  #include <OrbitalInfoCore.h>  #include <OrbitalInfoCore.h>
50  #include <InclinationInfo.h>  #include <InclinationInfo.h>
51    
52    //
53    // Tracker and ToF classes headers and definitions
54    //
55    #include <ToFLevel2.h>
56    #include <TrkLevel2.h>
57    #include <ExtTrack.h> // new tracking code
58    
59  using namespace std;  using namespace std;
60    
# Line 54  using namespace std; Line 62  using namespace std;
62  // CORE ROUTINE  // CORE ROUTINE
63  //  //
64  //  //
65  int OrbitalInfoCore(UInt_t run, TFile *file, GL_TABLES *glt, Int_t OrbitalInfoargc, char *OrbitalInfoargv[]){  int OrbitalInfoCore(UInt_t run, TFile *file, GL_TABLES *glt, Int_t OrbitalInfoargc, char *OrbitalInfoargv[]){  
66    //    //
67    Int_t i = 0;    Int_t i = 0;
68    TString host = glt->CGetHost();    TString host = glt->CGetHost();
# Line 64  int OrbitalInfoCore(UInt_t run, TFile *f Line 72  int OrbitalInfoCore(UInt_t run, TFile *f
72    //    //
73    stringstream myquery;    stringstream myquery;
74    myquery.str("");    myquery.str("");
75    myquery << "SET time_zone='+0:00'";    myquery << "SET time_zone='+0:00';";
76    dbc->Query(myquery.str().c_str());    delete dbc->Query(myquery.str().c_str());
77      delete dbc->Query("SET sql_mode = 'NO_UNSIGNED_SUBTRACTION';");
78    //    //
79    TString processFolder = Form("OrbitalInfoFolder_%u",run);    TString processFolder = Form("OrbitalInfoFolder_%u",run);
80    //    //
# Line 83  int OrbitalInfoCore(UInt_t run, TFile *f Line 92  int OrbitalInfoCore(UInt_t run, TFile *f
92        if ( !strcmp(OrbitalInfoargv[i],"-processFolder") ) {        if ( !strcmp(OrbitalInfoargv[i],"-processFolder") ) {
93          if ( OrbitalInfoargc < i+1 ){          if ( OrbitalInfoargc < i+1 ){
94            throw -3;            throw -3;
95          };          }
96          processFolder = (TString)OrbitalInfoargv[i+1];          processFolder = (TString)OrbitalInfoargv[i+1];
97          i++;          i++;
98        };        }
99        if ( (!strcmp(OrbitalInfoargv[i],"--debug")) || (!strcmp(OrbitalInfoargv[i],"-g")) ) {        if ( (!strcmp(OrbitalInfoargv[i],"--debug")) || (!strcmp(OrbitalInfoargv[i],"-g")) ) {
100          verbose = true;          verbose = true;
101          debug = true;          debug = true;
102        };        }
103        if ( (!strcmp(OrbitalInfoargv[i],"--verbose")) || (!strcmp(OrbitalInfoargv[i],"-v")) ) {        if ( (!strcmp(OrbitalInfoargv[i],"--verbose")) || (!strcmp(OrbitalInfoargv[i],"-v")) ) {
104          verbose = true;          verbose = true;
105        };        }
106        if ( (!strcmp(OrbitalInfoargv[i],"--standalone")) ) {        if ( (!strcmp(OrbitalInfoargv[i],"--standalone")) ) {
107          standalone = true;          standalone = true;
108        };        }
109        if ( (!strcmp(OrbitalInfoargv[i],"--calculate-pitch")) ) {        if ( (!strcmp(OrbitalInfoargv[i],"--calculate-pitch")) ) {
110          standalone = false;          standalone = false;
111        };        }
112        i++;        i++;
113      };      }
114    };    }
115      if ( debug ){
116        printf("START\n");
117        gObjectTable->Print();
118      }
119    //    //
120    const char* outDir = gSystem->DirName(gSystem->DirName(file->GetPath()));    const char* outDir = gSystem->DirName(gSystem->DirName(file->GetPath()));
121    //    //
# Line 121  int OrbitalInfoCore(UInt_t run, TFile *f Line 134  int OrbitalInfoCore(UInt_t run, TFile *f
134    TTree *OrbitalInfotrclone = 0;    TTree *OrbitalInfotrclone = 0;
135    Bool_t reproc = false;    Bool_t reproc = false;
136    Bool_t reprocall = false;    Bool_t reprocall = false;
137      Bool_t igrfloaded = false;
138    UInt_t nobefrun = 0;    UInt_t nobefrun = 0;
139    UInt_t noaftrun = 0;    UInt_t noaftrun = 0;
140    UInt_t numbofrun = 0;    UInt_t numbofrun = 0;
# Line 128  int OrbitalInfoCore(UInt_t run, TFile *f Line 142  int OrbitalInfoCore(UInt_t run, TFile *f
142    TString fname;    TString fname;
143    UInt_t totfileentries = 0;    UInt_t totfileentries = 0;
144    UInt_t idRun = 0;    UInt_t idRun = 0;
145      UInt_t anni5 = 60 * 60 * 24 * 365 * 5 ;//1576800
146    //    //
147    // My variables. Vitaly.    // My variables. Vitaly.
148    //    //
# Line 180  int OrbitalInfoCore(UInt_t run, TFile *f Line 195  int OrbitalInfoCore(UInt_t run, TFile *f
195    //    //
196    // IGRF stuff    // IGRF stuff
197    //    //
198    Float_t dimo = 0.0; // dipole moment (computed from dat files)    Float_t dimo = 0.0; // dipole moment (computed from dat files) // EM GCC 4.7
199    Float_t bnorth, beast, bdown, babs;    Float_t bnorth, beast, bdown, babs;
200    Float_t xl; // L value    Float_t xl; // L value
201    Float_t icode; // code value for L accuracy (see fortran code)    Float_t icode; // code value for L accuracy (see fortran code)
# Line 223  int OrbitalInfoCore(UInt_t run, TFile *f Line 238  int OrbitalInfoCore(UInt_t run, TFile *f
238    //    //
239    //Quaternions classes    //Quaternions classes
240    //    //
241    Quaternions *L_QQ_Q_l_lower = new Quaternions();    Quaternions *L_QQ_Q_l_lower = 0;
242    InclinationInfo *RYPang_lower = new InclinationInfo();    InclinationInfo *RYPang_lower = 0;
243    Quaternions *L_QQ_Q_l_upper = new Quaternions();    Quaternions *L_QQ_Q_l_upper = 0;
244    InclinationInfo *RYPang_upper = new InclinationInfo();    InclinationInfo *RYPang_upper = 0;
245        
246    cEci eCi;    cEci eCi;
247        
248    // Initialize fortran routines!!!    // Initialize fortran routines!!!
249      Int_t ltp1 = 0;
250    Int_t ltp2 = 0;    Int_t ltp2 = 0;
251    Int_t ltp3 = 0;    GL_PARAM *glparam0 = new GL_PARAM();
   Int_t uno = 1;  
   const char *niente = " ";  
252    GL_PARAM *glparam = new GL_PARAM();    GL_PARAM *glparam = new GL_PARAM();
253    GL_PARAM *glparam2 = new GL_PARAM();    GL_PARAM *glparam2 = new GL_PARAM();
254    
255    //    //
256    // Orientation variables. Vitaly    // Orientation variables. Vitaly
257    //    //
258    
259    UInt_t evfrom = 0;    UInt_t evfrom = 0;
260    UInt_t jumped = 0;    UInt_t jumped = 0;
261    Int_t itr = -1;        Int_t itr = -1;    
262    Double_t A1;    //  Double_t A1;
263    Double_t A2;    //  Double_t A2;
264    Double_t A3;    //  Double_t A3;
265    Double_t Px = 0;    Double_t Px = 0;
266    Double_t Py = 0;          Double_t Py = 0;      
267    Double_t Pz = 0;      Double_t Pz = 0;  
268    TTree *ttof = 0;    TTree *ttof = 0;
269    ToFLevel2 *tof = new ToFLevel2();    ToFLevel2 *tof = new ToFLevel2();
270      TTree *ttrke = 0;
271      TrkLevel2 *trke = new TrkLevel2();
272    OrientationInfo *PO = new OrientationInfo();    OrientationInfo *PO = new OrientationInfo();
273    Int_t nz = 6;    Int_t nz = 6;
274    Float_t zin[6];    Float_t zin[6];
275    Int_t nevtofl2 = 0;    Int_t nevtofl2 = 0;
276      Int_t nevtrkl2 = 0;
277    if ( verbose ) cout<<"Reading quaternions external file"<<endl;    if ( verbose ) cout<<"Reading quaternions external file"<<endl;
278    cout.setf(ios::fixed,ios::floatfield);      cout.setf(ios::fixed,ios::floatfield);  
279    /******Reading recovered quaternions...*********/    /******Reading recovered quaternions...*********/
   //cout<<"START reading recovered quaternions..."<<endl;  
280    vector<Double_t> recqtime;    vector<Double_t> recqtime;
281    vector<Float_t> recq0;    vector<Float_t> recq0;
282    vector<Float_t> recq1;    vector<Float_t> recq1;
283    vector<Float_t> recq2;    vector<Float_t> recq2;
284    vector<Float_t> recq3;    vector<Float_t> recq3;
285    Float_t Norm = 1;    Float_t Norm = 1;
286    Int_t parerror=glparam->Query_GL_PARAM(1,303,dbc); // parameters stored in DB in GL_PRAM table      recqtime.reserve(1500000);
287    ifstream in((glparam->PATH+glparam->NAME).Data(),ios::in);    recq0.reserve(1500000);
288      recq1.reserve(1500000);
289      recq2.reserve(1500000);
290      recq3.reserve(1500000);
291    
292      vector<UInt_t> RTtime1;
293      vector<UInt_t> RTtime2;
294      vector<Double_t> RTbank1;
295      vector<Double_t> RTbank2;
296      vector<Double_t> RTbpluto1;
297      vector<Double_t> RTbpluto2;
298      vector<Int_t> RTazim;
299      vector<UInt_t> RTstart;
300      vector<UInt_t> RTpluto2;
301      vector<UInt_t> RTpluto1;
302      vector<Int_t> RTerrq;
303      vector<Int_t> RTqual;
304      RTtime1.reserve(200000);
305      RTtime2.reserve(200000);
306      RTbank1.reserve(200000);
307      RTbank2.reserve(200000);
308      RTbpluto1.reserve(200000);
309      RTbpluto2.reserve(200000);
310      RTazim.reserve(200000);
311      RTstart.reserve(200000);
312      RTpluto1.reserve(200000);
313      RTpluto2.reserve(200000);
314      RTerrq.reserve(200000);
315      RTqual.reserve(200000);
316    
317      TClonesArray *tcNucleiTrk = NULL;
318      TClonesArray *tcExtNucleiTrk = NULL;
319      TClonesArray *tcExtTrk = NULL;
320      TClonesArray *tcNucleiTof = NULL;
321      TClonesArray *tcExtNucleiTof = NULL;
322      TClonesArray *tcExtTof = NULL;
323      TClonesArray *torbNucleiTrk = NULL;
324      TClonesArray *torbExtNucleiTrk = NULL;
325      TClonesArray *torbExtTrk = NULL;
326      Bool_t hasNucleiTrk = false;
327      Bool_t hasExtNucleiTrk = false;
328      Bool_t hasExtTrk = false;
329      Bool_t hasNucleiTof = false;
330      Bool_t hasExtNucleiTof = false;
331      Bool_t hasExtTof = false;
332    
333      ifstream in;
334      ifstream an;
335      //  ofstream mc;
336      //  TString gr;
337      Int_t parerror2=0;
338    
339      Int_t parerror=glparam0->Query_GL_PARAM(1,303,dbc); // parameters stored in DB in GL_PRAM table
340      if ( verbose ) cout<<parerror<<"\t"<<(char*)(glparam0->PATH+glparam0->NAME).Data()<<endl;
341    if ( parerror<0 ) {    if ( parerror<0 ) {
342      code = parerror;      code = parerror;
343      goto closeandexit;      goto closeandexit;
344    };    }
345    //cout<<"ifstream loaded..."<<endl;    in.open((char*)(glparam0->PATH+glparam0->NAME).Data(),ios::in);
346    while(!in.eof()){    while(!in.eof()){
347      recqtime.resize(recqtime.size()+1);      recqtime.resize(recqtime.size()+1);
348      Int_t sizee = recqtime.size();      Int_t sizee = recqtime.size();
# Line 286  int OrbitalInfoCore(UInt_t run, TFile *f Line 356  int OrbitalInfoCore(UInt_t run, TFile *f
356      in>>recq2[sizee-1];      in>>recq2[sizee-1];
357      in>>recq3[sizee-1];      in>>recq3[sizee-1];
358      in>>Norm;      in>>Norm;
359      //cout<<recqtime[sizee]<<endl;  /* CHECK RECOVERED QUATERNIONS PROBLEM
360        if(recqtime[sizee-1]>=1160987921.75 && recqtime[sizee-1]<=1160987932.00){
361          cout<<"We found it at start"<<"\t"<<recqtime[sizee-1]<<endl;
362        } */
363    }    }
364      in.close();
365    if ( verbose ) cout<<"We have read recovered data"<<endl;    if ( verbose ) cout<<"We have read recovered data"<<endl;
366      if (debug) cout << "size of recovered quaterions data set is " << recqtime.size() << endl;
367      if ( debug )  printf(" RQ size %i RQ capacity %i \n",(int)recqtime.size(),(int)recqtime.capacity());
368      
369      if ( verbose ) cout<<"read Rotation Table"<<endl;
370      
371      parerror2=glparam0->Query_GL_PARAM(1,305,dbc);
372    
373      if ( verbose ) cout<<parerror2<<"\t"<<(char*)(glparam0->PATH+glparam0->NAME).Data()<<endl;
374    parerror=glparam->Query_GL_PARAM(1,301,dbc); // parameters stored in DB in GL_PRAM table      if ( parerror2<0 ) {
   if ( parerror<0 ) {  
     code = parerror;  
     goto closeandexit;  
   };  
   ltp2 = (Int_t)(glparam->PATH+glparam->NAME).Length();  
   if ( verbose ) printf(" Reading Earth's Magnetic Field parameter file: %s \n",(glparam->PATH+glparam->NAME).Data());  
   //  
   parerror=glparam2->Query_GL_PARAM(1,302,dbc); // parameters stored in DB in GL_PRAM table  
   if ( parerror<0 ) {  
375      code = parerror;      code = parerror;
376      goto closeandexit;      goto closeandexit;
377    };    }
378    ltp3 = (Int_t)(glparam2->PATH+glparam2->NAME).Length();    an.open((char*)(glparam0->PATH+glparam0->NAME).Data(),ios::in);
379    if ( verbose ) printf(" Reading Earth's Magnetic Field parameter file: %s \n",(glparam2->PATH+glparam2->NAME).Data());    while(!an.eof()){
380    //      RTtime1.resize(RTtime1.size()+1);
381    initize_((char *)niente,&uno,(char *)(glparam->PATH+glparam->NAME).Data(),&ltp2,(char *)(glparam2->PATH+glparam2->NAME).Data(),&ltp3);      Int_t sizee = RTtime1.size();
382    //      RTbank1.resize(sizee+1);
383    // End IGRF stuff//      RTazim.resize(sizee+1);
384    //      RTerrq.resize(sizee+1);
385        RTstart.resize(sizee+1);
386        RTpluto1.resize(sizee+1);
387        RTbpluto1.resize(sizee+1);
388        RTqual.resize(sizee+1);
389        an>>RTtime1[sizee-1];
390        an>>RTbank1[sizee-1];
391        an>>RTstart[sizee-1];
392        an>>RTpluto1[sizee-1];
393        an>>RTbpluto1[sizee-1];
394        an>>RTazim[sizee-1];
395        an>>RTerrq[sizee-1];
396        an>>RTqual[sizee-1];
397        if(sizee>1) {
398          RTtime2.resize(sizee+1);
399          RTbank2.resize(sizee+1);
400          RTpluto2.resize(sizee+1);
401          RTbpluto2.resize(sizee+1);
402          RTtime2[sizee-2]=RTtime1[sizee-1];
403          RTpluto2[sizee-2]=RTpluto1[sizee-1];
404          RTbank2[sizee-2]=RTbank1[sizee-1];
405          RTbpluto2[sizee-2]=RTbpluto1[sizee-1];
406        }
407      }
408      an.close();
409      //cout<<"put some number here"<<endl;
410      //Int_t yupi;
411      //cin>>yupi;
412      
413      if ( verbose ) cout<<"We have read Rotation Table"<<endl;
414        //Geomagnetic coordinates calculations staff
415      
416      if ( debug ) printf(" RT size %i RT capacity %i \n",(int)RTtime2.size(),(int)RTtime2.capacity());
417    
418      GMtype_CoordGeodetic location;
419      //  GMtype_CoordDipole GMlocation;
420      GMtype_Ellipsoid Ellip;
421      GMtype_Data G0, G1, H1;
422            
423      //  { // this braces is necessary to avoid jump to label 'closeandexit'  error   // but it is wrong since the variable "igpath" will not exist outside. To overcome the "jump to label 'closeandexit'  error" it is necessary to set the "igpath" before line 276
424      //    TString igpath="/data03/Malakhov/pam9Malakhov/installed10/calib/orb-param/";
425      //  }
426    
427      //cout << G0.element[0] << "\t" << G1.element[0] << "\t" << H1.element[0] << endl;
428      //cout << G0.element[5] << "\t" << G1.element[5] << "\t" << H1.element[5] << endl;
429    
430      GM_SetEllipsoid(&Ellip);
431    
432      // IGRF stuff moved inside run loop!  
433    
434    for (Int_t ip=0;ip<nz;ip++){    for (Int_t ip=0;ip<nz;ip++){
435      zin[ip] = tof->GetZTOF(tof->GetToFPlaneID(ip));      zin[ip] = tof->GetZTOF(tof->GetToFPlaneID(ip));
436    };    };
437    //    //
438    if ( !standalone ){    if ( !standalone ){
439      //      //
440      // Does it contain the Tracker tree?      // Does it contain the Tracker and ToF trees?
441      //      //
442      ttof = (TTree*)file->Get("ToF");      ttof = (TTree*)file->Get("ToF");
443      if ( !ttof ) {      if ( !ttof ) {
444        if ( verbose ) printf(" OrbitalInfo - ERROR: no tof tree\n");        if ( verbose ) printf(" OrbitalInfo - ERROR: no tof tree\n");
445        code = -900;        code = -900;
446        goto closeandexit;        goto closeandexit;
447      };      }
448      ttof->SetBranchAddress("ToFLevel2",&tof);        ttof->SetBranchAddress("ToFLevel2",&tof);  
449      nevtofl2 = ttof->GetEntries();      nevtofl2 = ttof->GetEntries();
450    };  
451        //
452        // Look for extended tracking algorithm
453        //
454        if ( verbose ) printf("Look for extended and nuclei tracking algorithms in ToF\n");
455        // Nuclei tracking algorithm
456        Int_t checkAlgo = 0;
457        tcNucleiTof =  new TClonesArray("ToFTrkVar");
458        checkAlgo = ttof->SetBranchAddress("TrackNuclei",&tcNucleiTof);    
459        if ( !checkAlgo ){
460          if ( verbose ) printf(" Nuclei tracking algorithm ToF branch found! :D \n");
461          hasNucleiTof = true;
462        } else {
463          if ( verbose ) printf(" Nuclei tracking algorithm ToF branch not found :( !\n");
464          printf(" ok, this is not a problem (it depends on tracker settings) \n");
465          delete tcNucleiTof;
466          tcNucleiTof=NULL; // 10RED reprocessing bug  
467        }
468        // Nuclei tracking algorithm using calorimeter points
469        tcExtNucleiTof =  new TClonesArray("ToFTrkVar");
470        checkAlgo = ttof->SetBranchAddress("RecoveredTrackNuclei",&tcExtNucleiTof);    
471        if ( !checkAlgo ){
472          if ( verbose ) printf(" Recovered nuclei tracking algorithm ToF branch found! :D \n");
473          hasExtNucleiTof = true;
474        } else {
475          if ( verbose ) printf(" Recovered nuclei tracking algorithm ToF branch not found :( !\n");
476          printf(" ok, this is not a problem (it depends on tracker settings) \n");
477          delete tcExtNucleiTof;
478          tcExtNucleiTof=NULL; // 10RED reprocessing bug  
479        }
480        // Tracking algorithm using calorimeter points
481        tcExtTof =  new TClonesArray("ToFTrkVar");
482        checkAlgo = ttof->SetBranchAddress("RecoveredTrack",&tcExtTof);
483        if ( !checkAlgo ){
484          if ( verbose ) printf(" Recovered track algorithm ToF branch found! :D \n");
485          hasExtTof = true;
486        } else {
487          if ( verbose ) printf(" Recovered track algorithm ToF branch not found :( !\n");
488          printf(" ok, this is not a problem (it depends on tracker settings) \n");
489          delete tcExtTof;
490          tcExtTof=NULL; // 10RED reprocessing bug  
491        }
492    
493        ttrke = (TTree*)file->Get("Tracker");
494        if ( !ttrke ) {
495          if ( verbose ) printf(" OrbitalInfo - ERROR: no trk tree\n");
496          code = -903;
497          goto closeandexit;
498        }
499        ttrke->SetBranchAddress("TrkLevel2",&trke);  
500        nevtrkl2 = ttrke->GetEntries();
501    
502        //
503        // Look for extended tracking algorithm
504        //
505        if ( verbose ) printf("Look for extended and nuclei tracking algorithms\n");
506        // Nuclei tracking algorithm
507        checkAlgo = 0;
508        tcNucleiTrk =  new TClonesArray("TrkTrack");
509        checkAlgo = ttrke->SetBranchAddress("TrackNuclei",&tcNucleiTrk);    
510        if ( !checkAlgo ){
511          if ( verbose ) printf(" Nuclei tracking algorithm branch found! :D \n");
512          hasNucleiTrk = true;
513        } else {
514          if ( verbose ) printf(" Nuclei tracking algorithm branch not found :( !\n");
515          printf(" ok, this is not a problem (it depends on tracker settings) \n");
516          delete tcNucleiTrk;
517          tcNucleiTrk=NULL; // 10RED reprocessing bug  
518        }
519        // Nuclei tracking algorithm using calorimeter points
520        tcExtNucleiTrk =  new TClonesArray("ExtTrack");
521        checkAlgo = ttrke->SetBranchAddress("RecoveredTrackNuclei",&tcExtNucleiTrk);    
522        if ( !checkAlgo ){
523          if ( verbose ) printf(" Recovered nuclei tracking algorithm branch found! :D \n");
524          hasExtNucleiTrk = true;
525        } else {
526          if ( verbose ) printf(" Recovered nuclei tracking algorithm branch not found :( !\n");
527          printf(" ok, this is not a problem (it depends on tracker settings) \n");
528          delete tcExtNucleiTrk;
529          tcExtNucleiTrk=NULL; // 10RED reprocessing bug  
530        }
531        // Tracking algorithm using calorimeter points
532        tcExtTrk =  new TClonesArray("ExtTrack");
533        checkAlgo = ttrke->SetBranchAddress("RecoveredTrack",&tcExtTrk);
534        if ( !checkAlgo ){
535          if ( verbose ) printf(" Recovered track algorithm branch found! :D \n");
536          hasExtTrk = true;
537        } else {
538          if ( verbose ) printf(" Recovered track algorithm branch not found :( !\n");
539          printf(" ok, this is not a problem (it depends on tracker settings) \n");
540          delete tcExtTrk;
541          tcExtTrk=NULL; // 10RED reprocessing bug  
542        }
543    
544        if ( (hasNucleiTrk && !hasNucleiTof) || (!hasNucleiTrk && hasNucleiTof) ||
545             (hasExtNucleiTrk && !hasExtNucleiTof) || (!hasExtNucleiTrk && hasExtNucleiTof) ||
546             (hasExtTrk && !hasExtTof) || (!hasExtTrk && hasExtTof)
547             ){
548          if ( verbose ) printf(" ERROR: Mismatch between tracker and tof tree branches concerning extended tracking algorithm(s)\n");
549          if ( debug ) printf("hasNucleiTrk %i hasExtNucleiTrk %i hasExtTrk %i \n",hasNucleiTrk,hasExtNucleiTrk,hasExtTrk);
550          if ( debug ) printf("hasNucleiTof %i hasExtNucleiTof %i hasExtTof %i \n",hasNucleiTof,hasExtNucleiTof,hasExtTof);
551          throw -901;
552        }
553    
554      }
555    //    //
556    // Let's start!    // Let's start!
557    //    //
# Line 416  int OrbitalInfoCore(UInt_t run, TFile *f Line 640  int OrbitalInfoCore(UInt_t run, TFile *f
640        //        //
641        reprocall = true;        reprocall = true;
642        //        //
643        if (verbose) printf("\n OrbitalInfo - WARNING: Reprocessing all runs\n");        if (verbose) printf("\n OrbitalInfo - WARNING: Reprocessing all runs\n Deleting old tree...\n");
644        //        //
645      } else {      } else {
646        //        //
# Line 434  int OrbitalInfoCore(UInt_t run, TFile *f Line 658  int OrbitalInfoCore(UInt_t run, TFile *f
658        tempOrbitalInfo = OrbitalInfotrclone->CloneTree(-1,"fast");        tempOrbitalInfo = OrbitalInfotrclone->CloneTree(-1,"fast");
659        tempOrbitalInfo->SetName("OrbitalInfo-old");        tempOrbitalInfo->SetName("OrbitalInfo-old");
660        tempfile->Write();        tempfile->Write();
661          tempOrbitalInfo->Delete();
662        tempfile->Close();          tempfile->Close();  
663      }      }
664      //      //
665      // Delete the old tree from old file and memory      // Delete the old tree from old file and memory
666      //      //
667        OrbitalInfotrclone->Clear();
668      OrbitalInfotrclone->Delete("all");      OrbitalInfotrclone->Delete("all");
669      //      //
670      if (verbose) printf(" ...done!\n");      if (verbose) printf(" ...done!\n");
# Line 453  int OrbitalInfoCore(UInt_t run, TFile *f Line 679  int OrbitalInfoCore(UInt_t run, TFile *f
679    orbitalinfo->Set();//ELENA **TEMPORANEO?**    orbitalinfo->Set();//ELENA **TEMPORANEO?**
680    OrbitalInfotr->Branch("OrbitalInfo","OrbitalInfo",&orbitalinfo);    OrbitalInfotr->Branch("OrbitalInfo","OrbitalInfo",&orbitalinfo);
681    //    //
682      // create new branches for new tracking algorithms
683      //
684      if ( hasNucleiTrk ){
685        torbNucleiTrk = new TClonesArray("OrbitalInfoTrkVar",1);
686        OrbitalInfotr->Branch("TrackNuclei",&torbNucleiTrk);
687      }
688      if ( hasExtNucleiTrk ){
689        torbExtNucleiTrk = new TClonesArray("OrbitalInfoTrkVar",1);
690        OrbitalInfotr->Branch("RecoveredTrackNuclei",&torbExtNucleiTrk);
691      }
692      if ( hasExtTrk ){
693        torbExtTrk = new TClonesArray("OrbitalInfoTrkVar",1);
694        OrbitalInfotr->Branch("RecoveredTrack",&torbExtTrk);
695      }
696    
697      //
698    if ( reproc && !reprocall ){    if ( reproc && !reprocall ){
699      //      //
700      //  open new file and retrieve also tree informations      //  open new file and retrieve also tree informations
# Line 474  int OrbitalInfoCore(UInt_t run, TFile *f Line 716  int OrbitalInfoCore(UInt_t run, TFile *f
716          //          //
717          // copy orbitalinfoclone to mydec          // copy orbitalinfoclone to mydec
718          //          //
719          orbitalinfo->Clear();          //      orbitalinfo->Clear();
720          //          //
721          memcpy(&orbitalinfo,&orbitalinfoclone,sizeof(orbitalinfoclone));          memcpy(&orbitalinfo,&orbitalinfoclone,sizeof(orbitalinfoclone));
722          //          //
# Line 484  int OrbitalInfoCore(UInt_t run, TFile *f Line 726  int OrbitalInfoCore(UInt_t run, TFile *f
726          //          //
727        };        };
728        if (verbose) printf(" Finished successful copying!\n");        if (verbose) printf(" Finished successful copying!\n");
729      };                };
730    };    };
731    //    //
732    //    //
733    // Get the list of run to be processed, if only one run has to be processed the list will contain one entry only.    // Get the list of run to be processed, if only one run has to be processed the list will contain one entry only.
734    //    //
735    runlist = runinfo->GetRunList();    runlist = runinfo->GetRunList();
736      if ( debug ){
737        printf("BEFORE LOOP ON RUN\n");
738        gObjectTable->Print();
739      }
740    //    //
741    // Loop over the run to be processed    // Loop over the run to be processed
742    //    //
743    for (UInt_t irun=0; irun < numbofrun; irun++){    for (UInt_t irun=0; irun < numbofrun; irun++){ //===>
744    
745        L_QQ_Q_l_lower = new Quaternions();
746        RYPang_lower = new InclinationInfo();
747        L_QQ_Q_l_upper = new Quaternions();
748        RYPang_upper = new InclinationInfo();
749    
750      //      //
751      // retrieve the first run ID to be processed using the RunInfo list      // retrieve the first run ID to be processed using the RunInfo list
752      //      //
# Line 557  int OrbitalInfoCore(UInt_t run, TFile *f Line 809  int OrbitalInfoCore(UInt_t run, TFile *f
809      //      //
810      //    if ( !totevent ) goto closeandexit;      //    if ( !totevent ) goto closeandexit;
811      // Open Level0 file      // Open Level0 file
812        if ( l0File ) l0File->Close();
813      l0File = new TFile(fname.Data());      l0File = new TFile(fname.Data());
814      if ( !l0File ) {      if ( !l0File ) {
815        if ( debug ) printf(" OrbitalInfo - ERROR: problems opening Level0 file\n");        if ( debug ) printf(" OrbitalInfo - ERROR: problems opening Level0 file\n");
# Line 595  int OrbitalInfoCore(UInt_t run, TFile *f Line 848  int OrbitalInfoCore(UInt_t run, TFile *f
848        code = -12;        code = -12;
849        goto closeandexit;        goto closeandexit;
850      };      };
851      //  
     //     TTree *tp = (TTree*)l0File->Get("RunHeader");  
     //     tp->SetBranchAddress("Header", &eH);  
     //     tp->SetBranchAddress("RunHeader", &reh);  
     //     tp->GetEntry(0);  
     //     ph = eH->GetPscuHeader();  
     //     ULong_t TimeSync = reh->LAST_TIME_SYNC_INFO;  
     //     ULong_t ObtSync = reh->OBT_TIME_SYNC;      
     //     if ( debug ) printf(" 1 TimeSync %lu ObtSync %lu DeltaOBT %lu\n",TimeSync,ObtSync,TimeSync-ObtSync);  
     //  
852      ULong_t TimeSync = (ULong_t)dbtime->GetTimesync();      ULong_t TimeSync = (ULong_t)dbtime->GetTimesync();
853      ULong_t ObtSync = (ULong_t)(dbtime->GetObt0()/1000);      ULong_t ObtSync = (ULong_t)(dbtime->GetObt0()/1000);
854      ULong_t DeltaOBT = TimeSync - ObtSync;      ULong_t DeltaOBT = TimeSync - ObtSync;
# Line 640  int OrbitalInfoCore(UInt_t run, TFile *f Line 884  int OrbitalInfoCore(UInt_t run, TFile *f
884          //          //
885          l0fid[i] = (UInt_t)atoll(Row->GetField(0));          l0fid[i] = (UInt_t)atoll(Row->GetField(0));
886          i--;          i--;
887            if (Row){  // memleak!
888              delete Row;
889              Row = 0;
890            }
891          Row = pResult->Next();            Row = pResult->Next();  
892          //          //
893        };        }
894          if (Row) delete Row;
895        pResult->Delete();        pResult->Delete();
896      };      }
897      //      //
898      myquery.str("");      myquery.str("");
899      myquery << "select ID_ROOT_L0 from GL_RUN where RUNHEADER_TIME>" << runinfo->RUNHEADER_TIME << " group by ID_ROOT_L0 order by RUNHEADER_TIME asc limit 5;";      myquery << "select ID_ROOT_L0 from GL_RUN where RUNHEADER_TIME>" << runinfo->RUNHEADER_TIME << " group by ID_ROOT_L0 order by RUNHEADER_TIME asc limit 5;";
# Line 662  int OrbitalInfoCore(UInt_t run, TFile *f Line 911  int OrbitalInfoCore(UInt_t run, TFile *f
911          //          //
912          l0fid[i] = (UInt_t)atoll(Row->GetField(0));          l0fid[i] = (UInt_t)atoll(Row->GetField(0));
913          i++;          i++;
914            if (Row){  // memleak!
915              delete Row;
916              Row = 0;
917            }
918          Row = pResult->Next();            Row = pResult->Next();  
919          //          //
920        };        }
921          if (Row) delete Row;
922        pResult->Delete();        pResult->Delete();
923      };      }
924      //      //
925      i = 0;      i = 0;
926      UInt_t previd = 0;      UInt_t previd = 0;
# Line 685  int OrbitalInfoCore(UInt_t run, TFile *f Line 939  int OrbitalInfoCore(UInt_t run, TFile *f
939            if ( debug ) printf(" Using inclination informations from file: %s \n",(((TString)gSystem->ExpandPathName(Row->GetField(0)))+"/"+(TString)Row->GetField(1)).Data());            if ( debug ) printf(" Using inclination informations from file: %s \n",(((TString)gSystem->ExpandPathName(Row->GetField(0)))+"/"+(TString)Row->GetField(1)).Data());
940            ch->Add(((TString)gSystem->ExpandPathName(Row->GetField(0)))+"/"+(TString)Row->GetField(1));            ch->Add(((TString)gSystem->ExpandPathName(Row->GetField(0)))+"/"+(TString)Row->GetField(1));
941            //            //
942              if (Row) delete Row;
943            pResult->Delete();            pResult->Delete();
944          };          }
945        };        }
946        i++;        i++;
947      };      }
948      //      //
     //    l0trm = (TTree*)l0File->Get("Mcmd");  
     //    ch->ls();  
949      ch->SetBranchAddress("Mcmd",&mcmdev);      ch->SetBranchAddress("Mcmd",&mcmdev);
     //    printf(" entries %llu \n", ch->GetEntries());  
     //    l0trm = ch->GetTree();  
     //    neventsm = l0trm->GetEntries();  
950      neventsm = ch->GetEntries();      neventsm = ch->GetEntries();
951      if ( debug ) printf(" entries %u \n", neventsm);      if ( debug ) printf(" entries %u \n", neventsm);
     //    neventsm = 0;  
952      //      //
953      if (neventsm == 0){      if (neventsm == 0){
954        if ( debug ) printf("InclinationInfo - WARNING: No quaternions in this File");        if ( debug ) printf("InclinationInfo - WARNING: No quaternions in this File");
       //      l0File->Close();  
955        code = 900;        code = 900;
       //      goto closeandexit;  
956      }      }
957      //      //
958            Double_t lowerqtime = 0;    
     //    l0trm->SetBranchAddress("Mcmd", &mcmdev);  
     //    l0trm->SetBranchAddress("Header", &eh);  
     //  
     //  
     //  
   
 //    UInt_t mctren = 0;      
 //    UInt_t mcreen = 0;          
     UInt_t numrec = 0;  
     //  
     Double_t upperqtime = 0;  
     Double_t lowerqtime = 0;  
       
 //    Double_t incli = 0;  
 //    oi = 0;  
 //    UInt_t ooi = 0;  
959      //      //
960      // init quaternions information from mcmd-packets      // init quaternions information from mcmd-packets
961      //      //
962      Bool_t isf = true;      Bool_t isf = true;
 //    Int_t fgh = 0;  
963    
964      vector<Float_t> q0;      vector<Float_t> q0;
965      vector<Float_t> q1;      vector<Float_t> q1;
# Line 741  int OrbitalInfoCore(UInt_t run, TFile *f Line 971  int OrbitalInfoCore(UInt_t run, TFile *f
971      vector<Float_t> qYaw;      vector<Float_t> qYaw;
972      vector<Int_t> qmode;      vector<Int_t> qmode;
973    
974        q0.reserve(4096);
975        q1.reserve(4096);
976        q2.reserve(4096);
977        q3.reserve(4096);
978        qtime.reserve(4096);
979        qPitch.reserve(4096);
980        qRoll.reserve(4096);
981        qYaw.reserve(4096);
982        qmode.reserve(4096);
983        if ( debug ) printf(" q0 capa %i \n",(int)q0.capacity());
984      Int_t nt = 0;      Int_t nt = 0;
       
     //init sine-function interpolation  
       
     //cout<<"Sine coeficient initialisation..."<<endl;  
     vector<Sine> q0sine;  
     vector<Sine> q1sine;  
     vector<Sine> q2sine;  
     vector<Sine> q3sine;  
     vector<Sine> Yawsine;  
   
     /*TH2F* q0testing = new TH2F();  
       TH2F* q1testing = new TH2F();  
       TH2F* q2testing = new TH2F();  
       TH2F* q3testing = new TH2F();  
       TH2F* Pitchtesting = new TH2F();  
     */  
985      UInt_t must = 0;      UInt_t must = 0;
986    
987        Int_t currentYear = 0;
988        Int_t previousYear = 0;
989    
990      //      //
991      // run over all the events of the run      // run over all the events of the run
992      //      //
993      if (verbose) printf("\n Ready to start! \n\n Processed events: \n\n");      if (verbose) printf("\n Ready to start! \n\n Processed events: \n\n");
994        if ( debug ){
995          printf("BEFORE LOOP ON EVENTS\n");
996          gObjectTable->Print();
997        }
998      //      //
999      //      //
1000      for ( re = runinfo->EV_FROM; re < (runinfo->EV_FROM+runinfo->NEVENTS); re++){      for ( re = runinfo->EV_FROM; re < (runinfo->EV_FROM+runinfo->NEVENTS); re++){
1001          //for ( re = runinfo->EV_FROM; re < (runinfo->EV_FROM+10); re++){
1002    
1003        //        //
1004        if ( procev%1000 == 0 && procev > 0 && verbose ) printf(" %iK \n",procev/1000);          if ( procev%1000 == 0 && procev > 0 && verbose ) printf(" %iK \n",procev/1000);  
1005        if ( debug ) printf(" %i \n",procev);              if ( debug ) printf(" %i \n",procev);      
# Line 788  int OrbitalInfoCore(UInt_t run, TFile *f Line 1021  int OrbitalInfoCore(UInt_t run, TFile *f
1021          continue;          continue;
1022        }        }
1023    
1024          // just for testing:
1025          //      if (re >= 5+runinfo->EV_FROM) atime += anni5;
1026          //      if (re >= 7+runinfo->EV_FROM) atime += anni5;
1027          //      if (re >= 9+runinfo->EV_FROM) atime += anni5;
1028    
1029          //
1030          // open IGRF files and do it only once if we are processing a full level2 file
1031          //
1032          Float_t kkyear;
1033          UInt_t kyear, kmonth, kday, khour, kmin, ksec;
1034          //
1035          TTimeStamp kt = TTimeStamp(atime, kTRUE);
1036          kt.GetDate(kTRUE, 0, &kyear, &kmonth, &kday);
1037          kt.GetTime(kTRUE, 0, &khour, &kmin, &ksec);
1038          kkyear = (float) kyear
1039            + (kmonth*31.+ (float) kday)/365.
1040            + (khour*3600.+kmin*60.+(float)ksec)/(24.*3600.*365.);
1041          currentYear = int(kkyear/5.) * 5;
1042          if ( debug ) printf(" prevy %i curry %i igrfloaded %i \n",previousYear,currentYear,igrfloaded);
1043          if ( currentYear != previousYear ) igrfloaded = false;
1044          previousYear = currentYear;
1045          if ( debug ) printf(" prevy %i curry %i igrfloaded %i \n",previousYear,currentYear,igrfloaded);
1046          //
1047          if ( !igrfloaded ){
1048            
1049            igrfloaded = true;
1050            
1051            parerror=glparam->Query_GL_PARAM(atime,302,dbc); // parameters stored in DB in GL_PRAM table  
1052            if ( parerror<0 ) {
1053              code = parerror;
1054              goto closeandexit;
1055            }
1056            ltp1 = (Int_t)(glparam->PATH+glparam->NAME).Length();
1057            if ( verbose ) printf(" Reading Earth's Magnetic Field parameter file: %s \n",(glparam->PATH+glparam->NAME).Data());
1058            //
1059            if ( glparam->NAME.EndsWith("s.txt") || glparam->NAME.EndsWith("s.dat") ){
1060              if ( verbose ) printf("ERROR: Current date is beyond the latest secular variation file time span. Please update IGRF files to process data\n");
1061              throw -906;
1062            }
1063            //
1064            int isSecular = false;
1065            //
1066            parerror=glparam2->Query_GL_PARAM(atime+anni5,302,dbc); // parameters stored in DB in GL_PRAM table  
1067            if ( parerror<0 ) {
1068              code = parerror;
1069              goto closeandexit;
1070            }
1071            ltp2 = (Int_t)(glparam2->PATH+glparam2->NAME).Length();
1072            if ( verbose ) printf(" Reading Earth's Magnetic Field parameter file: %s \n",(glparam2->PATH+glparam2->NAME).Data());
1073            if ( glparam2->NAME.EndsWith("s.txt") || glparam2->NAME.EndsWith("s.dat") ){
1074              isSecular = true;
1075              if ( verbose ) printf(" Using secular variation file and hence fortran subroutine 'extrapolation'\n");
1076            } else {
1077              if ( verbose ) printf(" Using two field measurement files and hence fortran subroutine 'interpolation'\n");
1078            }
1079            //
1080            initize_(&isSecular,(char *)(glparam->PATH+glparam->NAME).Data(),&ltp1,(char *)(glparam2->PATH+glparam2->NAME).Data(),&ltp2);
1081            //
1082            if (debug) cout<<"initize: "<<(char *)(glparam->PATH+glparam->NAME).Data()<<"\t"<<(char *)(glparam2->PATH+glparam2->NAME).Data()<<"\t isSecular? "<<isSecular<<endl;  
1083    
1084            //        GM_ScanIGRF(dbc, &G0, &G1, &H1);
1085            TString igrfFile1 = glparam->PATH+glparam->NAME;
1086            TString igrfFile2 = glparam2->PATH+glparam2->NAME;
1087            GM_SetIGRF(isSecular,igrfFile1,igrfFile2, &G0, &G1, &H1);
1088          }
1089          //
1090          // End IGRF stuff//
1091          //
1092    
1093        //        //
1094        // retrieve tof informations        // retrieve tof informations
1095        //        //
# Line 803  int OrbitalInfoCore(UInt_t run, TFile *f Line 1105  int OrbitalInfoCore(UInt_t run, TFile *f
1105            if ( verbose ) printf(" OrbitalInfo - ERROR: no tof events with entry = %i in Level2 file\n",itr);            if ( verbose ) printf(" OrbitalInfo - ERROR: no tof events with entry = %i in Level2 file\n",itr);
1106            if ( debug ) printf(" nobefrun %u re %u evfrom %u jumped %u reprocall %i \n",nobefrun,re,evfrom,jumped,reprocall);            if ( debug ) printf(" nobefrun %u re %u evfrom %u jumped %u reprocall %i \n",nobefrun,re,evfrom,jumped,reprocall);
1107            l0File->Close();            l0File->Close();
1108            code = -901;            code = -904;
1109            goto closeandexit;            goto closeandexit;
1110          };          };
1111          //          //
1112          tof->Clear();          tof->Clear();
1113          //          //
1114          if ( ttof->GetEntry(itr) <= 0 ) throw -36;          // Clones array must be cleared before going on
1115            //
1116            if ( hasNucleiTof ){
1117              tcNucleiTof->Delete();
1118            }
1119            if ( hasExtNucleiTof ){
1120              tcExtNucleiTof->Delete();
1121            }          
1122            if ( hasExtTof ){
1123              tcExtTof->Delete();
1124            }
1125            //
1126            if ( verbose ) printf(" get tof tree entries... entry = %i in Level2 file\n",itr);
1127            if ( ttof->GetEntry(itr) <= 0 ){
1128              if ( verbose ) printf(" problems with tof tree entries... entry = %i in Level2 file\n",itr);
1129              if ( verbose ) printf(" nobefrun %u re %u evfrom %u jumped %u reprocall %i \n",nobefrun,re,evfrom,jumped,reprocall);
1130              throw -36;
1131            }
1132            if ( verbose ) printf(" gat0\n");
1133          //          //
1134        };        }
1135          //
1136          // retrieve tracker informations
1137          //
1138          if ( !standalone ){
1139            if ( itr > nevtrkl2 ){  
1140              if ( verbose ) printf(" OrbitalInfo - ERROR: no trk events with entry = %i in Level2 file\n",itr);
1141              if ( debug ) printf(" nobefrun %u re %u evfrom %u jumped %u reprocall %i \n",nobefrun,re,evfrom,jumped,reprocall);
1142              l0File->Close();
1143              code = -905;
1144              goto closeandexit;
1145            }
1146            //
1147            if ( verbose ) printf(" gat1\n");
1148            trke->Clear();
1149            //
1150            // Clones array must be cleared before going on
1151            //
1152            if ( hasNucleiTrk ){
1153              if ( verbose ) printf(" gat2\n");
1154              tcNucleiTrk->Delete();
1155              if ( verbose ) printf(" gat3\n");
1156              torbNucleiTrk->Delete();
1157            }
1158            if ( hasExtNucleiTrk ){
1159              if ( verbose ) printf(" gat4\n");
1160              tcExtNucleiTrk->Delete();
1161              if ( verbose ) printf(" gat5\n");
1162              torbExtNucleiTrk->Delete();
1163            }          
1164            if ( hasExtTrk ){
1165              if ( verbose ) printf(" gat6\n");
1166              tcExtTrk->Delete();
1167              if ( verbose ) printf(" gat7\n");
1168              torbExtTrk->Delete();
1169            }
1170            //
1171            if ( verbose ) printf(" get trk tree entries... entry = %i in Level2 file\n",itr);
1172            if ( ttrke->GetEntry(itr) <= 0 ) throw -36;
1173            //
1174          }
1175    
1176        //        //
1177        procev++;        procev++;
1178        //        //
# Line 823  int OrbitalInfoCore(UInt_t run, TFile *f Line 1184  int OrbitalInfoCore(UInt_t run, TFile *f
1184        OrbitalInfoTrkVar *t_orb = new OrbitalInfoTrkVar();        OrbitalInfoTrkVar *t_orb = new OrbitalInfoTrkVar();
1185        if( !(orbitalinfo->OrbitalInfoTrk) ) orbitalinfo->OrbitalInfoTrk = new TClonesArray("OrbitalInfoTrkVar",2);        if( !(orbitalinfo->OrbitalInfoTrk) ) orbitalinfo->OrbitalInfoTrk = new TClonesArray("OrbitalInfoTrkVar",2);
1186        TClonesArray &tor = *orbitalinfo->OrbitalInfoTrk;        TClonesArray &tor = *orbitalinfo->OrbitalInfoTrk;
1187    
1188          // Geomagnetic coordinates calculation variables
1189          GMtype_CoordSpherical CoordSpherical, DipoleSpherical;
1190          GMtype_CoordCartesian CoordCartesian, DipoleCartesian;
1191          GMtype_Model Model;
1192          GMtype_Pole Pole;
1193    
1194        //        //
1195        // Fill OBT, pkt_num and absTime        // Fill OBT, pkt_num and absTime
1196        //              //      
# Line 852  int OrbitalInfoCore(UInt_t run, TFile *f Line 1220  int OrbitalInfoCore(UInt_t run, TFile *f
1220              + (month*31.+ (float) day)/365.              + (month*31.+ (float) day)/365.
1221              + (hour*3600.+min*60.+(float)sec)/(24.*3600.*365.);              + (hour*3600.+min*60.+(float)sec)/(24.*3600.*365.);
1222            //            //
1223            if ( debug ) printf(" %i compute magnetic dipole moment get dipole moment for year\n",procev);                  if ( debug ) printf(" %i compute magnetic dipole moment get dipole moment for year\n",procev);            
1224              if ( debug ) printf(" %i jyear %f dimo %f \n",procev,jyear,dimo);
1225            feldcof_(&jyear, &dimo); // get dipole moment for year            feldcof_(&jyear, &dimo); // get dipole moment for year
1226            if ( debug ) printf(" %i compute magnetic dipole moment end\n",procev);                  if ( debug ) printf(" %i compute magnetic dipole moment end\n",procev);
1227    
1228              //      GM_TimeAdjustCoefs(year, jyear, G0, G1, H1, &Model);
1229              GM_TimeAdjustCoefs(GM_STARTYEAR, (jyear-currentYear+GM_STARTYEAR), G0, G1, H1, &Model);  // EM: input this way due to the new way of storing data into Gn,H1 and to avoid changing GM_Time...
1230              GM_PoleLocation(Model, &Pole);
1231              
1232          } else {          } else {
1233            code = -56;            code = -56;
1234            goto closeandexit;            goto closeandexit;
# Line 864  int OrbitalInfoCore(UInt_t run, TFile *f Line 1238  int OrbitalInfoCore(UInt_t run, TFile *f
1238        //        //
1239        cOrbit orbits(*gltle->GetTle());        cOrbit orbits(*gltle->GetTle());
1240        //        //
       if ( debug ) printf(" I am Here \n");  
       //  
1241        // synchronize with quaternions data        // synchronize with quaternions data
1242        //        //
1243        if ( isf && neventsm>0 ){        if ( isf && neventsm>0 ){
# Line 873  int OrbitalInfoCore(UInt_t run, TFile *f Line 1245  int OrbitalInfoCore(UInt_t run, TFile *f
1245          // First event          // First event
1246          //          //
1247          isf = false;          isf = false;
1248          upperqtime = atime;          //      upperqtime = atime;
1249          lowerqtime = runinfo->RUNHEADER_TIME;          lowerqtime = runinfo->RUNHEADER_TIME;
1250          for ( ik = 0; ik < neventsm; ik++){  //number of macrocommad packets          for ( ik = 0; ik < neventsm; ik++){  //number of macrocommad packets
1251            if ( ch->GetEntry(ik) <= 0 ) throw -36;            if ( ch->GetEntry(ik) <= 0 ) throw -36;
1252            tmpSize = mcmdev->Records->GetEntries();            tmpSize = mcmdev->Records->GetEntries();
1253            numrec = tmpSize;            //      numrec = tmpSize;
1254              if ( debug ) cout << "packet number " << ik <<"\tnumber of subpackets is " << tmpSize << endl;
1255            for (Int_t j3 = 0;j3<tmpSize;j3++){  //number of subpackets            for (Int_t j3 = 0;j3<tmpSize;j3++){  //number of subpackets
             if ( debug ) printf(" ik %i j3 %i eh eh eh \n",ik,j3);  
1256              mcmdrc = (pamela::McmdRecord*)mcmdev->Records->At(j3);              mcmdrc = (pamela::McmdRecord*)mcmdev->Records->At(j3);
1257              if ( mcmdrc ){ // missing inclination bug [8RED 090116]              if ( mcmdrc ){ // missing inclination bug [8RED 090116]
1258                  if ( debug ) printf(" pluto \n");
1259                if ((int)mcmdrc->ID1 == 226 && mcmdrc->Mcmd_Block_crc_ok == 1){ //Check that it is Inclination Packet                if ((int)mcmdrc->ID1 == 226 && mcmdrc->Mcmd_Block_crc_ok == 1){ //Check that it is Inclination Packet
1260                  L_QQ_Q_l_upper->fill(mcmdrc->McmdData);                 L_QQ_Q_l_upper->fill(mcmdrc->McmdData);
1261                  for (UInt_t ui = 0; ui < 6; ui++){                  for (UInt_t ui = 0; ui < 6; ui++){
1262                    if (ui>0){                    if (ui>0){
1263                      if (L_QQ_Q_l_upper->time[ui]>L_QQ_Q_l_upper->time[0]){                      if (L_QQ_Q_l_upper->time[ui]>L_QQ_Q_l_upper->time[0]){
1264                          if ( debug ) printf(" here1 %i \n",ui);
1265                        Double_t u_time = dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[ui]*1000-DeltaOBT*1000));                        Double_t u_time = dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[ui]*1000-DeltaOBT*1000));
1266                        Int_t recSize = recqtime.size();                        Int_t recSize = recqtime.size();
1267                        for(Int_t mu = nt;mu<recSize;mu++){                        if(lowerqtime > recqtime[recSize-1]){
1268                          if(recqtime[mu]>lowerqtime && recqtime[mu]<u_time){                           // to avoid interpolation between bad quaternions arrays
1269                            nt=mu;                           if(sqrt(pow(L_QQ_Q_l_upper->quat[ui][0],2)+pow(L_QQ_Q_l_upper->quat[ui][1],2)+pow(L_QQ_Q_l_upper->quat[ui][2],2)+pow(L_QQ_Q_l_upper->quat[ui][3],2))>0.99999){
                           Int_t sizeqmcmd = qtime.size();  
                           inclresize(qtime,q0,q1,q2,q3,qmode,qRoll,qPitch,qYaw);  
                           qtime[sizeqmcmd]=recqtime[mu];  
                           q0[sizeqmcmd]=recq0[mu];  
                           q1[sizeqmcmd]=recq1[mu];  
                           q2[sizeqmcmd]=recq2[mu];  
                           q3[sizeqmcmd]=recq3[mu];  
                           qmode[sizeqmcmd]=-10;  
                           orbits.getPosition((double) (qtime[sizeqmcmd] - gltle->GetFromTime())/60., &eCi);  
                           RYPang_upper->TransAngle(eCi.getPos().m_x,eCi.getPos().m_y,eCi.getPos().m_z,eCi.getVel().m_x,eCi.getVel().m_y,eCi.getVel().m_z,recq0[mu],recq1[mu],recq2[mu],recq3[mu]);  
                           qRoll[sizeqmcmd]=RYPang_upper->Kren;  
                           qYaw[sizeqmcmd]=RYPang_upper->Ryskanie;  
                           qPitch[sizeqmcmd]=RYPang_upper->Tangazh;  
                         }  
                         if(recqtime[mu]>=u_time){  
1270                            Int_t sizeqmcmd = qtime.size();                            Int_t sizeqmcmd = qtime.size();
1271                            inclresize(qtime,q0,q1,q2,q3,qmode,qRoll,qPitch,qYaw);                            inclresize(qtime,q0,q1,q2,q3,qmode,qRoll,qPitch,qYaw);
1272                            qtime[sizeqmcmd]=u_time;                            qtime[sizeqmcmd]=u_time;
# Line 922  int OrbitalInfoCore(UInt_t run, TFile *f Line 1281  int OrbitalInfoCore(UInt_t run, TFile *f
1281                            qRoll[sizeqmcmd]=RYPang_upper->Kren;                            qRoll[sizeqmcmd]=RYPang_upper->Kren;
1282                            qYaw[sizeqmcmd]=RYPang_upper->Ryskanie;                            qYaw[sizeqmcmd]=RYPang_upper->Ryskanie;
1283                            qPitch[sizeqmcmd]=RYPang_upper->Tangazh;                            qPitch[sizeqmcmd]=RYPang_upper->Tangazh;
1284                            break;                           }
1285                          }
1286                          for(Int_t mu = nt;mu<recSize;mu++){
1287                            if(recqtime[mu]>lowerqtime && recqtime[mu]<u_time){
1288                              if(sqrt(pow(recq0[mu],2)+pow(recq1[mu],2)+pow(recq2[mu],2)+pow(recq3[mu],2))>0.99999){
1289                                nt=mu;
1290                                Int_t sizeqmcmd = qtime.size();
1291                                inclresize(qtime,q0,q1,q2,q3,qmode,qRoll,qPitch,qYaw);
1292                                qtime[sizeqmcmd]=recqtime[mu];
1293                                q0[sizeqmcmd]=recq0[mu];
1294                                q1[sizeqmcmd]=recq1[mu];
1295                                q2[sizeqmcmd]=recq2[mu];
1296                                q3[sizeqmcmd]=recq3[mu];
1297                                qmode[sizeqmcmd]=-10;
1298                                orbits.getPosition((double) (qtime[sizeqmcmd] - gltle->GetFromTime())/60., &eCi);
1299                                RYPang_upper->TransAngle(eCi.getPos().m_x,eCi.getPos().m_y,eCi.getPos().m_z,eCi.getVel().m_x,eCi.getVel().m_y,eCi.getVel().m_z,recq0[mu],recq1[mu],recq2[mu],recq3[mu]);
1300                                qRoll[sizeqmcmd]=RYPang_upper->Kren;
1301                                qYaw[sizeqmcmd]=RYPang_upper->Ryskanie;
1302                                qPitch[sizeqmcmd]=RYPang_upper->Tangazh;
1303    /* CHECK RECOVERED QUATERNIONS PROBLEM */
1304    if(recqtime[mu]>=1160987921.75 && recqtime[mu]<=1160987932.00){
1305      cout<<"We found it while checking all quaternions"<<"\t"<<recqtime[mu]<<endl;
1306    }
1307                              }
1308                            }
1309                            if(recqtime[mu]>=u_time){
1310                              if(sqrt(pow(L_QQ_Q_l_upper->quat[ui][0],2)+pow(L_QQ_Q_l_upper->quat[ui][1],2)+pow(L_QQ_Q_l_upper->quat[ui][2],2)+pow(L_QQ_Q_l_upper->quat[ui][3],2))>0.99999){
1311                                Int_t sizeqmcmd = qtime.size();
1312                                inclresize(qtime,q0,q1,q2,q3,qmode,qRoll,qPitch,qYaw);
1313                                qtime[sizeqmcmd]=u_time;
1314                                q0[sizeqmcmd]=L_QQ_Q_l_upper->quat[ui][0];
1315                                q1[sizeqmcmd]=L_QQ_Q_l_upper->quat[ui][1];
1316                                q2[sizeqmcmd]=L_QQ_Q_l_upper->quat[ui][2];
1317                                q3[sizeqmcmd]=L_QQ_Q_l_upper->quat[ui][3];
1318                                qmode[sizeqmcmd]=holeq(lowerqtime,qtime[sizeqmcmd],L_QQ_Q_l_lower,L_QQ_Q_l_upper,ui);
1319                                lowerqtime = u_time;
1320                                orbits.getPosition((double) (u_time - gltle->GetFromTime())/60., &eCi);
1321                                RYPang_upper->TransAngle(eCi.getPos().m_x,eCi.getPos().m_y,eCi.getPos().m_z,eCi.getVel().m_x,eCi.getVel().m_y,eCi.getVel().m_z,L_QQ_Q_l_upper->quat[ui][0],L_QQ_Q_l_upper->quat[ui][1],L_QQ_Q_l_upper->quat[ui][2],L_QQ_Q_l_upper->quat[ui][3]);
1322                                qRoll[sizeqmcmd]=RYPang_upper->Kren;
1323                                qYaw[sizeqmcmd]=RYPang_upper->Ryskanie;
1324                                qPitch[sizeqmcmd]=RYPang_upper->Tangazh;
1325    /* CHECK RECOVERED QUATERNIONS PROBLEM */
1326    if(recqtime[mu]>=1160987921.75 && recqtime[mu]<=1160987932.00){
1327      cout<<"We found it while checking all quaternions"<<"\t"<<recqtime[mu]<<endl;
1328    }
1329                                break;
1330                              }
1331                          }                          }
1332                        }                        }
1333                      }                      }
1334                    }else{                    }else{
1335                        if ( debug ) printf(" here2 %i \n",ui);
1336                      Double_t u_time = dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));                      Double_t u_time = dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));
1337                      if(lowerqtime>u_time)nt=0;                      if(lowerqtime>u_time)nt=0;
1338                      Int_t recSize = recqtime.size();                      Int_t recSize = recqtime.size();
1339                      for(Int_t mu = nt;mu<recSize;mu++){                      if(lowerqtime > recqtime[recSize-1]){
1340                        if(recqtime[mu]>lowerqtime && recqtime[mu]<u_time){                        if(sqrt(pow(L_QQ_Q_l_upper->quat[ui][0],2)+pow(L_QQ_Q_l_upper->quat[ui][1],2)+pow(L_QQ_Q_l_upper->quat[ui][2],2)+pow(L_QQ_Q_l_upper->quat[ui][3],2))>0.99999){
                         nt=mu;  
                         Int_t sizeqmcmd = qtime.size();  
                         inclresize(qtime,q0,q1,q2,q3,qmode,qRoll,qPitch,qYaw);  
                         qtime[sizeqmcmd]=recqtime[mu];  
                         q0[sizeqmcmd]=recq0[mu];  
                         q1[sizeqmcmd]=recq1[mu];  
                         q2[sizeqmcmd]=recq2[mu];  
                         q3[sizeqmcmd]=recq3[mu];  
                         qmode[sizeqmcmd]=-10;  
                         orbits.getPosition((double) (qtime[sizeqmcmd] - gltle->GetFromTime())/60., &eCi);  
                         RYPang_upper->TransAngle(eCi.getPos().m_x,eCi.getPos().m_y,eCi.getPos().m_z,eCi.getVel().m_x,eCi.getVel().m_y,eCi.getVel().m_z,recq0[mu],recq1[mu],recq2[mu],recq3[mu]);  
                         qRoll[sizeqmcmd]=RYPang_upper->Kren;  
                         qYaw[sizeqmcmd]=RYPang_upper->Ryskanie;  
                         qPitch[sizeqmcmd]=RYPang_upper->Tangazh;  
                       }  
                       if(recqtime[mu]>=u_time){  
1341                          Int_t sizeqmcmd = qtime.size();                          Int_t sizeqmcmd = qtime.size();
1342                          inclresize(qtime,q0,q1,q2,q3,qmode,qRoll,qPitch,qYaw);                          inclresize(qtime,q0,q1,q2,q3,qmode,qRoll,qPitch,qYaw);
1343                          qtime[sizeqmcmd]=u_time;                          qtime[sizeqmcmd]=u_time;
# Line 962  int OrbitalInfoCore(UInt_t run, TFile *f Line 1352  int OrbitalInfoCore(UInt_t run, TFile *f
1352                          qRoll[sizeqmcmd]=RYPang_upper->Kren;                          qRoll[sizeqmcmd]=RYPang_upper->Kren;
1353                          qYaw[sizeqmcmd]=RYPang_upper->Ryskanie;                          qYaw[sizeqmcmd]=RYPang_upper->Ryskanie;
1354                          qPitch[sizeqmcmd]=RYPang_upper->Tangazh;                          qPitch[sizeqmcmd]=RYPang_upper->Tangazh;
1355                          CopyQ(L_QQ_Q_l_lower,L_QQ_Q_l_upper);                        }
1356                          break;                      }
1357                        for(Int_t mu = nt;mu<recSize;mu++){
1358                          if(recqtime[mu]>lowerqtime && recqtime[mu]<u_time){
1359                             if(sqrt(pow(recq0[mu],2)+pow(recq1[mu],2)+pow(recq2[mu],2)+pow(recq3[mu],2))>0.99999){
1360    //                         nt=mu;
1361                               Int_t sizeqmcmd = qtime.size();
1362                               inclresize(qtime,q0,q1,q2,q3,qmode,qRoll,qPitch,qYaw);
1363                               qtime[sizeqmcmd]=recqtime[mu];
1364                               q0[sizeqmcmd]=recq0[mu];
1365                               q1[sizeqmcmd]=recq1[mu];
1366                               q2[sizeqmcmd]=recq2[mu];
1367                               q3[sizeqmcmd]=recq3[mu];
1368                               qmode[sizeqmcmd]=-10;
1369                               orbits.getPosition((double) (qtime[sizeqmcmd] - gltle->GetFromTime())/60., &eCi);
1370                               RYPang_upper->TransAngle(eCi.getPos().m_x,eCi.getPos().m_y,eCi.getPos().m_z,eCi.getVel().m_x,eCi.getVel().m_y,eCi.getVel().m_z,recq0[mu],recq1[mu],recq2[mu],recq3[mu]);
1371                               qRoll[sizeqmcmd]=RYPang_upper->Kren;
1372                               qYaw[sizeqmcmd]=RYPang_upper->Ryskanie;
1373                               qPitch[sizeqmcmd]=RYPang_upper->Tangazh;
1374    /* CHECK RECOVERED QUATERNIONS PROBLEM */
1375    if(recqtime[mu]>=1160987921.75 && recqtime[mu]<=1160987932.00){
1376      cout<<"We found it while checking all quaternions"<<"\t"<<recqtime[mu]<<endl;
1377    }
1378                             }
1379                          }
1380                          if(recqtime[mu]>=u_time){
1381                             if(sqrt(pow(L_QQ_Q_l_upper->quat[0][0],2)+pow(L_QQ_Q_l_upper->quat[0][1],2)+pow(L_QQ_Q_l_upper->quat[0][2],2)+pow(L_QQ_Q_l_upper->quat[0][3],2))>0.99999){
1382                               Int_t sizeqmcmd = qtime.size();
1383                               inclresize(qtime,q0,q1,q2,q3,qmode,qRoll,qPitch,qYaw);
1384                               qtime[sizeqmcmd]=u_time;
1385                               q0[sizeqmcmd]=L_QQ_Q_l_upper->quat[0][0];
1386                               q1[sizeqmcmd]=L_QQ_Q_l_upper->quat[0][1];
1387                               q2[sizeqmcmd]=L_QQ_Q_l_upper->quat[0][2];
1388                               q3[sizeqmcmd]=L_QQ_Q_l_upper->quat[0][3];
1389                               qmode[sizeqmcmd]=holeq(lowerqtime,qtime[sizeqmcmd],L_QQ_Q_l_lower,L_QQ_Q_l_upper,ui);
1390                               lowerqtime = u_time;
1391                               orbits.getPosition((double) (u_time - gltle->GetFromTime())/60., &eCi);
1392                               RYPang_upper->TransAngle(eCi.getPos().m_x,eCi.getPos().m_y,eCi.getPos().m_z,eCi.getVel().m_x,eCi.getVel().m_y,eCi.getVel().m_z,L_QQ_Q_l_upper->quat[0][0],L_QQ_Q_l_upper->quat[0][1],L_QQ_Q_l_upper->quat[0][2],L_QQ_Q_l_upper->quat[0][3]);
1393                               qRoll[sizeqmcmd]=RYPang_upper->Kren;
1394                               qYaw[sizeqmcmd]=RYPang_upper->Ryskanie;
1395                               qPitch[sizeqmcmd]=RYPang_upper->Tangazh;
1396                               CopyQ(L_QQ_Q_l_lower,L_QQ_Q_l_upper);
1397    /* CHECK RECOVERED QUATERNIONS PROBLEM */
1398    if(recqtime[mu]>=1160987921.75 && recqtime[mu]<=1160987932.00){
1399      cout<<"We found it while checking all quaternions"<<"\t"<<recqtime[mu]<<endl;
1400    }
1401                               break;
1402                             }
1403                        }                        }
1404                      }                      }
1405                    }                    }
1406                  }                  }
1407                }                }
1408              }              }
1409                //if ( debug ) cout << "subpacket " << j3 << "\t qtime = " << qtime[qtime.size()-1] << endl;
1410            }            }
1411          }          }
1412            
1413            if(qtime.size()==0){                            // in case if no orientation information in data
1414              if ( debug ) cout << "qtime.size() = 0" << endl;
1415              for(UInt_t my=0;my<recqtime.size();my++){
1416                if(sqrt(pow(recq0[my],2)+pow(recq1[my],2)+pow(recq2[my],2)+pow(recq3[my],2))>0.99999){
1417                  Int_t sizeqmcmd = qtime.size();
1418                  inclresize(qtime,q0,q1,q2,q3,qmode,qRoll,qPitch,qYaw);
1419                  qtime[sizeqmcmd]=recqtime[my];
1420                  q0[sizeqmcmd]=recq0[my];
1421                  q1[sizeqmcmd]=recq1[my];
1422                  q2[sizeqmcmd]=recq2[my];
1423                  q3[sizeqmcmd]=recq3[my];
1424                  qmode[sizeqmcmd]=-10;
1425                  orbits.getPosition((double) (qtime[sizeqmcmd] - gltle->GetFromTime())/60., &eCi);
1426                  RYPang_upper->TransAngle(eCi.getPos().m_x,eCi.getPos().m_y,eCi.getPos().m_z,eCi.getVel().m_x,eCi.getVel().m_y,eCi.getVel().m_z,recq0[my],recq1[my],recq2[my],recq3[my]);
1427                  qRoll[sizeqmcmd]=RYPang_upper->Kren;
1428                  qYaw[sizeqmcmd]=RYPang_upper->Ryskanie;
1429                  qPitch[sizeqmcmd]=RYPang_upper->Tangazh;
1430                }
1431              }
1432            }
1433            
1434    
1435          sineparam(q0sine,qtime,q0,qRoll,qPitch,0.58);          if ( debug ) printf(" puffi \n");
         sineparam(q1sine,qtime,q1,qRoll,qPitch,0.79);  
         sineparam(q2sine,qtime,q2,qRoll,qPitch,0.79);  
         sineparam(q3sine,qtime,q3,qRoll,qPitch,0.58);  
         sineparam(Yawsine,qtime,qYaw,qRoll,qPitch,4);  
1436          Double_t tmin = 9999999999.;          Double_t tmin = 9999999999.;
1437          Double_t tmax = 0.;          Double_t tmax = 0.;
1438          for(UInt_t tre = 0;tre<qtime.size();tre++){          for(UInt_t tre = 0;tre<qtime.size();tre++){
1439            if(qtime[tre]>tmax)tmax = qtime[tre];            if(qtime[tre]>tmax)tmax = qtime[tre];
1440            if(qtime[tre]<tmin)tmin = qtime[tre];            if(qtime[tre]<tmin)tmin = qtime[tre];
1441          }          }
1442                    // sorting quaternions by time
1443          //q0testing->SetName("q0testing");         Bool_t t = true;
1444          //q1testing->SetName("q1testing");          while(t){
1445          //q2testing->SetName("q2testing");           t=false;
1446          //q3testing->SetName("q3testing");            for(UInt_t i=0;i<qtime.size()-1;i++){
1447                        if(qtime[i]>qtime[i+1]){
1448  //      Int_t ss=10.*(tmax-tmin);                Double_t tmpr = qtime[i];
1449          //q0testing->SetBins(ss,tmin,tmax,1000,-1.,1.);                qtime[i]=qtime[i+1];
1450          //Pitchtesting->SetBins(ss,tmin,tmax,1000,-40.,40.);                qtime[i+1] = tmpr;
1451                  tmpr = q0[i];
1452  //      for(Int_t tre = 0;tre<qtime.size();tre++){                q0[i]=q0[i+1];
1453            //cout<<"q0["<<tre<<" = "<<q0[tre]<<endl;                q0[i+1] = tmpr;
1454            //q0testing->Fill(qtime[tre],q0[tre]);                tmpr = q1[i];
1455            //q1testing->Fill(qtime[tre],q1[tre]);                q1[i]=q1[i+1];
1456            //Pitchtesting->Fill(qtime[tre],qPitch[tre],100);                q1[i+1] = tmpr;
1457            //if(qmode[tre] == -10)Pitchtesting->Fill(qtime[tre],10,100);                tmpr = q2[i];
1458            //q2testing->Fill(qtime[tre],q2[tre],100);                q2[i]=q2[i+1];
1459            //q3testing->Fill(qtime[tre],q3[tre],100);                q2[i+1] = tmpr;
1460  //      }                tmpr = q3[i];
1461                          q3[i]=q3[i+1];
1462          //for(Int_t tre=0;tre<q0sine.size();tre++)cout<<q1sine[tre].A<<"*sin("<<q1sine[tre].b<<"x+"<<q1sine[tre].c<<")\t time start: "<<q1sine[tre].startPoint<<"\ttime end: "<<q1sine[tre].finishPoint<<endl;                q3[i+1] = tmpr;
1463          //for(Int_t tre=0;tre<q0sine.size();tre++)cout<<q1sine[tre].A<<"*sin("<<q1sine[tre].b<<"x+"<<q1sine[tre].c<<")\t time start: "<<q0sine[tre].startPoint<<"\ttime end: "<<q0sine[tre].finishPoint<<endl;                tmpr = qRoll[i];
1464                  qRoll[i]=qRoll[i+1];
1465                  qRoll[i+1] = tmpr;
1466                  tmpr = qYaw[i];
1467                  qYaw[i]=qYaw[i+1];
1468                  qYaw[i+1] = tmpr;
1469                  tmpr = qPitch[i];
1470                  qPitch[i]=qPitch[i+1];
1471                  qPitch[i+1] = tmpr;
1472                    t=true;
1473                }
1474              }
1475            }
1476    
1477            if ( debug ){
1478              cout << "we have loaded quaternions: size of quaternions set is "<< qtime.size() << endl;
1479             for(UInt_t i=0;i<qtime.size();i++) cout << qtime[i] << "\t";
1480              cout << endl << endl;
1481              Int_t lopu;
1482              cin >> lopu;
1483           }
1484    
1485        } // if we processed first event        } // if we processed first event
1486    
1487                
1488        //Filling Inclination information        //Filling Inclination information
1489        Double_t incli = 0;        Double_t incli = 0;
1490        for(UInt_t mu = must;mu<qtime.size()-1;mu++){        if ( qtime.size() > 1 ){
1491          if(qtime[mu+1]>qtime[mu]){          if ( debug ) cout << "ok quaternions is exist and mu = " << must << endl;
1492            if(atime<=qtime[mu+1] && atime>=qtime[mu]){          if ( debug ) cout << "qtimes[ " << qtime[0] << " , " << qtime[qtime.size()-1] << " ]\tatime = "<<atime<<endl;
1493              must = mu;          for(UInt_t mu = must;mu<qtime.size()-1;mu++){
1494              incli = (qPitch[mu+1]-qPitch[mu])/(qtime[mu+1]-qtime[mu]);            if ( debug ) printf(" ??grfuffi %i sixe %i must %i \n",mu,qtime.size()-1,must);
1495              orbitalinfo->theta =  incli*atime+qPitch[mu+1]-incli*qtime[mu+1];            if(qtime[mu+1]>qtime[mu]){
1496              incli = (qRoll[mu+1]-qRoll[mu])/(qtime[mu+1]-qtime[mu]);              if ( debug ) cout << "qtime[" << mu << "] = " << qtime[mu] << "\tqtime[" << mu+1 << "] = " << qtime[mu+1] << "\tatime = " << atime << endl;
1497              orbitalinfo->etha =  incli*atime+qRoll[mu+1]-incli*qtime[mu+1];              if(atime<=qtime[mu+1] && atime>=qtime[mu]){
1498              incli = (qYaw[mu+1]-qYaw[mu])/(qtime[mu+1]-qtime[mu]);                if ( debug ) cout << "here we have found proper quaternions for interpolation: mu = "<<mu<<endl;
1499              orbitalinfo->phi =  incli*atime+qYaw[mu+1]-incli*qtime[mu+1];                must = mu;
1500                              incli = (qPitch[mu+1]-qPitch[mu])/(qtime[mu+1]-qtime[mu]);
1501              incli = (q0[mu+1]-q0[mu])/(qtime[mu+1]-qtime[mu]);                orbitalinfo->theta =  incli*atime+qPitch[mu+1]-incli*qtime[mu+1];
1502              orbitalinfo->q0t =  incli*atime+q0[mu+1]-incli*qtime[mu+1];                incli = (qRoll[mu+1]-qRoll[mu])/(qtime[mu+1]-qtime[mu]);
1503              incli = (q1[mu+1]-q1[mu])/(qtime[mu+1]-qtime[mu]);                orbitalinfo->etha =  incli*atime+qRoll[mu+1]-incli*qtime[mu+1];
1504              orbitalinfo->q1t =  incli*atime+q1[mu+1]-incli*qtime[mu+1];                incli = (qYaw[mu+1]-qYaw[mu])/(qtime[mu+1]-qtime[mu]);
1505              incli = (q2[mu+1]-q2[mu])/(qtime[mu+1]-qtime[mu]);                orbitalinfo->phi =  incli*atime+qYaw[mu+1]-incli*qtime[mu+1];
1506              orbitalinfo->q2t =  incli*atime+q2[mu+1]-incli*qtime[mu+1];                
1507              incli = (q3[mu+1]-q3[mu])/(qtime[mu+1]-qtime[mu]);                incli = (q0[mu+1]-q0[mu])/(qtime[mu+1]-qtime[mu]);
1508              orbitalinfo->q3t =  incli*atime+q3[mu+1]-incli*qtime[mu+1];                orbitalinfo->q0 =  incli*atime+q0[mu+1]-incli*qtime[mu+1];
1509                              incli = (q1[mu+1]-q1[mu])/(qtime[mu+1]-qtime[mu]);
1510              orbitalinfo->TimeGap = qtime[mu+1]-qtime[mu];                orbitalinfo->q1 =  incli*atime+q1[mu+1]-incli*qtime[mu+1];
1511              orbitalinfo->mode = qmode[mu+1];                incli = (q2[mu+1]-q2[mu])/(qtime[mu+1]-qtime[mu]);
1512              if(qmode[mu+1]==-10) orbitalinfo->R10r = true;else orbitalinfo->R10r = false;                orbitalinfo->q2 =  incli*atime+q2[mu+1]-incli*qtime[mu+1];
1513              if(qmode[mu+1]==-10 || qmode[mu+1]==0 || qmode[mu+1]==1 || qmode[mu+1]==3 || qmode[mu+1]==4 || qmode[mu+1]==6){                incli = (q3[mu+1]-q3[mu])/(qtime[mu+1]-qtime[mu]);
1514                //linear interpolation                orbitalinfo->q3 =  incli*atime+q3[mu+1]-incli*qtime[mu+1];
1515                incli = (q0[mu+1]-q0[mu])/(qtime[mu+1]-qtime[mu]);                Float_t tg = (qtime[mu+1]-qtime[mu])/1000.0;
1516                orbitalinfo->q0 =  incli*atime+q0[mu+1]-incli*qtime[mu+1];                if(tg>=1) tg=0.00;
1517                incli = (q1[mu+1]-q1[mu])/(qtime[mu+1]-qtime[mu]);                orbitalinfo->TimeGap = TMath::Min(TMath::Abs(qtime[mu+1])-atime,TMath::Abs(atime-qtime[mu]))+tg;//qtime[mu+1]-qtime[mu];
1518                orbitalinfo->q1 =  incli*atime+q1[mu+1]-incli*qtime[mu+1];                orbitalinfo->mode = qmode[mu+1];
1519                incli = (q2[mu+1]-q2[mu])/(qtime[mu+1]-qtime[mu]);                //if(atime==qtime[mu] || atime==qtime[mu+1]) orbitalinfo->qkind = 0; else orbitalinfo->qkind=1;
1520                orbitalinfo->q2 =  incli*atime+q2[mu+1]-incli*qtime[mu+1];                //if(qmode[mu+1]==-10) orbitalinfo->R10r = true;else orbitalinfo->R10r = false;
1521                incli = (q3[mu+1]-q3[mu])/(qtime[mu+1]-qtime[mu]);                if ( debug ) printf(" grfuffi4 %i \n",mu);
1522                orbitalinfo->q3 =  incli*atime+q3[mu+1]-incli*qtime[mu+1];                break;
1523              }else{              }
1524                //sine interpolation            }
1525                for(UInt_t mt=0;mt<q0sine.size();mt++){          }
                 if(atime<=q0sine[mt].finishPoint && atime>=q0sine[mt].startPoint){  
                   if(!q0sine[mt].NeedFit)orbitalinfo->q0=q0sine[mt].A*sin(q0sine[mt].b*atime+q0sine[mt].c);else{  
                     incli = (q0[mu+1]-q0[mu])/(qtime[mu+1]-qtime[mu]);  
                     orbitalinfo->q0 =  incli*atime+q0[mu+1]-incli*qtime[mu+1];  
                   }  
                 }  
                 if(atime<=q1sine[mt].finishPoint && atime>=q1sine[mt].startPoint){  
                   if(!q1sine[mt].NeedFit)orbitalinfo->q1=q1sine[mt].A*sin(q1sine[mt].b*atime+q1sine[mt].c);else{  
                     incli = (q1[mu+1]-q1[mu])/(qtime[mu+1]-qtime[mu]);  
                     orbitalinfo->q1 =  incli*atime+q1[mu+1]-incli*qtime[mu+1];  
                   }  
                 }  
                 if(atime<=q2sine[mt].finishPoint && atime>=q2sine[mt].startPoint){  
                   if(!q2sine[mt].NeedFit)orbitalinfo->q2=q0sine[mt].A*sin(q2sine[mt].b*atime+q2sine[mt].c);else{  
                     incli = (q2[mu+1]-q2[mu])/(qtime[mu+1]-qtime[mu]);  
                     orbitalinfo->q2 =  incli*atime+q2[mu+1]-incli*qtime[mu+1];  
                   }  
                 }  
                 if(atime<=q3sine[mt].finishPoint && atime>=q3sine[mt].startPoint){  
                   if(!q3sine[mt].NeedFit)orbitalinfo->q3=q0sine[mt].A*sin(q3sine[mt].b*atime+q3sine[mt].c);else{  
                     incli = (q3[mu+1]-q3[mu])/(qtime[mu+1]-qtime[mu]);  
                     orbitalinfo->q3 =  incli*atime+q3[mu+1]-incli*qtime[mu+1];  
                   }  
                 }  
                 if(atime<=Yawsine[mt].finishPoint && atime>=Yawsine[mt].startPoint){  
                   if(!Yawsine[mt].NeedFit)orbitalinfo->phi=Yawsine[mt].A*sin(Yawsine[mt].b*atime+Yawsine[mt].c);else{  
                     incli = (qYaw[mu+1]-qYaw[mu])/(qtime[mu+1]-qtime[mu]);  
                     orbitalinfo->phi =  incli*atime+qYaw[mu+1]-incli*qtime[mu+1];  
                   }  
                 }  
               }  
             }  
             //q0testing->Fill(atime,orbitalinfo->q0,100);  
             //q1testing->Fill(atime,orbitalinfo->q1,100);  
             //Pitchtesting->Fill(atime,orbitalinfo->etha);  
             //q2testing->Fill(atime,orbitalinfo->q2);  
             //q3testing->Fill(atime,orbitalinfo->q3);  
             break;  
           }  
         }  
1526        }        }
1527          if ( debug ) printf(" grfuffi5  \n");
1528        //        //
1529        // ops no inclination information        // ops no inclination information
1530        //        //
1531          
1532        if ( orbitalinfo->q0< -999 || orbitalinfo->q1 < -999 || orbitalinfo->q2 < -999 || orbitalinfo->q3 < -999 || orbitalinfo->q0 != orbitalinfo->q0 || orbitalinfo->q1 != orbitalinfo->q1 || orbitalinfo->q2 != orbitalinfo->q2 || orbitalinfo->q3 != orbitalinfo->q3 ){        if ( orbitalinfo->q0< -999 || orbitalinfo->q1 < -999 || orbitalinfo->q2 < -999 || orbitalinfo->q3 < -999 || orbitalinfo->q0 != orbitalinfo->q0 || orbitalinfo->q1 != orbitalinfo->q1 || orbitalinfo->q2 != orbitalinfo->q2 || orbitalinfo->q3 != orbitalinfo->q3 ){
1533            if ( debug ) cout << "ops no iclination information" << endl;
1534          orbitalinfo->mode = 10;          orbitalinfo->mode = 10;
1535          orbitalinfo->q0 = -1000.;          orbitalinfo->q0 = -1000.;
1536          orbitalinfo->q1 = -1000.;          orbitalinfo->q1 = -1000.;
# Line 1101  int OrbitalInfoCore(UInt_t run, TFile *f Line 1539  int OrbitalInfoCore(UInt_t run, TFile *f
1539          orbitalinfo->etha = -1000.;          orbitalinfo->etha = -1000.;
1540          orbitalinfo->phi = -1000.;          orbitalinfo->phi = -1000.;
1541          orbitalinfo->theta = -1000.;          orbitalinfo->theta = -1000.;
1542        };          orbitalinfo->TimeGap = -1000.;
1543            //orbitalinfo->qkind = -1000;
1544            
1545            //      if ( debug ){
1546            //        Int_t lopu;
1547            //         cin >> lopu;
1548            //      }
1549            if ( debug ) printf(" grfuffi6 \n");
1550          }
1551        //        //
1552          if ( debug ) printf(" filling \n");
1553        // #########################################################################################################################          // #########################################################################################################################  
1554        //        //
1555        // fill orbital positions        // fill orbital positions
# Line 1113  int OrbitalInfoCore(UInt_t run, TFile *f Line 1560  int OrbitalInfoCore(UInt_t run, TFile *f
1560        lon = (coo.m_Lon > M_PI) ? rad2deg(coo.m_Lon - 2*M_PI) : rad2deg(coo.m_Lon);        lon = (coo.m_Lon > M_PI) ? rad2deg(coo.m_Lon - 2*M_PI) : rad2deg(coo.m_Lon);
1561        lat = rad2deg(coo.m_Lat);        lat = rad2deg(coo.m_Lat);
1562        alt = coo.m_Alt;        alt = coo.m_Alt;
1563        //  
1564          cOrbit orbits2(*gltle->GetTle());
1565          orbits2.getPosition((double) (atime - gltle->GetFromTime())/60., &eCi);
1566          //      Float_t x=eCi.getPos().m_x;
1567          //      Float_t y=eCi.getPos().m_y;
1568          //      Float_t z=eCi.getPos().m_z;
1569          
1570          TVector3 V(eCi.getVel().m_x,eCi.getVel().m_y,eCi.getVel().m_z);
1571          TVector3 Pos(eCi.getPos().m_x,eCi.getPos().m_y,eCi.getPos().m_z);
1572          
1573          Float_t dlon=Pos.Phi()*TMath::RadToDeg()-lon;
1574          
1575          Pos.RotateZ(-dlon*TMath::DegToRad());
1576          V.RotateZ(-dlon*TMath::DegToRad());
1577          Float_t diro;
1578          if(V.Z()>0) diro=1; else diro=-1;
1579          
1580          // 10REDNEW
1581          Int_t errq=0;
1582          Int_t azim=0;
1583          Int_t qual=0;
1584          Int_t MU=0;
1585          for(UInt_t mu = 0;mu<RTtime2.size()-1;mu++){
1586            if(atime<RTstart[mu+1] && atime>=RTstart[mu]){
1587              errq=RTerrq[mu];
1588              azim=RTazim[mu];
1589              qual=RTqual[mu];
1590              MU=mu;
1591              break;
1592            }
1593          }
1594          orbitalinfo->errq = errq;
1595          orbitalinfo->azim = azim;
1596          orbitalinfo->rtqual=qual;
1597          orbitalinfo->qkind = 0;
1598          
1599          if ( debug ) printf(" coord done \n");
1600        if( lon<180 && lon>-180 && lat<90 && lat>-90 && alt>0 ){          if( lon<180 && lon>-180 && lat<90 && lat>-90 && alt>0 ){  
1601          //                //      
1602          orbitalinfo->lon = lon;          orbitalinfo->lon = lon;
1603          orbitalinfo->lat = lat;          orbitalinfo->lat = lat;
1604          orbitalinfo->alt = alt ;          orbitalinfo->alt = alt;
1605            orbitalinfo->V = V;
1606    
1607            //      GMtype_CoordGeodetic  location;
1608            location.lambda = lon;
1609            location.phi = lat;
1610            location.HeightAboveEllipsoid = alt;
1611    
1612            GM_GeodeticToSpherical(Ellip, location, &CoordSpherical);
1613            GM_SphericalToCartesian(CoordSpherical,  &CoordCartesian);
1614            GM_EarthCartToDipoleCartCD(Pole, CoordCartesian, &DipoleCartesian);
1615            GM_CartesianToSpherical(DipoleCartesian, &DipoleSpherical);
1616            orbitalinfo->londip = DipoleSpherical.lambda;
1617            orbitalinfo->latdip = DipoleSpherical.phig;
1618    
1619            if(debug)cout<<"geodetic:\t"<<lon<<"\t"<<lat<<"\tgeomagnetic:\t"<<orbitalinfo->londip<<"\t"<<orbitalinfo->latdip<<endl;
1620    
1621          //          //
1622          // compute mag field components and L shell.          // compute mag field components and L shell.
1623          //          //
1624            if ( debug ) printf(" call igrf feldg \n");
1625          feldg_(&lat, &lon, &alt, &bnorth, &beast, &bdown, &babs);          feldg_(&lat, &lon, &alt, &bnorth, &beast, &bdown, &babs);
1626            if ( debug ) printf(" call igrf shellg \n");
1627          shellg_(&lat, &lon, &alt, &dimo, &xl, &icode, &bab1);          shellg_(&lat, &lon, &alt, &dimo, &xl, &icode, &bab1);
1628            if ( debug ) printf(" call igrf findb \n");
1629          findb0_(&stps, &bdel, &value, &bequ, &rr0);          findb0_(&stps, &bdel, &value, &bequ, &rr0);
1630          //          //
1631            if ( debug ) printf(" done igrf \n");
1632          orbitalinfo->Bnorth = bnorth;          orbitalinfo->Bnorth = bnorth;
1633          orbitalinfo->Beast = beast;          orbitalinfo->Beast = beast;
1634          orbitalinfo->Bdown = bdown;          orbitalinfo->Bdown = bdown;
1635          orbitalinfo->Babs = babs;          orbitalinfo->Babs = babs;
1636            orbitalinfo->M = dimo;
1637          orbitalinfo->BB0 = babs/bequ;          orbitalinfo->BB0 = babs/bequ;
1638          orbitalinfo->L = xl;                orbitalinfo->L = xl;      
1639          // Set Stormer vertical cutoff using L shell.          // Set Stormer vertical cutoff using L shell.
1640          orbitalinfo->cutoffsvl = 14.9/(xl*xl);          orbitalinfo->cutoffsvl = 14.295 / (xl*xl); //
1641            if(debug)cout << "L = " << xl << "\tM = " << dimo << "\tvertical cutoff:  "<< orbitalinfo->cutoffsvl << endl;
1642    
1643            
1644    //           ---------- Forwarded message ----------
1645    //           Date: Wed, 09 May 2012 12:16:47 +0200
1646    //           From: Alessandro Bruno <alessandro.bruno@ba.infn.it>
1647    //           To: Mirko Boezio <mirko.boezio@ts.infn.it>
1648    //           Cc: Francesco S. Cafagna <Francesco.Cafagna@ba.infn.it>
1649    //           Subject: Störmer vertical cutoff
1650    
1651    //           Ciao Mirko,
1652    //           volevo segnalarti che il valore dello Störmer vertical cutoff nel Level2 è
1653    //           sovrastimato di circa il 4%.
1654    //           Dopo un'approfondita analisi con l'IGRF-05 abbiamo ricavano un valore pari
1655    //           a: 14.295 / L^2 anzichè 14.9 / L^2, valore obsoleto in quanto riferito agli
1656    //           anni '50.
1657    //        
1658            //14.9/(xl*xl);
1659            orbitalinfo->igrf_icode = icode;
1660          //          //
1661        };              }      
1662        //        //
1663        if ( debug ) printf(" pitch angle \n");        if ( debug ) printf(" pitch angle \n");
1664        //        //
1665        // pitch angles        // pitch angles
1666        //        //
1667        if ( orbitalinfo->mode != 10 && orbitalinfo->mode != 5 && orbitalinfo->mode !=7 && orbitalinfo->mode != 9 ){        if( orbitalinfo->TimeGap>0){
1668          //          //
1669          Float_t Bx = -orbitalinfo->Bdown;                       //don't need for PamExp ExpOnly for all geography areas          if ( debug ) printf(" timegap %f \n",orbitalinfo->TimeGap);
1670          Float_t By = orbitalinfo->Beast;                        //don't need for PamExp ExpOnly for all geography areas          Float_t Bx = -orbitalinfo->Bdown;
1671          Float_t Bz = orbitalinfo->Bnorth;                       //don't need for PamExp ExpOnly for all geography areas          Float_t By = orbitalinfo->Beast;
1672          //          Float_t Bz = orbitalinfo->Bnorth;
1673          TMatrixD Fij = PO->ECItoGreenwich(PO->QuatoECI(orbitalinfo->q0,orbitalinfo->q1,orbitalinfo->q2,orbitalinfo->q3),orbitalinfo->absTime);  
1674          TMatrixD Dij = PO->GreenwichtoGEO(orbitalinfo->lat,orbitalinfo->lon,Fij);  //      TMatrixD Qiji(3,3);
1675            TMatrixD Qij = PO->QuatoECI(orbitalinfo->q0,orbitalinfo->q1,orbitalinfo->q2,orbitalinfo->q3);
1676            TMatrixD Dij = PO->ECItoGEO(Qij,orbitalinfo->absTime,orbitalinfo->lat,orbitalinfo->lon);
1677    
1678    //10REDNEW
1679            // If initial orientation data have reason to be inaccurate
1680           Float_t tg = 0.00;
1681           Float_t tmptg;
1682           if(MU!=0){
1683    //      if(orbitalinfo->TimeGap>0 && errq==0 && azim==0){               // 10RED CHECK  (comparison between three metod of recovering orientation)
1684           if((atime>=RTstart[MU] && atime<RTstart[MU+1] && RTbank1[MU]==0 && RTbank2[MU]==0 && TMath::Abs(orbitalinfo->etha)>0.1) || ((RTbank1[MU]!=0 || RTbank2[MU]!=0) && atime>=RTstart[MU] && atime<RTstart[MU+1] && azim==0 && (errq!=0 || orbitalinfo->TimeGap>10.0 || ((modf(orbitalinfo->TimeGap,&tmptg)*1000>10 || modf(orbitalinfo->TimeGap,&tmptg)*1000==0.0) && orbitalinfo->TimeGap>2.0)))){
1685            //found in Rotation Table this data for this time interval
1686            if(atime<RTtime1[0])
1687              orbitalinfo->azim = 5;        //means that RotationTable no started yet
1688           else{
1689                    // search for angle betwean velosity and direction to north in tangential to Earth surfase plane in satellite position
1690                  Double_t bank=RTstart[MU];
1691                  Double_t tlat=orbitalinfo->lat;
1692    
1693                  tg=modf(orbitalinfo->TimeGap,&tg)*1000;
1694    
1695                  if(atime>=RTpluto1[MU] && atime<=RTpluto2[MU]){
1696                    Double_t kar=(RTbank2[MU]-RTbank1[MU])/(RTtime2[MU]-RTtime1[MU]);
1697                    Double_t bak=RTbank1[MU]-kar*RTtime1[MU];
1698                    bank=kar*atime+bak;
1699                  }
1700                  if(atime>=RTstart[MU] && atime<RTpluto1[MU]){
1701                     Double_t s_dBdt2=(RTbpluto1[MU]-RTbank1[MU])/(Int_t)(RTpluto1[MU]-RTstart[MU]);
1702                     Double_t s_t2=((Double_t)RTpluto1[MU]+(Double_t)RTstart[MU])/2. - RTstart[MU];
1703                     Double_t s_t1=RTstart[MU]-RTstart[MU];
1704                     Double_t s_k=s_dBdt2/(s_t2-s_t1);
1705                     Double_t s_b=-s_k*s_t1;
1706                     Double_t s_t3=RTpluto1[MU]-RTstart[MU];
1707                     Double_t s_b3=RTbpluto1[MU];
1708                     Double_t s_c=s_b3-0.5*s_k*s_t3*s_t3 -s_b*s_t3;
1709                     bank=0.5*s_k*(atime-RTstart[MU])*(atime-RTstart[MU]) + s_b*(atime-RTstart[MU]) + s_c;
1710                 }
1711                  if(atime>RTpluto2[MU] && atime<=RTstart[MU+1]){
1712                     Double_t s_dBdt2=(RTbpluto2[MU] - RTbank2[MU])/(Int_t)(RTpluto2[MU]-RTstart[MU+1]);
1713                     Double_t s_t2=((Double_t)RTpluto2[MU]+(Double_t)RTstart[MU+1])/2. - RTstart[MU];
1714                     Double_t s_t1=RTstart[MU+1]-RTstart[MU];
1715                     Double_t s_k=s_dBdt2/(s_t2-s_t1);
1716                     Double_t s_b=-s_k*s_t1;
1717                     Double_t s_t3=RTpluto2[MU]-RTstart[MU];
1718                     Double_t s_b3=RTbpluto2[MU];
1719                     Double_t s_c=s_b3-0.5*s_k*s_t3*s_t3 -s_b*s_t3;
1720                   bank=0.5*s_k*(atime-RTstart[MU])*(atime-RTstart[MU]) + s_b*(atime-RTstart[MU]) + s_c;
1721                 }
1722                  if(TMath::Abs(orbitalinfo->etha-bank)>0.1){
1723                    orbitalinfo->etha=bank;
1724                    Double_t spitch = 0.00001;  // temprary not zero to avoid problem with tranzition from Euler angles to orientation matrix
1725    
1726                    //Estimations of pitch angle of satellite
1727                    if(TMath::Abs(bank)>0.7){
1728                       Float_t spitch1=TMath::DegToRad()*0.7*diro;//RTdir1[MU];
1729                       Float_t spitch2=TMath::DegToRad()*0.7*diro;//RTdir2[MU];
1730                       Float_t kva=(spitch2-spitch1)/(RTtime2[MU]-RTtime1[MU]);
1731                       Float_t bva=spitch1-kva*RTtime1[MU];
1732                       spitch=kva*atime+bva;
1733                    }
1734    
1735                    //Calculate Yaw angle accordingly with fit, see picture FitYaw.jpg
1736                    Double_t yaw=0.00001;  // temprary not zero to avoid problem with tranzition from Euler angles to orientation matrix
1737                    if(TMath::Abs(tlat)<70)
1738                      yaw = -3.7e-8*tlat*tlat*tlat*tlat + 1.4e-7*tlat*tlat*tlat - 0.0005*tlat*tlat - 0.00025*tlat + 3.6;
1739                    yaw = diro*yaw; //because should be different sign for ascending and descending orbits!
1740                    orbitalinfo->phi=yaw;
1741    
1742                    if(TMath::Abs(bank)>0.5 && TMath::Abs(yaw-orbitalinfo->phi)<3.0) yaw=orbitalinfo->phi;
1743    
1744    //              Qiji = PO->EulertoEci(eCi.getPos().m_x,eCi.getPos().m_y,eCi.getPos().m_z,eCi.getVel().m_x,eCi.getVel().m_y,eCi.getVel().m_z,bank,yaw,spitch);           // 10RED CHECK
1745                    Qij = PO->EulertoEci(eCi.getPos().m_x,eCi.getPos().m_y,eCi.getPos().m_z,eCi.getVel().m_x,eCi.getVel().m_y,eCi.getVel().m_z,bank,yaw,spitch);            // STANDARD
1746                    orbitalinfo->qkind = 1;
1747                 }
1748    
1749              //Qij = PO->GEOtoECI(Dij,orbitalinfo->absTime,orbitalinfo->lat,orbitalinfo->lon); // to convert from Dij to Qij
1750    
1751            } // end of if(atime<RTtime1[0]
1752            } // end of (((orbitalinfo->TimeGap>60.0 && TMath...
1753           } // end of MU~=0
1754    
1755            TMatrixD qij = PO->ColPermutation(Qij);
1756            TMatrixD Fij = PO->ECItoGreenwich(Qij,orbitalinfo->absTime);
1757            TMatrixD Gij = PO->ColPermutation(Fij);
1758            Dij = PO->ECItoGEO(Qij,orbitalinfo->absTime,orbitalinfo->lat,orbitalinfo->lon);
1759          TMatrixD Iij = PO->ColPermutation(Dij);          TMatrixD Iij = PO->ColPermutation(Dij);
1760          //          TVector3 SP = PO->GetSunPosition(orbitalinfo->absTime);
1761            // go to Pamela reference frame from Resurs reference frame
1762            Float_t tmpy = SP.Y();
1763            SP.SetY(SP.Z());
1764            SP.SetZ(-tmpy);
1765            TVector3 SunZenith;
1766            SunZenith.SetMagThetaPhi(1,23.439281*TMath::DegToRad(),TMath::Pi()/2.);
1767            TVector3 SunMag = -SP;
1768            SunMag.Rotate(-45*TMath::DegToRad(),SunZenith);
1769            tmpy=SunMag.Y();
1770            SunMag.SetY(SunMag.Z());
1771            SunMag.SetZ(-tmpy);
1772    
1773          orbitalinfo->Iij.ResizeTo(Iij);          orbitalinfo->Iij.ResizeTo(Iij);
1774          orbitalinfo->Iij = Iij;          orbitalinfo->Iij = Iij;
1775          //          //
1776          A1 = Iij(0,2);          //      A1 = Iij(0,2);
1777          A2 = Iij(1,2);          //      A2 = Iij(1,2);
1778          A3 = Iij(2,2);          //      A3 = Iij(2,2);
1779          //                //
1780          //      orbitalinfo->pamzenitangle = (Float_t)PO->GetPitchAngle(1,0,0,A1,A2,A3);                        // Angle between zenit and Pamela's main axiz          //      orbitalinfo->pamzenitangle = (Float_t)PO->GetPitchAngle(1,0,0,A1,A2,A3);                        // Angle between zenit and Pamela's main axiz
1781          //      orbitalinfo->pamBangle = (Float_t)PO->GetPitchAngle(A1,A2,A3,Bx,By,Bz);                 // Angle between Pamela's main axiz and B          //      orbitalinfo->pamBangle = (Float_t)PO->GetPitchAngle(A1,A2,A3,Bx,By,Bz);                 // Angle between Pamela's main axiz and B
1782          //          //
1783          if ( !standalone && tof->ntrk() > 0 ){          if ( debug ) printf(" matrixes done  \n");
1784            if ( !standalone ){
1785              if ( debug ) printf(" !standalone \n");
1786            //            //
1787              // Standard tracking algorithm
1788              //
1789            Int_t nn = 0;            Int_t nn = 0;
1790              if ( verbose ) printf(" standard tracking \n");
1791            for(Int_t nt=0; nt < tof->ntrk(); nt++){              for(Int_t nt=0; nt < tof->ntrk(); nt++){  
1792              //              //
1793              ToFTrkVar *ptt = tof->GetToFTrkVar(nt);              ToFTrkVar *ptt = tof->GetToFTrkVar(nt);
1794                if (debug) cout<<"tof->ntrk() = "<<tof->ntrk()<<"\tptt->trkseqno = "<<ptt->trkseqno<<"\ttrke->ntrk() = "<<trke->ntrk()<<endl;
1795              Double_t E11x = ptt->xtr_tof[0]; // tr->x[0];              Double_t E11x = ptt->xtr_tof[0]; // tr->x[0];
1796              Double_t E11y = ptt->ytr_tof[0]; //tr->y[0];              Double_t E11y = ptt->ytr_tof[0]; //tr->y[0];
1797              Double_t E11z = zin[0];              Double_t E11z = zin[0];
# Line 1174  int OrbitalInfoCore(UInt_t run, TFile *f Line 1799  int OrbitalInfoCore(UInt_t run, TFile *f
1799              Double_t E22y = ptt->ytr_tof[3];//tr->y[3];              Double_t E22y = ptt->ytr_tof[3];//tr->y[3];
1800              Double_t E22z = zin[3];              Double_t E22z = zin[3];
1801              if ( (E11x < 100. && E11y < 100. && E22x < 100. && E22y < 100.) || ptt->trkseqno != -1  ){              if ( (E11x < 100. && E11y < 100. && E22x < 100. && E22y < 100.) || ptt->trkseqno != -1  ){
1802                  TrkTrack *mytrack = trke->GetStoredTrack(ptt->trkseqno);
1803                  Float_t rig=1/mytrack->GetDeflection();
1804                Double_t norm = sqrt(pow(E22x-E11x,2)+pow(E22y-E11y,2)+pow(E22z-E11z,2));                Double_t norm = sqrt(pow(E22x-E11x,2)+pow(E22y-E11y,2)+pow(E22z-E11z,2));
1805                //              Double_t MyAzim = TMath::RadToDeg()*atan(TMath::Abs(E22y-E11y)/TMath::Abs(E22x-E11x));                //
               //              if(E22x-E11x>=0 && E22y-E11y <0) MyAzim =  360. - MyAzim;  
               //              if(E22x-E11x>=0 && E22y-E11y >=0) MyAzim = MyAzim;  
               //              if(E22x-E11x<0 && E22y-E11y >0) MyAzim = 180. - MyAzim;  
               //              if(E22x-E11x<0 && E22y-E11y <0) MyAzim = 180. + MyAzim;  
1806                Px = (E22x-E11x)/norm;                Px = (E22x-E11x)/norm;
1807                Py = (E22y-E11y)/norm;                Py = (E22y-E11y)/norm;
1808                Pz = (E22z-E11z)/norm;                Pz = (E22z-E11z)/norm;
# Line 1190  int OrbitalInfoCore(UInt_t run, TFile *f Line 1813  int OrbitalInfoCore(UInt_t run, TFile *f
1813                t_orb->Eij.ResizeTo(Eij);                t_orb->Eij.ResizeTo(Eij);
1814                t_orb->Eij = Eij;                t_orb->Eij = Eij;
1815                //                //
1816                TMatrixD Sij = PO->PamelatoGEO(Fij,Px,Py,Pz);                TMatrixD Sij = PO->PamelatoGEO(Gij,Px,Py,Pz);
1817                t_orb->Sij.ResizeTo(Sij);                t_orb->Sij.ResizeTo(Sij);
1818                t_orb->Sij = Sij;                t_orb->Sij = Sij;
1819                //                            //            
1820                t_orb->pitch = (Float_t)PO->GetPitchAngle(Eij(0,0),Eij(1,0),Eij(2,0),Bx,By,Bz);                t_orb->pitch = (Float_t)PO->GetPitchAngle(Eij(0,0),Eij(1,0),Eij(2,0),Bx,By,Bz);
1821                //                //
1822                  // SunPosition in instrumental reference frame
1823                  TMatrixD Kij = PO->PamelatoGEO(qij,Px,Py,Pz);
1824                  TMatrixD Lij = PO->PamelatoGEO(qij,0,0,1);
1825                  t_orb->sunangle=(Float_t)PO->GetPitchAngle(Kij(0,0),Kij(1,0),Kij(2,0),-SP.X(),-SP.Y(),-SP.Z());
1826                  t_orb->sunmagangle=(Float_t)PO->GetPitchAngle(Kij(0,0),Kij(1,0),Kij(2,0),SunMag.X(),SunMag.Y(),SunMag.Z());
1827                //                //
               Double_t omega = PO->GetPitchAngle(Eij(0,0),Eij(1,0),Eij(2,0),cos(orbitalinfo->lon+TMath::Pi()/2)-sin(orbitalinfo->lon+TMath::Pi()/2),cos(orbitalinfo->lon+TMath::Pi()/2)+sin(orbitalinfo->lon+TMath::Pi()/2),1);  
1828                //                //
1829                t_orb->cutoff = 59.3/(pow(orbitalinfo->L,2)*pow((1+sqrt(1-pow(orbitalinfo->L,-3/2)*cos(omega))),2));                Double_t omega = PO->GetPitchAngle(-Eij(0,0),-Eij(1,0),-Eij(2,0),1,0,0) * TMath::DegToRad();
1830                  TVector3 Bxy(0,By,Bz);
1831                  TVector3 Exy(0,-Eij(1,0),-Eij(2,0));
1832                  Double_t dzeta=Bxy.Angle(Exy);
1833                  if (-Eij(1,0) < 0) dzeta=2.0*TMath::Pi() - dzeta;
1834                  
1835                  if(debug) cout << "omega = "<<omega*TMath::RadToDeg()<<"\tdzeta = "<<dzeta*TMath::RadToDeg()<<endl;
1836    
1837                  // Formula from D.F. Smart *, M.A. Shea [2005]; A review of geomagnetic cutoff rigidities for earth-orbiting spacecraft
1838                  if(rig>=0) t_orb->cutoff = 59.3/(pow(orbitalinfo->L,2)*pow(1+sqrt(1-sin(omega)*sin(dzeta)*pow(cos(orbitalinfo->lat*TMath::DegToRad()),3)),2));
1839                  else       t_orb->cutoff = 59.3/(pow(orbitalinfo->L,2)*pow(1+sqrt(1-sin(omega)*sin(TMath::Pi()+dzeta)*pow(cos(orbitalinfo->lat*TMath::DegToRad()),3)),2));
1840                  if (debug) cout << "R = " << rig << "\tcutoff = " << t_orb->cutoff << endl;
1841    
1842                //                //
1843                if ( t_orb->pitch != t_orb->pitch ) t_orb->pitch = -1000.;                if ( t_orb->pitch != t_orb->pitch ) t_orb->pitch = -1000.;
1844                if ( t_orb->cutoff != t_orb->cutoff ) t_orb->cutoff = -1000.;                if ( t_orb->cutoff != t_orb->cutoff ) t_orb->cutoff = -1000.;
1845                  if ( t_orb->sunangle != t_orb->sunangle ) t_orb->sunangle = -1000.;
1846                  if ( t_orb->sunmagangle != t_orb->sunmagangle ) t_orb->sunmagangle = -1000.;
1847                //                //
1848                if ( debug ) printf(" orbitalinfo->cutoffsvl %f vitaly %f \n",orbitalinfo->cutoffsvl,t_orb->cutoff);                if ( debug ) printf(" orbitalinfo->cutoffsvl %f vitaly %f \n",orbitalinfo->cutoffsvl,t_orb->cutoff);
1849                //                //
# Line 1211  int OrbitalInfoCore(UInt_t run, TFile *f Line 1852  int OrbitalInfoCore(UInt_t run, TFile *f
1852                //                //
1853                t_orb->Clear();                t_orb->Clear();
1854                //                //
1855              };              }
1856              //              //
1857            };            } // end standard tracking algorithm
1858    
1859              //
1860              // Code for extended tracking algorithm:
1861              //
1862              if ( hasNucleiTrk ){
1863                Int_t ttentry = 0;
1864                if ( verbose ) printf(" hasNucleiTrk \n");
1865                for(Int_t nt=0; nt < tcNucleiTof->GetEntries() ; nt++){  
1866                  //
1867                  if ( verbose ) printf(" got1\n");
1868                  ToFTrkVar *ptt = (ToFTrkVar*)(tcNucleiTof->At(nt));
1869                  if (verbose) cout<<" tcNucleiTof->GetEntries() = "<<tcNucleiTof->GetEntries()<<"\tptt->trkseqno = "<<ptt->trkseqno<<endl;
1870                  Double_t E11x = ptt->xtr_tof[0]; // tr->x[0];
1871                  Double_t E11y = ptt->ytr_tof[0]; //tr->y[0];
1872                  Double_t E11z = zin[0];
1873                  Double_t E22x = ptt->xtr_tof[3];//tr->x[3];
1874                  Double_t E22y = ptt->ytr_tof[3];//tr->y[3];
1875                  Double_t E22z = zin[3];
1876                  if ( (E11x < 100. && E11y < 100. && E22x < 100. && E22y < 100.) || ptt->trkseqno != -1  ){
1877                    TrkTrack *mytrack = (TrkTrack*)(tcNucleiTrk->At(ptt->trkseqno));
1878                    if ( verbose ) printf(" got tcNucleiTrk \n");
1879                    Float_t rig=1/mytrack->GetDeflection();
1880                    Double_t norm = sqrt(pow(E22x-E11x,2)+pow(E22y-E11y,2)+pow(E22z-E11z,2));
1881                    //
1882                    Px = (E22x-E11x)/norm;
1883                    Py = (E22y-E11y)/norm;
1884                    Pz = (E22z-E11z)/norm;
1885                    //
1886                    t_orb->trkseqno = ptt->trkseqno;
1887                    //
1888                    TMatrixD Eij = PO->PamelatoGEO(Iij,Px,Py,Pz);
1889                    t_orb->Eij.ResizeTo(Eij);      
1890                    t_orb->Eij = Eij;      
1891                    //
1892                    TMatrixD Sij = PO->PamelatoGEO(Gij,Px,Py,Pz);
1893                    t_orb->Sij.ResizeTo(Sij);
1894                    t_orb->Sij = Sij;
1895                    //          
1896                    t_orb->pitch = (Float_t)PO->GetPitchAngle(Eij(0,0),Eij(1,0),Eij(2,0),Bx,By,Bz);
1897                    //
1898                    // SunPosition in instrumental reference frame
1899                    TMatrixD Kij = PO->PamelatoGEO(qij,Px,Py,Pz);
1900                    TMatrixD Lij = PO->PamelatoGEO(qij,0,0,1);
1901                    t_orb->sunangle=(Float_t)PO->GetPitchAngle(Kij(0,0),Kij(1,0),Kij(2,0),-SP.X(),-SP.Y(),-SP.Z());
1902                    t_orb->sunmagangle=(Float_t)PO->GetPitchAngle(Kij(0,0),Kij(1,0),Kij(2,0),SunMag.X(),SunMag.Y(),SunMag.Z());
1903                    //
1904                    //
1905                    Double_t omega = PO->GetPitchAngle(-Eij(0,0),-Eij(1,0),-Eij(2,0),1,0,0) * TMath::DegToRad();
1906                    TVector3 Bxy(0,By,Bz);
1907                    TVector3 Exy(0,-Eij(1,0),-Eij(2,0));
1908                    Double_t dzeta=Bxy.Angle(Exy);
1909                    if (-Eij(1,0) < 0) dzeta=2.0*TMath::Pi() - dzeta;
1910                    
1911                    if(debug) cout << "omega = "<<omega*TMath::RadToDeg()<<"\tdzeta = "<<dzeta*TMath::RadToDeg()<<endl;
1912                    
1913                    // Formula from D.F. Smart *, M.A. Shea [2005]; A review of geomagnetic cutoff rigidities for earth-orbiting spacecraft
1914                    if(rig>=0) t_orb->cutoff = 59.3/(pow(orbitalinfo->L,2)*pow(1+sqrt(1-sin(omega)*sin(dzeta)*pow(cos(orbitalinfo->lat*TMath::DegToRad()),3)),2));
1915                    else       t_orb->cutoff = 59.3/(pow(orbitalinfo->L,2)*pow(1+sqrt(1-sin(omega)*sin(TMath::Pi()+dzeta)*pow(cos(orbitalinfo->lat*TMath::DegToRad()),3)),2));
1916                    if (debug) cout << "R = " << rig << "\tcutoff = " << t_orb->cutoff << endl;
1917                    
1918                    //
1919                    if ( t_orb->pitch != t_orb->pitch ) t_orb->pitch = -1000.;
1920                    if ( t_orb->cutoff != t_orb->cutoff ) t_orb->cutoff = -1000.;
1921                    if ( t_orb->sunangle != t_orb->sunangle ) t_orb->sunangle = -1000.;
1922                    if ( t_orb->sunmagangle != t_orb->sunmagangle ) t_orb->sunmagangle = -1000.;
1923                    //
1924                    if ( debug ) printf(" orbitalinfo->cutoffsvl %f vitaly %f \n",orbitalinfo->cutoffsvl,t_orb->cutoff);
1925                    //
1926                    TClonesArray &tt1 = *torbNucleiTrk;
1927                    new(tt1[ttentry]) OrbitalInfoTrkVar(*t_orb);
1928                    ttentry++;
1929                    //
1930                    t_orb->Clear();
1931                    //
1932                  }
1933                  //
1934                }
1935              } // end standard tracking algorithm: nuclei
1936              if ( hasExtNucleiTrk ){
1937                Int_t ttentry = 0;
1938                if ( verbose ) printf(" hasExtNucleiTrk \n");
1939                for(Int_t nt=0; nt < tcExtNucleiTof->GetEntries() ; nt++){  
1940                  //
1941                  if ( verbose ) printf(" got2\n");
1942                  ToFTrkVar *ptt = (ToFTrkVar*)(tcExtNucleiTof->At(nt));
1943                  if (verbose) cout<<" tcExtNucleiTof->GetEntries() = "<<tcExtNucleiTof->GetEntries()<<"\tptt->trkseqno = "<<ptt->trkseqno<<endl;
1944                  Double_t E11x = ptt->xtr_tof[0]; // tr->x[0];
1945                  Double_t E11y = ptt->ytr_tof[0]; //tr->y[0];
1946                  Double_t E11z = zin[0];
1947                  Double_t E22x = ptt->xtr_tof[3];//tr->x[3];
1948                  Double_t E22y = ptt->ytr_tof[3];//tr->y[3];
1949                  Double_t E22z = zin[3];
1950                  if ( (E11x < 100. && E11y < 100. && E22x < 100. && E22y < 100.) || ptt->trkseqno != -1  ){
1951                    ExtTrack *mytrack = (ExtTrack*)(tcExtNucleiTrk->At(ptt->trkseqno));
1952                    if ( verbose ) printf(" got tcExtNucleiTrk \n");
1953                    Float_t rig=1/mytrack->GetDeflection();
1954                    Double_t norm = sqrt(pow(E22x-E11x,2)+pow(E22y-E11y,2)+pow(E22z-E11z,2));
1955                    //
1956                    Px = (E22x-E11x)/norm;
1957                    Py = (E22y-E11y)/norm;
1958                    Pz = (E22z-E11z)/norm;
1959                    //
1960                    t_orb->trkseqno = ptt->trkseqno;
1961                    //
1962                    TMatrixD Eij = PO->PamelatoGEO(Iij,Px,Py,Pz);
1963                    t_orb->Eij.ResizeTo(Eij);      
1964                    t_orb->Eij = Eij;      
1965                    //
1966                    TMatrixD Sij = PO->PamelatoGEO(Gij,Px,Py,Pz);
1967                    t_orb->Sij.ResizeTo(Sij);
1968                    t_orb->Sij = Sij;
1969                    //          
1970                    t_orb->pitch = (Float_t)PO->GetPitchAngle(Eij(0,0),Eij(1,0),Eij(2,0),Bx,By,Bz);
1971                    //
1972                    // SunPosition in instrumental reference frame
1973                    TMatrixD Kij = PO->PamelatoGEO(qij,Px,Py,Pz);
1974                    TMatrixD Lij = PO->PamelatoGEO(qij,0,0,1);
1975                    t_orb->sunangle=(Float_t)PO->GetPitchAngle(Kij(0,0),Kij(1,0),Kij(2,0),-SP.X(),-SP.Y(),-SP.Z());
1976                    t_orb->sunmagangle=(Float_t)PO->GetPitchAngle(Kij(0,0),Kij(1,0),Kij(2,0),SunMag.X(),SunMag.Y(),SunMag.Z());
1977                    //
1978                    //
1979                    Double_t omega = PO->GetPitchAngle(-Eij(0,0),-Eij(1,0),-Eij(2,0),1,0,0) * TMath::DegToRad();
1980                    TVector3 Bxy(0,By,Bz);
1981                    TVector3 Exy(0,-Eij(1,0),-Eij(2,0));
1982                    Double_t dzeta=Bxy.Angle(Exy);
1983                    if (-Eij(1,0) < 0) dzeta=2.0*TMath::Pi() - dzeta;
1984                    
1985                    if(debug) cout << "omega = "<<omega*TMath::RadToDeg()<<"\tdzeta = "<<dzeta*TMath::RadToDeg()<<endl;
1986                    
1987                    // Formula from D.F. Smart *, M.A. Shea [2005]; A review of geomagnetic cutoff rigidities for earth-orbiting spacecraft
1988                    if(rig>=0) t_orb->cutoff = 59.3/(pow(orbitalinfo->L,2)*pow(1+sqrt(1-sin(omega)*sin(dzeta)*pow(cos(orbitalinfo->lat*TMath::DegToRad()),3)),2));
1989                    else       t_orb->cutoff = 59.3/(pow(orbitalinfo->L,2)*pow(1+sqrt(1-sin(omega)*sin(TMath::Pi()+dzeta)*pow(cos(orbitalinfo->lat*TMath::DegToRad()),3)),2));
1990                    if (debug) cout << "R = " << rig << "\tcutoff = " << t_orb->cutoff << endl;
1991                    
1992                    //
1993                    if ( t_orb->pitch != t_orb->pitch ) t_orb->pitch = -1000.;
1994                    if ( t_orb->cutoff != t_orb->cutoff ) t_orb->cutoff = -1000.;
1995                    if ( t_orb->sunangle != t_orb->sunangle ) t_orb->sunangle = -1000.;
1996                    if ( t_orb->sunmagangle != t_orb->sunmagangle ) t_orb->sunmagangle = -1000.;
1997                    //
1998                    if ( debug ) printf(" orbitalinfo->cutoffsvl %f vitaly %f \n",orbitalinfo->cutoffsvl,t_orb->cutoff);
1999                    //
2000                    TClonesArray &tt2 = *torbExtNucleiTrk;
2001                    new(tt2[ttentry]) OrbitalInfoTrkVar(*t_orb);
2002                    ttentry++;
2003                    //
2004                    t_orb->Clear();
2005                    //
2006                  }
2007                  //
2008                }
2009              } // end standard tracking algorithm: nuclei extended
2010             if ( hasExtTrk ){
2011                Int_t ttentry = 0;
2012                if ( verbose ) printf(" hasExtTrk \n");
2013                for(Int_t nt=0; nt < tcExtTof->GetEntries() ; nt++){  
2014                  //
2015                  if ( verbose ) printf(" got3\n");
2016                  ToFTrkVar *ptt = (ToFTrkVar*)(tcExtTof->At(nt));
2017                  if (verbose) cout<<" tcExtTof->GetEntries() = "<<tcExtTof->GetEntries()<<"\tptt->trkseqno = "<<ptt->trkseqno<<endl;
2018                  Double_t E11x = ptt->xtr_tof[0]; // tr->x[0];
2019                  Double_t E11y = ptt->ytr_tof[0]; //tr->y[0];
2020                  Double_t E11z = zin[0];
2021                  Double_t E22x = ptt->xtr_tof[3];//tr->x[3];
2022                  Double_t E22y = ptt->ytr_tof[3];//tr->y[3];
2023                  Double_t E22z = zin[3];
2024                  if ( (E11x < 100. && E11y < 100. && E22x < 100. && E22y < 100.) || ptt->trkseqno != -1  ){
2025                    ExtTrack *mytrack = (ExtTrack*)(tcExtTrk->At(ptt->trkseqno));
2026                    if ( verbose ) printf(" got tcExtTrk \n");
2027                    Float_t rig=1/mytrack->GetDeflection();
2028                    Double_t norm = sqrt(pow(E22x-E11x,2)+pow(E22y-E11y,2)+pow(E22z-E11z,2));
2029                    //
2030                    Px = (E22x-E11x)/norm;
2031                    Py = (E22y-E11y)/norm;
2032                    Pz = (E22z-E11z)/norm;
2033                    //
2034                    t_orb->trkseqno = ptt->trkseqno;
2035                    //
2036                    TMatrixD Eij = PO->PamelatoGEO(Iij,Px,Py,Pz);
2037                    t_orb->Eij.ResizeTo(Eij);      
2038                    t_orb->Eij = Eij;      
2039                    //
2040                    TMatrixD Sij = PO->PamelatoGEO(Gij,Px,Py,Pz);
2041                    t_orb->Sij.ResizeTo(Sij);
2042                    t_orb->Sij = Sij;
2043                    //          
2044                    t_orb->pitch = (Float_t)PO->GetPitchAngle(Eij(0,0),Eij(1,0),Eij(2,0),Bx,By,Bz);
2045                    //
2046                    // SunPosition in instrumental reference frame
2047                    TMatrixD Kij = PO->PamelatoGEO(qij,Px,Py,Pz);
2048                    TMatrixD Lij = PO->PamelatoGEO(qij,0,0,1);
2049                    t_orb->sunangle=(Float_t)PO->GetPitchAngle(Kij(0,0),Kij(1,0),Kij(2,0),-SP.X(),-SP.Y(),-SP.Z());
2050                    t_orb->sunmagangle=(Float_t)PO->GetPitchAngle(Kij(0,0),Kij(1,0),Kij(2,0),SunMag.X(),SunMag.Y(),SunMag.Z());
2051                    //
2052                    //
2053                    Double_t omega = PO->GetPitchAngle(-Eij(0,0),-Eij(1,0),-Eij(2,0),1,0,0) * TMath::DegToRad();
2054                    TVector3 Bxy(0,By,Bz);
2055                    TVector3 Exy(0,-Eij(1,0),-Eij(2,0));
2056                    Double_t dzeta=Bxy.Angle(Exy);
2057                    if (-Eij(1,0) < 0) dzeta=2.0*TMath::Pi() - dzeta;
2058                    
2059                    if(debug) cout << "omega = "<<omega*TMath::RadToDeg()<<"\tdzeta = "<<dzeta*TMath::RadToDeg()<<endl;
2060                    
2061                    // Formula from D.F. Smart *, M.A. Shea [2005]; A review of geomagnetic cutoff rigidities for earth-orbiting spacecraft
2062                    if(rig>=0) t_orb->cutoff = 59.3/(pow(orbitalinfo->L,2)*pow(1+sqrt(1-sin(omega)*sin(dzeta)*pow(cos(orbitalinfo->lat*TMath::DegToRad()),3)),2));
2063                    else       t_orb->cutoff = 59.3/(pow(orbitalinfo->L,2)*pow(1+sqrt(1-sin(omega)*sin(TMath::Pi()+dzeta)*pow(cos(orbitalinfo->lat*TMath::DegToRad()),3)),2));
2064                    if (debug) cout << "R = " << rig << "\tcutoff = " << t_orb->cutoff << endl;
2065                    
2066                    //
2067                    if ( t_orb->pitch != t_orb->pitch ) t_orb->pitch = -1000.;
2068                    if ( t_orb->cutoff != t_orb->cutoff ) t_orb->cutoff = -1000.;
2069                    if ( t_orb->sunangle != t_orb->sunangle ) t_orb->sunangle = -1000.;
2070                    if ( t_orb->sunmagangle != t_orb->sunmagangle ) t_orb->sunmagangle = -1000.;
2071                    //
2072                    if ( debug ) printf(" orbitalinfo->cutoffsvl %f vitaly %f \n",orbitalinfo->cutoffsvl,t_orb->cutoff);
2073                    //
2074                    TClonesArray &tt3 = *torbExtTrk;
2075                    new(tt3[ttentry]) OrbitalInfoTrkVar(*t_orb);
2076                    ttentry++;
2077                    //
2078                    t_orb->Clear();
2079                    //
2080                  }
2081                  //
2082                }
2083              } // end standard tracking algorithm: extended
2084    
2085          } else {          } else {
2086            if ( debug ) printf(" mmm... mode %u standalone %i ntrk %i \n",orbitalinfo->mode,standalone,tof->ntrk());            if ( debug ) printf(" mmm... mode %u standalone  \n",orbitalinfo->mode);
2087          };          }
2088          //          //
2089        } else {        } else { // HERE IT MISS ALL CODE FOR EXTENDED TRACKING!
2090          if ( !standalone && tof->ntrk() > 0 ){          if ( !standalone ){
2091            //            //
2092              if ( verbose ) printf(" no orb info for tracks \n");
2093            Int_t nn = 0;            Int_t nn = 0;
2094            for(Int_t nt=0; nt < tof->ntrk(); nt++){              for(Int_t nt=0; nt < tof->ntrk(); nt++){  
2095              //              //
# Line 1235  int OrbitalInfoCore(UInt_t run, TFile *f Line 2104  int OrbitalInfoCore(UInt_t run, TFile *f
2104                //                            //            
2105                t_orb->pitch = -1000.;                t_orb->pitch = -1000.;
2106                //                //
2107                  t_orb->sunangle = -1000.;
2108                  //
2109                  t_orb->sunmagangle = -1000;
2110                  //
2111                t_orb->cutoff = -1000.;                t_orb->cutoff = -1000.;
2112                //                //
2113                new(tor[nn]) OrbitalInfoTrkVar(*t_orb);                new(tor[nn]) OrbitalInfoTrkVar(*t_orb);
# Line 1242  int OrbitalInfoCore(UInt_t run, TFile *f Line 2115  int OrbitalInfoCore(UInt_t run, TFile *f
2115                //                //
2116                t_orb->Clear();                t_orb->Clear();
2117                //                //
2118              };              }
2119              //              //
2120            };                }
2121          };            //
2122        };            // Code for extended tracking algorithm:
2123              //
2124              if ( hasNucleiTrk ){
2125                Int_t ttentry = 0;
2126                if ( verbose ) printf(" hasNucleiTrk \n");
2127                for(Int_t nt=0; nt < tcNucleiTof->GetEntries() ; nt++){  
2128                  //  
2129                  ToFTrkVar *ptt = (ToFTrkVar*)(tcNucleiTof->At(nt));
2130                  if ( ptt->trkseqno != -1  ){
2131                    //
2132                    t_orb->trkseqno = ptt->trkseqno;
2133                    //
2134                    t_orb->Eij = 0;
2135                    //
2136                    t_orb->Sij = 0;
2137                    //          
2138                    t_orb->pitch = -1000.;
2139                    //
2140                    t_orb->sunangle = -1000.;
2141                    //
2142                    t_orb->sunmagangle = -1000;
2143                    //
2144                    t_orb->cutoff = -1000.;
2145                    //
2146                    TClonesArray &tz1 = *torbNucleiTrk;
2147                    new(tz1[ttentry]) OrbitalInfoTrkVar(*t_orb);
2148                    ttentry++;
2149                    //
2150                    t_orb->Clear();
2151                    //
2152                  }
2153                  //
2154                }
2155              }
2156              if ( hasExtNucleiTrk ){
2157                Int_t ttentry = 0;
2158                if ( verbose ) printf(" hasExtNucleiTrk \n");
2159                for(Int_t nt=0; nt < tcExtNucleiTof->GetEntries() ; nt++){  
2160                  //
2161                  if ( verbose ) printf(" got2\n");
2162                  ToFTrkVar *ptt = (ToFTrkVar*)(tcExtNucleiTof->At(nt));
2163                  if ( ptt->trkseqno != -1  ){
2164                    //
2165                    t_orb->trkseqno = ptt->trkseqno;
2166                    //
2167                    t_orb->Eij = 0;
2168                    //
2169                    t_orb->Sij = 0;
2170                    //          
2171                    t_orb->pitch = -1000.;
2172                    //
2173                    t_orb->sunangle = -1000.;
2174                    //
2175                    t_orb->sunmagangle = -1000;
2176                    //
2177                    t_orb->cutoff = -1000.;
2178                    //
2179                    TClonesArray &tz2 = *torbExtNucleiTrk;
2180                    new(tz2[ttentry]) OrbitalInfoTrkVar(*t_orb);
2181                    ttentry++;
2182                    //
2183                    t_orb->Clear();
2184                    //
2185                  }
2186                  //
2187                }
2188              }
2189              if ( hasExtTrk ){
2190                Int_t ttentry = 0;
2191                if ( verbose ) printf(" hasExtTrk \n");
2192                for(Int_t nt=0; nt < tcExtTof->GetEntries() ; nt++){  
2193                  //
2194                  if ( verbose ) printf(" got3\n");
2195                  ToFTrkVar *ptt = (ToFTrkVar*)(tcExtTof->At(nt));
2196                  if ( ptt->trkseqno != -1  ){
2197                    //
2198                    t_orb->trkseqno = ptt->trkseqno;
2199                    //
2200                    t_orb->Eij = 0;
2201                    //
2202                    t_orb->Sij = 0;
2203                    //          
2204                    t_orb->pitch = -1000.;
2205                    //
2206                    t_orb->sunangle = -1000.;
2207                    //
2208                    t_orb->sunmagangle = -1000;
2209                    //
2210                    t_orb->cutoff = -1000.;
2211                    //
2212                    TClonesArray &tz3 = *torbExtNucleiTrk;
2213                    new(tz3[ttentry]) OrbitalInfoTrkVar(*t_orb);
2214                    ttentry++;
2215                    //
2216                    t_orb->Clear();
2217                    //
2218                  }
2219                  //
2220                }
2221              }
2222            }
2223          } // if( orbitalinfo->TimeGap>0){
2224        //        //
2225        // Fill the class        // Fill the class
2226        //        //
2227        OrbitalInfotr->Fill();        OrbitalInfotr->Fill();
2228        //        //
2229          //      tor.Clear("C"); // memory leak?
2230          tor.Delete(); // memory leak?      
2231        delete t_orb;        delete t_orb;
2232        //        //
2233      }; // loop over the events in the run        //      printf(" q0 size %i q0 capacity %i \n",(int)q0.size(),(int)q0.capacity());
2234        } // loop over the events in the run
2235    
2236    
2237      //      //
2238      // Here you may want to clear some variables before processing another run        // Here you may want to clear some variables before processing another run  
2239      //      //
2240    
2241      //gStyle->SetOptStat(000000);      //    OrbitalInfotr->FlushBaskets();
     //gStyle->SetPalette(1);  
       
     /*TCanvas* c1 = new TCanvas("c1","",1200,800);  
     //c1->Divide(1,4);  
     c1->cd(1);  
     //q0testing->Draw("colz");  
     //c1->cd(2);  
     //q1testing->Draw("colz");  
     //c1->cd(3);  
     Pitchtesting->Draw("colz");  
     //c1->cd(4);  
     //q3testing->Draw("colz");  
     c1->SaveAs("9.Rollhyst.png");  
     delete c1;*/  
2242    
2243        if ( verbose ) printf(" Clear before new run \n");
2244      delete dbtime;      delete dbtime;
2245      if ( L_QQ_Q_l_upper ) delete L_QQ_Q_l_upper;  
2246        if ( mcmdrc ) mcmdrc->Clear();
2247        mcmdrc = 0;
2248        
2249        if ( verbose ) printf(" Clear before new run1 \n");
2250      if ( L_QQ_Q_l_lower ) delete L_QQ_Q_l_lower;      if ( L_QQ_Q_l_lower ) delete L_QQ_Q_l_lower;
2251        if ( verbose ) printf(" Clear before new run2 \n");
2252        if ( L_QQ_Q_l_upper ) delete L_QQ_Q_l_upper;
2253        if ( verbose ) printf(" Clear before new run3 \n");
2254      if ( RYPang_upper ) delete RYPang_upper;      if ( RYPang_upper ) delete RYPang_upper;
2255        if ( verbose ) printf(" Clear before new run4 \n");
2256      if ( RYPang_lower ) delete RYPang_lower;      if ( RYPang_lower ) delete RYPang_lower;
2257    }; // process all the runs  
2258      
2259        if ( l0tr ){
2260          if ( verbose ) printf(" delete l0tr\n");
2261          l0tr->Delete();
2262          l0tr = 0;
2263        }
2264        //    if ( l0head ){
2265        //      printf(" delete l0head\n");
2266        //  l0head->Reset();
2267        //  delete l0head;
2268        //  printf(" delete l0head done\n");
2269        //  l0head = 0;
2270        // }
2271        if (eh) {
2272          if ( verbose ) printf(" delete eh\n");
2273          delete eh;
2274          eh = 0;
2275        }
2276    
2277        if ( verbose ) printf(" close file \n");
2278        if ( l0File ) l0File->Close("R");
2279        if ( verbose ) printf(" End run \n");
2280    
2281        q0.clear();
2282        q1.clear();
2283        q2.clear();
2284        q3.clear();
2285        qtime.clear();
2286        qPitch.clear();
2287        qRoll.clear();
2288        qYaw.clear();
2289        qmode.clear();
2290    
2291        if (ch){
2292          if ( verbose ) printf(" delete ch\n");
2293          ch->Delete();
2294          ch = 0;
2295        }
2296      } // process all the runs    <===
2297      if ( debug ){
2298        printf("AFTER LOOP ON RUNs\n");
2299        gObjectTable->Print();
2300      }
2301      //  
2302    if (verbose) printf("\n Finished processing data \n");    if (verbose) printf("\n Finished processing data \n");
2303    //    //
2304   closeandexit:   closeandexit:
# Line 1303  int OrbitalInfoCore(UInt_t run, TFile *f Line 2320  int OrbitalInfoCore(UInt_t run, TFile *f
2320          //          //
2321          // copy orbitalinfoclone to OrbitalInfo          // copy orbitalinfoclone to OrbitalInfo
2322          //          //
2323          orbitalinfo->Clear();          //      orbitalinfo->Clear();
2324          //          //
2325          memcpy(&orbitalinfo,&orbitalinfoclone,sizeof(orbitalinfoclone));          memcpy(&orbitalinfo,&orbitalinfoclone,sizeof(orbitalinfoclone));
2326          //          //
# Line 1313  int OrbitalInfoCore(UInt_t run, TFile *f Line 2330  int OrbitalInfoCore(UInt_t run, TFile *f
2330        };        };
2331        if (verbose) printf(" Finished successful copying!\n");        if (verbose) printf(" Finished successful copying!\n");
2332      };      };
2333        //if ( OrbitalInfotrclone )    OrbitalInfotrclone->Clear();        
2334        //if ( OrbitalInfotrclone )    OrbitalInfotrclone->Delete();        
2335    };    };
2336    //    //
2337    // Close files, delete old tree(s), write and close level2 file    // Close files, delete old tree(s), write and close level2 file
2338    //    //
2339    
2340    if ( l0File ) l0File->Close();    if ( l0File ) l0File->Close();
   if ( tempfile ) tempfile->Close();              
2341    if ( myfold ) gSystem->Unlink(tempname.str().c_str());    if ( myfold ) gSystem->Unlink(tempname.str().c_str());
2342    //    //
   if ( runinfo ) runinfo->Close();      
2343    if ( OrbitalInfotr ) OrbitalInfotr->SetName("OrbitalInfo");        if ( OrbitalInfotr ) OrbitalInfotr->SetName("OrbitalInfo");    
   if ( tof ) tof->Delete();  
   if ( ttof ) ttof->Delete();  
2344    //    //
2345    if ( file ){    if ( file ){
2346      file->cd();      file->cd();
2347      file->Write();      if ( OrbitalInfotr ) OrbitalInfotr->Write("OrbitalInfo", TObject::kOverwrite); // 10 RED bug fixed
2348    };    };
2349    //    //
2350      if (verbose) printf("\n Exiting...\n");
2351    
2352    if ( myfold ) gSystem->Unlink(OrbitalInfofolder.str().c_str());    if ( myfold ) gSystem->Unlink(OrbitalInfofolder.str().c_str());
2353    //    //
2354    // the end    // the end
# Line 1339  int OrbitalInfoCore(UInt_t run, TFile *f Line 2357  int OrbitalInfoCore(UInt_t run, TFile *f
2357      dbc->Close();      dbc->Close();
2358      delete dbc;      delete dbc;
2359    };    };
   if (verbose) printf("\n Exiting...\n");  
   if(OrbitalInfotr)OrbitalInfotr->Delete();  
2360    //    //
2361      if (verbose) printf("\n Exiting...\n");
2362      if ( tempfile ) tempfile->Close();            
2363      
2364    if ( PO ) delete PO;    if ( PO ) delete PO;
2365    if ( orbitalinfo ) delete orbitalinfo;    if ( gltle ) delete gltle;
2366    if ( orbitalinfoclone ) delete orbitalinfoclone;    if ( glparam ) delete glparam;
2367      if ( glparam2 ) delete glparam2;
2368      if (verbose) printf("\n Exiting3...\n");
2369    if ( glroot ) delete glroot;    if ( glroot ) delete glroot;
2370      if (verbose) printf("\n Exiting4...\n");
2371      if ( runinfo ) runinfo->Close();    
2372    if ( runinfo ) delete runinfo;    if ( runinfo ) delete runinfo;
2373    
2374      if ( tcNucleiTrk ){
2375        tcNucleiTrk->Delete();
2376        delete tcNucleiTrk;
2377        tcNucleiTrk = NULL;
2378      }
2379      if ( tcExtNucleiTrk ){
2380        tcExtNucleiTrk->Delete();
2381        delete tcExtNucleiTrk;
2382        tcExtNucleiTrk = NULL;
2383      }
2384      if ( tcExtTrk ){
2385        tcExtTrk->Delete();
2386        delete tcExtTrk;
2387        tcExtTrk = NULL;
2388      }
2389    
2390      if ( tcNucleiTof ){
2391        tcNucleiTof->Delete();
2392        delete tcNucleiTof;
2393        tcNucleiTof = NULL;
2394      }
2395      if ( tcExtNucleiTof ){
2396        tcExtNucleiTof->Delete();
2397        delete tcExtNucleiTof;
2398        tcExtNucleiTof = NULL;
2399      }
2400      if ( tcExtTof ){
2401        tcExtTof->Delete();
2402        delete tcExtTof;
2403        tcExtTrk = NULL;
2404      }
2405    
2406    
2407      if ( tof ) delete tof;
2408      if ( trke ) delete trke;
2409    
2410      if ( debug ){  
2411      cout << "1   0x" << OrbitalInfotr << endl;
2412      cout << "2   0x" << OrbitalInfotrclone << endl;
2413      cout << "3   0x" << l0tr << endl;
2414      cout << "4   0x" << tempOrbitalInfo << endl;
2415      cout << "5   0x" << ttof << endl;
2416      }
2417    //    //
2418      if ( debug )  file->ls();
2419      //
2420      if ( debug ){
2421        printf("BEFORE EXITING\n");
2422        gObjectTable->Print();
2423      }
2424    if(code < 0)  throw code;    if(code < 0)  throw code;
2425    return(code);    return(code);
2426  }  }
# Line 1394  UInt_t holeq(Double_t lower,Double_t upp Line 2467  UInt_t holeq(Double_t lower,Double_t upp
2467    Bool_t R10l = false;     // Sign of R10 mode in lower quaternions array    Bool_t R10l = false;     // Sign of R10 mode in lower quaternions array
2468    Bool_t R10u = false;     // Sign of R10 mode in upper quaternions array    Bool_t R10u = false;     // Sign of R10 mode in upper quaternions array
2469    Bool_t insm = false;     // Sign that we inside quaternions array    Bool_t insm = false;     // Sign that we inside quaternions array
2470    Bool_t mxtml = false;    // Sign of mixt mode in lower quaternions array    //  Bool_t mxtml = false;    // Sign of mixt mode in lower quaternions array
2471    Bool_t mxtmu = false;    // Sign of mixt mode in upper quaternions array    //  Bool_t mxtmu = false;    // Sign of mixt mode in upper quaternions array
2472    Bool_t npasm = false;     // Sign of normall pass between R10 and non R10 or between non R10 and R10    Bool_t npasm = false;     // Sign of normall pass between R10 and non R10 or between non R10 and R10
2473    UInt_t NCQl = 6;       // Number of correct quaternions in lower array    UInt_t NCQl = 6;       // Number of correct quaternions in lower array
2474    UInt_t NCQu = 6;       // Number of correct quaternions in upper array    //  UInt_t NCQu = 6;       // Number of correct quaternions in upper array
2475    if (f>0){    if (f>0){
2476      insm = true;      insm = true;
2477      if(Qupper->time[f]-Qupper->time[f-1]==30) R10u = false;      if(Qupper->time[f]-Qupper->time[f-1]==30) R10u = false;
# Line 1410  UInt_t holeq(Double_t lower,Double_t upp Line 2483  UInt_t holeq(Double_t lower,Double_t upp
2483      if((Qlower->time[5]-Qlower->time[0]==150)&&(Qlower->time[1]-Qlower->time[0]==30)) R10l = false;      if((Qlower->time[5]-Qlower->time[0]==150)&&(Qlower->time[1]-Qlower->time[0]==30)) R10l = false;
2484      if((Qupper->time[5]-Qupper->time[0]==150)&&(Qupper->time[1]-Qupper->time[0]==30)) R10u = false;      if((Qupper->time[5]-Qupper->time[0]==150)&&(Qupper->time[1]-Qupper->time[0]==30)) R10u = false;
2485      if((Qlower->time[5]-Qlower->time[0]<2)&&(Qlower->time[1]-Qlower->time[0]==30)){      if((Qlower->time[5]-Qlower->time[0]<2)&&(Qlower->time[1]-Qlower->time[0]==30)){
2486        mxtml = true;        //      mxtml = true;
2487        for(UInt_t i = 1; i < 6; i++){        for(UInt_t i = 1; i < 6; i++){
2488          if(Qlower->time[i]-Qlower->time[0]==30*i) NCQl=i;          if(Qlower->time[i]-Qlower->time[0]==30*i) NCQl=i;
2489        }        }
2490      }      }
2491      if((Qupper->time[5]-Qupper->time[0]<2)&&(Qupper->time[1]-Qupper->time[0]==30)){      //    if((Qupper->time[5]-Qupper->time[0]<2)&&(Qupper->time[1]-Qupper->time[0]==30)){
2492        mxtmu = true;        //      mxtmu = true;
2493        for(UInt_t i = 1; i < 6; i++){        //      for(UInt_t i = 1; i < 6; i++){
2494          if(Qupper->time[i]-Qupper->time[0]==30*i) NCQu=i;        //        if(Qupper->time[i]-Qupper->time[0]==30*i) NCQu=i;
2495        }        //      }
2496      }      //    }
2497    }    }
2498        
2499    if(((upper-lower==1.5)||(upper-lower==3.)||(upper-lower==30.)||(upper-lower==31.5)||(upper-lower==33.)||(upper-lower==181.5)||(upper-lower==210.)||(upper-lower==211.5))&&!insm) npasm = true;    if(((upper-lower==1.5)||(upper-lower==3.)||(upper-lower==30.)||(upper-lower==31.5)||(upper-lower==33.)||(upper-lower==181.5)||(upper-lower==210.)||(upper-lower==211.5))&&!insm) npasm = true;
# Line 1452  void inclresize(vector<Double_t>& t,vect Line 2525  void inclresize(vector<Double_t>& t,vect
2525    Yaw.resize(sizee);    Yaw.resize(sizee);
2526  }  }
2527    
2528  //Find fitting sine functions for q0,q1,q2,q3 and Yaw-angle;  // geomagnetic calculation staff
2529  void sineparam(vector<Sine>& qsine, vector<Double_t>& qtime, vector<Float_t>& q, vector<Float_t>& Roll, vector<Float_t>& Pitch, Float_t limsin){  
2530    UInt_t mulast = 0;  void GM_ScanIGRF(TSQLServer *dbc, GMtype_Data *G0, GMtype_Data *G1, GMtype_Data *H1)
2531    UInt_t munow = 0;  {
2532    UInt_t munext = 0;    GL_PARAM *glp = new GL_PARAM();
2533    Bool_t increase = false;    Int_t parerror=glp->Query_GL_PARAM(1,304,dbc); // parameters stored in DB in GL_PRAM table  
2534    Bool_t decrease = false;    if ( parerror<0 ) {
2535    Bool_t Max_is_defined = false;      throw -902;
2536    Bool_t Start_point_is_defined = false;    }
2537    Bool_t Period_is_defined = false;          /*This function scans inputs G0, G1, and H1 of the IGRF table into 3 data arrays*/
2538    Bool_t Large_gap = false;    //    TString SATH="/data03/Malakhov/pam9Malakhov/installed10/calib/orb-param/";
2539    Bool_t normal_way = true;          int i;
2540    Bool_t small_gap_on_ridge = false;          double temp;
2541    Double_t t1 = 0;          char buffer[200];
2542    Double_t t1A = 0;          FILE *IGRF;
2543    Int_t sinesize = 0;          IGRF = fopen((glp->PATH+glp->NAME).Data(), "r");
2544    Int_t nfi = 0;          //      IGRF = fopen(PATH+"IGRF.tab", "r");
2545    for(UInt_t mu = 0;mu<qtime.size();mu++){          G0->size = 25;
2546      if(Roll[mu]<1. && Pitch[mu]<1.){          G1->size = 25;
2547      if(munext==0 && munow!=0)munext=mu;          H1->size = 25;
2548      if(munow==0 && mulast!=0)munow=mu;          for( i = 0; i < 4; i++)
2549      if(mulast==0)mulast=mu;          {
2550      if(mulast!=0 && munow!=0 && munext!=0){mulast=munow;munow=munext;munext=mu;}                  fgets(buffer, 200, IGRF);
     if(TMath::Abs(q[munow])>TMath::Abs(q[mulast]) && TMath::Abs(q[munow])>TMath::Abs(q[munext]) && TMath::Abs(q[munow])>limsin && qtime[munext]-qtime[mulast]>400)small_gap_on_ridge = true;  
     if(munext>mulast && (qtime[munext]-qtime[mulast]>=2000 || qtime[munext]-qtime[mulast]<0)){if(Large_gap){normal_way = false;Large_gap = false;}else{Large_gap = true;normal_way = false;}}else normal_way = true;  
     if(Large_gap || small_gap_on_ridge){  
       //cout<<"Large gap..."<<endl;  
       //if(small_gap_on_ridge)cout<<"small gap..."<<endl;  
       increase = false;  
       decrease = false;  
       if(nfi>0){  
         qsine.resize(qsine.size()-1);  
         sinesize = qsine.size();  
       }else{  
         if(!Period_is_defined){  
           if(qsine.size()>1){  
             qsine[sinesize-1].b = qsine[sinesize-2].b;  
             qsine[sinesize-1].c = qsine[sinesize-2].c;  
           }else{  
             qsine[sinesize-1].b = TMath::Pi()/1591.54;  
             qsine[sinesize-1].c = qsine[sinesize-1].startPoint;  
           }  
         }  
         if(!Max_is_defined){  
           if(qsine.size()>1)qsine[sinesize-1].A = qsine[sinesize-2].A;else qsine[sinesize-1].A = limsin;  
         }  
         qsine[sinesize-1].NeedFit = true;  
       }  
       qsine[sinesize-1].finishPoint = qtime[munow];  
       nfi = 0;  
       Max_is_defined = false;  
       Start_point_is_defined = false;  
       Period_is_defined = false;  
       small_gap_on_ridge = false;  
     }  
     if(munext > munow && munow > mulast && normal_way){  
       if(!increase && !decrease){  
         qsine.resize(qsine.size()+1);  
         sinesize = qsine.size();  
         qsine[sinesize-1].startPoint=qtime[mulast];  
         if(q[munext]>q[munow] && q[munow]>q[mulast]) increase = true;  
         if(q[munext]<q[munow] && q[munow]<q[mulast]) decrease = true;  
       }  
       //if(TMath::Abs(q[munow])>TMath::Abs(q[mulast]) && TMath::Abs(q[munow])>TMath::Abs(q[munext]) && TMath::Abs(q[munow])>limsin && qtime[munow]-qtime[mulast]>=400 || qtime[munext]-qtime[munow]>=400){small_gap_on_ridge = true;mu--;continue;}  
       if(TMath::Abs(q[munow])>TMath::Abs(q[mulast]) && TMath::Abs(q[munow])>TMath::Abs(q[munext]) && TMath::Abs(q[munow])>limsin && qtime[munow]-qtime[mulast]<400 && qtime[munext]-qtime[munow]<400){  
         //cout<<"Max point is qtime = "<<qtime[munow]<<"\tq = "<<q[munow]<<endl;  
         if(q[munow]>q[mulast]){  
           increase = false;  
           decrease = true;  
         }  
         if(q[munow]<q[mulast]){  
           increase = true;  
           decrease = false;  
2551          }          }
2552          if(Max_is_defined && !Start_point_is_defined){          fscanf(IGRF, "g 1 0 %lf ", &G0->element[0]);
2553            Double_t qPer = qtime[munow]-t1A;          for(i = 1; i <= 22; i++)
2554            if(qPer>1000){          {
2555              //cout<<"qsine["<<sinesize-1<<"] = "<<qPer<<" = "<<qtime[munow]<<" - "<<t1A<<"\tlim = "<<limsin<<endl;                  fscanf(IGRF ,"%lf ", &G0->element[i]);
             qsine[sinesize-1].b=TMath::Pi()/qPer;  
             if(decrease)qsine[sinesize-1].c=-qsine[sinesize-1].b*t1A;  
             if(increase)qsine[sinesize-1].c=-qsine[sinesize-1].b*(t1A-qPer);  
             Period_is_defined = true;  
           }  
2556          }          }
2557          Max_is_defined = true;          fscanf(IGRF ,"%lf\n", &temp);
2558          qsine[sinesize-1].A = TMath::Abs(q[munow]);          G0->element[23] = temp * 5 + G0->element[22];
2559          if(Start_point_is_defined && Period_is_defined){          G0->element[24] = G0->element[23] + 5 * temp;
2560            qsine[sinesize-1].finishPoint = qtime[munow];          fscanf(IGRF, "g 1 1 %lf ", &G1->element[0]);
2561            nfi++;          for(i = 1; i <= 22; i++)
2562            qsine[sinesize-1].NeedFit = false;          {
2563            Max_is_defined = false;                  fscanf( IGRF, "%lf ", &G1->element[i]);
           Start_point_is_defined = false;  
           Period_is_defined = false;  
           qsine.resize(qsine.size()+1);  
           sinesize = qsine.size();  
           qsine[sinesize-1].startPoint = qtime[munow];  
2564          }          }
2565          if(!Start_point_is_defined) t1A=qtime[munow];          fscanf(IGRF, "%lf\n", &temp);
2566        }          G1->element[23] = temp * 5 + G1->element[22];
2567        //if((q[munow]>=0 && q[mulast]<=0) || (q[munow]<=0 && q[mulast]>=0))cout<<"cross zero point diference = "<<qtime[munext] - qtime[mulast]<<"\tqlast = "<<qtime[mulast]<<"\tqnow = "<<qtime[munow]<<"\tqnext = "<<qtime[munext]<<endl;          G1->element[24] = temp * 5 + G1->element[23];
2568        if(((q[munow]>=0 && q[mulast]<=0) || (q[munow]<=0 && q[mulast]>=0)) && qtime[munow]-qtime[mulast]<2000 && qtime[munext]-qtime[munow]<2000){          fscanf(IGRF, "h 1 1 %lf ", &H1->element[0]);
2569          Double_t tcrosszero = 0;          for(i = 1; i <= 22; i++)
2570          //cout<<"cross zero point...qtime = "<<qtime[munow]<<endl;          {
2571          if(q[munow]==0.) tcrosszero = qtime[munow];else                  fscanf( IGRF, "%lf ", &H1->element[i]);
           if(q[mulast]==0.)tcrosszero = qtime[mulast];else{  
             Double_t k_ = (q[munow]-q[mulast])/(qtime[munow]-qtime[mulast]);  
             Double_t b_ = q[munow]-k_*qtime[munow];  
             tcrosszero = -b_/k_;  
           }  
         if(Start_point_is_defined){  
           //cout<<"Start Point allready defined"<<endl;  
           Double_t qPer = tcrosszero - t1;  
           qsine[sinesize-1].b = TMath::Pi()/qPer;  
           //cout<<"qsine["<<sinesize-1<<"].b = "<<TMath::Pi()/qPer<<endl;  
           Period_is_defined = true;  
           Float_t x0 = 0;  
           if(decrease)x0 = t1;  
           if(increase)x0 = tcrosszero;  
           qsine[sinesize-1].c = -qsine[sinesize-1].b*x0;  
           if(Max_is_defined){  
             //cout<<"Max was previous defined"<<endl;  
             qsine[sinesize-1].finishPoint = qtime[munow];  
             nfi++;  
             qsine[sinesize-1].NeedFit = false;  
             Max_is_defined = false;  
             t1 = tcrosszero;  
             Start_point_is_defined = true;  
             Period_is_defined = false;  
             qsine.resize(qsine.size()+1);  
             sinesize = qsine.size();  
             qsine[sinesize-1].startPoint = qtime[munow];  
           }  
         }else{  
           t1 = tcrosszero;  
           Start_point_is_defined = true;  
2572          }          }
2573        }          fscanf(IGRF, "%lf\n", &temp);
2574      }          H1->element[23] = temp * 5 + H1->element[22];
2575      }          H1->element[24] = temp * 5 + H1->element[23];
2576      if ( glp ) delete glp;
2577      /*
2578      printf("############################## SCAN IGRF ######################################\n");
2579      printf("       G0      G1     H1\n");
2580      printf(" size  %10i %10i %10i \n",G0->size,G1->size,H1->size);
2581      for ( i = 0; i < 30; i++){
2582        printf("%5i  %10.2f %10.2f %10.2f \n",i,G0->element[i],G1->element[i],H1->element[i]);
2583      }  
2584      printf("###############################################################################\n");
2585      */
2586    } /*GM_ScanIGRF*/
2587    
2588    
2589    
2590    
2591    void GM_SetIGRF(Int_t isSecular, TString ifile1, TString ifile2, GMtype_Data *G0, GMtype_Data *G1, GMtype_Data *H1)
2592    {
2593      /*This function scans inputs G0, G1, and H1 of the IGRF table into 3 data arrays*/
2594      int i;
2595      double temp,temp2;
2596      int it1,it2;
2597      char buffer[200];
2598      FILE *IGRF;
2599      G0->size = 2;
2600      G1->size = 2;
2601      H1->size = 2;
2602    
2603      for( i = 0; i < 30; i++){
2604        G0->element[i] = 0.;
2605        G1->element[i] = 0.;
2606        H1->element[i] = 0.;
2607    }    }
2608    
2609    //cout<<"FINISH SINE INTERPOLATION FUNCTION..."<<endl<<endl;    IGRF = fopen(ifile1.Data(), "r");
2610  }    for( i = 0; i < 2; i++){
2611        fgets(buffer, 200, IGRF);
2612      }
2613      fscanf(IGRF, "%3i%3i%12lf%11lf",&it1,&it2, &G0->element[0],&temp);
2614      fscanf(IGRF, "%3i%3i%12lf%11lf",&it1,&it2, &G1->element[0],&H1->element[0]);
2615      fclose(IGRF);
2616    
2617      IGRF = fopen(ifile2.Data(), "r");
2618      for( i = 0; i < 2; i++){
2619        fgets(buffer, 200, IGRF);
2620      }
2621      if ( isSecular ){
2622        fscanf(IGRF, "%3i%3i%12lf%11lf",&it1,&it2,&temp,&temp2);
2623        G0->element[1] = temp * 5. + G0->element[0];
2624        fscanf(IGRF, "%3i%3i%12lf%11lf",&it1,&it2,&temp,&temp2);
2625        G1->element[1] = temp * 5. + G1->element[0];
2626        H1->element[1] = temp2 * 5. + H1->element[0];
2627      } else {
2628        fscanf(IGRF, "%3i%3i%12lf%11lf",&it1,&it2, &G0->element[1],&temp);
2629        fscanf(IGRF, "%3i%3i%12lf%11lf",&it1,&it2, &G1->element[1],&H1->element[1]);
2630      }
2631      fclose(IGRF);
2632      /*
2633      printf("############################## SCAN IGRF ######################################\n");
2634      printf("       G0      G1     H1\n");
2635      printf(" size  %10i %10i %10i \n",G0->size,G1->size,H1->size);
2636      for ( i = 0; i < 30; i++){
2637        printf("%5i  %10.2f %10.2f %10.2f \n",i,G0->element[i],G1->element[i],H1->element[i]);
2638      }  
2639      printf("###############################################################################\n");
2640      */
2641    } /*GM_ScanIGRF*/
2642    
2643    void GM_SetEllipsoid(GMtype_Ellipsoid *Ellip)
2644    {
2645            /*This function sets the WGS84 reference ellipsoid to its default values*/
2646            Ellip->a        =                       6378.137; /*semi-major axis of the ellipsoid in */
2647            Ellip->b        =                       6356.7523142;/*semi-minor axis of the ellipsoid in */
2648            Ellip->fla      =                       1/298.257223563;/* flattening */
2649            Ellip->eps      =                       sqrt(1- ( Ellip->b *    Ellip->b) / (Ellip->a * Ellip->a ));  /*first eccentricity */
2650            Ellip->epssq    =                       (Ellip->eps * Ellip->eps);   /*first eccentricity squared */
2651            Ellip->re       =                       6371.2;/* Earth's radius */
2652    } /*GM_SetEllipsoid*/
2653    
2654    
2655    void GM_EarthCartToDipoleCartCD(GMtype_Pole Pole, GMtype_CoordCartesian EarthCoord, GMtype_CoordCartesian *DipoleCoords)
2656    {
2657            /*This function converts from Earth centered cartesian coordinates to dipole centered cartesian coordinates*/
2658            double X, Y, Z, CosPhi, SinPhi, CosLambda, SinLambda;
2659            CosPhi = cos(TMath::DegToRad()*Pole.phi);
2660            SinPhi = sin(TMath::DegToRad()*Pole.phi);
2661            CosLambda = cos(TMath::DegToRad()*Pole.lambda);
2662            SinLambda = sin(TMath::DegToRad()*Pole.lambda);
2663            X = EarthCoord.x;
2664            Y = EarthCoord.y;
2665            Z = EarthCoord.z;
2666            
2667            /*These equations are taken from a document by Wallace H. Campbell*/
2668            DipoleCoords->x = X * CosPhi * CosLambda + Y * CosPhi * SinLambda - Z * SinPhi;
2669            DipoleCoords->y = -X * SinLambda + Y * CosLambda;
2670            DipoleCoords->z = X * SinPhi * CosLambda + Y * SinPhi * SinLambda + Z * CosPhi;
2671    } /*GM_EarthCartToDipoleCartCD*/
2672    
2673    void GM_GeodeticToSpherical(GMtype_Ellipsoid Ellip, GMtype_CoordGeodetic CoordGeodetic, GMtype_CoordSpherical *CoordSpherical)
2674    {
2675            double CosLat, SinLat, rc, xp, zp; /*all local variables */
2676            /*
2677            ** Convert geodetic coordinates, (defined by the WGS-84
2678            ** reference ellipsoid), to Earth Centered Earth Fixed Cartesian
2679            ** coordinates, and then to spherical coordinates.
2680            */
2681    
2682            CosLat = cos(TMath::DegToRad()*CoordGeodetic.phi);
2683            SinLat = sin(TMath::DegToRad()*CoordGeodetic.phi);
2684    
2685            /* compute the local radius of curvature on the WGS-84 reference ellipsoid */
2686    
2687            rc = Ellip.a / sqrt(1.0 - Ellip.epssq * SinLat * SinLat);
2688    
2689            /* compute ECEF Cartesian coordinates of specified point (for longitude=0) */
2690    
2691            xp = (rc + CoordGeodetic.HeightAboveEllipsoid) * CosLat;
2692            zp = (rc*(1.0 - Ellip.epssq) + CoordGeodetic.HeightAboveEllipsoid) * SinLat;
2693    
2694            /* compute spherical radius and angle lambda and phi of specified point */
2695    
2696            CoordSpherical->r = sqrt(xp * xp + zp * zp);
2697            CoordSpherical->phig = TMath::RadToDeg()*asin(zp / CoordSpherical->r);     /* geocentric latitude */
2698            CoordSpherical->lambda = CoordGeodetic.lambda;                   /* longitude */
2699    } /*GM_GeodeticToSpherical*/
2700    
2701    void GM_PoleLocation(GMtype_Model Model, GMtype_Pole *Pole)
2702    {
2703            /*This function finds the location of the north magnetic pole in spherical coordinates.  The equations are
2704            **from Wallace H. Campbell's Introduction to Geomagnetic Fields*/
2705    
2706            Pole->phi = TMath::RadToDeg()*-atan(sqrt(Model.h1 * Model.h1 + Model.g1 * Model.g1)/Model.g0);
2707            Pole->lambda = TMath::RadToDeg()*atan(Model.h1/Model.g1);
2708    } /*GM_PoleLocation*/
2709    
2710    void GM_SphericalToCartesian(GMtype_CoordSpherical CoordSpherical, GMtype_CoordCartesian *CoordCartesian)
2711    {
2712            /*This function converts spherical coordinates into Cartesian coordinates*/
2713            double CosPhi = cos(TMath::DegToRad()*CoordSpherical.phig);
2714            double SinPhi = sin(TMath::DegToRad()*CoordSpherical.phig);
2715            double CosLambda = cos(TMath::DegToRad()*CoordSpherical.lambda);
2716            double SinLambda = sin(TMath::DegToRad()*CoordSpherical.lambda);
2717            
2718            CoordCartesian->x = CoordSpherical.r * CosPhi * CosLambda;
2719            CoordCartesian->y = CoordSpherical.r * CosPhi * SinLambda;
2720            CoordCartesian->z = CoordSpherical.r * SinPhi;
2721    } /*GM_SphericalToCartesian*/
2722    
2723    void GM_TimeAdjustCoefs(Float_t year, Float_t jyear, GMtype_Data g0d, GMtype_Data g1d, GMtype_Data h1d, GMtype_Model *Model)
2724    {
2725            /*This function calls GM_LinearInterpolation for the coefficients to estimate the value of the
2726            **coefficient for the given date*/
2727            int index;
2728            double x;
2729            index = (year - GM_STARTYEAR) / 5;
2730            x = (jyear - GM_STARTYEAR) / 5.;
2731            Model->g0 = GM_LinearInterpolation(index, index+1, g0d.element[index], g0d.element[index+1], x);
2732            Model->g1 = GM_LinearInterpolation(index, index+1, g1d.element[index], g1d.element[index+1], x);
2733            Model->h1 = GM_LinearInterpolation(index, index+1, h1d.element[index], h1d.element[index+1], x);
2734    } /*GM_TimeAdjustCoefs*/
2735    
2736    double GM_LinearInterpolation(double x1, double x2, double y1, double y2, double x)
2737    {
2738            /*This function takes a linear interpolation between two given points for x*/
2739            double weight, y;
2740            weight  = (x - x1) / (x2 - x1);
2741            y = y1 * (1. - weight) + y2 * weight;
2742            //        printf(" x1 %f x2 %f y1 %f y2 %f x %f ==> y %f \n",x1,x2,y1,y2,x,y);
2743            return y;
2744    }/*GM_LinearInterpolation*/
2745    
2746    void GM_CartesianToSpherical(GMtype_CoordCartesian CoordCartesian, GMtype_CoordSpherical *CoordSpherical)
2747    {
2748            /*This function converts a point from Cartesian coordinates into spherical coordinates*/
2749            double X, Y, Z;
2750            
2751            X = CoordCartesian.x;
2752            Y = CoordCartesian.y;
2753            Z = CoordCartesian.z;
2754    
2755            CoordSpherical->r = sqrt(X * X + Y * Y + Z * Z);
2756            CoordSpherical->phig = TMath::RadToDeg()*asin(Z / (CoordSpherical->r));
2757            CoordSpherical->lambda = TMath::RadToDeg()*atan2(Y, X);
2758    } /*GM_CartesianToSpherical*/

Legend:
Removed from v.1.45  
changed lines
  Added in v.1.82

  ViewVC Help
Powered by ViewVC 1.1.23