/[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.1 by mocchiut, Fri May 19 13:15:57 2006 UTC revision 1.70 by mocchiut, Fri Apr 4 08:46:01 2014 UTC
# Line 1  Line 1 
 //  
1  // C/C++ headers  // C/C++ headers
2  //  //
3  #include <fstream>  #include <fstream>
# Line 9  Line 8 
8  //  //
9  // ROOT headers  // ROOT headers
10  //  //
11    //#include <TCanvas.h>
12    #include <TH2F.h> //for test only. Vitaly.
13    #include <TVector3.h>
14    //#include <TF1.h>
15    
16  #include <TTree.h>  #include <TTree.h>
17  #include <TClassEdit.h>  #include <TClassEdit.h>
18  #include <TObject.h>  #include <TObject.h>
19  #include <TList.h>  #include <TList.h>
20  #include <TArrayL.h>  #include <TArrayI.h>
21  #include <TSystem.h>  #include <TSystem.h>
22  #include <TSystemDirectory.h>  #include <TSystemDirectory.h>
23  #include <TString.h>  #include <TString.h>
# Line 23  Line 27 
27  #include <TSQLRow.h>  #include <TSQLRow.h>
28  #include <TSQLResult.h>  #include <TSQLResult.h>
29  //  //
30    // RunInfo header
31    //
32    #include <RunInfo.h>
33    #include <GLTables.h>
34    //
35  // YODA headers  // YODA headers
36  //  //
37  #include <PamelaRun.h>  #include <PamelaRun.h>
 #include <RegistryEvent.h>  
38  #include <PscuHeader.h>  #include <PscuHeader.h>
39  #include <PscuEvent.h>  #include <PscuEvent.h>
40  #include <EventHeader.h>  #include <EventHeader.h>
41  #include <RegistryEvent.h>  #include <mcmd/McmdEvent.h>
42  //  #include <mcmd/McmdRecord.h>
 // RunInfo header  
 //  
 #include <RunInfo.h>  
 #include <GLTables.h>  
43  //  //
44  // This program headers  // This program headers
45  //  //
46  #include <OrbitalInfo.h>  #include <OrbitalInfo.h>
 #include <OrbitalInfoCore.h>  
47  #include <OrbitalInfoVerl2.h>  #include <OrbitalInfoVerl2.h>
48    #include <OrbitalInfoCore.h>
49    #include <InclinationInfo.h>
50    
51    //
52    // Tracker and ToF classes headers and definitions
53    //
54    #include <ToFLevel2.h>
55    #include <TrkLevel2.h>
56    
57  using namespace std;  using namespace std;
58    
# Line 49  using namespace std; Line 60  using namespace std;
60  // CORE ROUTINE  // CORE ROUTINE
61  //  //
62  //  //
63    int OrbitalInfoCore(UInt_t run, TFile *file, GL_TABLES *glt, Int_t OrbitalInfoargc, char *OrbitalInfoargv[]){
64  int OrbitalInfoCore(ULong64_t run, TFile *file, TSQLServer *dbc, Int_t OrbitalInfoargc, char *OrbitalInfoargv[]){    //
65    Int_t i = 0;    Int_t i = 0;
66      TString host = glt->CGetHost();
67      TString user = glt->CGetUser();
68      TString psw = glt->CGetPsw();
69      TSQLServer *dbc = TSQLServer::Connect(host.Data(),user.Data(),psw.Data());
70      //
71      stringstream myquery;
72      myquery.str("");
73      myquery << "SET time_zone='+0:00'";
74      delete dbc->Query(myquery.str().c_str());
75    //    //
76    TString processFolder = "OrbitalInfoFolder";    TString processFolder = Form("OrbitalInfoFolder_%u",run);
77    //    //
78    // Set these to true to have a very verbose output.    // Set these to true to have a very verbose output.
79    //    //
80    Bool_t debug = false;    Bool_t debug = false;
81    //    //
82    Bool_t verbose = false;    Bool_t verbose = false;
83      //
84      Bool_t standalone = false;
85      //
86    if ( OrbitalInfoargc > 0 ){    if ( OrbitalInfoargc > 0 ){
87      i = 0;      i = 0;
88      while ( i < OrbitalInfoargc ){      while ( i < OrbitalInfoargc ){
# Line 73  int OrbitalInfoCore(ULong64_t run, TFile Line 95  int OrbitalInfoCore(ULong64_t run, TFile
95        };        };
96        if ( (!strcmp(OrbitalInfoargv[i],"--debug")) || (!strcmp(OrbitalInfoargv[i],"-g")) ) {        if ( (!strcmp(OrbitalInfoargv[i],"--debug")) || (!strcmp(OrbitalInfoargv[i],"-g")) ) {
97          verbose = true;          verbose = true;
98            debug = true;
99        };        };
100        if ( (!strcmp(OrbitalInfoargv[i],"--verbose")) || (!strcmp(OrbitalInfoargv[i],"-v")) ) {        if ( (!strcmp(OrbitalInfoargv[i],"--verbose")) || (!strcmp(OrbitalInfoargv[i],"-v")) ) {
101          verbose = true;          verbose = true;
102        };        };
103          if ( (!strcmp(OrbitalInfoargv[i],"--standalone")) ) {
104            standalone = true;
105          };
106          if ( (!strcmp(OrbitalInfoargv[i],"--calculate-pitch")) ) {
107            standalone = false;
108          };
109        i++;        i++;
110      };      };
111    };    };
# Line 84  int OrbitalInfoCore(ULong64_t run, TFile Line 113  int OrbitalInfoCore(ULong64_t run, TFile
113    const char* outDir = gSystem->DirName(gSystem->DirName(file->GetPath()));    const char* outDir = gSystem->DirName(gSystem->DirName(file->GetPath()));
114    //    //
115    TTree *OrbitalInfotr = 0;    TTree *OrbitalInfotr = 0;
116    Long64_t nevents = 0LL;    UInt_t nevents = 0;
117      UInt_t neventsm = 0;
118    //    //
119    // variables needed to reprocess data    // variables needed to reprocess data
120    //    //
121      Long64_t maxsize = 10000000000LL;  
122      TTree::SetMaxTreeSize(maxsize);
123      //
124    TString OrbitalInfoversion;    TString OrbitalInfoversion;
125    ItoRunInfo *runinfo = 0;    ItoRunInfo *runinfo = 0;
126    TArrayL *runlist = 0;    TArrayI *runlist = 0;
127    TTree *OrbitalInfotrclone = 0;    TTree *OrbitalInfotrclone = 0;
128    Bool_t reproc = false;    Bool_t reproc = false;
129    Bool_t reprocall = false;    Bool_t reprocall = false;
130      Bool_t igrfloaded = false;
131    UInt_t nobefrun = 0;    UInt_t nobefrun = 0;
132    UInt_t noaftrun = 0;    UInt_t noaftrun = 0;
133    UInt_t numbofrun = 0;    UInt_t numbofrun = 0;
134    stringstream ftmpname;    stringstream ftmpname;
135    TString fname;    TString fname;
136    Long64_t totfileentries = 0ULL;    UInt_t totfileentries = 0;
137    Long64_t idRun = 0LL;    UInt_t idRun = 0;
138      UInt_t anni5 = 60 * 60 * 24 * 365 * 5 ;//1576800
139      //
140      // My variables. Vitaly.
141      //
142    //  UInt_t oi = 0;
143      Int_t tmpSize = 0;
144    //    //
145    // variables needed to handle error signals    // variables needed to handle error signals
146    //    //
# Line 111  int OrbitalInfoCore(ULong64_t run, TFile Line 151  int OrbitalInfoCore(ULong64_t run, TFile
151    //    //
152    OrbitalInfo *orbitalinfo = new OrbitalInfo();    OrbitalInfo *orbitalinfo = new OrbitalInfo();
153    OrbitalInfo *orbitalinfoclone = new OrbitalInfo();    OrbitalInfo *orbitalinfoclone = new OrbitalInfo();
154    
155    //    //
156    // define variables for opening and reading level0 file    // define variables for opening and reading level0 file
157    //    //
158    TFile *l0File = 0;    TFile *l0File = 0;
159    TTree *l0tr = 0;    TTree *l0tr = 0;
160    TBranch *l0registry = 0;    //  TTree *l0trm = 0;
161    pamela::RegistryEvent *l0reg=0;    TChain *ch = 0;
162      // EM: open also header branch
163      TBranch *l0head = 0;
164      pamela::EventHeader *eh = 0;
165      pamela::PscuHeader *ph = 0;
166      pamela::McmdEvent *mcmdev = 0;
167      pamela::McmdRecord *mcmdrc = 0;
168      // end EM
169      
170      //  pamela::RunHeaderEvent *reh = new pamela::RunHeaderEvent;
171      //  pamela::EventHeader    *eH  = new pamela::EventHeader;
172      
173    //    //
174    // Define other basic variables    // Define other basic variables
175    //    //
# Line 126  int OrbitalInfoCore(ULong64_t run, TFile Line 178  int OrbitalInfoCore(ULong64_t run, TFile
178    stringstream file3;    stringstream file3;
179    stringstream qy;    stringstream qy;
180    Int_t totevent = 0;    Int_t totevent = 0;
181    ULong64_t atime = 0ULL;    UInt_t atime = 0;
182    Int_t ei = 0;    UInt_t re = 0;
183    Int_t re = 0;    UInt_t ik = 0;
184    
185      // Position
186      Float_t lon, lat, alt;
187    
188      //
189      // IGRF stuff
190      //
191      Double_t dimo = 0.0; // dipole moment (computed from dat files) // EM GCC 4.7
192      Float_t bnorth, beast, bdown, babs;
193      Float_t xl; // L value
194      Float_t icode; // code value for L accuracy (see fortran code)
195      Float_t bab1; // What's  the difference with babs?
196      Float_t stps = 0.005; // step size for field line tracing
197      Float_t bdel = 0.01; // required accuracy
198      Float_t bequ;  // equatorial b value (also called b_0)
199      Bool_t value = 0; // false if bequ is not the minimum b value
200      Float_t rr0; // equatorial radius normalized to earth radius
201    
202    //    //
203    // Working filename    // Working filename
204    //    //
# Line 143  int OrbitalInfoCore(ULong64_t run, TFile Line 213  int OrbitalInfoCore(ULong64_t run, TFile
213    TTree *tempOrbitalInfo = 0;    TTree *tempOrbitalInfo = 0;
214    stringstream tempname;    stringstream tempname;
215    stringstream OrbitalInfofolder;    stringstream OrbitalInfofolder;
216      Bool_t myfold = false;
217    tempname.str("");    tempname.str("");
218    tempname << outDir;    tempname << outDir;
219    tempname << "/" << processFolder.Data();    tempname << "/" << processFolder.Data();
220    OrbitalInfofolder.str("");    OrbitalInfofolder.str("");
221    OrbitalInfofolder << tempname.str().c_str();    OrbitalInfofolder << tempname.str().c_str();
   gSystem->MakeDirectory(OrbitalInfofolder.str().c_str());  
222    tempname << "/OrbitalInfotree_run";    tempname << "/OrbitalInfotree_run";
223    tempname << run << ".root";      tempname << run << ".root";  
224      UInt_t totnorun = 0;
225    //    //
226    // DB classes    // DB classes
227    //    //
228    GL_ROOT *glroot = new GL_ROOT();    GL_ROOT *glroot = new GL_ROOT();
229      GL_TIMESYNC *dbtime = 0;
230      GL_TLE *gltle = new GL_TLE();
231      //
232      //Quaternions classes
233      //
234      Quaternions *L_QQ_Q_l_lower = 0;
235      InclinationInfo *RYPang_lower = 0;
236      Quaternions *L_QQ_Q_l_upper = 0;
237      InclinationInfo *RYPang_upper = 0;
238      
239      cEci eCi;
240      
241      // Initialize fortran routines!!!
242      Int_t ltp1 = 0;
243      Int_t ltp2 = 0;
244      Int_t ltp3 = 0;
245      //  Int_t uno = 1;
246      //  const char *niente = " ";
247      GL_PARAM *glparam0 = new GL_PARAM();
248      GL_PARAM *glparam = new GL_PARAM();
249      GL_PARAM *glparam2 = new GL_PARAM();
250      GL_PARAM *glparam3 = new GL_PARAM();
251    
252      //
253      // Orientation variables. Vitaly
254      //
255      UInt_t evfrom = 0;
256      UInt_t jumped = 0;
257      Int_t itr = -1;    
258      //  Double_t A1;
259      //  Double_t A2;
260      //  Double_t A3;
261      Double_t Px = 0;
262      Double_t Py = 0;      
263      Double_t Pz = 0;  
264      TTree *ttof = 0;
265      ToFLevel2 *tof = new ToFLevel2();
266      TTree *ttrke = 0;
267      TrkLevel2 *trke = new TrkLevel2();
268      OrientationInfo *PO = new OrientationInfo();
269      Int_t nz = 6;
270      Float_t zin[6];
271      Int_t nevtofl2 = 0;
272      Int_t nevtrkl2 = 0;
273      if ( verbose ) cout<<"Reading quaternions external file"<<endl;
274      cout.setf(ios::fixed,ios::floatfield);  
275      /******Reading recovered quaternions...*********/
276      vector<Double_t> recqtime;
277      vector<Float_t> recq0;
278      vector<Float_t> recq1;
279      vector<Float_t> recq2;
280      vector<Float_t> recq3;
281      Float_t Norm = 1;
282      Int_t parerror=glparam0->Query_GL_PARAM(1,303,dbc); // parameters stored in DB in GL_PRAM table
283      cout<<parerror<<"\t"<<(char*)(glparam0->PATH+glparam0->NAME).Data()<<endl;
284      ifstream in((char*)(glparam0->PATH+glparam0->NAME).Data(),ios::in);
285      if ( parerror<0 ) {
286        code = parerror;
287        //goto closeandexit;
288      }
289      while(!in.eof()){
290        recqtime.resize(recqtime.size()+1);
291        Int_t sizee = recqtime.size();
292        recq0.resize(sizee);
293        recq1.resize(sizee);
294        recq2.resize(sizee);
295        recq3.resize(sizee);
296        in>>recqtime[sizee-1];
297        in>>recq0[sizee-1];
298        in>>recq1[sizee-1];
299        in>>recq2[sizee-1];
300        in>>recq3[sizee-1];
301        in>>Norm;
302      }
303      in.close();
304      if ( verbose ) cout<<"We have read recovered data"<<endl;
305      if (debug) cout << "size of recovered quaterions data set is " << recqtime.size() << endl;
306    
307      vector<UInt_t> RTtime1;
308      vector<UInt_t> RTtime2;
309      vector<Double_t> RTbank1;
310      vector<Double_t> RTbank2;
311      vector<Int_t> RTazim;
312      vector<Int_t> RTdir1;
313      vector<Int_t> RTdir2;
314      vector<Int_t> RTerrq;
315    
316    // 10RED CHECK
317    
318    //  TH2F* DIFFX = new TH2F("diffx","",100,0,100,90,0,90);
319    //  TH2F* DIFFY = new TH2F("diffy","",100,0,100,90,0,90);
320    //  TH2F* DIFFZ = new TH2F("diffz","",100,0,100,90,0,90);
321    
322      ofstream mc;
323      TString gr = "methodscomparison_";
324      gr+=run;
325      gr+=".txt";
326      mc.open(gr);
327      mc.setf(ios::fixed,ios::floatfield);
328    // 10RED CHECK END
329    
330      if ( verbose ) cout<<"read Rotation Table"<<endl;
331    
332      Int_t parerror2=glparam0->Query_GL_PARAM(1,305,dbc);
333      ifstream an((char*)(glparam0->PATH+glparam0->NAME).Data(),ios::in);
334      cout<<parerror2<<"\t"<<(char*)(glparam0->PATH+glparam0->NAME).Data()<<endl;
335    //  if ( parerror2<0 ) {
336    //    code = parerror;
337        //goto closeandexit;
338    //  }
339    
340    //ifstream an("/data03/Malakhov/pam9Malakhov/installed10/calib/orb-param/RDBCC.txt",ios::in);
341      while(!an.eof()){
342        RTtime1.resize(RTtime1.size()+1);
343        Int_t sizee = RTtime1.size();
344        RTbank1.resize(sizee+1);
345        RTazim.resize(sizee+1);
346        RTdir1.resize(sizee+1);
347        RTerrq.resize(sizee+1);
348        an>>RTtime1[sizee-1];
349        an>>RTbank1[sizee-1];
350        an>>RTazim[sizee-1];
351        an>>RTdir1[sizee-1];
352        an>>RTerrq[sizee-1];
353        if(sizee>1) {
354          RTtime2.resize(sizee+1);
355          RTbank2.resize(sizee+1);
356          RTdir2.resize(sizee+1);
357          RTtime2[sizee-2]=RTtime1[sizee-1];
358          RTbank2[sizee-2]=RTbank1[sizee-1];
359          RTdir2[sizee-2]=RTdir1[sizee-1];
360        }
361      }
362      an.close();
363      //cout<<"put some number here"<<endl;
364      //Int_t yupi;
365      //cin>>yupi;
366      
367      if ( verbose ) cout<<"We have read Rotation Table"<<endl;
368        //Geomagnetic coordinates calculations staff
369    
370      GMtype_CoordGeodetic location;
371      //  GMtype_CoordDipole GMlocation;
372      GMtype_Ellipsoid Ellip;
373      GMtype_Data G0, G1, H1;
374            
375      //  { // 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
376      //    TString igpath="/data03/Malakhov/pam9Malakhov/installed10/calib/orb-param/";
377      //  }
378    
379      //  GM_ScanIGRF(glparam->PATH, &G0, &G1, &H1);
380      GM_ScanIGRF(dbc, &G0, &G1, &H1);
381    
382      //cout << G0.element[0] << "\t" << G1.element[0] << "\t" << H1.element[0] << endl;
383      //cout << G0.element[5] << "\t" << G1.element[5] << "\t" << H1.element[5] << endl;
384    
385      GM_SetEllipsoid(&Ellip);
386    
387      // IGRF stuff moved inside run loop!  
388    
389      for (Int_t ip=0;ip<nz;ip++){
390        zin[ip] = tof->GetZTOF(tof->GetToFPlaneID(ip));
391      };
392      //
393      if ( !standalone ){
394        //
395        // Does it contain the Tracker tree?
396        //
397        ttof = (TTree*)file->Get("ToF");
398        if ( !ttof ) {
399          if ( verbose ) printf(" OrbitalInfo - ERROR: no tof tree\n");
400          code = -900;
401          goto closeandexit;
402        }
403        ttof->SetBranchAddress("ToFLevel2",&tof);  
404        nevtofl2 = ttof->GetEntries();
405    
406        ttrke = (TTree*)file->Get("Tracker");
407        if ( !ttrke ) {
408          if ( verbose ) printf(" OrbitalInfo - ERROR: no trk tree\n");
409          code = -903;
410          goto closeandexit;
411        }
412        ttrke->SetBranchAddress("TrkLevel2",&trke);  
413        nevtrkl2 = ttrke->GetEntries();
414      }
415    //    //
416    // Let's start!    // Let's start!
417    //    //
# Line 162  int OrbitalInfoCore(ULong64_t run, TFile Line 419  int OrbitalInfoCore(ULong64_t run, TFile
419    // if run != 0 we must process only that run but first we have to check if the tree MyDetector2 already exist in the file    // if run != 0 we must process only that run but first we have to check if the tree MyDetector2 already exist in the file
420    // if it exists we are reprocessing data and we must delete that entries, if not we must create it.    // if it exists we are reprocessing data and we must delete that entries, if not we must create it.
421    //    //
422    if ( run == 0ULL )  reproc = true;    if ( run == 0 )  reproc = true;
423    //    //
424    //    //
425    // Output file is "outputfile"    // Output file is "outputfile"
# Line 209  int OrbitalInfoCore(ULong64_t run, TFile Line 466  int OrbitalInfoCore(ULong64_t run, TFile
466    // number of run to be processed    // number of run to be processed
467    //    //
468    numbofrun = runinfo->GetNoRun();    numbofrun = runinfo->GetNoRun();
469      totnorun = runinfo->GetRunEntries();
470    //    //
471    // Try to access the OrbitalInfo tree in the file, if it exists we are reprocessing data if not we are processing a new run    // Try to access the OrbitalInfo tree in the file, if it exists we are reprocessing data if not we are processing a new run
472    //    //
# Line 219  int OrbitalInfoCore(ULong64_t run, TFile Line 477  int OrbitalInfoCore(ULong64_t run, TFile
477      // tree does not exist, we are not reprocessing      // tree does not exist, we are not reprocessing
478      //      //
479      reproc = false;      reproc = false;
480      if ( run == 0ULL ){      if ( run == 0 ){
481        if (verbose) printf(" OrbitalInfo - WARNING: you are reprocessing data but OrbitalInfo tree does not exist!\n");        if (verbose) printf(" OrbitalInfo - WARNING: you are reprocessing data but OrbitalInfo tree does not exist!\n");
482      }      }
483      if ( runinfo->IsReprocessing() && run != 0ULL ) {      if ( runinfo->IsReprocessing() && run != 0 ) {
484        if (verbose) printf(" OrbitalInfo - WARNING: it seems you are not reprocessing data but OrbitalInfo\n versioning information already exists in RunInfo.\n");        if (verbose) printf(" OrbitalInfo - WARNING: it seems you are not reprocessing data but OrbitalInfo\n versioning information already exists in RunInfo.\n");
485      }      }
486    } else {    } else {
487      //      //
488      // tree exists, we are reprocessing data. Are we reprocessing a single run or all the file?      // tree exists, we are reprocessing data. Are we reprocessing a single run or all the file?
489      //      //
490        OrbitalInfotrclone->SetAutoSave(900000000000000LL);
491      reproc = true;      reproc = true;
492      //      //
493      //      //
494      if (verbose) printf("\n Preparing the pre-processing...\n");      if (verbose) printf("\n Preparing the pre-processing...\n");
495      //      //
496      if ( run == 0ULL ){      if ( run == 0 || totnorun == 1 ){
497        //        //
498        // we are reprocessing all the file        // we are reprocessing all the file
499        // if we are reprocessing everything we don't need to copy any old event and we can just work with the new tree and delete the old one immediately        // if we are reprocessing everything we don't need to copy any old event and we can just work with the new tree and delete the old one immediately
500        //        //
501        reprocall = true;        reprocall = true;
502        //        //
503        if (verbose) printf("\n OrbitalInfo - WARNING: Reprocessing all runs\n");        if (verbose) printf("\n OrbitalInfo - WARNING: Reprocessing all runs\n Deleting old tree...\n");
504        //        //
505      } else {      } else {
506        //        //
# Line 249  int OrbitalInfoCore(ULong64_t run, TFile Line 508  int OrbitalInfoCore(ULong64_t run, TFile
508        //        //
509        reprocall = false;        reprocall = false;
510        //        //
511        if (verbose) printf("\n OrbitalInfo - WARNING: Reprocessing run number %llu \n",run);        if (verbose) printf("\n OrbitalInfo - WARNING: Reprocessing run number %u \n",run);
512        //        //
513        // copying old tree to a new file        // copying old tree to a new file
514        //        //
515          gSystem->MakeDirectory(OrbitalInfofolder.str().c_str());
516          myfold = true;
517        tempfile = new TFile(tempname.str().c_str(),"RECREATE");        tempfile = new TFile(tempname.str().c_str(),"RECREATE");
518        tempOrbitalInfo = OrbitalInfotrclone->CloneTree(-1,"fast");        tempOrbitalInfo = OrbitalInfotrclone->CloneTree(-1,"fast");
519        tempOrbitalInfo->SetName("OrbitalInfo-old");        tempOrbitalInfo->SetName("OrbitalInfo-old");
520        tempfile->Write();        tempfile->Write();
521          tempOrbitalInfo->Delete();
522        tempfile->Close();          tempfile->Close();  
523      }      }
524      //      //
525      // Delete the old tree from old file and memory      // Delete the old tree from old file and memory
526      //      //
527        OrbitalInfotrclone->Clear();
528      OrbitalInfotrclone->Delete("all");      OrbitalInfotrclone->Delete("all");
529      //      //
530      if (verbose) printf(" ...done!\n");      if (verbose) printf(" ...done!\n");
# Line 272  int OrbitalInfoCore(ULong64_t run, TFile Line 535  int OrbitalInfoCore(ULong64_t run, TFile
535    //    //
536    file->cd();    file->cd();
537    OrbitalInfotr = new TTree("OrbitalInfo-new","PAMELA OrbitalInfo data");    OrbitalInfotr = new TTree("OrbitalInfo-new","PAMELA OrbitalInfo data");
538      OrbitalInfotr->SetAutoSave(900000000000000LL);
539      orbitalinfo->Set();//ELENA **TEMPORANEO?**
540    OrbitalInfotr->Branch("OrbitalInfo","OrbitalInfo",&orbitalinfo);    OrbitalInfotr->Branch("OrbitalInfo","OrbitalInfo",&orbitalinfo);
541    //    //
542    if ( reproc && !reprocall ){    if ( reproc && !reprocall ){
# Line 280  int OrbitalInfoCore(ULong64_t run, TFile Line 545  int OrbitalInfoCore(ULong64_t run, TFile
545      //      //
546      tempfile = new TFile(tempname.str().c_str(),"READ");      tempfile = new TFile(tempname.str().c_str(),"READ");
547      OrbitalInfotrclone = (TTree*)tempfile->Get("OrbitalInfo-old");      OrbitalInfotrclone = (TTree*)tempfile->Get("OrbitalInfo-old");
548        OrbitalInfotrclone->SetAutoSave(900000000000000LL);
549      OrbitalInfotrclone->SetBranchAddress("OrbitalInfo",&orbitalinfoclone);      OrbitalInfotrclone->SetBranchAddress("OrbitalInfo",&orbitalinfoclone);
550      //            //      
551      if ( nobefrun > 0 ){      if ( nobefrun > 0 ){
552        if (verbose){        if (verbose){
553        printf("\n Pre-processing: copying events from the old tree before the processed run\n");            printf("\n Pre-processing: copying events from the old tree before the processed run\n");  
554        printf(" Copying %u events in the file which are before the beginning of the run %llu \n",nobefrun,run);          printf(" Copying %u events in the file which are before the beginning of the run %u \n",nobefrun,run);
555        printf(" Start copying at event number 0, end copying at event number %u \n",nobefrun);          printf(" Start copying at event number 0, end copying at event number %u \n",nobefrun);
556        }        }
557        for (UInt_t j = 0; j < nobefrun; j++){        for (UInt_t j = 0; j < nobefrun; j++){
558          //          //
559          OrbitalInfotrclone->GetEntry(j);                    if ( OrbitalInfotrclone->GetEntry(j) <= 0 ) throw -36;    
560          //          //
561          // copy orbitalinfoclone to mydec          // copy orbitalinfoclone to mydec
562          //          //
563          orbitalinfo = new OrbitalInfo();          orbitalinfo->Clear();
564            //
565          memcpy(&orbitalinfo,&orbitalinfoclone,sizeof(orbitalinfoclone));          memcpy(&orbitalinfo,&orbitalinfoclone,sizeof(orbitalinfoclone));
566          //          //
567          // Fill entry in the new tree          // Fill entry in the new tree
# Line 303  int OrbitalInfoCore(ULong64_t run, TFile Line 570  int OrbitalInfoCore(ULong64_t run, TFile
570          //          //
571        };        };
572        if (verbose) printf(" Finished successful copying!\n");        if (verbose) printf(" Finished successful copying!\n");
573      };                };
574    };    };
575    //    //
576      //
577    // 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.
578    //    //
579    runlist = runinfo->GetRunList();    runlist = runinfo->GetRunList();
# Line 313  int OrbitalInfoCore(ULong64_t run, TFile Line 581  int OrbitalInfoCore(ULong64_t run, TFile
581    // Loop over the run to be processed    // Loop over the run to be processed
582    //    //
583    for (UInt_t irun=0; irun < numbofrun; irun++){    for (UInt_t irun=0; irun < numbofrun; irun++){
584    
585        L_QQ_Q_l_lower = new Quaternions();
586        RYPang_lower = new InclinationInfo();
587        L_QQ_Q_l_upper = new Quaternions();
588        RYPang_upper = new InclinationInfo();
589    
590      //      //
591      // retrieve the first run ID to be processed using the RunInfo list      // retrieve the first run ID to be processed using the RunInfo list
592      //      //
593        
594      idRun = runlist->At(irun);      idRun = runlist->At(irun);
595      if (verbose){      if (verbose){
596        printf("\n\n\n ####################################################################### \n");        printf("\n\n\n ####################################################################### \n");
# Line 323  int OrbitalInfoCore(ULong64_t run, TFile Line 598  int OrbitalInfoCore(ULong64_t run, TFile
598        printf(" ####################################################################### \n\n\n");        printf(" ####################################################################### \n\n\n");
599      }      }
600      //      //
601      runinfo->ID_REG_RUN = 0ULL;      runinfo->ID_ROOT_L0 = 0;
602      //      //
603      // store in the runinfo class the GL_RUN variables for our run      // store in the runinfo class the GL_RUN variables for our run
604      //      //
605      sgnl = 0;      sgnl = 0;
606      sgnl = runinfo->GetRunInfo(idRun);      sgnl = runinfo->GetRunInfo(idRun);
607      if ( sgnl ){      if ( sgnl ){
608        //printf("\n OrbitalInfo - ERROR: RunInfo exited with non-zero status\n");        if ( debug ) printf("\n OrbitalInfo - ERROR: RunInfo exited with non-zero status\n");
609        code = sgnl;        code = sgnl;
610        goto closeandexit;        goto closeandexit;
611      } else {      } else {
# Line 339  int OrbitalInfoCore(ULong64_t run, TFile Line 614  int OrbitalInfoCore(ULong64_t run, TFile
614      //      //
615      // now you can access that variables using the RunInfo class this way runinfo->ID_REG_RUN      // now you can access that variables using the RunInfo class this way runinfo->ID_REG_RUN
616      //      //
617      if ( runinfo->ID_REG_RUN == 0 ){      if ( runinfo->ID_ROOT_L0 == 0 ){
618        //printf("\n OrbitalInfo - ERROR: no run with ID_RUN = %i \n\n Exiting... \n\n",(int)idRun);        if ( debug ) printf("\n OrbitalInfo - ERROR: no run with ID_RUN = %u \n\n Exiting... \n\n",idRun);
619        code = -5;        code = -5;
620        goto closeandexit;            goto closeandexit;    
621      };      };
622      //      //
623        // prepare the timesync for the db
624        //
625        dbtime = new GL_TIMESYNC(runinfo->ID_ROOT_L0,"ID",dbc);
626      
627        //
628      // Search in the DB the path and name of the LEVEL0 file to be processed.      // Search in the DB the path and name of the LEVEL0 file to be processed.
629      //      //
630      glroot->Query_GL_ROOT(runinfo->ID_REG_RUN,dbc);      glroot->Query_GL_ROOT(runinfo->ID_ROOT_L0,dbc);
631      //      //
632      ftmpname.str("");      ftmpname.str("");
633      ftmpname << glroot->PATH.Data() << "/";      ftmpname << glroot->PATH.Data() << "/";
634      ftmpname << glroot->NAME.Data();      ftmpname << glroot->NAME.Data();
635      fname = ftmpname.str().c_str();      fname = ftmpname.str().c_str();
636        ftmpname.str("");
637      //      //
638      // print out informations      // print nout informations
639      //      //
640      totevent = runinfo->EV_REG_PHYS_TO - runinfo->EV_REG_PHYS_FROM + 1;      totevent = runinfo->NEVENTS;
641        evfrom = runinfo->EV_FROM;
642        //cout<<"totevents = "<<totevent<<"\n";
643      if (verbose){      if (verbose){
644        printf("\n LEVEL0 data file: %s \n",fname.Data());        printf("\n LEVEL0 data file: %s \n",fname.Data());
645        printf(" RUN HEADER absolute time is:  %llu \n",runinfo->RUNHEADER_TIME);        printf(" RUN HEADER absolute time is:  %u \n",runinfo->RUNHEADER_TIME);
646        printf(" RUN TRAILER absolute time is: %llu \n",runinfo->RUNTRAILER_TIME);        printf(" RUN TRAILER absolute time is: %u \n",runinfo->RUNTRAILER_TIME);
647        printf(" %i events to be processed for run %llu: from %i to %i (reg entries)\n\n",totevent,idRun,runinfo->EV_REG_PHYS_FROM,runinfo->EV_REG_PHYS_TO);        printf(" %i events to be processed for run %u: from %i to %i \n\n",totevent,idRun,runinfo->EV_FROM+1,runinfo->EV_FROM+totevent);
648      }//      }//
649        //
650        //    if ( !totevent ) goto closeandexit;
651      // Open Level0 file      // Open Level0 file
652        if ( l0File ) l0File->Close();
653      l0File = new TFile(fname.Data());      l0File = new TFile(fname.Data());
654      if ( !l0File ) {      if ( !l0File ) {
655        //printf(" OrbitalInfo - ERROR: problems opening Level0 file\n");        if ( debug ) printf(" OrbitalInfo - ERROR: problems opening Level0 file\n");
656        code = -6;        code = -6;
657        goto closeandexit;        goto closeandexit;
658      };      };
659      l0tr = (TTree*)l0File->Get("Physics");      l0tr = (TTree*)l0File->Get("Physics");
660      if ( !l0tr ) {      if ( !l0tr ) {
661        //printf(" OrbitalInfo - ERROR: no Physics tree in Level0 file\n");        if ( debug ) printf(" OrbitalInfo - ERROR: no Physics tree in Level0 file\n");
662        l0File->Close();        l0File->Close();
663        code = -7;        code = -7;
664        goto closeandexit;        goto closeandexit;
665      };      };
666      l0registry = l0tr->GetBranch("Registry");      // EM: open header branch as well
667      if ( !l0registry ) {      l0head = l0tr->GetBranch("Header");
668        //printf(" OrbitalInfo - ERROR: no Registry branch in Level0 tree\n");      if ( !l0head ) {
669          if ( debug ) printf(" OrbitalInfo - ERROR: no Header branch in Level0 tree\n");
670        l0File->Close();        l0File->Close();
671        code = -9;        code = -8;
672        goto closeandexit;            goto closeandexit;    
673      };      };
674        l0tr->SetBranchAddress("Header", &eh);
675        // end EM
676        nevents = l0head->GetEntries();
677      //      //
678      l0tr->SetBranchAddress("Registry", &l0reg);      if ( nevents < 1 && totevent ) {
679      //        if ( debug ) printf(" OrbitalInfo - ERROR: Level0 file is empty\n\n");
     nevents = l0registry->GetEntries();  
     //  
     if ( nevents < 1 ) {  
       //printf(" OrbitalInfo - ERROR: Level0 file is empty\n\n");  
680        l0File->Close();        l0File->Close();
681        code = -11;        code = -11;
682        goto closeandexit;        goto closeandexit;
683      };      };
684      //      //
685      if ( runinfo->EV_REG_PHYS_TO > nevents-1 ) {      if ( runinfo->EV_TO > nevents-1 && totevent ) {
686        //printf(" OrbitalInfo - ERROR: too few entries in the registry tree\n");        if ( debug ) printf(" OrbitalInfo - ERROR: too few entries in the registry tree\n");
687        l0File->Close();        l0File->Close();
688        code = -12;        code = -12;
689        goto closeandexit;        goto closeandexit;
690      };      };
691    
692        //
693        // open IGRF files and do it only once if we are processing a full level2 file
694        //
695        if ( !igrfloaded ){
696    
697          if ( l0head->GetEntry(runinfo->EV_FROM) > 0 ){
698            igrfloaded = true;
699            //
700            // absolute time of first event of the run (it should not matter a lot)
701            //
702            ph = eh->GetPscuHeader();
703            atime = dbtime->DBabsTime(ph->GetOrbitalTime());
704            
705            parerror=glparam->Query_GL_PARAM(atime-anni5,301,dbc); // parameters stored in DB in GL_PRAM table  
706            if ( parerror<0 ) {
707              code = parerror;
708              goto closeandexit;
709            }
710            ltp1 = (Int_t)(glparam->PATH+glparam->NAME).Length();
711            if ( verbose ) printf(" Reading Earth's Magnetic Field parameter file: %s \n",(glparam->PATH+glparam->NAME).Data());
712            //
713            parerror=glparam2->Query_GL_PARAM(atime,301,dbc); // parameters stored in DB in GL_PRAM table  
714            if ( parerror<0 ) {
715              code = parerror;
716              goto closeandexit;
717            }
718            ltp2 = (Int_t)(glparam2->PATH+glparam2->NAME).Length();
719            if ( verbose ) printf(" Reading Earth's Magnetic Field parameter file: %s \n",(glparam2->PATH+glparam2->NAME).Data());
720            //
721            parerror=glparam3->Query_GL_PARAM(atime,302,dbc); // parameters stored in DB in GL_PRAM table
722            if ( parerror<0 ) {
723              code = parerror;
724              goto closeandexit;
725            }
726            ltp3 = (Int_t)(glparam3->PATH+glparam3->NAME).Length();
727            if ( verbose ) printf(" Reading Earth's Magnetic Field parameter file: %s \n",(glparam3->PATH+glparam3->NAME).Data());
728            //
729            initize_((char *)(glparam->PATH+glparam->NAME).Data(),&ltp1,(char *)(glparam2->PATH+glparam2->NAME).Data(),&ltp2,(char *)(glparam3->PATH+glparam3->NAME).Data(),&ltp3);
730            //
731            if (debug) cout<<"initize: "<<(char *)(glparam->PATH+glparam->NAME).Data()<<"\t"<<(char *)(glparam2->PATH+glparam2->NAME).Data()<<"\t"<<(char *)(glparam3->PATH+glparam3->NAME).Data()<<endl;
732          }
733        }
734        //
735        // End IGRF stuff//
736        //
737    
738        //
739        //     TTree *tp = (TTree*)l0File->Get("RunHeader");
740        //     tp->SetBranchAddress("Header", &eH);
741        //     tp->SetBranchAddress("RunHeader", &reh);
742        //     tp->GetEntry(0);
743        //     ph = eH->GetPscuHeader();
744        //     ULong_t TimeSync = reh->LAST_TIME_SYNC_INFO;
745        //     ULong_t ObtSync = reh->OBT_TIME_SYNC;    
746        //     if ( debug ) printf(" 1 TimeSync %lu ObtSync %lu DeltaOBT %lu\n",TimeSync,ObtSync,TimeSync-ObtSync);
747        //
748        ULong_t TimeSync = (ULong_t)dbtime->GetTimesync();
749        ULong_t ObtSync = (ULong_t)(dbtime->GetObt0()/1000);
750        ULong_t DeltaOBT = TimeSync - ObtSync;
751    
752        if ( debug ) printf(" 2 TimeSync %lu ObtSync %lu DeltaOBT %lu\n",(ULong_t)(dbtime->GetTimesync()/1000),(ULong_t)dbtime->GetObt0(),TimeSync-ObtSync);
753        //
754        // Read MCMDs from up to 11 files, 5 before and 5 after the present one in order to have some kind of inclination information
755        //
756        ch = new TChain("Mcmd","Mcmd");
757        //
758        // look in the DB to find the closest files to this run
759        //
760        TSQLResult *pResult = 0;
761        TSQLRow *Row = 0;
762        stringstream myquery;
763        UInt_t l0fid[10];
764        Int_t i = 0;
765        memset(l0fid,0,10*sizeof(Int_t));
766        //
767        myquery.str("");
768        myquery << "select ID_ROOT_L0 from GL_RUN where RUNHEADER_TIME<=" << runinfo->RUNHEADER_TIME << " group by ID_ROOT_L0 order by RUNHEADER_TIME desc limit 5;";
769        //
770        pResult = dbc->Query(myquery.str().c_str());
771        //
772        i = 9;
773        if( pResult ){
774          //
775          Row = pResult->Next();
776          //
777          while ( Row ){
778            //
779            // store infos and exit
780            //
781            l0fid[i] = (UInt_t)atoll(Row->GetField(0));
782            i--;
783            Row = pResult->Next();  
784            //
785          };
786          pResult->Delete();
787        };
788        //
789        myquery.str("");
790        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;";
791        //
792        pResult = dbc->Query(myquery.str().c_str());
793        //
794        i = 0;
795        if( pResult ){
796          //
797          Row = pResult->Next();
798          //
799          while ( Row ){
800            //
801            // store infos and exit
802            //
803            l0fid[i] = (UInt_t)atoll(Row->GetField(0));
804            i++;
805            Row = pResult->Next();  
806            //
807          };
808          pResult->Delete();
809        };
810        //
811        i = 0;
812        UInt_t previd = 0;
813        while ( i < 10 ){
814          if ( l0fid[i] && previd != l0fid[i] ){
815            previd = l0fid[i];
816            myquery.str("");
817            myquery << "select PATH,NAME from GL_ROOT where ID=" << l0fid[i] << " ;";
818            //
819            pResult = dbc->Query(myquery.str().c_str());
820            //
821            if( pResult ){
822              //
823              Row = pResult->Next();
824              //
825              if ( debug ) printf(" Using inclination informations from file: %s \n",(((TString)gSystem->ExpandPathName(Row->GetField(0)))+"/"+(TString)Row->GetField(1)).Data());
826              ch->Add(((TString)gSystem->ExpandPathName(Row->GetField(0)))+"/"+(TString)Row->GetField(1));
827              //
828              pResult->Delete();
829            };
830          };
831          i++;
832        };
833        //
834        //    l0trm = (TTree*)l0File->Get("Mcmd");
835        //    ch->ls();
836        ch->SetBranchAddress("Mcmd",&mcmdev);
837        //    printf(" entries %llu \n", ch->GetEntries());
838        //    l0trm = ch->GetTree();
839        //    neventsm = l0trm->GetEntries();
840        neventsm = ch->GetEntries();
841        if ( debug ) printf(" entries %u \n", neventsm);
842        //    neventsm = 0;
843        //
844        if (neventsm == 0){
845          if ( debug ) printf("InclinationInfo - WARNING: No quaternions in this File");
846          //      l0File->Close();
847          code = 900;
848          //      goto closeandexit;
849        }
850        //
851        
852        //    l0trm->SetBranchAddress("Mcmd", &mcmdev);
853        //    l0trm->SetBranchAddress("Header", &eh);
854        //
855        //
856        //
857    
858    //    UInt_t mctren = 0;    
859    //    UInt_t mcreen = 0;        
860    //    UInt_t numrec = 0;
861        //
862        //    Double_t upperqtime = 0;
863        Double_t lowerqtime = 0;
864        
865        //    Double_t incli = 0;
866        //    oi = 0;
867        //    UInt_t ooi = 0;
868        //
869        // init quaternions information from mcmd-packets
870        //
871        Bool_t isf = true;
872        //    Int_t fgh = 0;
873    
874        vector<Float_t> q0;
875        vector<Float_t> q1;
876        vector<Float_t> q2;
877        vector<Float_t> q3;
878        vector<Double_t> qtime;
879        vector<Float_t> qPitch;
880        vector<Float_t> qRoll;
881        vector<Float_t> qYaw;
882        vector<Int_t> qmode;
883    
884        Int_t nt = 0;
885        
886        UInt_t must = 0;
887    
888      //      //
889      // run over all the events of the run      // run over all the events of the run
890      //      //
891      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");
892      //      //
893      for ( re = runinfo->EV_REG_PHYS_FROM; re <= runinfo->EV_REG_PHYS_TO; re++){      //
894        for ( re = runinfo->EV_FROM; re < (runinfo->EV_FROM+runinfo->NEVENTS); re++){
895        //        //
896        if ( procev%1000 == 0 && procev > 0 && verbose) printf(" %iK \n",procev/1000);            if ( procev%1000 == 0 && procev > 0 && verbose ) printf(" %iK \n",procev/1000);  
897          if ( debug ) printf(" %i \n",procev);      
898        //        //
899        l0registry->GetEntry(re);        if ( l0head->GetEntry(re) <= 0 ) throw -36;
900        //        //
901        // absolute time of this event        // absolute time of this event
902        //        //
903        atime = l0reg->absTime;        ph = eh->GetPscuHeader();
904        //        atime = dbtime->DBabsTime(ph->GetOrbitalTime());
905        // physics events is at entry number ei where        if ( debug ) printf(" %i absolute time \n",procev);      
       //  
       ei = l0reg->event;  
906        //        //
907        // paranoid check        // paranoid check
908        //        //
909        if ( (atime > runinfo->RUNTRAILER_TIME) || (atime < runinfo->RUNHEADER_TIME)  ) {        if ( (atime > (runinfo->RUNTRAILER_TIME+1)) || (atime < (runinfo->RUNHEADER_TIME-1))  ) {
910          if (verbose) printf(" OrbitalInfo - WARNING: event at time outside the run time window, skipping it\n");          if (verbose) printf(" OrbitalInfo - WARNING: event at time outside the run time window, skipping it\n");
911          goto jumpev;          jumped++;
912            //      debug = true;
913            continue;
914          }
915    
916          //
917          // retrieve tof informations
918          //
919          if ( !reprocall ){
920            itr = nobefrun + (re - evfrom - jumped);
921            //itr = re-(46438+200241);
922          } else {
923            itr = runinfo->GetFirstEntry() + (re - evfrom - jumped);
924        };        };
925        //        //
926          if ( !standalone ){
927            if ( itr > nevtofl2 ){  
928              if ( verbose ) printf(" OrbitalInfo - ERROR: no tof events with entry = %i in Level2 file\n",itr);
929              if ( debug ) printf(" nobefrun %u re %u evfrom %u jumped %u reprocall %i \n",nobefrun,re,evfrom,jumped,reprocall);
930              l0File->Close();
931              code = -904;
932              goto closeandexit;
933            };
934            //
935            tof->Clear();
936            //
937            if ( ttof->GetEntry(itr) <= 0 ){
938             if ( verbose ) printf(" problems with tof tree entries... entry = %i in Level2 file\n",itr);
939             if ( verbose ) printf(" nobefrun %u re %u evfrom %u jumped %u reprocall %i \n",nobefrun,re,evfrom,jumped,reprocall);
940             throw -36;
941            }
942            //
943          }
944          //
945          // retrieve tracker informations
946          //
947          if ( !standalone ){
948            if ( itr > nevtrkl2 ){  
949              if ( verbose ) printf(" OrbitalInfo - ERROR: no trk events with entry = %i in Level2 file\n",itr);
950              if ( debug ) printf(" nobefrun %u re %u evfrom %u jumped %u reprocall %i \n",nobefrun,re,evfrom,jumped,reprocall);
951              l0File->Close();
952              code = -905;
953              goto closeandexit;
954            };
955            //
956            trke->Clear();
957            //
958            if ( ttrke->GetEntry(itr) <= 0 ) throw -36;
959            //
960          }
961    
962    
963          //
964        procev++;        procev++;
965        //        //
966        // start processing        // start processing
967        //        //
968        orbitalinfo = new OrbitalInfo();        if ( debug ) printf(" %i start processing \n",procev);      
969        orbitalinfo->absTime = l0reg->absTime;        orbitalinfo->Clear();
970          //
971          OrbitalInfoTrkVar *t_orb = new OrbitalInfoTrkVar();
972          if( !(orbitalinfo->OrbitalInfoTrk) ) orbitalinfo->OrbitalInfoTrk = new TClonesArray("OrbitalInfoTrkVar",2);
973          TClonesArray &tor = *orbitalinfo->OrbitalInfoTrk;
974    
975          // Geomagnetic coordinates calculation variables
976          GMtype_CoordSpherical CoordSpherical, DipoleSpherical;
977          GMtype_CoordCartesian CoordCartesian, DipoleCartesian;
978          GMtype_Model Model;
979          GMtype_Pole Pole;
980    
981          //
982          // Fill OBT, pkt_num and absTime
983          //      
984          orbitalinfo->pkt_num = ph->GetCounter();
985          orbitalinfo->OBT = ph->GetOrbitalTime();
986          orbitalinfo->absTime = atime;
987          if ( debug ) printf(" %i pktnum obt abstime \n",procev);      
988          //
989          // Propagate the orbit from the tle time to atime, using SGP(D)4.
990          //
991          if ( debug ) printf(" %i sgp4 \n",procev);      
992          cCoordGeo coo;
993          Float_t jyear=0.;    
994          //
995          if(atime >= gltle->GetToTime()) {
996            if ( !gltle->Query(atime, dbc) ){
997              //      
998              // Compute the magnetic dipole moment.
999              //
1000              if ( debug ) printf(" %i compute magnetic dipole moment \n",procev);      
1001              UInt_t year, month, day, hour, min, sec;
1002              //
1003              TTimeStamp t = TTimeStamp(atime, kTRUE);
1004              t.GetDate(kTRUE, 0, &year, &month, &day);
1005              t.GetTime(kTRUE, 0, &hour, &min, &sec);
1006              jyear = (float) year
1007                + (month*31.+ (float) day)/365.
1008                + (hour*3600.+min*60.+(float)sec)/(24.*3600.*365.);
1009              //
1010              if ( debug ) printf(" %i compute magnetic dipole moment get dipole moment for year\n",procev);            
1011              if ( debug ) printf(" %i jyear %f dimo %f \n",procev,jyear,dimo);
1012              feldcof_(&jyear, &dimo); // get dipole moment for year
1013              if ( debug ) printf(" %i compute magnetic dipole moment end\n",procev);
1014    
1015              GM_TimeAdjustCoefs(year, jyear, G0, G1, H1, &Model);
1016              GM_PoleLocation(Model, &Pole);
1017              
1018            } else {
1019              code = -56;
1020              goto closeandexit;
1021            };
1022          }
1023          coo = getCoo(atime, gltle->GetFromTime(), gltle->GetTle());
1024          //
1025          cOrbit orbits(*gltle->GetTle());
1026          //
1027          // synchronize with quaternions data
1028          //
1029          if ( isf && neventsm>0 ){
1030            //
1031            // First event
1032            //
1033            isf = false;
1034            //      upperqtime = atime;
1035            lowerqtime = runinfo->RUNHEADER_TIME;
1036            for ( ik = 0; ik < neventsm; ik++){  //number of macrocommad packets
1037              if ( ch->GetEntry(ik) <= 0 ) throw -36;
1038              tmpSize = mcmdev->Records->GetEntries();
1039              //      numrec = tmpSize;
1040              if ( debug ) cout << "packet number " << ik <<"\tnumber of subpackets is " << tmpSize << endl;
1041              for (Int_t j3 = 0;j3<tmpSize;j3++){  //number of subpackets
1042                mcmdrc = (pamela::McmdRecord*)mcmdev->Records->At(j3);
1043                if ( mcmdrc ){ // missing inclination bug [8RED 090116]
1044                  if ( debug ) printf(" pluto \n");
1045                  if ((int)mcmdrc->ID1 == 226 && mcmdrc->Mcmd_Block_crc_ok == 1){ //Check that it is Inclination Packet
1046                   L_QQ_Q_l_upper->fill(mcmdrc->McmdData);
1047                    for (UInt_t ui = 0; ui < 6; ui++){
1048                      if (ui>0){
1049                        if (L_QQ_Q_l_upper->time[ui]>L_QQ_Q_l_upper->time[0]){
1050                          if ( debug ) printf(" here1 %i \n",ui);
1051                          Double_t u_time = dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[ui]*1000-DeltaOBT*1000));
1052                          Int_t recSize = recqtime.size();
1053                          if(lowerqtime > recqtime[recSize-1]){
1054                             // to avoid interpolation between bad quaternions arrays
1055                             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){
1056                              Int_t sizeqmcmd = qtime.size();
1057                              inclresize(qtime,q0,q1,q2,q3,qmode,qRoll,qPitch,qYaw);
1058                              qtime[sizeqmcmd]=u_time;
1059                              q0[sizeqmcmd]=L_QQ_Q_l_upper->quat[ui][0];
1060                              q1[sizeqmcmd]=L_QQ_Q_l_upper->quat[ui][1];
1061                              q2[sizeqmcmd]=L_QQ_Q_l_upper->quat[ui][2];
1062                              q3[sizeqmcmd]=L_QQ_Q_l_upper->quat[ui][3];
1063                              qmode[sizeqmcmd]=holeq(lowerqtime,qtime[sizeqmcmd],L_QQ_Q_l_lower,L_QQ_Q_l_upper,ui);
1064                              lowerqtime = u_time;
1065                              orbits.getPosition((double) (u_time - gltle->GetFromTime())/60., &eCi);
1066                              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]);
1067                              qRoll[sizeqmcmd]=RYPang_upper->Kren;
1068                              qYaw[sizeqmcmd]=RYPang_upper->Ryskanie;
1069                              qPitch[sizeqmcmd]=RYPang_upper->Tangazh;
1070                             }
1071                          }
1072                          for(Int_t mu = nt;mu<recSize;mu++){
1073                            if(recqtime[mu]>lowerqtime && recqtime[mu]<u_time){
1074                              if(sqrt(pow(recq0[mu],2)+pow(recq1[mu],2)+pow(recq2[mu],2)+pow(recq3[mu],2))>0.99999){
1075                                nt=mu;
1076                                Int_t sizeqmcmd = qtime.size();
1077                                inclresize(qtime,q0,q1,q2,q3,qmode,qRoll,qPitch,qYaw);
1078                                qtime[sizeqmcmd]=recqtime[mu];
1079                                q0[sizeqmcmd]=recq0[mu];
1080                                q1[sizeqmcmd]=recq1[mu];
1081                                q2[sizeqmcmd]=recq2[mu];
1082                                q3[sizeqmcmd]=recq3[mu];
1083                                qmode[sizeqmcmd]=-10;
1084                                orbits.getPosition((double) (qtime[sizeqmcmd] - gltle->GetFromTime())/60., &eCi);
1085                                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]);
1086                                qRoll[sizeqmcmd]=RYPang_upper->Kren;
1087                                qYaw[sizeqmcmd]=RYPang_upper->Ryskanie;
1088                                qPitch[sizeqmcmd]=RYPang_upper->Tangazh;
1089                              }
1090                            }
1091                            if(recqtime[mu]>=u_time){
1092                              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){
1093                                Int_t sizeqmcmd = qtime.size();
1094                                inclresize(qtime,q0,q1,q2,q3,qmode,qRoll,qPitch,qYaw);
1095                                qtime[sizeqmcmd]=u_time;
1096                                q0[sizeqmcmd]=L_QQ_Q_l_upper->quat[ui][0];
1097                                q1[sizeqmcmd]=L_QQ_Q_l_upper->quat[ui][1];
1098                                q2[sizeqmcmd]=L_QQ_Q_l_upper->quat[ui][2];
1099                                q3[sizeqmcmd]=L_QQ_Q_l_upper->quat[ui][3];
1100                                qmode[sizeqmcmd]=holeq(lowerqtime,qtime[sizeqmcmd],L_QQ_Q_l_lower,L_QQ_Q_l_upper,ui);
1101                                lowerqtime = u_time;
1102                                orbits.getPosition((double) (u_time - gltle->GetFromTime())/60., &eCi);
1103                                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]);
1104                                qRoll[sizeqmcmd]=RYPang_upper->Kren;
1105                                qYaw[sizeqmcmd]=RYPang_upper->Ryskanie;
1106                                qPitch[sizeqmcmd]=RYPang_upper->Tangazh;
1107                                break;
1108                              }
1109                            }
1110                          }
1111                        }
1112                      }else{
1113                        if ( debug ) printf(" here2 %i \n",ui);
1114                        Double_t u_time = dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));
1115                        if(lowerqtime>u_time)nt=0;
1116                        Int_t recSize = recqtime.size();
1117                        if(lowerqtime > recqtime[recSize-1]){
1118                          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){
1119                            Int_t sizeqmcmd = qtime.size();
1120                            inclresize(qtime,q0,q1,q2,q3,qmode,qRoll,qPitch,qYaw);
1121                            qtime[sizeqmcmd]=u_time;
1122                            q0[sizeqmcmd]=L_QQ_Q_l_upper->quat[0][0];
1123                            q1[sizeqmcmd]=L_QQ_Q_l_upper->quat[0][1];
1124                            q2[sizeqmcmd]=L_QQ_Q_l_upper->quat[0][2];
1125                            q3[sizeqmcmd]=L_QQ_Q_l_upper->quat[0][3];
1126                            qmode[sizeqmcmd]=holeq(lowerqtime,qtime[sizeqmcmd],L_QQ_Q_l_lower,L_QQ_Q_l_upper,ui);
1127                            lowerqtime = u_time;
1128                            orbits.getPosition((double) (u_time - gltle->GetFromTime())/60., &eCi);
1129                            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]);
1130                            qRoll[sizeqmcmd]=RYPang_upper->Kren;
1131                            qYaw[sizeqmcmd]=RYPang_upper->Ryskanie;
1132                            qPitch[sizeqmcmd]=RYPang_upper->Tangazh;
1133                          }
1134                        }
1135                        for(Int_t mu = nt;mu<recSize;mu++){
1136                          if(recqtime[mu]>lowerqtime && recqtime[mu]<u_time){
1137                             if(sqrt(pow(recq0[mu],2)+pow(recq1[mu],2)+pow(recq2[mu],2)+pow(recq3[mu],2))>0.99999){
1138                               nt=mu;
1139                               Int_t sizeqmcmd = qtime.size();
1140                               inclresize(qtime,q0,q1,q2,q3,qmode,qRoll,qPitch,qYaw);
1141                               qtime[sizeqmcmd]=recqtime[mu];
1142                               q0[sizeqmcmd]=recq0[mu];
1143                               q1[sizeqmcmd]=recq1[mu];
1144                               q2[sizeqmcmd]=recq2[mu];
1145                               q3[sizeqmcmd]=recq3[mu];
1146                               qmode[sizeqmcmd]=-10;
1147                               orbits.getPosition((double) (qtime[sizeqmcmd] - gltle->GetFromTime())/60., &eCi);
1148                               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]);
1149                               qRoll[sizeqmcmd]=RYPang_upper->Kren;
1150                               qYaw[sizeqmcmd]=RYPang_upper->Ryskanie;
1151                               qPitch[sizeqmcmd]=RYPang_upper->Tangazh;
1152                             }
1153                          }
1154                          if(recqtime[mu]>=u_time){
1155                             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){
1156                               Int_t sizeqmcmd = qtime.size();
1157                               inclresize(qtime,q0,q1,q2,q3,qmode,qRoll,qPitch,qYaw);
1158                               qtime[sizeqmcmd]=u_time;
1159                               q0[sizeqmcmd]=L_QQ_Q_l_upper->quat[0][0];
1160                               q1[sizeqmcmd]=L_QQ_Q_l_upper->quat[0][1];
1161                               q2[sizeqmcmd]=L_QQ_Q_l_upper->quat[0][2];
1162                               q3[sizeqmcmd]=L_QQ_Q_l_upper->quat[0][3];
1163                               qmode[sizeqmcmd]=holeq(lowerqtime,qtime[sizeqmcmd],L_QQ_Q_l_lower,L_QQ_Q_l_upper,ui);
1164                               lowerqtime = u_time;
1165                               orbits.getPosition((double) (u_time - gltle->GetFromTime())/60., &eCi);
1166                               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]);
1167                               qRoll[sizeqmcmd]=RYPang_upper->Kren;
1168                               qYaw[sizeqmcmd]=RYPang_upper->Ryskanie;
1169                               qPitch[sizeqmcmd]=RYPang_upper->Tangazh;
1170                               CopyQ(L_QQ_Q_l_lower,L_QQ_Q_l_upper);
1171                               break;
1172                             }
1173                          }
1174                        }
1175                      }
1176                    }
1177                  }
1178                }
1179                //if ( debug ) cout << "subpacket " << j3 << "\t qtime = " << qtime[qtime.size()-1] << endl;
1180              }
1181            }
1182            
1183            if(qtime.size()==0){                            // in case if no orientation information in data
1184              if ( debug ) cout << "qtime.size() = 0" << endl;
1185              for(UInt_t my=0;my<recqtime.size();my++){
1186                if(sqrt(pow(recq0[my],2)+pow(recq1[my],2)+pow(recq2[my],2)+pow(recq3[my],2))>0.99999){
1187                  Int_t sizeqmcmd = qtime.size();
1188                  inclresize(qtime,q0,q1,q2,q3,qmode,qRoll,qPitch,qYaw);
1189                  qtime[sizeqmcmd]=recqtime[my];
1190                  q0[sizeqmcmd]=recq0[my];
1191                  q1[sizeqmcmd]=recq1[my];
1192                  q2[sizeqmcmd]=recq2[my];
1193                  q3[sizeqmcmd]=recq3[my];
1194                  qmode[sizeqmcmd]=-10;
1195                  orbits.getPosition((double) (qtime[sizeqmcmd] - gltle->GetFromTime())/60., &eCi);
1196                  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]);
1197                  qRoll[sizeqmcmd]=RYPang_upper->Kren;
1198                  qYaw[sizeqmcmd]=RYPang_upper->Ryskanie;
1199                  qPitch[sizeqmcmd]=RYPang_upper->Tangazh;
1200                }
1201              }
1202            }
1203            
1204    
1205            if ( debug ) printf(" puffi \n");
1206            Double_t tmin = 9999999999.;
1207            Double_t tmax = 0.;
1208            for(UInt_t tre = 0;tre<qtime.size();tre++){
1209              if(qtime[tre]>tmax)tmax = qtime[tre];
1210              if(qtime[tre]<tmin)tmin = qtime[tre];
1211            }
1212            // sorting quaternions by time
1213           Bool_t t = true;
1214            while(t){
1215             t=false;
1216              for(UInt_t i=0;i<qtime.size()-1;i++){
1217                if(qtime[i]>qtime[i+1]){
1218                  Double_t tmpr = qtime[i];
1219                  qtime[i]=qtime[i+1];
1220                  qtime[i+1] = tmpr;
1221                  tmpr = q0[i];
1222                  q0[i]=q0[i+1];
1223                  q0[i+1] = tmpr;
1224                  tmpr = q1[i];
1225                  q1[i]=q1[i+1];
1226                  q1[i+1] = tmpr;
1227                  tmpr = q2[i];
1228                  q2[i]=q2[i+1];
1229                  q2[i+1] = tmpr;
1230                  tmpr = q3[i];
1231                  q3[i]=q3[i+1];
1232                  q3[i+1] = tmpr;
1233                  tmpr = qRoll[i];
1234                  qRoll[i]=qRoll[i+1];
1235                  qRoll[i+1] = tmpr;
1236                  tmpr = qYaw[i];
1237                  qYaw[i]=qYaw[i+1];
1238                  qYaw[i+1] = tmpr;
1239                  tmpr = qPitch[i];
1240                  qPitch[i]=qPitch[i+1];
1241                  qPitch[i+1] = tmpr;
1242                    t=true;
1243                }
1244              }
1245            }
1246    
1247            if ( debug ){
1248              cout << "we have loaded quaternions: size of quaternions set is "<< qtime.size() << endl;
1249             for(UInt_t i=0;i<qtime.size();i++) cout << qtime[i] << "\t";
1250              cout << endl << endl;
1251              Int_t lopu;
1252              cin >> lopu;
1253           }
1254    
1255          } // if we processed first event
1256    
1257          
1258          //Filling Inclination information
1259          Double_t incli = 0;
1260          if ( qtime.size() > 1 ){
1261            if ( debug ) cout << "ok quaternions is exist and mu = " << must << endl;
1262            if ( debug ) cout << "qtimes[ " << qtime[0] << " , " << qtime[qtime.size()-1] << " ]\tatime = "<<atime<<endl;
1263            for(UInt_t mu = must;mu<qtime.size()-1;mu++){
1264              if ( debug ) printf(" ??grfuffi %i sixe %i must %i \n",mu,qtime.size()-1,must);
1265              if(qtime[mu+1]>qtime[mu]){
1266                if ( debug ) cout << "qtime[" << mu << "] = " << qtime[mu] << "\tqtime[" << mu+1 << "] = " << qtime[mu+1] << "\tatime = " << atime << endl;
1267                if(atime<=qtime[mu+1] && atime>=qtime[mu]){
1268                  if ( debug ) cout << "here we have found proper quaternions for interpolation: mu = "<<mu<<endl;
1269                  must = mu;
1270                  incli = (qPitch[mu+1]-qPitch[mu])/(qtime[mu+1]-qtime[mu]);
1271                  orbitalinfo->theta =  incli*atime+qPitch[mu+1]-incli*qtime[mu+1];
1272                  incli = (qRoll[mu+1]-qRoll[mu])/(qtime[mu+1]-qtime[mu]);
1273                  orbitalinfo->etha =  incli*atime+qRoll[mu+1]-incli*qtime[mu+1];
1274                  incli = (qYaw[mu+1]-qYaw[mu])/(qtime[mu+1]-qtime[mu]);
1275                  orbitalinfo->phi =  incli*atime+qYaw[mu+1]-incli*qtime[mu+1];
1276                  
1277                  incli = (q0[mu+1]-q0[mu])/(qtime[mu+1]-qtime[mu]);
1278                  orbitalinfo->q0 =  incli*atime+q0[mu+1]-incli*qtime[mu+1];
1279                  incli = (q1[mu+1]-q1[mu])/(qtime[mu+1]-qtime[mu]);
1280                  orbitalinfo->q1 =  incli*atime+q1[mu+1]-incli*qtime[mu+1];
1281                  incli = (q2[mu+1]-q2[mu])/(qtime[mu+1]-qtime[mu]);
1282                  orbitalinfo->q2 =  incli*atime+q2[mu+1]-incli*qtime[mu+1];
1283                  incli = (q3[mu+1]-q3[mu])/(qtime[mu+1]-qtime[mu]);
1284                  orbitalinfo->q3 =  incli*atime+q3[mu+1]-incli*qtime[mu+1];
1285                  Float_t tg = (qtime[mu+1]-qtime[mu])/1000.;
1286                  if(tg>=1) tg=0.00;
1287                  orbitalinfo->TimeGap = TMath::Min(TMath::Abs(qtime[mu+1])-atime,TMath::Abs(atime-qtime[mu]))+tg;//qtime[mu+1]-qtime[mu];
1288                  orbitalinfo->mode = qmode[mu+1];
1289                  
1290                  //if(atime==qtime[mu] || atime==qtime[mu+1]) orbitalinfo->qkind = 0; else orbitalinfo->qkind=1;
1291                  //if(qmode[mu+1]==-10) orbitalinfo->R10r = true;else orbitalinfo->R10r = false;
1292                  if ( debug ) printf(" grfuffi4 %i \n",mu);
1293                  
1294                  break;
1295                }
1296              }
1297            }
1298          }
1299          if ( debug ) printf(" grfuffi5  \n");
1300          //
1301          // ops no inclination information
1302          //
1303          
1304          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 ){
1305            if ( debug ) cout << "ops no iclination information" << endl;
1306            orbitalinfo->mode = 10;
1307            orbitalinfo->q0 = -1000.;
1308            orbitalinfo->q1 = -1000.;
1309            orbitalinfo->q2 = -1000.;
1310            orbitalinfo->q3 = -1000.;
1311            orbitalinfo->etha = -1000.;
1312            orbitalinfo->phi = -1000.;
1313            orbitalinfo->theta = -1000.;
1314            orbitalinfo->TimeGap = -1000.;
1315            //orbitalinfo->qkind = -1000;
1316            
1317            //      if ( debug ){
1318            //        Int_t lopu;
1319            //         cin >> lopu;
1320            //      }
1321            if ( debug ) printf(" grfuffi6 \n");
1322          }
1323          //
1324          if ( debug ) printf(" filling \n");
1325          // #########################################################################################################################  
1326          //
1327          // fill orbital positions
1328          //        
1329          // Build coordinates in the right range.  We want to convert,
1330          // longitude from (0, 2*pi) to (-180deg, 180deg).  Altitude is
1331          // in meters.
1332          lon = (coo.m_Lon > M_PI) ? rad2deg(coo.m_Lon - 2*M_PI) : rad2deg(coo.m_Lon);
1333          lat = rad2deg(coo.m_Lat);
1334          alt = coo.m_Alt;
1335    
1336          cOrbit orbits2(*gltle->GetTle());
1337          orbits2.getPosition((double) (atime - gltle->GetFromTime())/60., &eCi);
1338          //      Float_t x=eCi.getPos().m_x;
1339          //      Float_t y=eCi.getPos().m_y;
1340          //      Float_t z=eCi.getPos().m_z;
1341          
1342          TVector3 V(eCi.getVel().m_x,eCi.getVel().m_y,eCi.getVel().m_z);
1343          TVector3 Pos(eCi.getPos().m_x,eCi.getPos().m_y,eCi.getPos().m_z);
1344          
1345          Float_t dlon=Pos.Phi()*TMath::RadToDeg()-lon;
1346          
1347          Pos.RotateZ(-dlon*TMath::DegToRad());
1348          V.RotateZ(-dlon*TMath::DegToRad());
1349          Float_t diro;
1350          if(V.Z()>0) diro=1; else diro=-1;
1351          
1352          // 10REDNEW
1353          Int_t errq=0;
1354          Int_t azim=0;;
1355          for(UInt_t mu = must;mu<RTtime2.size()-1;mu++){
1356            if(atime<=RTtime2[mu] && atime>=RTtime1[mu]){
1357              errq=RTerrq[mu];
1358              azim=RTazim[mu];
1359            }
1360          }
1361          orbitalinfo->errq = errq;
1362          orbitalinfo->azim = azim;
1363          orbitalinfo->qkind = 0;
1364          
1365          if ( debug ) printf(" coord done \n");
1366          if( lon<180 && lon>-180 && lat<90 && lat>-90 && alt>0 ){  
1367            //      
1368            orbitalinfo->lon = lon;
1369            orbitalinfo->lat = lat;
1370            orbitalinfo->alt = alt;
1371            orbitalinfo->V = V;
1372    
1373            //      GMtype_CoordGeodetic  location;
1374            location.lambda = lon;
1375            location.phi = lat;
1376            location.HeightAboveEllipsoid = alt;
1377    
1378            GM_GeodeticToSpherical(Ellip, location, &CoordSpherical);
1379            GM_SphericalToCartesian(CoordSpherical,  &CoordCartesian);
1380            GM_EarthCartToDipoleCartCD(Pole, CoordCartesian, &DipoleCartesian);
1381            GM_CartesianToSpherical(DipoleCartesian, &DipoleSpherical);
1382            orbitalinfo->londip = DipoleSpherical.lambda;
1383            orbitalinfo->latdip = DipoleSpherical.phig;
1384    
1385            if(debug)cout<<"geodetic:\t"<<lon<<"\t"<<lat<<"\tgeomagnetic:\t"<<orbitalinfo->londip<<"\t"<<orbitalinfo->latdip<<endl;
1386    
1387            //
1388            // compute mag field components and L shell.
1389            //
1390            if ( debug ) printf(" call igrf feldg \n");
1391            feldg_(&lat, &lon, &alt, &bnorth, &beast, &bdown, &babs);
1392            if ( debug ) printf(" call igrf shellg \n");
1393            shellg_(&lat, &lon, &alt, &dimo, &xl, &icode, &bab1);
1394            if ( debug ) printf(" call igrf findb \n");
1395            findb0_(&stps, &bdel, &value, &bequ, &rr0);
1396            //
1397            if ( debug ) printf(" done igrf \n");
1398            orbitalinfo->Bnorth = bnorth;
1399            orbitalinfo->Beast = beast;
1400            orbitalinfo->Bdown = bdown;
1401            orbitalinfo->Babs = babs;
1402            orbitalinfo->M = dimo;
1403            orbitalinfo->BB0 = babs/bequ;
1404            orbitalinfo->L = xl;      
1405            // Set Stormer vertical cutoff using L shell.
1406            orbitalinfo->cutoffsvl = 14.295 / (xl*xl); //
1407            if(debug)cout << "L = " << xl << "\tM = " << dimo << "\tvertical cutoff:  "<< orbitalinfo->cutoffsvl << endl;
1408    
1409            /*
1410              ---------- Forwarded message ----------
1411              Date: Wed, 09 May 2012 12:16:47 +0200
1412              From: Alessandro Bruno <alessandro.bruno@ba.infn.it>
1413              To: Mirko Boezio <mirko.boezio@ts.infn.it>
1414              Cc: Francesco S. Cafagna <Francesco.Cafagna@ba.infn.it>
1415              Subject: Störmer vertical cutoff
1416    
1417              Ciao Mirko,
1418              volevo segnalarti che il valore dello Störmer vertical cutoff nel Level2 è
1419              sovrastimato di circa il 4%.
1420              Dopo un'approfondita analisi con l'IGRF-05 abbiamo ricavano un valore pari
1421              a: 14.295 / L^2 anzichè 14.9 / L^2, valore obsoleto in quanto riferito agli
1422              anni '50.
1423            */
1424            //14.9/(xl*xl);
1425            orbitalinfo->igrf_icode = icode;
1426            //
1427          }      
1428          //
1429          if ( debug ) printf(" pitch angle \n");
1430          //
1431          // pitch angles
1432          //
1433          if( orbitalinfo->TimeGap>0){
1434            //
1435            if ( debug ) printf(" timegap %f \n",orbitalinfo->TimeGap);
1436            Float_t Bx = -orbitalinfo->Bdown;
1437            Float_t By = orbitalinfo->Beast;
1438            Float_t Bz = orbitalinfo->Bnorth;
1439    
1440            TMatrixD Qiji(3,3);
1441            TMatrixD Qij = PO->QuatoECI(orbitalinfo->q0,orbitalinfo->q1,orbitalinfo->q2,orbitalinfo->q3);
1442            TMatrixD Dij = PO->ECItoGEO(Qij,orbitalinfo->absTime,orbitalinfo->lat,orbitalinfo->lon);
1443    
1444    //10REDNEW
1445            /* If initial orientation data have reason to be inaccurate */
1446            Double_t tg = 0;
1447            cout<<modf(orbitalinfo->TimeGap,&tg)<<endl;
1448    //      if(orbitalinfo->TimeGap>0 && errq==0 && azim==0){               // 10RED CHECK  (comparison between three metod of recovering orientation)
1449            if(((orbitalinfo->TimeGap>60.0 && TMath::Abs(orbitalinfo->etha)>0.5) || errq!=0 || modf(orbitalinfo->TimeGap,&tg)*1000>700 || modf(orbitalinfo->TimeGap,&tg)*1000==0.0 ) && azim==0){           //Standard condition to use this;               One of these two cases should be commented
1450            /*  found in Rotation Table this data for this time interval*/
1451            if(atime<RTtime1[0])
1452              orbitalinfo->azim = 5;        //means that RotationTable no started yet
1453           else{
1454              for(UInt_t mu = must;mu<RTtime2.size()-1;mu++){
1455                if(atime<=RTtime2[mu] && atime>=RTtime1[mu]){
1456                    // search for angle betwean velosity and direction to north in tangential to Earth surfase plane in satellite position
1457                  Double_t tlat=orbitalinfo->lat;
1458    /*            Double_t phint=(163.7-0.0002387*tlat-0.005802*tlat*tlat-0.005802e-7*tlat*tlat*tlat-1.776e-6*tlat*tlat*tlat*tlat+1.395e-10*tlat*tlat*tlat*tlat*tlat);
1459                  Double_t phin=TMath::Abs(90.0*(1+diro)-phint);
1460                  Double_t phi=TMath::Abs(90.0*(1-diro)-TMath::RadToDeg()*atan(TMath::Abs(tan(TMath::DegToRad()*phin))/sqrt(1+pow(tan(TMath::DegToRad()*tlat),2))));
1461                      
1462                    //Get vectors of Satellite reference frame axis in GEO in satndard case (No rotations, all Euler angles equals to 0)
1463                  TVector3 XDij(0,sin(TMath::DegToRad()*phi),cos(TMath::DegToRad()*phi));
1464                  TVector3 YDij(1,0,0);
1465                  TVector3 ZDij(0,sin(TMath::DegToRad()*(phi+90)),cos(TMath::DegToRad()*(phi+90.0)));
1466    
1467                    //Get Vectors to rotate about
1468                  TVector3 B1 = V;
1469                  B1.RotateZ(-lon*TMath::DegToRad());
1470                  B1.RotateY(lat*TMath::DegToRad());
1471                  Float_t elipangle=TMath::ACos((pow(B1.Y(),2)+pow(B1.Z(),2))/B1.Mag()/sqrt(pow(B1.Y(),2)+pow(B1.Z(),2)));
1472                  TVector3 Tre(0,B1.Y(),B1.Z());
1473                  if(B1.X()<0) elipangle=-elipangle;
1474                  TVector3 Vperp=B1;                // axis to rotate around initial Dij on ellip and spitch angles
1475                  Vperp.RotateX(TMath::Pi()/2.);
1476                  Vperp.SetX(0);
1477    */            Double_t kar=(RTbank2[mu]-RTbank1[mu])/(RTtime2[mu]-RTtime1[mu]);
1478                  Double_t bak=RTbank1[mu]-kar*RTtime1[mu];
1479                  Double_t bank=kar*atime+bak;
1480                  Float_t spitch = 0.00001;  // temprary not zero to avoid problem with tranzition from Euler angles to orientation matrix
1481    
1482                    //Estimations of pitch angle of satellite
1483                  if(TMath::Abs(bank)>0.7){
1484                     Float_t spitch1=TMath::DegToRad()*0.7*RTdir1[mu];
1485                     Float_t spitch2=TMath::DegToRad()*0.7*RTdir2[mu];
1486                     Float_t kva=(spitch2-spitch1)/(RTtime2[mu]-RTtime1[mu]);
1487                     Float_t bva=spitch1-kva*RTtime1[mu];
1488                     spitch=kva*atime+bva;
1489                  }
1490    /*            //spitch=0.0;
1491                  //Rotations future Dij matrix on ellip and spitch angles
1492                  XDij.Rotate(-elipangle-spitch,Vperp);
1493                  YDij.Rotate(-elipangle-spitch,Vperp);
1494                  ZDij.Rotate(-elipangle-spitch,Vperp);
1495                    
1496                    //Rotation on bank angle;
1497                  if(TMath::Abs(bank)>0.5){
1498                     XDij.Rotate(TMath::DegToRad()*bank,B1);
1499                     YDij.Rotate(TMath::DegToRad()*bank,B1);
1500                     ZDij.Rotate(TMath::DegToRad()*bank,B1);
1501                  }
1502                  Dij(0,0)=XDij.X(); Dij(1,0)=XDij.Y(); Dij(2,0)=XDij.Z();
1503                  Dij(0,1)=YDij.X(); Dij(1,1)=YDij.Y(); Dij(2,1)=YDij.Z();
1504                  Dij(0,2)=ZDij.X(); Dij(1,2)=ZDij.Y(); Dij(2,2)=ZDij.Z();
1505    */
1506                  //Calculate Yaw angle accordingly with fit, see picture FitYaw.jpg
1507                  Double_t yaw=0.00001;  // temprary not zero to avoid problem with tranzition from Euler angles to orientation matrix
1508                  if(TMath::Abs(tlat)<70)
1509                        yaw = -3.7e-8*tlat*tlat*tlat*tlat + 1.4e-7*tlat*tlat*tlat - 0.0005*tlat*tlat - 0.00025*tlat + 3.6;
1510                  yaw = diro*yaw;   //because should be different sign for ascending and descending orbits!
1511    
1512                  if(TMath::Abs(bank)>0.5 && TMath::Abs(yaw-orbitalinfo->phi)<3.0) yaw=orbitalinfo->phi;
1513    
1514    //            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
1515                  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
1516                  orbitalinfo->qkind = 1;
1517    
1518                  break;
1519                }
1520              }     // enf of  loop for(UInt_t mu = must;mu<RTtime2.size()-1;mu++){
1521    
1522              //Qij = PO->GEOtoECI(Dij,orbitalinfo->absTime,orbitalinfo->lat,orbitalinfo->lon); // to convert from Dij to Qij
1523    
1524            } // end of if(atime<RTtime1[0]
1525            } // end of f(((orbitalinfo->TimeGap>60.0 && TMath...
1526    
1527            TMatrixD qij = PO->ColPermutation(Qij);
1528            TMatrixD Fij = PO->ECItoGreenwich(Qij,orbitalinfo->absTime);
1529            TMatrixD Gij = PO->ColPermutation(Fij);
1530            Dij = PO->ECItoGEO(Qij,orbitalinfo->absTime,orbitalinfo->lat,orbitalinfo->lon);
1531            TMatrixD Iij = PO->ColPermutation(Dij);
1532            TVector3 SP = PO->GetSunPosition(orbitalinfo->absTime);
1533            // go to Pamela reference frame from Resurs reference frame
1534            Float_t tmpy = SP.Y();
1535            SP.SetY(SP.Z());
1536            SP.SetZ(-tmpy);
1537            TVector3 SunZenith;
1538            SunZenith.SetMagThetaPhi(1,23.439281*TMath::DegToRad(),TMath::Pi()/2.);
1539            TVector3 SunMag = -SP;
1540            SunMag.Rotate(-45*TMath::DegToRad(),SunZenith);
1541            tmpy=SunMag.Y();
1542            SunMag.SetY(SunMag.Z());
1543            SunMag.SetZ(-tmpy);
1544    
1545            orbitalinfo->Iij.ResizeTo(Iij);
1546            orbitalinfo->Iij = Iij;
1547            //
1548            //      A1 = Iij(0,2);
1549            //      A2 = Iij(1,2);
1550            //      A3 = Iij(2,2);
1551            //
1552            //      orbitalinfo->pamzenitangle = (Float_t)PO->GetPitchAngle(1,0,0,A1,A2,A3);                        // Angle between zenit and Pamela's main axiz
1553            //      orbitalinfo->pamBangle = (Float_t)PO->GetPitchAngle(A1,A2,A3,Bx,By,Bz);                 // Angle between Pamela's main axiz and B
1554            //
1555            if ( debug ) printf(" matrixes done  \n");
1556            if ( !standalone && tof->ntrk() > 0 ){
1557              if ( debug ) printf(" !standalone \n");
1558              //
1559              Int_t nn = 0;
1560              for(Int_t nt=0; nt < tof->ntrk(); nt++){  
1561                //
1562                ToFTrkVar *ptt = tof->GetToFTrkVar(nt);
1563                if (debug) cout<<"tof->ntrk() = "<<tof->ntrk()<<"\tptt->trkseqno = "<<ptt->trkseqno<<"\ttrke->ntrk() = "<<trke->ntrk()<<endl;
1564                Double_t E11x = ptt->xtr_tof[0]; // tr->x[0];
1565                Double_t E11y = ptt->ytr_tof[0]; //tr->y[0];
1566                Double_t E11z = zin[0];
1567                Double_t E22x = ptt->xtr_tof[3];//tr->x[3];
1568                Double_t E22y = ptt->ytr_tof[3];//tr->y[3];
1569                Double_t E22z = zin[3];
1570                if ( (E11x < 100. && E11y < 100. && E22x < 100. && E22y < 100.) || ptt->trkseqno != -1  ){
1571                  TrkTrack *mytrack = trke->GetStoredTrack(ptt->trkseqno);
1572                  Float_t rig=1/mytrack->GetDeflection();
1573                  Double_t norm = sqrt(pow(E22x-E11x,2)+pow(E22y-E11y,2)+pow(E22z-E11z,2));
1574                  //              Double_t MyAzim = TMath::RadToDeg()*atan(TMath::Abs(E22y-E11y)/TMath::Abs(E22x-E11x));
1575                  //              if(E22x-E11x>=0 && E22y-E11y <0) MyAzim =  360. - MyAzim;
1576                  //              if(E22x-E11x>=0 && E22y-E11y >=0) MyAzim = MyAzim;
1577                  //              if(E22x-E11x<0 && E22y-E11y >0) MyAzim = 180. - MyAzim;
1578                  //              if(E22x-E11x<0 && E22y-E11y <0) MyAzim = 180. + MyAzim;
1579                  Px = (E22x-E11x)/norm;
1580                  Py = (E22y-E11y)/norm;
1581                  Pz = (E22z-E11z)/norm;
1582                  //
1583                  t_orb->trkseqno = ptt->trkseqno;
1584                  //
1585                  TMatrixD Eij = PO->PamelatoGEO(Iij,Px,Py,Pz);
1586                  t_orb->Eij.ResizeTo(Eij);
1587                  t_orb->Eij = Eij;
1588                  //
1589                  TMatrixD Sij = PO->PamelatoGEO(Gij,Px,Py,Pz);
1590                  t_orb->Sij.ResizeTo(Sij);
1591                  t_orb->Sij = Sij;
1592                  //            
1593                  t_orb->pitch = (Float_t)PO->GetPitchAngle(Eij(0,0),Eij(1,0),Eij(2,0),Bx,By,Bz);
1594                  //
1595                    // SunPosition in instrumental reference frame
1596                  TMatrixD Kij = PO->PamelatoGEO(qij,Px,Py,Pz);
1597                  TMatrixD Lij = PO->PamelatoGEO(qij,0,0,1);
1598                  t_orb->sunangle=(Float_t)PO->GetPitchAngle(Kij(0,0),Kij(1,0),Kij(2,0),-SP.X(),-SP.Y(),-SP.Z());
1599                  t_orb->sunmagangle=(Float_t)PO->GetPitchAngle(Kij(0,0),Kij(1,0),Kij(2,0),SunMag.X(),SunMag.Y(),SunMag.Z());
1600    
1601                  //
1602                  //
1603                  //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);
1604                  Double_t omega = PO->GetPitchAngle(-Eij(0,0),-Eij(1,0),-Eij(2,0),1,0,0) * TMath::DegToRad();
1605                  TVector3 Bxy(0,By,Bz);
1606                  TVector3 Exy(0,-Eij(1,0),-Eij(2,0));
1607                  Double_t dzeta=Bxy.Angle(Exy);
1608                  if (-Eij(1,0) < 0) dzeta=2.0*TMath::Pi() - dzeta;
1609    
1610                    if(debug) cout << "omega = "<<omega*TMath::RadToDeg()<<"\tdzeta = "<<dzeta*TMath::RadToDeg()<<endl;
1611    
1612                    // Formula from D.F. Smart *, M.A. Shea [2005]; A review of geomagnetic cutoff rigidities for earth-orbiting spacecraft
1613                  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));
1614                  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));
1615                  if (debug) cout << "R = " << rig << "\tcutoff = " << t_orb->cutoff << endl;
1616    
1617                  //t_orb->cutoff = 59.3/(pow(orbitalinfo->L,2)*pow((1+sqrt(1-pow(orbitalinfo->L,-3/2)*cos(omega))),2));
1618    
1619                  //
1620                  if ( t_orb->pitch != t_orb->pitch ) t_orb->pitch = -1000.;
1621                  if ( t_orb->cutoff != t_orb->cutoff ) t_orb->cutoff = -1000.;
1622                  if ( t_orb->sunangle != t_orb->sunangle ) t_orb->sunangle = -1000.;
1623                  if ( t_orb->sunmagangle != t_orb->sunmagangle ) t_orb->sunmagangle = -1000.;
1624                  //
1625                  if ( debug ) printf(" orbitalinfo->cutoffsvl %f vitaly %f \n",orbitalinfo->cutoffsvl,t_orb->cutoff);
1626                  //
1627                  new(tor[nn]) OrbitalInfoTrkVar(*t_orb);
1628                  nn++;
1629                  //
1630                  t_orb->Clear();
1631                  //
1632                };
1633                //
1634              };
1635            } else {
1636              if ( debug ) printf(" mmm... mode %u standalone  \n",orbitalinfo->mode);
1637            }
1638            //
1639          } else {
1640            if ( !standalone && tof->ntrk() > 0 ){
1641              //
1642              Int_t nn = 0;
1643              for(Int_t nt=0; nt < tof->ntrk(); nt++){  
1644                //
1645                ToFTrkVar *ptt = tof->GetToFTrkVar(nt);
1646                if ( ptt->trkseqno != -1  ){
1647                  //
1648                  t_orb->trkseqno = ptt->trkseqno;
1649                  //
1650                  t_orb->Eij = 0;  
1651                  //
1652                  t_orb->Sij = 0;
1653                  //            
1654                  t_orb->pitch = -1000.;
1655                  //
1656                  t_orb->sunangle = -1000.;
1657                  //
1658                  t_orb->sunmagangle = -1000;
1659                  //
1660                  t_orb->cutoff = -1000.;
1661                  //
1662                  new(tor[nn]) OrbitalInfoTrkVar(*t_orb);
1663                  nn++;
1664                  //
1665                  t_orb->Clear();
1666                  //
1667                };
1668                //
1669              };    
1670            };
1671          };        // if( orbitalinfo->TimeGap>0){
1672          //
1673          // Fill the class
1674          //
1675        OrbitalInfotr->Fill();        OrbitalInfotr->Fill();
       //      
1676        //        //
1677      jumpev:        delete t_orb;
       debug = false;  
1678        //        //
1679      };      }; // loop over the events in the run
1680      //      //
1681      // Here you may want to clear some variables before processing another run        // Here you may want to clear some variables before processing another run  
1682      //      //
1683      ei = 0;  
1684        if ( verbose ) printf(" Clear before new run \n");
1685        delete dbtime;
1686    
1687        if ( mcmdrc ) mcmdrc->Clear();
1688        mcmdrc = 0;
1689        
1690        if ( verbose ) printf(" Clear before new run1 \n");
1691        if ( L_QQ_Q_l_lower ) delete L_QQ_Q_l_lower;
1692        if ( verbose ) printf(" Clear before new run2 \n");
1693        if ( L_QQ_Q_l_upper ) delete L_QQ_Q_l_upper;
1694        if ( verbose ) printf(" Clear before new run3 \n");
1695        if ( RYPang_upper ) delete RYPang_upper;
1696        if ( verbose ) printf(" Clear before new run4 \n");
1697        if ( RYPang_lower ) delete RYPang_lower;
1698    
1699        if ( l0tr ) l0tr->Delete();
1700        
1701        if ( verbose ) printf(" End run \n");
1702    
1703    }; // process all the runs    }; // process all the runs
1704    //    
1705    if (verbose) printf("\n Finished processing data \n");    if (verbose) printf("\n Finished processing data \n");
1706    //    //
1707   closeandexit:   closeandexit:
# Line 464  int OrbitalInfoCore(ULong64_t run, TFile Line 1719  int OrbitalInfoCore(ULong64_t run, TFile
1719          //          //
1720          // Get entry from old tree          // Get entry from old tree
1721          //          //
1722          OrbitalInfotrclone->GetEntry(j);                    if ( OrbitalInfotrclone->GetEntry(j) <= 0 ) throw -36;    
1723          //          //
1724          // copy orbitalinfoclone to OrbitalInfo          // copy orbitalinfoclone to OrbitalInfo
1725          //          //
1726          orbitalinfo = new OrbitalInfo();          orbitalinfo->Clear();
1727            //
1728          memcpy(&orbitalinfo,&orbitalinfoclone,sizeof(orbitalinfoclone));          memcpy(&orbitalinfo,&orbitalinfoclone,sizeof(orbitalinfoclone));
1729          //          //
1730          // Fill entry in the new tree          // Fill entry in the new tree
# Line 477  int OrbitalInfoCore(ULong64_t run, TFile Line 1733  int OrbitalInfoCore(ULong64_t run, TFile
1733        };        };
1734        if (verbose) printf(" Finished successful copying!\n");        if (verbose) printf(" Finished successful copying!\n");
1735      };      };
1736        //if ( OrbitalInfotrclone )    OrbitalInfotrclone->Clear();        
1737        //if ( OrbitalInfotrclone )    OrbitalInfotrclone->Delete();        
1738    };    };
1739    //    //
1740    // Close files, delete old tree(s), write and close level2 file    // Close files, delete old tree(s), write and close level2 file
1741    //    //
   if ( l0File ) l0File->Close();  
   if ( tempfile ) tempfile->Close();              
   gSystem->Unlink(tempname.str().c_str());  
1742    
1743    //if ( code < 0 ) printf("\n OrbitalInfo - ERROR: an error occurred, try to save anyway...\n");    if ( l0File ) l0File->Close();
1744    //printf("\n Writing and closing rootple\n");    if ( myfold ) gSystem->Unlink(tempname.str().c_str());
1745    if ( runinfo ) runinfo->Close();        //
1746    if ( OrbitalInfotr ) OrbitalInfotr->SetName("OrbitalInfo");        if ( OrbitalInfotr ) OrbitalInfotr->SetName("OrbitalInfo");    
1747      //
1748    if ( file ){    if ( file ){
1749      file->cd();      file->cd();
1750      file->Write();      if ( OrbitalInfotr ) OrbitalInfotr->Write("OrbitalInfo", TObject::kOverwrite); // 10 RED bug fixed
1751    };    };
1752    //    //
1753    gSystem->Unlink(OrbitalInfofolder.str().c_str());    if (verbose) printf("\n Exiting...\n");
1754    
1755      if ( myfold ) gSystem->Unlink(OrbitalInfofolder.str().c_str());
1756    //    //
1757    // the end    // the end
1758    //    //
1759      if ( dbc ){
1760        dbc->Close();
1761        delete dbc;
1762      };
1763      //
1764    if (verbose) printf("\n Exiting...\n");    if (verbose) printf("\n Exiting...\n");
1765    if(OrbitalInfotr)OrbitalInfotr->Delete();    if ( tempfile ) tempfile->Close();            
1766      
1767      if ( PO ) delete PO;
1768      if ( gltle ) delete gltle;
1769      if ( glparam ) delete glparam;
1770      if ( glparam2 ) delete glparam2;
1771      if ( glparam3 ) delete glparam3;
1772      if (verbose) printf("\n Exiting3...\n");
1773      if ( glroot ) delete glroot;
1774      if (verbose) printf("\n Exiting4...\n");
1775      if ( runinfo ) runinfo->Close();    
1776      if ( runinfo ) delete runinfo;
1777    
1778      if ( tof ) delete tof;
1779      if ( trke ) delete trke;
1780    
1781      if ( debug ){  
1782      cout << "1   0x" << OrbitalInfotr << endl;
1783      cout << "2   0x" << OrbitalInfotrclone << endl;
1784      cout << "3   0x" << l0tr << endl;
1785      cout << "4   0x" << tempOrbitalInfo << endl;
1786      cout << "5   0x" << ttof << endl;
1787      }
1788      //
1789      if ( debug )  file->ls();
1790      //
1791    if(code < 0)  throw code;    if(code < 0)  throw code;
1792    return(code);    return(code);
1793  }  }
1794    
1795    
1796    //
1797    // Returns the cCoordGeo structure holding the geographical
1798    // coordinates for the event (see sgp4.h).
1799    //
1800    // atime is the abstime of the event in UTC unix time.
1801    // tletime is the time of the tle in UTC unix time.
1802    // tle is the previous and nearest tle (compared to atime).
1803    cCoordGeo getCoo(UInt_t atime, UInt_t tletime, cTle *tle)
1804    {
1805      cEci eci;
1806      cOrbit orbit(*tle);
1807      orbit.getPosition((double) (atime - tletime)/60., &eci);
1808      
1809      return eci.toGeo();
1810    }
1811    
1812    // function of copyng of quatrnions classes
1813    
1814    void CopyQ(Quaternions *Q1, Quaternions *Q2){
1815      for(UInt_t i = 0; i < 6; i++){
1816        Q1->time[i]=Q2->time[i];
1817        for (UInt_t j = 0; j < 4; j++)Q1->quat[i][j]=Q2->quat[i][j];
1818      }
1819      return;
1820    }
1821    
1822    // functions of copyng InclinationInfo classes
1823    
1824    void CopyAng(InclinationInfo *A1, InclinationInfo *A2){
1825      A1->Tangazh = A2->Tangazh;
1826      A1->Ryskanie = A2->Ryskanie;
1827      A1->Kren = A2->Kren;
1828      return;
1829    }
1830    
1831    UInt_t holeq(Double_t lower,Double_t upper,Quaternions *Qlower, Quaternions *Qupper, UInt_t f){
1832      
1833      UInt_t hole = 10;
1834      Bool_t R10l = false;     // Sign of R10 mode in lower quaternions array
1835      Bool_t R10u = false;     // Sign of R10 mode in upper quaternions array
1836      Bool_t insm = false;     // Sign that we inside quaternions array
1837      //  Bool_t mxtml = false;    // Sign of mixt mode in lower quaternions array
1838      //  Bool_t mxtmu = false;    // Sign of mixt mode in upper quaternions array
1839      Bool_t npasm = false;     // Sign of normall pass between R10 and non R10 or between non R10 and R10
1840      UInt_t NCQl = 6;       // Number of correct quaternions in lower array
1841      //  UInt_t NCQu = 6;       // Number of correct quaternions in upper array
1842      if (f>0){
1843        insm = true;
1844        if(Qupper->time[f]-Qupper->time[f-1]==30) R10u = false;
1845        if(Qupper->time[f]-Qupper->time[f-1]<1) R10u = true;
1846      }else{
1847        insm = false;
1848        if((Qlower->time[5]-Qlower->time[0]<2)&&(Qlower->time[1]-Qlower->time[0]<2)) R10l = true;
1849        if((Qupper->time[5]-Qupper->time[0]<2)&&(Qupper->time[1]-Qupper->time[0]<2)) R10u = true;
1850        if((Qlower->time[5]-Qlower->time[0]==150)&&(Qlower->time[1]-Qlower->time[0]==30)) R10l = false;
1851        if((Qupper->time[5]-Qupper->time[0]==150)&&(Qupper->time[1]-Qupper->time[0]==30)) R10u = false;
1852        if((Qlower->time[5]-Qlower->time[0]<2)&&(Qlower->time[1]-Qlower->time[0]==30)){
1853          //      mxtml = true;
1854          for(UInt_t i = 1; i < 6; i++){
1855            if(Qlower->time[i]-Qlower->time[0]==30*i) NCQl=i;
1856          }
1857        }
1858        //    if((Qupper->time[5]-Qupper->time[0]<2)&&(Qupper->time[1]-Qupper->time[0]==30)){
1859          //      mxtmu = true;
1860          //      for(UInt_t i = 1; i < 6; i++){
1861          //        if(Qupper->time[i]-Qupper->time[0]==30*i) NCQu=i;
1862          //      }
1863        //    }
1864      }
1865      
1866      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;
1867      
1868      
1869      if (R10u&&insm) hole=0; // best event R10
1870      if ((upper-lower<=5)&&(!insm)&&R10l&&R10u) hole = 1; // when first of 6 quaternions in array is correct
1871      if (((!R10u)&&insm)||((!insm)&&(!R10u)&&(!R10l)&&((upper-lower==210+(6-NCQl)*30)||(upper-lower==30)))) hole = 2; //non R10
1872      if (npasm&&(!insm)&&((R10l&&!R10u)||(R10u&&!R10l))) hole = 3; //normall pass from R10 to non R10 or from non R10 to R10
1873      if ((!npasm)&&(upper-lower<=300)&&(!insm)&&((R10l&&!R10u)||(R10u&&!R10l))) hole = 4; // eliminable hole between R10 and non R10 or between non R10 and R10
1874      if ((upper-lower>=300)&&(!insm)&&((R10l&&!R10u)||(R10u&&!R10l))) hole = 5; //uneliminable hole between R10 and non R10 or between non R10 and R10
1875      if ((upper-lower>5)&&(upper-lower<=300)&&R10u&&R10l) hole = 6; // eliminable hole inside R10
1876      if ((upper-lower>300)&&R10u&&R10l) hole = 7; //uneliminable hole inside R10
1877      if ((upper-lower>210)&&(upper-lower<=1200)&&(!R10u)&&(!R10l)) hole = 8; //eliminable hole inside non R10
1878      if ((upper-lower>1200)&&!R10u&&!R10l) hole = 9; // uneliminable hole inside non R10
1879      return hole;
1880    }
1881    
1882    void inclresize(vector<Double_t>& t,vector<Float_t>& q0,vector<Float_t>& q1,vector<Float_t>& q2,vector<Float_t>& q3,vector<Int_t>& mode,vector<Float_t>& Roll,vector<Float_t>& Pitch,vector<Float_t>& Yaw){
1883      Int_t sizee = t.size()+1;
1884      t.resize(sizee);
1885      q0.resize(sizee);
1886      q1.resize(sizee);
1887      q2.resize(sizee);
1888      q3.resize(sizee);
1889      mode.resize(sizee);
1890      Roll.resize(sizee);
1891      Pitch.resize(sizee);
1892      Yaw.resize(sizee);
1893    }
1894    
1895    // geomagnetic calculation staff
1896    
1897    //void GM_ScanIGRF(TString PATH, GMtype_Data *G0, GMtype_Data *G1, GMtype_Data *H1)
1898    void GM_ScanIGRF(TSQLServer *dbc, GMtype_Data *G0, GMtype_Data *G1, GMtype_Data *H1)
1899    {
1900      GL_PARAM *glp = new GL_PARAM();
1901      Int_t parerror=glp->Query_GL_PARAM(1,304,dbc); // parameters stored in DB in GL_PRAM table  
1902      if ( parerror<0 ) {
1903        throw -902;
1904      }
1905            /*This function scans inputs G0, G1, and H1 of the IGRF table into 3 data arrays*/
1906      //    TString SATH="/data03/Malakhov/pam9Malakhov/installed10/calib/orb-param/";
1907            int i;
1908            double temp;
1909            char buffer[200];
1910            FILE *IGRF;
1911            IGRF = fopen((glp->PATH+glp->NAME).Data(), "r");
1912            //      IGRF = fopen(PATH+"IGRF.tab", "r");
1913            G0->size = 25;
1914            G1->size = 25;
1915            H1->size = 25;
1916            for( i = 0; i < 4; i++)
1917            {
1918                    fgets(buffer, 200, IGRF);
1919            }
1920            fscanf(IGRF, "g 1 0 %lf ", &G0->element[0]);
1921            for(i = 1; i <= 22; i++)
1922            {
1923                    fscanf(IGRF ,"%lf ", &G0->element[i]);
1924            }
1925            fscanf(IGRF ,"%lf\n", &temp);
1926            G0->element[23] = temp * 5 + G0->element[22];
1927            G0->element[24] = G0->element[23] + 5 * temp;
1928            fscanf(IGRF, "g 1 1 %lf ", &G1->element[0]);
1929            for(i = 1; i <= 22; i++)
1930            {
1931                    fscanf( IGRF, "%lf ", &G1->element[i]);
1932            }
1933            fscanf(IGRF, "%lf\n", &temp);
1934            G1->element[23] = temp * 5 + G1->element[22];
1935            G1->element[24] = temp * 5 + G1->element[23];
1936            fscanf(IGRF, "h 1 1 %lf ", &H1->element[0]);
1937            for(i = 1; i <= 22; i++)
1938            {
1939                    fscanf( IGRF, "%lf ", &H1->element[i]);
1940            }
1941            fscanf(IGRF, "%lf\n", &temp);
1942            H1->element[23] = temp * 5 + H1->element[22];
1943            H1->element[24] = temp * 5 + H1->element[23];
1944      if ( glp ) delete glp;
1945    } /*GM_ScanIGRF*/
1946    
1947    void GM_SetEllipsoid(GMtype_Ellipsoid *Ellip)
1948    {
1949            /*This function sets the WGS84 reference ellipsoid to its default values*/
1950            Ellip->a        =                       6378.137; /*semi-major axis of the ellipsoid in */
1951            Ellip->b        =                       6356.7523142;/*semi-minor axis of the ellipsoid in */
1952            Ellip->fla      =                       1/298.257223563;/* flattening */
1953            Ellip->eps      =                       sqrt(1- ( Ellip->b *    Ellip->b) / (Ellip->a * Ellip->a ));  /*first eccentricity */
1954            Ellip->epssq    =                       (Ellip->eps * Ellip->eps);   /*first eccentricity squared */
1955            Ellip->re       =                       6371.2;/* Earth's radius */
1956    } /*GM_SetEllipsoid*/
1957    
1958    
1959    void GM_EarthCartToDipoleCartCD(GMtype_Pole Pole, GMtype_CoordCartesian EarthCoord, GMtype_CoordCartesian *DipoleCoords)
1960    {
1961            /*This function converts from Earth centered cartesian coordinates to dipole centered cartesian coordinates*/
1962            double X, Y, Z, CosPhi, SinPhi, CosLambda, SinLambda;
1963            CosPhi = cos(TMath::DegToRad()*Pole.phi);
1964            SinPhi = sin(TMath::DegToRad()*Pole.phi);
1965            CosLambda = cos(TMath::DegToRad()*Pole.lambda);
1966            SinLambda = sin(TMath::DegToRad()*Pole.lambda);
1967            X = EarthCoord.x;
1968            Y = EarthCoord.y;
1969            Z = EarthCoord.z;
1970            
1971            /*These equations are taken from a document by Wallace H. Campbell*/
1972            DipoleCoords->x = X * CosPhi * CosLambda + Y * CosPhi * SinLambda - Z * SinPhi;
1973            DipoleCoords->y = -X * SinLambda + Y * CosLambda;
1974            DipoleCoords->z = X * SinPhi * CosLambda + Y * SinPhi * SinLambda + Z * CosPhi;
1975    } /*GM_EarthCartToDipoleCartCD*/
1976    
1977    void GM_GeodeticToSpherical(GMtype_Ellipsoid Ellip, GMtype_CoordGeodetic CoordGeodetic, GMtype_CoordSpherical *CoordSpherical)
1978    {
1979            double CosLat, SinLat, rc, xp, zp; /*all local variables */
1980            /*
1981            ** Convert geodetic coordinates, (defined by the WGS-84
1982            ** reference ellipsoid), to Earth Centered Earth Fixed Cartesian
1983            ** coordinates, and then to spherical coordinates.
1984            */
1985    
1986            CosLat = cos(TMath::DegToRad()*CoordGeodetic.phi);
1987            SinLat = sin(TMath::DegToRad()*CoordGeodetic.phi);
1988    
1989            /* compute the local radius of curvature on the WGS-84 reference ellipsoid */
1990    
1991            rc = Ellip.a / sqrt(1.0 - Ellip.epssq * SinLat * SinLat);
1992    
1993            /* compute ECEF Cartesian coordinates of specified point (for longitude=0) */
1994    
1995            xp = (rc + CoordGeodetic.HeightAboveEllipsoid) * CosLat;
1996            zp = (rc*(1.0 - Ellip.epssq) + CoordGeodetic.HeightAboveEllipsoid) * SinLat;
1997    
1998            /* compute spherical radius and angle lambda and phi of specified point */
1999    
2000            CoordSpherical->r = sqrt(xp * xp + zp * zp);
2001            CoordSpherical->phig = TMath::RadToDeg()*asin(zp / CoordSpherical->r);     /* geocentric latitude */
2002            CoordSpherical->lambda = CoordGeodetic.lambda;                   /* longitude */
2003    } /*GM_GeodeticToSpherical*/
2004    
2005    void GM_PoleLocation(GMtype_Model Model, GMtype_Pole *Pole)
2006    {
2007            /*This function finds the location of the north magnetic pole in spherical coordinates.  The equations are
2008            **from Wallace H. Campbell's Introduction to Geomagnetic Fields*/
2009    
2010            Pole->phi = TMath::RadToDeg()*-atan(sqrt(Model.h1 * Model.h1 + Model.g1 * Model.g1)/Model.g0);
2011            Pole->lambda = TMath::RadToDeg()*atan(Model.h1/Model.g1);
2012    } /*GM_PoleLocation*/
2013    
2014    void GM_SphericalToCartesian(GMtype_CoordSpherical CoordSpherical, GMtype_CoordCartesian *CoordCartesian)
2015    {
2016            /*This function converts spherical coordinates into Cartesian coordinates*/
2017            double CosPhi = cos(TMath::DegToRad()*CoordSpherical.phig);
2018            double SinPhi = sin(TMath::DegToRad()*CoordSpherical.phig);
2019            double CosLambda = cos(TMath::DegToRad()*CoordSpherical.lambda);
2020            double SinLambda = sin(TMath::DegToRad()*CoordSpherical.lambda);
2021            
2022            CoordCartesian->x = CoordSpherical.r * CosPhi * CosLambda;
2023            CoordCartesian->y = CoordSpherical.r * CosPhi * SinLambda;
2024            CoordCartesian->z = CoordSpherical.r * SinPhi;
2025    } /*GM_SphericalToCartesian*/
2026    
2027    void GM_TimeAdjustCoefs(Float_t year, Float_t jyear, GMtype_Data g0d, GMtype_Data g1d, GMtype_Data h1d, GMtype_Model *Model)
2028    {
2029            /*This function calls GM_LinearInterpolation for the coefficients to estimate the value of the
2030            **coefficient for the given date*/
2031            int index;
2032            double x;
2033            index = (year - GM_STARTYEAR) / 5;
2034            x = (jyear - GM_STARTYEAR) / 5;
2035            Model->g0 = GM_LinearInterpolation(index, index+1, g0d.element[index], g0d.element[index+1], x);
2036            Model->g1 = GM_LinearInterpolation(index, index+1, g1d.element[index], g1d.element[index+1], x);
2037            Model->h1 = GM_LinearInterpolation(index, index+1, h1d.element[index], h1d.element[index+1], x);
2038    } /*GM_TimeAdjustCoefs*/
2039    
2040    double GM_LinearInterpolation(double x1, double x2, double y1, double y2, double x)
2041    {
2042            /*This function takes a linear interpolation between two given points for x*/
2043            double weight, y;
2044            weight  = (x - x1) / (x2 - x1);
2045            y = y1 * (1 - weight) + y2 * weight;
2046            return y;
2047    }/*GM_LinearInterpolation*/
2048    
2049    void GM_CartesianToSpherical(GMtype_CoordCartesian CoordCartesian, GMtype_CoordSpherical *CoordSpherical)
2050    {
2051            /*This function converts a point from Cartesian coordinates into spherical coordinates*/
2052            double X, Y, Z;
2053            
2054            X = CoordCartesian.x;
2055            Y = CoordCartesian.y;
2056            Z = CoordCartesian.z;
2057    
2058            CoordSpherical->r = sqrt(X * X + Y * Y + Z * Z);
2059            CoordSpherical->phig = TMath::RadToDeg()*asin(Z / (CoordSpherical->r));
2060            CoordSpherical->lambda = TMath::RadToDeg()*atan2(Y, X);
2061    } /*GM_CartesianToSpherical*/

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

  ViewVC Help
Powered by ViewVC 1.1.23