]> git.uio.no Git - u/mrichter/AliRoot.git/blob - PWG1/ITS/AliAlignmentDataFilterITS.cxx
Reverting commit 47149, it breaks the compilation
[u/mrichter/AliRoot.git] / PWG1 / ITS / AliAlignmentDataFilterITS.cxx
1 /**************************************************************************
2  * Copyright(c) 1998-2009, ALICE Experiment at CERN, All rights reserved. *
3  *                                                                        *
4  * Author: The ALICE Off-line Project.                                    *
5  * Contributors are mentioned in the code where appropriate.              *
6  *                                                                        *
7  * Permission to use, copy, modify and distribute this software and its   *
8  * documentation strictly for non-commercial purposes is hereby granted   *
9  * without fee, provided that the above copyright notice appears in all   *
10  * copies and that both the copyright notice and this permission notice   *
11  * appear in the supporting documentation. The authors make no claims     *
12  * about the suitability of this software for any purpose. It is          *
13  * provided "as is" without express or implied warranty.                  *
14  **************************************************************************/
15
16 /////////////////////////////////////////////////////////////
17 //
18 // AliAnalysisTask to extract from ESD tracks the AliTrackPointArrays
19 // with ITS points for selected tracks. This are the input data for alignment
20 //
21 // Author: A.Dainese, andrea.dainese@pd.infn.it
22 /////////////////////////////////////////////////////////////
23
24 #include <TTree.h>
25 #include <TFile.h>
26 #include <TSystem.h>
27 #include <TChain.h>
28 #include <TNtuple.h>
29 #include <TList.h>
30 #include <TH1F.h>
31 #include <TH2F.h>
32 #include <TMap.h>
33 #include <TVector3.h>
34 #include <TGeoManager.h>
35 #include <TRandom.h>
36
37 #include "AliLog.h"
38 #include "AliCDBEntry.h"
39 #include "AliGeomManager.h"
40 #include "AliITSReconstructor.h"
41 #include "AliITSAlignMille2Module.h"
42 #include "AliITSgeomTGeo.h"
43 #include "AliTrackPointArray.h"
44 #include "AliESDInputHandler.h"
45 #include "AliESDVertex.h"
46 #include "AliESDtrack.h"
47 #include "AliESDEvent.h"
48 #include "AliESDfriend.h"
49 #include "AliAnalysisTaskSE.h"
50 #include "AliAnalysisManager.h"
51 #include "AliAlignmentDataFilterITS.h"
52
53
54 ClassImp(AliAlignmentDataFilterITS)
55
56
57 //________________________________________________________________________
58 AliAlignmentDataFilterITS::AliAlignmentDataFilterITS():
59 AliAnalysisTaskSE(),
60 fOnlySPDFO(kFALSE),
61 fDownsamplelowpt(kFALSE),
62 fGeometryFileName("geometry.root"),
63 fITSRecoParam(0),
64 fESD(0),
65 fListOfHistos(0),
66 fspTree(0),
67 fHistNevents(0),
68 fHistNpoints(0),
69 fHistPt(0),
70 fHistLayer0(0),
71 fHistLayer1(0),
72 fHistLayer2(0),
73 fHistLayer3(0),
74 fHistLayer4(0),
75 fHistLayer5(0),
76 fntExtra(0),
77 fntCosmicMatching(0)
78 {
79   // Constructor
80 }
81
82 //________________________________________________________________________
83 AliAlignmentDataFilterITS::AliAlignmentDataFilterITS(const char *name):
84 AliAnalysisTaskSE(name),
85 fOnlySPDFO(kFALSE),
86 fDownsamplelowpt(kFALSE),
87 fGeometryFileName("geometry.root"),
88 fITSRecoParam(0),
89 fESD(0),
90 fListOfHistos(0),
91 fspTree(0),
92 fHistNevents(0),
93 fHistNpoints(0),
94 fHistPt(0),
95 fHistLayer0(0),
96 fHistLayer1(0),
97 fHistLayer2(0),
98 fHistLayer3(0),
99 fHistLayer4(0),
100 fHistLayer5(0),
101 fntExtra(0),
102 fntCosmicMatching(0)
103 {
104   // Constructor
105
106   // Define output slots here
107
108   // Output slot #1 writes into a TTree
109   DefineOutput(1,TTree::Class());  //My private output
110   // Output slot #2 writes into a TList
111   DefineOutput(2,TList::Class());  //My private output
112 }
113
114 //________________________________________________________________________
115 AliAlignmentDataFilterITS::~AliAlignmentDataFilterITS()
116 {
117   // Destructor
118   if (fListOfHistos) {
119     delete fListOfHistos;
120     fListOfHistos = 0;
121   }
122   if (fspTree) {
123     delete fspTree;
124     fspTree = 0;
125   }
126   if (fHistNevents) {
127     delete fHistNevents;
128     fHistNevents = 0;
129   }
130   if (fHistNpoints) {
131     delete fHistNpoints;
132     fHistNpoints = 0;
133   }
134   if (fHistPt) {
135     delete fHistPt;
136     fHistPt = 0;
137   }
138   if (fHistLayer0) {
139     delete fHistLayer0;
140     fHistLayer0 = 0;
141   }
142   if (fHistLayer1) {
143     delete fHistLayer1;
144     fHistLayer1 = 0;
145   }
146   if (fHistLayer2) {
147     delete fHistLayer2;
148     fHistLayer2 = 0;
149   }
150   if (fHistLayer3) {
151     delete fHistLayer3;
152     fHistLayer3 = 0;
153   }
154   if (fHistLayer4) {
155     delete fHistLayer4;
156     fHistLayer4 = 0;
157   }
158   if (fHistLayer5) {
159     delete fHistLayer5;
160     fHistLayer5 = 0;
161   }
162   if (fntExtra) {
163     delete fntExtra;
164     fntExtra = 0;
165   }
166   if (fntCosmicMatching) {
167     delete fntCosmicMatching;
168     fntCosmicMatching = 0;
169   }
170 }  
171
172
173 //________________________________________________________________________
174 void AliAlignmentDataFilterITS::UserCreateOutputObjects()
175 {
176   // Create the output container
177   //
178   
179   // load the geometry  
180   if(!gGeoManager) {    
181     printf("AliAlignmentDataFilterITS::CreateOutputObjects(): loading geometry from %s\n",fGeometryFileName.Data());
182     AliGeomManager::LoadGeometry(fGeometryFileName.Data());
183     if(!gGeoManager) { 
184       printf("AliAlignmentDataFilterITS::CreateOutputObjects(): no geometry loaded \n");
185       return;
186     }
187   }
188
189   // Several histograms are more conveniently managed in a TList
190   fListOfHistos = new TList();
191   fListOfHistos->SetOwner();
192
193   fHistNevents = new TH1F("fHistNevents", "Number of processed events; N events; bin",5,-0.5,4.5);
194   fHistNevents->Sumw2();
195   fHistNevents->SetMinimum(0);
196   fListOfHistos->Add(fHistNevents);
197
198   fHistNpoints = new TH1F("fHistNpoints", "Number of AliTrackPoints per track; N points; tracks",25,-0.5,24.5);
199   fHistNpoints->Sumw2();
200   fHistNpoints->SetMinimum(0);
201   fListOfHistos->Add(fHistNpoints);
202
203   fHistPt = new TH1F("fHistPt", "p_{t} of tracks; p_{t} [GeV/c]; tracks",100,0,50);
204   fHistPt->Sumw2();
205   fHistPt->SetMinimum(0);
206   fListOfHistos->Add(fHistPt);
207
208
209   Float_t zmax=14.;
210   Int_t nbinsphi=20,nbinsz=4;
211   fHistLayer0 = new TH2F("fHistLayer0","Points in layer inner SPD; global   #phi; global z [cm]",nbinsphi,-3.14,3.14,nbinsz,-zmax,zmax);
212   fListOfHistos->Add(fHistLayer0);
213   zmax=14.;
214   nbinsphi=40;nbinsz=4;
215   fHistLayer1 = new TH2F("fHistLayer1","Points in layer outer SPD; global   #phi; global z [cm]",nbinsphi,-3.14,3.14,nbinsz,-zmax,zmax);
216   fListOfHistos->Add(fHistLayer1);
217   zmax=22.;
218   nbinsphi=14;nbinsz=6;
219   fHistLayer2 = new TH2F("fHistLayer2","Points in layer inner SDD; global   #phi; global z [cm]",nbinsphi,-3.14,3.14,nbinsz,-zmax,zmax);
220   fListOfHistos->Add(fHistLayer2);
221   zmax=29.5;
222   nbinsphi=22;nbinsz=8;
223   fHistLayer3 = new TH2F("fHistLayer3","Points in layer outer SDD; global   #phi; global z [cm]",nbinsphi,-3.14,3.14,nbinsz,-zmax,zmax);
224   fListOfHistos->Add(fHistLayer3);
225   zmax=45.;
226   nbinsphi=34;nbinsz=23;
227   fHistLayer4 = new TH2F("fHistLayer4","Points in layer inner SSD; global   #phi; global z [cm]",nbinsphi,-3.14,3.14,nbinsz,-zmax,zmax);
228   fListOfHistos->Add(fHistLayer4);
229   zmax=51.;
230   nbinsphi=38;nbinsz=26;
231   fHistLayer5 = new TH2F("fHistLayer5","Points in layer outer SSD; global   #phi; global z [cm]",nbinsphi,-3.14,3.14,nbinsz,-zmax,zmax);
232   fListOfHistos->Add(fHistLayer5);
233
234
235   fntExtra = new TNtuple("fntExtra","extra clusters in ITS","ncls:layer:ladder:volid:phi:x:y:z:xloc:zloc:dxy:dz:d0mu:z0mu:pt");
236   fListOfHistos->Add(fntExtra);
237
238   fntCosmicMatching = new TNtuple("fntCosmicMatching","cosmic tracks matching in ITS","ncls1:ncls2:pt1:pt2:sigmad01:sigmad02:sigmaz01:sigmaz02:dxy:dz:phimu:thetamu:d0mu:z0mu");
239   fListOfHistos->Add(fntCosmicMatching);
240
241   fspTree = new TTree("spTree","Tree with ITS track points");
242   AliTrackPointArray *array = 0;
243   AliESDVertex *vertex = 0;
244   Float_t curv=0,curverr=0,runNumber=0;
245   TObjString *itsaligndata = 0;
246   TObjString *itscalibrespsdd = 0;
247   fspTree->Branch("SP","AliTrackPointArray",&array);
248   fspTree->Branch("vertex","AliESDVertex",&vertex);
249   fspTree->Branch("curv",&curv);
250   fspTree->Branch("curverr",&curverr);
251   fspTree->Branch("run",&runNumber);
252   fspTree->Branch("ITSAlignData",&itsaligndata);
253   fspTree->Branch("ITSCalibRespSDD",&itscalibrespsdd);
254
255   return;
256 }
257
258 //________________________________________________________________________
259 void AliAlignmentDataFilterITS::UserExec(Option_t */*option*/)
260 {
261   // Execute analysis for current event:
262   // write ITS AliTrackPoints for selected tracks to fspTree
263   
264   // check the geometry  
265   if(!gGeoManager) { 
266     printf("AliAlignmentDataFilterITS::Exec(): no geometry loaded \n");
267     return;
268   }
269
270   // check if we have AliITSRecoParam
271   if(!GetRecoParam()) {
272     if(!fITSRecoParam) {
273       printf("AliAlignmentDataFilterITS::Exec(): no AliITSRecoParam\n");
274       return;
275     }
276   }
277
278   fESD = dynamic_cast<AliESDEvent*>(InputEvent());
279   if(!fESD) {
280     printf("AliAlignmentDataFilterITS::Exec(): no ESD \n");
281     return;
282   } 
283
284   //AliESDfriend *esdfriend = (AliESDfriend*)(fESD->FindListObject("AliESDfriend"));
285
286   //if(!esdfriend) printf("AliAlignmentDataFilterITS::Exec(): no ESDfriend \n");
287   //fESD->SetESDfriend(esdfriend);
288
289   // Post the data for slot 0
290   fHistNevents->Fill(0);
291
292
293   // write field value to spTree UserInfo
294   if(!((fspTree->GetUserInfo())->FindObject("BzkGauss"))) {
295     Double_t bz=fESD->GetMagneticField();
296     TString bzString; bzString+=bz;
297     TObjString *bzObjString = new TObjString(bzString);
298     TList *bzList = new TList();         
299     bzList->SetOwner(1);         
300     bzList->SetName("BzkGauss");         
301     bzList->Add(bzObjString);
302     fspTree->GetUserInfo()->Add(bzList);
303   }
304
305   // write OCDB info to spTree UserInfo
306   if(!((fspTree->GetUserInfo())->FindObject("cdbList"))) {
307     TTree* tree = dynamic_cast<TTree*> (GetInputData(0));
308     if(!tree) {
309       printf("ERROR: Could not read chain from input slot 0\n");
310     } else {
311       // Get the OCDB path and the list of OCDB objects used for reco 
312       TMap *cdbMap = (TMap*)(tree->GetTree()->GetUserInfo())->FindObject("cdbMap");
313       TList *cdbList = (TList*)(tree->GetTree()->GetUserInfo())->FindObject("cdbList");
314       
315       //cdbList->Print();
316       // write the list to the user info of the output tree
317       if(!fspTree) {
318         printf("ERROR: fspTree does not exist\n");
319       } else {
320         TMap *cdbMapCopy = new TMap(cdbMap->GetEntries());       
321         cdbMapCopy->SetOwner(1);         
322         cdbMapCopy->SetName("cdbMap");   
323         TIter iter1(cdbMap->GetTable());         
324         
325         TPair* pair = 0;         
326         while((pair = dynamic_cast<TPair*> (iter1.Next()))){     
327           TObjString* keyStr = dynamic_cast<TObjString*> (pair->Key());  
328           TObjString* valStr = dynamic_cast<TObjString*> (pair->Value());        
329           if(keyStr && valStr) cdbMapCopy->Add(new TObjString(keyStr->GetName()), new TObjString(valStr->GetName()));    
330         }        
331         
332         TList *cdbListCopy = new TList();        
333         cdbListCopy->SetOwner(1);        
334         cdbListCopy->SetName("cdbList");         
335         
336         TIter iter2(cdbList);    
337         
338         TObjString* cdbEntry=0;
339         while((cdbEntry =(TObjString*)(iter2.Next()))) {
340           cdbListCopy->Add(new TObjString(*cdbEntry));
341         }        
342         cdbListCopy->Print();
343
344
345         fspTree->GetUserInfo()->Add(cdbMapCopy);         
346         fspTree->GetUserInfo()->Add(cdbListCopy);
347       }
348     }
349   }
350
351
352
353   // Process event as Cosmic or Collision
354   if(fESD->GetEventSpecie()<=1) {
355     printf("AliAlignmentDataFilterITS::Exec(): event specie not set !\n");
356     if(GetRecoParam()->GetAlignFilterCosmics()) {
357       FilterCosmic(fESD);
358     } else {
359       FilterCollision(fESD);
360     }
361   } else if(fESD->GetEventSpecie()==8) {
362     FilterCosmic(fESD);
363   } else {
364     FilterCollision(fESD);
365   }
366
367   PostData(2,fListOfHistos);
368
369   return;
370 }
371
372 //________________________________________________________________________
373 void AliAlignmentDataFilterITS::FilterCosmic(const AliESDEvent *esd)
374 {
375   // Extract ITS AliTrackPoints for Cosmics (check angular matching
376   // of top and bottom track, merge the two tracks, if requested)
377   //
378
379   // Set branch addresses for space points tree
380   AliTrackPointArray *arrayForTree=0;
381   AliESDVertex *vertexForTree=0;
382   Float_t curv,curverr,runNumber;
383   TObjString *itsaligndata=0;
384   TObjString *itscalibrespsdd = 0;
385   fspTree->SetBranchAddress("SP",&arrayForTree);
386   fspTree->SetBranchAddress("vertex",&vertexForTree);
387   fspTree->SetBranchAddress("curv",&curv);
388   fspTree->SetBranchAddress("curverr",&curverr);
389   fspTree->SetBranchAddress("run",&runNumber);
390   fspTree->SetBranchAddress("ITSAlignData",&itsaligndata);
391   fspTree->SetBranchAddress("ITSCalibRespSDD",&itscalibrespsdd);
392
393
394   runNumber = (Float_t)esd->GetRunNumber();
395   Int_t uid=10000+esd->GetEventNumberInFile();
396
397   TTree* esdTree = dynamic_cast<TTree*> (GetInputData(0));
398   if(!esdTree) return;
399   // Get the list of OCDB objects used for reco 
400   TList *cdbList = (TList*)(esdTree->GetTree()->GetUserInfo())->FindObject("cdbList");
401   TIter iter2(cdbList);      
402   TObjString* cdbEntry=0;
403   TString cdbEntryString;
404   while((cdbEntry =(TObjString*)(iter2.Next()))) {
405   cdbEntryString = cdbEntry->GetString();
406   if(cdbEntryString.Contains("ITS/Align/Data")) 
407     itsaligndata = new TObjString(*cdbEntry);
408   if(cdbEntryString.Contains("ITS/Calib/RespSDD")) 
409     itscalibrespsdd = new TObjString(*cdbEntry);
410   }      
411
412
413   TString triggeredClass = esd->GetFiredTriggerClasses(); 
414   if(fOnlySPDFO && !triggeredClass.Contains("C0SCO-ABCE-NOPF-CENT")) return;
415
416
417   Int_t ntracks = esd->GetNumberOfTracks();
418   if(ntracks<2) return;
419
420   if(esd->GetPrimaryVertexSPD()->GetNContributors()<0) return;
421
422   Double_t vtxpos[3]; esd->GetPrimaryVertexSPD()->GetXYZ(vtxpos);
423
424   Int_t *goodtracksArray = new Int_t[ntracks];
425   Float_t *phiArray = new Float_t[ntracks];
426   Float_t *thetaArray = new Float_t[ntracks];
427   Int_t *nclsArray = new Int_t[ntracks];
428   Int_t ngt=0;
429   Int_t itrack=0;
430   for (itrack=0; itrack < ntracks; itrack++) {
431     AliESDtrack *track = esd->GetTrack(itrack);
432     if (!track) continue;
433
434
435     if(track->GetNcls(0)<GetRecoParam()->GetAlignFilterMinITSPoints()) continue;
436
437     if((GetRecoParam()->GetAlignFilterOnlyITSSATracks()) && track->GetNcls(1)>0) continue;
438     if((GetRecoParam()->GetAlignFilterOnlyITSTPCTracks()) && track->GetNcls(1)==0) continue;
439
440     Float_t phi = track->GetAlpha()+TMath::ASin(track->GetSnp());
441     Float_t theta = 0.5*TMath::Pi()-TMath::ATan(track->GetTgl());
442
443     if(track->Pt()<GetRecoParam()->GetAlignFilterMinPt() || 
444        track->Pt()>GetRecoParam()->GetAlignFilterMaxPt()) continue;
445
446     goodtracksArray[ngt] = itrack;
447     phiArray[ngt]        = phi;
448     thetaArray[ngt]      = theta;
449     nclsArray[ngt]       = track->GetNcls(0);
450     ngt++;
451   }
452
453   if(ngt<2) {
454     delete [] goodtracksArray; goodtracksArray=0;
455     delete [] phiArray; phiArray=0;
456     delete [] thetaArray; thetaArray=0;
457     delete [] nclsArray; nclsArray=0;
458     return;
459   }
460
461   // check matching of the two tracks from the muon
462   Float_t min = 10000000.;
463   Int_t maxCls = 0;
464   Int_t good1 = -1, good2 = -1;
465   for(Int_t itr1=0; itr1<ngt-1; itr1++) {
466     for(Int_t itr2=itr1+1; itr2<ngt; itr2++) {
467       Float_t deltatheta = TMath::Abs(TMath::Pi()-thetaArray[itr1]-thetaArray[itr2]);
468       if(deltatheta>GetRecoParam()->GetAlignFilterMaxMatchingAngle()) continue;
469       Float_t deltaphi = TMath::Abs(TMath::Abs(phiArray[itr1]-phiArray[itr2])-TMath::Pi());
470       if(deltaphi>GetRecoParam()->GetAlignFilterMaxMatchingAngle()) continue;
471       if(nclsArray[itr1]+nclsArray[itr2] > maxCls) {
472         maxCls = nclsArray[itr1]+nclsArray[itr2];
473         min = deltatheta+deltaphi;
474         good1 = goodtracksArray[itr1];
475         good2 = goodtracksArray[itr2];
476       } else if(nclsArray[itr1]+nclsArray[itr2] == maxCls) {
477         if(deltatheta+deltaphi < min) {
478           min = deltatheta+deltaphi;
479           good1 = goodtracksArray[itr1];
480           good2 = goodtracksArray[itr2];
481         }
482       }
483     }
484   }
485   
486   delete [] goodtracksArray; goodtracksArray=0;
487   delete [] phiArray; phiArray=0;
488   delete [] thetaArray; thetaArray=0;
489   delete [] nclsArray; nclsArray=0;
490
491   if(good1<0) return;
492   AliDebug(2,"ok track matching");
493   
494   // track1 will be the inward track (top)
495   // track2 the outward (bottom)
496   AliESDtrack *track1=0; 
497   AliESDtrack *track2=0;
498   AliESDtrack *track = esd->GetTrack(good1);
499   if(track->Py()>0) { 
500     track1 = esd->GetTrack(good1);
501     track2 = esd->GetTrack(good2);
502   } else {
503     track1 = esd->GetTrack(good2);
504     track2 = esd->GetTrack(good1);
505   }
506
507   AliTrackPoint point;
508   const AliTrackPointArray *array=0;
509   Int_t ipt,volId,modId,layerId,lay,lad,det;
510   Int_t jpt=0;
511   Bool_t layerOK[6][2]; 
512   Int_t nclsTrk[2]={0,0};
513
514   for(Int_t l1=0;l1<6;l1++) for(Int_t l2=0;l2<2;l2++) layerOK[l1][l2]=kFALSE;
515     
516   for(itrack=0; itrack<2; itrack++) {
517     if(itrack==0) {
518       track = track1;
519     } else {
520       track = track2;
521     }
522     array = track->GetTrackPointArray();
523     if(!array) {
524       AliWarning("No tracks points avaialble");
525       continue;
526     }
527     for(ipt=0; ipt<array->GetNPoints(); ipt++) {
528       array->GetPoint(point,ipt);
529       volId = point.GetVolumeID();
530       if(volId<=0) continue;
531       layerId = AliGeomManager::VolUIDToLayer(volId,modId);
532       AliDebug(2,Form("%d %d %d  %f\n",ipt,layerId-1,volId,TMath::Sqrt(point.GetX()*point.GetX()+point.GetY()*point.GetY())));
533       if(point.IsExtra() && 
534          (GetRecoParam()->GetAlignFilterSkipExtra())) continue;
535       if(layerId<1 || layerId>6) continue;
536       if(!GetRecoParam()->GetAlignFilterUseLayer(layerId-1)) continue;
537       // check minAngleWrtITSModulePlanes
538       Double_t p[3]; track->GetDirection(p);
539       TVector3 pvec(p[0],p[1],p[2]);
540       Double_t rot[9]; AliGeomManager::GetOrigRotation(volId,rot);
541       TVector3 normvec(rot[1],rot[4],rot[7]);
542       Double_t angle = pvec.Angle(normvec);
543       if(angle>0.5*TMath::Pi()) angle = TMath::Pi()-angle;
544       angle = 0.5*TMath::Pi()-angle;
545       if(angle<GetRecoParam()->GetAlignFilterMinAngleWrtModulePlanes()) continue;
546       layerOK[layerId-1][itrack]=kTRUE;
547       jpt++;
548       nclsTrk[itrack]++;
549     }
550   }
551   AliDebug(2,Form("nClsTrk1 %d nClsTrk2 %d\n",nclsTrk[0],nclsTrk[1]));
552     
553   // read ITS cluster maps
554   Int_t map1[6],map2[6];
555   for(Int_t ilay=0;ilay<6;ilay++) {
556     map1[ilay]=0; map2[ilay]=0;
557     if(track1->HasPointOnITSLayer(ilay)) map1[ilay]=1;
558     if(track2->HasPointOnITSLayer(ilay)) map2[ilay]=1;
559   }
560   AliDebug(2,Form("ITS map 1: %d %d %d %d %d %d pt %f\n",map1[0],map1[1],map1[2],map1[3],map1[4],map1[5],track1->Pt()));
561   AliDebug(2,Form("ITS map 2: %d %d %d %d %d %d pt %f\n",map2[0],map2[1],map2[2],map2[3],map2[4],map2[5],track2->Pt()));
562   Int_t idx1[12],idx2[12];
563   track1->GetITSclusters(idx1);
564   track2->GetITSclusters(idx2);
565   AliDebug(2,Form("cls idx 1 %d %d %d %d %d %d %d %d %d %d %d %d\n",idx1[0],idx1[1],idx1[2],idx1[3],idx1[4],idx1[5],idx1[6],idx1[7],idx1[8],idx1[9],idx1[10],idx1[11]));
566   AliDebug(2,Form("cls idx 2 %d %d %d %d %d %d %d %d %d %d %d %d\n",idx2[0],idx2[1],idx2[2],idx2[3],idx2[4],idx2[5],idx2[6],idx2[7],idx2[8],idx2[9],idx2[10],idx2[11]));
567   
568
569   if(jpt<GetRecoParam()->GetAlignFilterMinITSPointsMerged()) return;
570   AliDebug(2,Form(" Total points %d, accepted\n",jpt));  
571   fHistNpoints->Fill(jpt);
572   fHistPt->Fill(0.5*(track1->Pt()+track2->Pt()));
573   
574   Float_t d0z0mu[2];
575   track1->GetDZ(0,0,0,esd->GetMagneticField(),d0z0mu);
576   //printf("d0mu %f  z0mu %f\n",d0z0mu[0],d0z0mu[1]);
577
578   vertexForTree = new AliESDVertex(*(esd->GetPrimaryVertexSPD()));
579   vertexForTree->SetID(0);
580
581   Float_t dzOverlap[2];
582   Float_t curvArray[2],curverrArray[2];
583   Double_t globExtra[3],locExtra[3];
584   if(GetRecoParam()->GetAlignFilterCosmicMergeTracks()) {
585     arrayForTree = new AliTrackPointArray(jpt);
586     arrayForTree->SetUniqueID(uid);
587   }
588   jpt=0;
589   for(itrack=0; itrack<2; itrack++) {
590     if(itrack==0) {
591       track = track1;
592     } else {
593       track = track2;
594     }
595     curvArray[itrack] = track->GetC(esd->GetMagneticField());
596     curverrArray[itrack] = TMath::Sqrt(track->GetSigma1Pt2())*track->GetC(esd->GetMagneticField())/track->OneOverPt();
597
598     if(!(GetRecoParam()->GetAlignFilterCosmicMergeTracks())) {
599       jpt=0;
600       arrayForTree = new AliTrackPointArray(nclsTrk[itrack]);
601       arrayForTree->SetUniqueID(uid);
602     }
603     array = track->GetTrackPointArray();
604     for(ipt=0; ipt<array->GetNPoints(); ipt++) {
605       array->GetPoint(point,ipt);
606       volId = point.GetVolumeID();
607       if(volId<=0) continue;
608       layerId = AliGeomManager::VolUIDToLayer(volId,modId);
609       if(layerId<1 || layerId>6 || !layerOK[layerId-1][itrack]) continue;
610       arrayForTree->AddPoint(jpt,&point);
611       jpt++;
612       switch(layerId) {
613       case 1:
614         fHistLayer0->Fill(TMath::ATan2(point.GetY(),point.GetX()),point.GetZ());
615         break;
616       case 2:
617         fHistLayer1->Fill(TMath::ATan2(point.GetY(),point.GetX()),point.GetZ());
618         break;
619       case 3:
620         fHistLayer2->Fill(TMath::ATan2(point.GetY(),point.GetX()),point.GetZ());
621         break;
622       case 4:
623         fHistLayer3->Fill(TMath::ATan2(point.GetY(),point.GetX()),point.GetZ());
624         break;
625       case 5:
626         fHistLayer4->Fill(TMath::ATan2(point.GetY(),point.GetX()),point.GetZ());
627         break;
628       case 6:
629         fHistLayer5->Fill(TMath::ATan2(point.GetY(),point.GetX()),point.GetZ());
630         break;
631       }
632       // Post the data for slot 2
633       if(jpt==1) PostData(2,fListOfHistos); // only if this is the first points
634       if(!point.IsExtra() || 
635          !(GetRecoParam()->GetAlignFilterFillQANtuples())) continue;
636       nclsTrk[itrack]--;
637       for(Int_t ll=1;ll<layerId;ll++) modId+=AliITSgeomTGeo::GetNLadders(ll)*AliITSgeomTGeo::GetNDetectors(ll);
638       AliITSgeomTGeo::GetModuleId(modId,lay,lad,det);
639       globExtra[0]=point.GetX();
640       globExtra[1]=point.GetY();
641       globExtra[2]=point.GetZ();
642       AliITSgeomTGeo::GlobalToLocal(lay,lad,det,globExtra,locExtra);
643       //printf("%d %d %d %d %d  %f %f %f\n",volId,modId,lay,lad,det,locExtra[0],locExtra[1],locExtra[2]);
644       track->GetDZ(point.GetX(),point.GetY(),point.GetZ(),esd->GetMagneticField(),dzOverlap);
645       AliTrackPoint pointT;
646       Float_t radius,radiusT,phiv,phivT,thetav,thetavT;
647       for(Int_t lll=0;lll<ipt;lll++) {
648         array->GetPoint(pointT,lll);
649         if(pointT.GetVolumeID()<=0) continue;
650         Int_t layerIdT = AliGeomManager::VolUIDToLayer(pointT.GetVolumeID(),modId);
651         if(layerIdT!=layerId) continue;
652         radius=TMath::Sqrt((point.GetX()-vtxpos[0])*(point.GetX()-vtxpos[0])+(point.GetY()-vtxpos[1])*(point.GetY()-vtxpos[1]));
653         radiusT=TMath::Sqrt((pointT.GetX()-vtxpos[0])*(pointT.GetX()-vtxpos[0])+(pointT.GetY()-vtxpos[1])*(pointT.GetY()-vtxpos[1]));
654         phiv=TMath::ATan2(point.GetY()-vtxpos[1],point.GetX()-vtxpos[0]);
655         phivT=TMath::ATan2(pointT.GetY()-vtxpos[1],pointT.GetX()-vtxpos[0]);
656         if(TMath::Abs(point.GetZ()-vtxpos[2])<0.00001 || TMath::Abs(pointT.GetZ()-vtxpos[2])<0.00001) continue;
657         thetav=TMath::ATan(radius/(point.GetZ()-vtxpos[2]));
658         thetavT=TMath::ATan(radiusT/(pointT.GetZ()-vtxpos[2]));
659         dzOverlap[0]=(Float_t)((phivT-phiv)*0.5*(radiusT+radius));
660         if(TMath::Abs(TMath::Tan(0.5*(thetav+thetavT)))<0.00001) continue;
661         dzOverlap[1]=(Float_t)((pointT.GetZ()-point.GetZ())-(radiusT-radius)/TMath::Tan(0.5*(thetav+thetavT)));
662         fntExtra->Fill((Float_t)nclsTrk[itrack],(Float_t)(layerId-1),lad,volId,TMath::ATan2(point.GetY(),point.GetX()),point.GetX(),point.GetY(),point.GetZ(),locExtra[0],locExtra[2],dzOverlap[0],dzOverlap[1],d0z0mu[0],d0z0mu[1],track->Pt());
663       }
664     }
665
666     if(!(GetRecoParam()->GetAlignFilterCosmicMergeTracks())) {
667       curv = curvArray[itrack];
668       curverr = curverrArray[itrack];
669       fspTree->Fill();
670     }
671   }
672
673   if(GetRecoParam()->GetAlignFilterCosmicMergeTracks()) {
674     curv = 0.5*(curvArray[0]-curvArray[1]);  // the "-" is because the two tracks have opposite curvature!
675     curverr = 0.5*TMath::Sqrt(curverrArray[0]*curverrArray[0]+curverrArray[1]*curverrArray[1]);
676     fspTree->Fill();
677   }
678   PostData(1,fspTree);
679
680   if(!(GetRecoParam()->GetAlignFilterFillQANtuples())) return; 
681   // fill ntuple with track-to-track matching
682   Float_t phimu,thetamu,phiout,thetaout,dphi,dtheta,rotymu,rotyout,droty;    
683   Float_t d0[2],z0[2];
684   Float_t sigmad0[2],sigmaz0[2];
685   phimu = track1->GetAlpha()+TMath::ASin(track1->GetSnp());
686   thetamu = 0.5*TMath::Pi()-TMath::ATan(track1->GetTgl());
687   phiout = track2->GetAlpha()+TMath::ASin(track2->GetSnp());
688   thetaout = 0.5*TMath::Pi()-TMath::ATan(track2->GetTgl());
689   rotymu = TMath::ATan2(track1->Px(),track1->Pz());
690   rotyout = TMath::ATan2(track2->Px(),track2->Pz());
691
692   dphi = phimu - (phiout+TMath::Pi());
693   dtheta = thetamu - (TMath::Pi()-thetaout);
694   if(rotymu>0) {
695     droty = rotymu - (rotyout+TMath::Pi());
696   } else {
697     droty = rotymu - (rotyout-TMath::Pi());
698   }
699
700   Double_t alpha = TMath::ATan2(track1->Py(),track1->Px());
701
702   track1->Propagate(alpha,0.,esd->GetMagneticField());
703   track2->Propagate(alpha,0.,esd->GetMagneticField());
704   d0[0] = track1->GetY();
705   z0[0] = track1->GetZ();
706   d0[1] = track2->GetY();
707   z0[1] = track2->GetZ();
708   Float_t dxy = -(d0[0]-d0[1]);
709   Float_t dz  = z0[0]-z0[1];
710   sigmad0[0] = TMath::Sqrt(track1->GetSigmaY2());
711   sigmaz0[0] = TMath::Sqrt(track1->GetSigmaZ2());
712   sigmad0[1] = TMath::Sqrt(track2->GetSigmaY2());
713   sigmaz0[1] = TMath::Sqrt(track2->GetSigmaZ2());
714   /*  
715   Double_t xyz1atxl0[3],xyz1atxl1[3],xyz2atxl0[3],xyz2atxl1[3];
716   track1->GetXYZAt(0.,esd->GetMagneticField(),xyz1atxl0);
717   track1->GetXYZAt(1.,esd->GetMagneticField(),xyz1atxl1);
718   track2->GetXYZAt(0.,esd->GetMagneticField(),xyz2atxl0);
719   track2->GetXYZAt(1.,esd->GetMagneticField(),xyz2atxl1);
720   Float_t x1aty0 = (xyz1atxl0[0]*xyz1atxl1[1]-xyz1atxl0[1]*xyz1atxl1[0])/(xyz1atxl1[1]-xyz1atxl0[1]);
721   Float_t x2aty0 = (xyz2atxl0[0]*xyz2atxl1[1]-xyz2atxl0[1]*xyz2atxl1[0])/(xyz2atxl1[1]-xyz2atxl0[1]);
722   Float_t dxaty0 = x1aty0-x2aty0;
723   */
724   fntCosmicMatching->Fill((Float_t)nclsTrk[0],(Float_t)nclsTrk[1],track1->Pt(),track2->Pt(),sigmad0[0],sigmad0[1],sigmaz0[0],sigmaz0[1],dxy,dz,phimu,thetamu,TMath::Abs(d0z0mu[0]),d0z0mu[1]);
725   
726   return;
727 }
728
729 //________________________________________________________________________
730 void AliAlignmentDataFilterITS::FilterCollision(const AliESDEvent *esd)
731 {
732   // Extract ITS AliTrackPoints for Cosmics (check angular matching
733   // of top and bottom track, merge the two tracks, if requested)
734   //
735
736   // Set branch addresses for space points tree
737   AliTrackPointArray *arrayForTree=0;
738   AliESDVertex *vertexForTree=0;
739   Float_t curv,curverr,runNumber;
740   TObjString *itsaligndata=0;
741   TObjString *itscalibrespsdd = 0;
742   fspTree->SetBranchAddress("SP",&arrayForTree);
743   fspTree->SetBranchAddress("vertex",&vertexForTree);
744   fspTree->SetBranchAddress("curv",&curv);
745   fspTree->SetBranchAddress("curverr",&curverr);
746   fspTree->SetBranchAddress("run",&runNumber);
747   fspTree->SetBranchAddress("ITSAlignData",&itsaligndata);
748   fspTree->SetBranchAddress("ITSCalibRespSDD",&itscalibrespsdd);
749
750
751   runNumber = (Float_t)esd->GetRunNumber();
752   Int_t uid=20000+esd->GetEventNumberInFile();
753
754   TTree* esdTree = dynamic_cast<TTree*> (GetInputData(0));
755   if(!esdTree) return;
756   // Get the list of OCDB objects used for reco 
757   TList *cdbList = (TList*)(esdTree->GetTree()->GetUserInfo())->FindObject("cdbList");
758   TIter iter2(cdbList);      
759   TObjString* cdbEntry=0;
760   TString cdbEntryString;
761   while((cdbEntry =(TObjString*)(iter2.Next()))) {
762   cdbEntryString = cdbEntry->GetString();
763   if(cdbEntryString.Contains("ITS/Align/Data")) 
764     itsaligndata = new TObjString(*cdbEntry);
765   if(cdbEntryString.Contains("ITS/Calib/RespSDD")) 
766     itscalibrespsdd = new TObjString(*cdbEntry);
767   }      
768
769   Int_t ntracks = esd->GetNumberOfTracks();
770
771   if(ntracks==0) return;
772
773   const AliESDVertex *vertexTracks = esd->GetPrimaryVertexTracks();
774   if(!vertexTracks) return;
775   if(vertexTracks->GetNContributors()<=0) return;
776
777   Double_t vtxpos[3]; vertexTracks->GetXYZ(vtxpos);
778
779   Int_t ncls=0;
780   Double_t pt=-10000.;
781   Double_t d0z0[2],covd0z0[3];
782   const AliTrackPointArray *array = 0;
783
784   for (Int_t itrack=0; itrack < ntracks; itrack++) {
785     AliESDtrack * track = esd->GetTrack(itrack);
786     if (!track) continue;
787
788     if(fDownsamplelowpt && TMath::Abs(esd->GetMagneticField())>0.01 &&
789        track->Pt()<gRandom->Rndm()) continue;
790
791     if(track->GetNcls(0)<GetRecoParam()->GetAlignFilterMinITSPoints()) continue;
792
793     if((GetRecoParam()->GetAlignFilterOnlyITSSATracks()) && track->GetNcls(1)>0) continue;
794     if((GetRecoParam()->GetAlignFilterOnlyITSTPCTracks()) && track->GetNcls(1)==0) continue;
795
796     if(track->Pt()<GetRecoParam()->GetAlignFilterMinPt() || 
797        track->Pt()>GetRecoParam()->GetAlignFilterMaxPt()) continue;
798
799     pt = track->Pt();
800     ncls = track->GetNcls(0);
801     Double_t maxd=10000.;
802     track->PropagateToDCA(vertexTracks,esd->GetMagneticField(),maxd,d0z0,covd0z0);
803
804     // read ITS cluster map
805     Int_t map[6];
806     for(Int_t ilay=0;ilay<6;ilay++) {
807       map[ilay]=0;
808       if(track->HasPointOnITSLayer(ilay)) map[ilay]=1;
809     }
810     AliDebug(2,Form("ITS map : %d %d %d %d %d %d pt %f\n",map[0],map[1],map[2],map[3],map[4],map[5],track->Pt()));
811     Int_t idx[12];
812     track->GetITSclusters(idx);
813     AliDebug(2,Form("cls idx %d %d %d %d %d %d %d %d %d %d %d %d\n",idx[0],idx[1],idx[2],idx[3],idx[4],idx[5],idx[6],idx[7],idx[8],idx[9],idx[10],idx[11]));
814     
815
816     AliTrackPoint point;
817     Int_t ipt,volId,modId,layerId,lay,lad,det;
818     Int_t jpt=0;
819     Bool_t layerOK[6]; for(Int_t l1=0;l1<6;l1++) layerOK[l1]=kFALSE;
820     
821     array = track->GetTrackPointArray();
822     if(!array) {printf("no track points\n"); continue;}
823     for(ipt=0; ipt<array->GetNPoints(); ipt++) {
824       array->GetPoint(point,ipt);
825       volId = point.GetVolumeID();
826       if(volId<=0) continue;
827       layerId = AliGeomManager::VolUIDToLayer(volId,modId);
828       if(layerId<1 || layerId>6) continue;
829       if(point.IsExtra() && 
830          (GetRecoParam()->GetAlignFilterSkipExtra())) continue;
831       layerOK[layerId-1]=kTRUE;
832       jpt++;
833     }
834
835     if(jpt < GetRecoParam()->GetAlignFilterMinITSPoints()) continue;
836
837     fHistNpoints->Fill(jpt);
838     fHistPt->Fill(pt);
839     PostData(2,fListOfHistos);
840
841     Float_t dzOverlap[2];
842     Double_t globExtra[3],locExtra[3];
843     arrayForTree = new AliTrackPointArray(jpt);
844     arrayForTree->SetUniqueID(uid);
845     jpt=0;
846     array = track->GetTrackPointArray();
847     if(!array) continue;
848     for(ipt=0; ipt<array->GetNPoints(); ipt++) {
849       array->GetPoint(point,ipt);
850       volId = point.GetVolumeID();
851       layerId = AliGeomManager::VolUIDToLayer(volId,modId);
852       if(layerId<1 || layerId>6 || !layerOK[layerId-1]) continue;
853       arrayForTree->AddPoint(jpt,&point);
854       switch(layerId) {
855       case 1:
856         fHistLayer0->Fill(TMath::ATan2(point.GetY(),point.GetX()),point.GetZ());
857         break;
858       case 2:
859         fHistLayer1->Fill(TMath::ATan2(point.GetY(),point.GetX()),point.GetZ());
860         break;
861       case 3:
862         fHistLayer2->Fill(TMath::ATan2(point.GetY(),point.GetX()),point.GetZ());
863         break;
864       case 4:
865         fHistLayer3->Fill(TMath::ATan2(point.GetY(),point.GetX()),point.GetZ());
866         break;
867       case 5:
868         fHistLayer4->Fill(TMath::ATan2(point.GetY(),point.GetX()),point.GetZ());
869         break;
870       case 6:
871         fHistLayer5->Fill(TMath::ATan2(point.GetY(),point.GetX()),point.GetZ());
872         break;
873       }
874       jpt++;
875       if(!point.IsExtra() || 
876          !(GetRecoParam()->GetAlignFilterFillQANtuples())) continue;
877       ncls--;
878       for(Int_t ll=1;ll<layerId;ll++) modId+=AliITSgeomTGeo::GetNLadders(ll)*AliITSgeomTGeo::GetNDetectors(ll);
879       AliITSgeomTGeo::GetModuleId(modId,lay,lad,det);
880       globExtra[0]=point.GetX();
881       globExtra[1]=point.GetY();
882       globExtra[2]=point.GetZ();
883       AliITSgeomTGeo::GlobalToLocal(lay,lad,det,globExtra,locExtra);
884       track->GetDZ(point.GetX(),point.GetY(),point.GetZ(),esd->GetMagneticField(),dzOverlap);
885       AliTrackPoint pointT;
886       Float_t radius,radiusT,phiv,phivT,thetav,thetavT;
887       for(Int_t lll=0;lll<ipt;lll++) {
888         array->GetPoint(pointT,lll);
889         Int_t layerIdT = AliGeomManager::VolUIDToLayer(pointT.GetVolumeID(),modId);
890         if(layerIdT!=layerId) continue;
891         radius=TMath::Sqrt((point.GetX()-vtxpos[0])*(point.GetX()-vtxpos[0])+(point.GetY()-vtxpos[1])*(point.GetY()-vtxpos[1]));
892         radiusT=TMath::Sqrt((pointT.GetX()-vtxpos[0])*(pointT.GetX()-vtxpos[0])+(pointT.GetY()-vtxpos[1])*(pointT.GetY()-vtxpos[1]));
893         phiv=TMath::ATan2(point.GetY()-vtxpos[1],point.GetX()-vtxpos[0]);
894         phivT=TMath::ATan2(pointT.GetY()-vtxpos[1],pointT.GetX()-vtxpos[0]);
895         if(TMath::Abs(point.GetZ()-vtxpos[2])<0.00001 || TMath::Abs(pointT.GetZ()-vtxpos[2])<0.00001) continue;
896         thetav=TMath::ATan(radius/(point.GetZ()-vtxpos[2]));
897         thetavT=TMath::ATan(radiusT/(pointT.GetZ()-vtxpos[2]));
898         dzOverlap[0]=(Float_t)((phivT-phiv)*0.5*(radiusT+radius));
899         if(TMath::Abs(TMath::Tan(0.5*(thetav+thetavT)))<0.00001) continue;
900         dzOverlap[1]=(Float_t)((pointT.GetZ()-point.GetZ())-(radiusT-radius)/TMath::Tan(0.5*(thetav+thetavT)));
901         fntExtra->Fill((Float_t)ncls,(Float_t)(layerId-1),lad,volId,TMath::ATan2(point.GetY(),point.GetX()),point.GetX(),point.GetY(),point.GetZ(),locExtra[0],locExtra[2],dzOverlap[0],dzOverlap[1],d0z0[0],d0z0[1],track->Pt());
902       }
903     }
904
905     curv = track->GetC(esd->GetMagneticField());
906     curverr = TMath::Sqrt(track->GetSigma1Pt2())*track->GetC(esd->GetMagneticField())/track->OneOverPt();
907
908     vertexForTree = new AliESDVertex(*vertexTracks);
909     if(vertexTracks->UsesTrack(track->GetID())) {
910       vertexForTree->SetID(1);
911     } else {
912       vertexForTree->SetID(0);
913     }
914
915     fspTree->Fill();
916  
917   } // end of tracks loop
918
919   PostData(1,fspTree);
920
921   return;
922 }
923
924 //________________________________________________________________________
925 void AliAlignmentDataFilterITS::Terminate(Option_t */*option*/)
926 {
927   // Terminate analysis
928   //
929   AliDebug(2,"AliITSAlignmentDataFiler: Terminate() \n");
930
931   fspTree = dynamic_cast<TTree*> (GetOutputData(1));
932   if (!fspTree) {     
933     printf("ERROR: fspTree not available\n");
934     return;
935   }
936
937   fListOfHistos = dynamic_cast<TList*> (GetOutputData(2));
938   if (!fListOfHistos) {     
939     printf("ERROR: fListOfHistos not available\n");
940     return;
941   }
942
943   fHistNevents = dynamic_cast<TH1F*>(fListOfHistos->FindObject("fHistNevents"));
944   fHistNpoints = dynamic_cast<TH1F*>(fListOfHistos->FindObject("fHistNpoints"));
945   fHistPt = dynamic_cast<TH1F*>(fListOfHistos->FindObject("fHistPt"));
946   fHistLayer0 = dynamic_cast<TH2F*>(fListOfHistos->FindObject("fHistLayer0"));
947   fHistLayer1 = dynamic_cast<TH2F*>(fListOfHistos->FindObject("fHistLayer1"));
948   fHistLayer2 = dynamic_cast<TH2F*>(fListOfHistos->FindObject("fHistLayer2"));
949   fHistLayer3 = dynamic_cast<TH2F*>(fListOfHistos->FindObject("fHistLayer3"));
950   fHistLayer4 = dynamic_cast<TH2F*>(fListOfHistos->FindObject("fHistLayer4"));
951   fHistLayer5 = dynamic_cast<TH2F*>(fListOfHistos->FindObject("fHistLayer5"));
952   fntExtra = dynamic_cast<TNtuple*>(fListOfHistos->FindObject("fntExtra"));
953   fntCosmicMatching = dynamic_cast<TNtuple*>(fListOfHistos->FindObject("fntCosmicMatching"));
954
955
956
957   return;
958 }
959 //-------------------------------------------------------------------------------
960 const AliITSRecoParam *AliAlignmentDataFilterITS::GetRecoParam() const 
961 {
962   //
963   // Return the ITSRecoParam object
964   //
965   if(AliITSReconstructor::GetRecoParam()) {
966     return AliITSReconstructor::GetRecoParam();
967   } else if(fITSRecoParam) {
968     return fITSRecoParam;
969   } else return NULL;
970 }
971 //--------------------------------------------------------------------------------
972 Int_t AliAlignmentDataFilterITS::WriteTrackPointsInIdealGeom(Char_t *fin, 
973                                                              Char_t *fout,
974                                                              Char_t *fmis,
975                                                              Char_t *fgeo,
976                                                              Bool_t prn)
977 {
978   //
979   // Convert AliTrackPoints in fin, reconstructed with fmis, back
980   // to ideal geometry
981   //
982   // M. Lunardon
983   //
984
985
986   TGeoHMatrix deltahm;
987
988   // Load geometry
989   if (gSystem->AccessPathName(fgeo)) {
990     printf("couldn't find geometry file %s - skipping...\n",fmis);
991     return -1;
992   }
993   
994   TFile *geofile=TFile::Open(fgeo);
995   TGeoManager *fgGeometry=NULL;
996
997   fgGeometry=(TGeoManager*)geofile->Get("ALICE");
998
999   if (!fgGeometry)
1000     fgGeometry=(TGeoManager*)geofile->Get("Geometry");
1001
1002   if (!fgGeometry) {
1003     AliCDBEntry *entry = (AliCDBEntry*)geofile->Get("AliCDBEntry");
1004     if (entry)
1005       fgGeometry = (TGeoManager*)entry->GetObject();
1006   }
1007
1008   if (!fgGeometry) return -1;
1009   AliGeomManager::SetGeometry(fgGeometry);
1010   if(!AliGeomManager::GetGeometry()) return -1;
1011   
1012   
1013   // open alignment file
1014   if (gSystem->AccessPathName(fmis)) {
1015     printf("couldn't open alignment file %s - skipping...\n",fmis);
1016     return -2;
1017   }
1018   TFile *pref = TFile::Open(fmis);
1019   if (!pref->IsOpen()) return -2;
1020   
1021   
1022   /// apply alignment to ideal geometry
1023   TClonesArray *prea=(TClonesArray*)pref->Get("ITSAlignObjs");
1024   if (!prea) {
1025     if (pref->Get("AliCDBEntry"))
1026       prea = (TClonesArray*) ((AliCDBEntry*)pref->Get("AliCDBEntry"))->GetObject();
1027   }
1028   if (!prea) return -3;  
1029   Int_t nprea=prea->GetEntriesFast();
1030   printf("Array of input misalignments with %d entries\n",nprea);
1031   AliGeomManager::ApplyAlignObjsToGeom(*prea); // apply all levels of objs
1032   
1033   AliTrackPointArray *tpain=NULL;
1034   TFile *tpainfile=NULL;
1035   TTree *treein=NULL;
1036   AliTrackPoint point; 
1037   AliITSAlignMille2Module *m2[2200];
1038   for (Int_t i=0; i<2198; i++)
1039     m2[i]=new AliITSAlignMille2Module(AliITSAlignMille2Module::GetVolumeIDFromIndex(i));  
1040   
1041   // open input file
1042   if (gSystem->AccessPathName(fin)) {
1043     printf("couldn't open file %s - skipping...\n",fin);
1044     return -4;
1045   }
1046   tpainfile = TFile::Open(fin);
1047   if (!tpainfile->IsOpen()) return -4;
1048   
1049   treein=(TTree*)tpainfile->Get("spTree");
1050   if (!treein) return -5;
1051   Float_t curv,curverr,runNumber;
1052   TObjString *itsaligndata=0;
1053   TObjString *itscalibrespsdd = 0;
1054   treein->SetBranchAddress("SP", &tpain);
1055   treein->SetBranchAddress("curv", &curv);
1056   treein->SetBranchAddress("curverr", &curverr);
1057   treein->SetBranchAddress("run",&runNumber);
1058   treein->SetBranchAddress("ITSAlignData",&itsaligndata);
1059   treein->SetBranchAddress("ITSCalibRespSDD",&itscalibrespsdd);
1060
1061   int ntrks=treein->GetEntries();
1062   printf("Reading %d tracks from %s\n",ntrks,fin);
1063   
1064   
1065   // open output file
1066   TFile *pointsFile = TFile::Open(fout,"RECREATE");
1067   if (!pointsFile || !pointsFile->IsOpen()) {
1068     printf("Can't open output file %s !",fout);
1069     return -6;
1070   }
1071   AliTrackPointArray *array = new AliTrackPointArray();
1072   
1073   // new!
1074   TTree *treeout=(TTree*)treein->Clone("spTree");
1075   treeout->Reset();
1076   treeout->SetBranchAddress("SP", &array);
1077   treeout->SetBranchAddress("curv", &curv);
1078   treeout->SetBranchAddress("curverr", &curverr);
1079   treeout->SetBranchAddress("run",&runNumber);
1080   treeout->SetBranchAddress("ITSAlignData",&itsaligndata);
1081   treeout->SetBranchAddress("ITSCalibRespSDD",&itscalibrespsdd);
1082
1083   // tracks main loop
1084   for (Int_t it=0; it<ntrks; it++) {    
1085     if (!(it%5000) ) printf("...processing track n. %d\n",it);
1086     
1087     treein->GetEvent(it);
1088     
1089     //////////////////////////////
1090     
1091     AliTrackPointArray *atp=tpain;
1092     AliTrackPointArray *atps=NULL;
1093     Int_t npts=atp->GetNPoints();
1094     
1095     AliTrackPoint p;
1096     // check points in specific places
1097     
1098     // build a new track
1099     atps=new AliTrackPointArray(npts);
1100         
1101     Int_t npto=0;
1102     for (int i=0; i<npts; i++) {
1103       atp->GetPoint(p,i);
1104       
1105       UShort_t volid=atp->GetVolumeID()[i];
1106       Int_t index=AliITSAlignMille2Module::GetIndexFromVolumeID(volid);
1107       
1108       if(index<0 || index>=2200) continue;
1109       // dealign point
1110       // get MODIFIED matrix
1111       TGeoHMatrix *svMatrix = m2[index]->GetSensitiveVolumeMatrix(p.GetVolumeID());
1112       //TGeoHMatrix *svOrigMatrix = mm->GetSensitiveVolumeOrigGlobalMatrix(p.GetVolumeID());
1113       
1114       Double_t pg[3],pl[3];
1115       pg[0]=p.GetX();
1116       pg[1]=p.GetY();
1117       pg[2]=p.GetZ();
1118       if (prn) printf("Global coordinates of measured point : X=%f  Y=%f  Z=%f \n",pg[0],pg[1],pg[2]);
1119       svMatrix->MasterToLocal(pg,pl);
1120       
1121       // check that things went OK: local y should be 0.
1122       if(TMath::Abs(pl[1])>1.e-6) {
1123         printf("AliAlignmentDataFilterITS::WriteTrackPointsInIdealGeom: ERROR, local y = %f (should be zero)\n",pl[1]);
1124         return -7;
1125       }
1126
1127       if (prn) printf("Local coordinates of measured point : X=%f  Y=%f  Z=%f \n",pl[0],pl[1],pl[2]);
1128       
1129       // update covariance matrix
1130       TGeoHMatrix hcov;
1131       Double_t hcovel[9];
1132       hcovel[0]=(Double_t)(p.GetCov()[0]);
1133       hcovel[1]=(Double_t)(p.GetCov()[1]);
1134       hcovel[2]=(Double_t)(p.GetCov()[2]);
1135       hcovel[3]=(Double_t)(p.GetCov()[1]);
1136       hcovel[4]=(Double_t)(p.GetCov()[3]);
1137       hcovel[5]=(Double_t)(p.GetCov()[4]);
1138       hcovel[6]=(Double_t)(p.GetCov()[2]);
1139       hcovel[7]=(Double_t)(p.GetCov()[4]);
1140       hcovel[8]=(Double_t)(p.GetCov()[5]);
1141       hcov.SetRotation(hcovel);
1142       // now rotate in local system
1143       hcov.Multiply(svMatrix);
1144       hcov.MultiplyLeft(&svMatrix->Inverse());
1145       // now hcov is LOCAL COVARIANCE MATRIX
1146       
1147       /// get original matrix of sens. vol.
1148       TGeoHMatrix *svOrigMatrix = m2[index]->GetSensitiveVolumeOrigGlobalMatrix(p.GetVolumeID());
1149       // modify global coordinates according with pre-aligment
1150       svOrigMatrix->LocalToMaster(pl,pg);
1151       // now rotate in local system
1152       hcov.Multiply(&svOrigMatrix->Inverse());
1153       hcov.MultiplyLeft(svOrigMatrix);
1154       // hcov is back in GLOBAL RF
1155       Float_t pcov[6];
1156       pcov[0]=hcov.GetRotationMatrix()[0];
1157       pcov[1]=hcov.GetRotationMatrix()[1];
1158       pcov[2]=hcov.GetRotationMatrix()[2];
1159       pcov[3]=hcov.GetRotationMatrix()[4];
1160       pcov[4]=hcov.GetRotationMatrix()[5];
1161       pcov[5]=hcov.GetRotationMatrix()[8];
1162       
1163       p.SetXYZ(pg[0],pg[1],pg[2],pcov);
1164       if (prn) printf("New global coordinates of measured point : X=%f  Y=%f  Z=%f \n",pg[0],pg[1],pg[2]);
1165       atps->AddPoint(npto,&p);
1166       if (prn) printf("Adding point[%d] = ( %f , %f , %f )     volid = %d\n",npto,atps->GetX()[npto],atps->GetY()[npto],atps->GetZ()[npto],atps->GetVolumeID()[npto] );
1167       if (prn) p.Print("");
1168       
1169       npto++;
1170     }
1171     
1172     
1173     ////////////////////////////////////////////////////////////
1174     array = atps;
1175     treeout->Fill();
1176     
1177     delete atps;
1178     atps=NULL;
1179     
1180   } // end loop on tracks
1181   
1182   pointsFile->Write();
1183   pointsFile->Close();
1184   tpainfile->Close();
1185   
1186   return 0;
1187 }