]> git.uio.no Git - u/mrichter/AliRoot.git/blob - TPC/AliTPCCorrection.cxx
- Inclusion of AliTPCSpaceCharge3D in TPCbase library
[u/mrichter/AliRoot.git] / TPC / AliTPCCorrection.cxx
1 /**************************************************************************
2  * Copyright(c) 1998-1999, 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 // Begin_Html
19 //   <h2>  AliTPCCorrection class   </h2>    
20 //  
21 //   The AliTPCCorrection class provides a general framework to deal with space point distortions. 
22 //   An correction class which inherits from here is for example AliTPCExBBShape or AliTPCExBTwist. <br> 
23 //   General virtual functions are (for example) CorrectPoint(x,roc) where x is the vector of initial 
24 //   positions in cartesian coordinates and roc represents the read-out chamber number according to 
25 //   the offline numbering convention. The vector x is overwritten with the corrected coordinates. <br> 
26 //   An alternative usage would be CorrectPoint(x,roc,dx), which leaves the vector x untouched, but 
27 //   returns the distortions via the vector dx. <br>
28 //   This class is normally used via the general class AliTPCComposedCorrection.   
29 //   <p>
30 //   Furthermore, the class contains basic geometrical descriptions like field cage radii 
31 //   (fgkIFCRadius, fgkOFCRadius) and length (fgkTPCZ0) plus the voltages. Also, the definitions 
32 //   of size and widths of the fulcrums building the grid of the final look-up table, which is 
33 //   then interpolated, is defined in kNX and fgkXList).
34 //   <p>
35 //   All physics-model classes below are derived from this class in order to not duplicate code 
36 //   and to allow a uniform treatment of all physics models.
37 //   <p>
38 //   <h3> Poisson solver </h3>    
39 //   A numerical solver of the Poisson equation (relaxation technique) is implemented for 2-dimensional 
40 //   geometries (r,z) as well as for 3-dimensional problems (r,$\phi$,z). The corresponding function 
41 //   names are PoissonRelaxation?D. The relevant function arguments are the arrays of the boundary and 
42 //   initial conditions (ArrayofArrayV, ArrayofChargeDensities) as well as the grid granularity which 
43 //   is used during the calculation. These inputs can be chosen according to the needs of the physical 
44 //   effect which is supposed to be simulated. In the 3D version, different symmetry conditions can be set
45 //   in order to reduce the calculation time (used in AliTPCFCVoltError3D).
46 //   <p>
47 //   <h3> Unified plotting functionality  </h3>    
48 //   Generic plot functions were implemented. They return a histogram pointer in the chosen plane of 
49 //   the TPC drift volume with a selectable grid granularity and the magnitude of the correction vector.
50 //   For example, the function CreateHistoDZinXY(z,nx,ny) returns a 2-dimensional histogram which contains 
51 //   the longitudinal corrections $dz$ in the (x,y)-plane at the given z position with the granularity of 
52 //   nx and ny. The magnitude of the corrections is defined by the class from which this function is called.
53 //   In the same manner, standard plots for the (r,$\phi$)-plane and for the other corrections like $dr$ and $rd\phi$ are available  
54 //   <p>                                                                      
55 //   Note: This class is normally used via the class AliTPCComposedCorrection
56 // End_Html
57 //
58 // Begin_Macro(source) 
59 //   {
60 //   gROOT->SetStyle("Plain"); gStyle->SetPalette(1);
61 //   TCanvas *c2 = new TCanvas("c2","c2",700,1050);  c2->Divide(2,3);
62 //   AliTPCROCVoltError3D roc; // EXAMPLE PLOTS - SEE BELOW
63 //   roc.SetOmegaTauT1T2(0,1,1); // B=0
64 //   Float_t z0 = 1; // at +1 cm -> A side
65 //   c2->cd(1); roc.CreateHistoDRinXY(1.,300,300)->Draw("cont4z"); 
66 //   c2->cd(3);roc.CreateHistoDRPhiinXY(1.,300,300)->Draw("cont4z"); 
67 //   c2->cd(5);roc.CreateHistoDZinXY(1.,300,300)->Draw("cont4z"); 
68 //   Float_t phi0=0.5;
69 //   c2->cd(2);roc.CreateHistoDRinZR(phi0)->Draw("surf2"); 
70 //   c2->cd(4);roc.CreateHistoDRPhiinZR(phi0)->Draw("surf2"); 
71 //   c2->cd(6);roc.CreateHistoDZinZR(phi0)->Draw("surf2"); 
72 //   return c2;
73 //   } 
74 // End_Macro
75 //
76 // Begin_Html
77 //   <p>
78 //   Date: 27/04/2010  <br>
79 //   Authors: Magnus Mager, Stefan Rossegger, Jim Thomas                     
80 // End_Html 
81 // _________________________________________________________________
82
83
84 #include "Riostream.h"
85
86 #include <TH2F.h>
87 #include <TMath.h>
88 #include <TROOT.h>
89 #include <TTreeStream.h>
90 #include <TTree.h>
91 #include <TFile.h>
92 #include <TTimeStamp.h>
93 #include <AliCDBStorage.h>
94 #include <AliCDBId.h>
95 #include <AliCDBMetaData.h>
96 #include "TVectorD.h"
97 #include "AliTPCParamSR.h"
98
99 #include "AliTPCCorrection.h"
100 #include "AliLog.h"
101
102 #include "AliExternalTrackParam.h"
103 #include "AliTrackPointArray.h"
104 #include "TDatabasePDG.h"
105 #include "AliTrackerBase.h"
106 #include "AliTPCROC.h"
107 #include "THnSparse.h"
108
109 #include "AliTPCLaserTrack.h"
110 #include "AliESDVertex.h"
111 #include "AliVertexerTracks.h"
112 #include "TDatabasePDG.h"
113 #include "TF1.h"
114 #include "TRandom.h"
115
116 #include "TDatabasePDG.h"
117
118 #include "AliTPCTransform.h"
119 #include "AliTPCcalibDB.h"
120 #include "AliTPCExB.h"
121
122 #include "AliTPCRecoParam.h"
123
124
125 ClassImp(AliTPCCorrection)
126
127
128 TObjArray *AliTPCCorrection::fgVisualCorrection=0;
129 // instance of correction for visualization
130
131
132 // FIXME: the following values should come from the database
133 const Double_t AliTPCCorrection::fgkTPCZ0    = 249.7;     // nominal gating grid position 
134 const Double_t AliTPCCorrection::fgkIFCRadius=  83.5;     // radius which renders the "18 rod manifold" best -> compare calc. of Jim Thomas
135 // compare gkIFCRadius=  83.05: Mean Radius of the Inner Field Cage ( 82.43 min,  83.70 max) (cm)
136 const Double_t AliTPCCorrection::fgkOFCRadius= 254.5;     // Mean Radius of the Outer Field Cage (252.55 min, 256.45 max) (cm)
137 const Double_t AliTPCCorrection::fgkZOffSet  =   0.2;     // Offset from CE: calculate all distortions closer to CE as if at this point
138 const Double_t AliTPCCorrection::fgkCathodeV = -100000.0; // Cathode Voltage (volts)
139 const Double_t AliTPCCorrection::fgkGG       =     -70.0; // Gating Grid voltage (volts)
140
141 const Double_t  AliTPCCorrection::fgkdvdE = 0.0024; // [cm/V] drift velocity dependency on the E field (from Magboltz for NeCO2N2 at standard environment)
142
143 const Double_t AliTPCCorrection::fgkEM = -1.602176487e-19/9.10938215e-31; // charge/mass in [C/kg]
144 const Double_t AliTPCCorrection::fgke0 = 8.854187817e-12;                 // vacuum permittivity [A·s/(V·m)]
145  
146
147 AliTPCCorrection::AliTPCCorrection() 
148   : TNamed("correction_unity","unity"),fILow(0),fJLow(0),fKLow(0), fT1(1), fT2(1)
149 {
150   //
151   // default constructor
152   //
153   if (!fgVisualCorrection) fgVisualCorrection= new TObjArray;
154
155   InitLookUpfulcrums();
156
157 }
158
159 AliTPCCorrection::AliTPCCorrection(const char *name,const char *title)
160 : TNamed(name,title),fILow(0),fJLow(0),fKLow(0), fT1(1), fT2(1)
161 {
162   //
163   // default constructor, that set the name and title
164   //
165   if (!fgVisualCorrection) fgVisualCorrection= new TObjArray;
166
167   InitLookUpfulcrums();
168
169 }
170
171 AliTPCCorrection::~AliTPCCorrection() {
172   // 
173   // virtual destructor
174   //
175 }
176
177 void AliTPCCorrection::CorrectPoint(Float_t x[],const Short_t roc) {
178   //
179   // Corrects the initial coordinates x (cartesian coordinates)
180   // according to the given effect (inherited classes)
181   // roc represents the TPC read out chamber (offline numbering convention)
182   //
183   Float_t dx[3];
184   GetCorrection(x,roc,dx);
185   for (Int_t j=0;j<3;++j) x[j]+=dx[j];
186 }
187
188 void AliTPCCorrection::CorrectPoint(const Float_t x[],const Short_t roc,Float_t xp[]) {
189   //
190   // Corrects the initial coordinates x (cartesian coordinates) and stores the new 
191   // (distorted) coordinates in xp. The distortion is set according to the given effect (inherited classes)
192   // roc represents the TPC read out chamber (offline numbering convention)
193   //
194   Float_t dx[3];
195   GetCorrection(x,roc,dx);
196   for (Int_t j=0;j<3;++j) xp[j]=x[j]+dx[j];
197 }
198
199 void AliTPCCorrection::DistortPoint(Float_t x[],const Short_t roc) {
200   //
201   // Distorts the initial coordinates x (cartesian coordinates)
202   // according to the given effect (inherited classes)
203   // roc represents the TPC read out chamber (offline numbering convention)
204   //
205   Float_t dx[3];
206   GetDistortion(x,roc,dx);
207   for (Int_t j=0;j<3;++j) x[j]+=dx[j];
208 }
209
210 void AliTPCCorrection::DistortPoint(const Float_t x[],const Short_t roc,Float_t xp[]) {
211   //
212   // Distorts the initial coordinates x (cartesian coordinates) and stores the new 
213   // (distorted) coordinates in xp. The distortion is set according to the given effect (inherited classes)
214   // roc represents the TPC read out chamber (offline numbering convention)
215   //
216   Float_t dx[3];
217   GetDistortion(x,roc,dx);
218   for (Int_t j=0;j<3;++j) xp[j]=x[j]+dx[j];
219 }
220
221 void AliTPCCorrection::GetCorrection(const Float_t /*x*/[],const Short_t /*roc*/,Float_t dx[]) {
222   //
223   // This function delivers the correction values dx in respect to the inital coordinates x
224   // roc represents the TPC read out chamber (offline numbering convention)
225   // Note: The dx is overwritten by the inherited effectice class ...
226   //
227   for (Int_t j=0;j<3;++j) { dx[j]=0.; }
228 }
229
230 void AliTPCCorrection::GetDistortion(const Float_t x[],const Short_t roc,Float_t dx[]) {
231   //
232   // This function delivers the distortion values dx in respect to the inital coordinates x
233   // roc represents the TPC read out chamber (offline numbering convention)
234   //
235   GetCorrection(x,roc,dx);
236   for (Int_t j=0;j<3;++j) dx[j]=-dx[j];
237 }
238
239 void AliTPCCorrection::Init() {
240   //
241   // Initialization funtion (not used at the moment)
242   //
243 }
244
245 void AliTPCCorrection::Update(const TTimeStamp &/*timeStamp*/) {
246   //
247   // Update function 
248   //
249 }
250
251 void AliTPCCorrection::Print(Option_t* /*option*/) const {
252   //
253   // Print function to check which correction classes are used 
254   // option=="d" prints details regarding the setted magnitude 
255   // option=="a" prints the C0 and C1 coefficents for calibration purposes
256   //
257   printf("TPC spacepoint correction: \"%s\"\n",GetTitle());
258 }
259
260 void AliTPCCorrection:: SetOmegaTauT1T2(Float_t /*omegaTau*/,Float_t t1,Float_t t2) {
261   //
262   // Virtual funtion to pass the wt values (might become event dependent) to the inherited classes
263   // t1 and t2 represent the "effective omegaTau" corrections and were measured in a dedicated
264   // calibration run
265   //
266   fT1=t1;
267   fT2=t2;
268   //SetOmegaTauT1T2(omegaTau, t1, t2);
269 }
270
271 TH2F* AliTPCCorrection::CreateHistoDRinXY(Float_t z,Int_t nx,Int_t ny) {
272   //
273   // Simple plot functionality.
274   // Returns a 2d hisogram which represents the corrections in radial direction (dr)
275   // in respect to position z within the XY plane.
276   // The histogramm has nx times ny entries. 
277   //
278   AliTPCParam* tpcparam = new AliTPCParamSR;
279
280   TH2F *h=CreateTH2F("dr_xy",GetTitle(),"x [cm]","y [cm]","dr [cm]",
281                      nx,-250.,250.,ny,-250.,250.);
282   Float_t x[3],dx[3];
283   x[2]=z;
284   Int_t roc=z>0.?0:18; // FIXME
285   for (Int_t iy=1;iy<=ny;++iy) {
286     x[1]=h->GetYaxis()->GetBinCenter(iy);
287     for (Int_t ix=1;ix<=nx;++ix) {
288       x[0]=h->GetXaxis()->GetBinCenter(ix);
289       GetCorrection(x,roc,dx);
290       Float_t r0=TMath::Sqrt((x[0]      )*(x[0]      )+(x[1]      )*(x[1]      ));
291       if (tpcparam->GetPadRowRadii(0,0)<=r0 && r0<=tpcparam->GetPadRowRadii(36,95)) {
292         Float_t r1=TMath::Sqrt((x[0]+dx[0])*(x[0]+dx[0])+(x[1]+dx[1])*(x[1]+dx[1]));
293         h->SetBinContent(ix,iy,r1-r0);
294       }
295       else
296         h->SetBinContent(ix,iy,0.);
297     }
298   }
299   delete tpcparam;
300   return h;
301 }
302
303 TH2F* AliTPCCorrection::CreateHistoDRPhiinXY(Float_t z,Int_t nx,Int_t ny) {
304   //
305   // Simple plot functionality.
306   // Returns a 2d hisogram which represents the corrections in rphi direction (drphi) 
307   // in respect to position z within the XY plane.
308   // The histogramm has nx times ny entries. 
309   //
310
311   AliTPCParam* tpcparam = new AliTPCParamSR;
312
313   TH2F *h=CreateTH2F("drphi_xy",GetTitle(),"x [cm]","y [cm]","drphi [cm]",
314                      nx,-250.,250.,ny,-250.,250.);
315   Float_t x[3],dx[3];
316   x[2]=z;
317   Int_t roc=z>0.?0:18; // FIXME
318   for (Int_t iy=1;iy<=ny;++iy) {
319     x[1]=h->GetYaxis()->GetBinCenter(iy);
320     for (Int_t ix=1;ix<=nx;++ix) {
321       x[0]=h->GetXaxis()->GetBinCenter(ix);
322       GetCorrection(x,roc,dx);
323       Float_t r0=TMath::Sqrt((x[0]      )*(x[0]      )+(x[1]      )*(x[1]      ));
324       if (tpcparam->GetPadRowRadii(0,0)<=r0 && r0<=tpcparam->GetPadRowRadii(36,95)) {
325         Float_t phi0=TMath::ATan2(x[1]      ,x[0]      );
326         Float_t phi1=TMath::ATan2(x[1]+dx[1],x[0]+dx[0]);
327
328         Float_t dphi=phi1-phi0;
329         if (dphi<TMath::Pi()) dphi+=TMath::TwoPi();
330         if (dphi>TMath::Pi()) dphi-=TMath::TwoPi();
331       
332         h->SetBinContent(ix,iy,r0*dphi);
333       }
334       else
335         h->SetBinContent(ix,iy,0.);
336     }
337   }
338   delete tpcparam;
339   return h;
340 }
341
342 TH2F* AliTPCCorrection::CreateHistoDZinXY(Float_t z,Int_t nx,Int_t ny) {
343   //
344   // Simple plot functionality.
345   // Returns a 2d hisogram which represents the corrections in longitudinal direction (dz)
346   // in respect to position z within the XY plane.
347   // The histogramm has nx times ny entries. 
348   //
349
350   AliTPCParam* tpcparam = new AliTPCParamSR;
351  
352   TH2F *h=CreateTH2F("dz_xy",GetTitle(),"x [cm]","y [cm]","dz [cm]",
353                      nx,-250.,250.,ny,-250.,250.);
354   Float_t x[3],dx[3];
355   x[2]=z;
356   Int_t roc=z>0.?0:18; // FIXME
357   for (Int_t iy=1;iy<=ny;++iy) {
358     x[1]=h->GetYaxis()->GetBinCenter(iy);
359     for (Int_t ix=1;ix<=nx;++ix) {
360       x[0]=h->GetXaxis()->GetBinCenter(ix);
361       GetCorrection(x,roc,dx);
362       Float_t r0=TMath::Sqrt((x[0]      )*(x[0]      )+(x[1]      )*(x[1]      ));
363       if (tpcparam->GetPadRowRadii(0,0)<=r0 && r0<=tpcparam->GetPadRowRadii(36,95)) {
364         h->SetBinContent(ix,iy,dx[2]);
365       }
366       else
367         h->SetBinContent(ix,iy,0.);
368     }
369   }
370   delete tpcparam;
371   return h;
372 }
373
374 TH2F* AliTPCCorrection::CreateHistoDRinZR(Float_t phi,Int_t nz,Int_t nr) {
375   //
376   // Simple plot functionality.
377   // Returns a 2d hisogram which represents the corrections in r direction (dr) 
378   // in respect to angle phi within the ZR plane.
379   // The histogramm has nx times ny entries. 
380   //
381   TH2F *h=CreateTH2F("dr_zr",GetTitle(),"z [cm]","r [cm]","dr [cm]",
382                      nz,-250.,250.,nr,85.,250.);
383   Float_t x[3],dx[3];
384   for (Int_t ir=1;ir<=nr;++ir) {
385     Float_t radius=h->GetYaxis()->GetBinCenter(ir);
386     x[0]=radius*TMath::Cos(phi);
387     x[1]=radius*TMath::Sin(phi);
388     for (Int_t iz=1;iz<=nz;++iz) {
389       x[2]=h->GetXaxis()->GetBinCenter(iz);
390       Int_t roc=x[2]>0.?0:18; // FIXME
391       GetCorrection(x,roc,dx);
392       Float_t r0=TMath::Sqrt((x[0]      )*(x[0]      )+(x[1]      )*(x[1]      ));
393       Float_t r1=TMath::Sqrt((x[0]+dx[0])*(x[0]+dx[0])+(x[1]+dx[1])*(x[1]+dx[1]));
394       h->SetBinContent(iz,ir,r1-r0);
395     }
396   }
397   return h;
398
399 }
400
401 TH2F* AliTPCCorrection::CreateHistoDRPhiinZR(Float_t phi,Int_t nz,Int_t nr) {
402   //
403   // Simple plot functionality.
404   // Returns a 2d hisogram which represents the corrections in rphi direction (drphi) 
405   // in respect to angle phi within the ZR plane.
406   // The histogramm has nx times ny entries. 
407   //
408   TH2F *h=CreateTH2F("drphi_zr",GetTitle(),"z [cm]","r [cm]","drphi [cm]",
409                      nz,-250.,250.,nr,85.,250.);
410   Float_t x[3],dx[3];
411   for (Int_t iz=1;iz<=nz;++iz) {
412     x[2]=h->GetXaxis()->GetBinCenter(iz);
413     Int_t roc=x[2]>0.?0:18; // FIXME
414     for (Int_t ir=1;ir<=nr;++ir) {
415       Float_t radius=h->GetYaxis()->GetBinCenter(ir);
416       x[0]=radius*TMath::Cos(phi);
417       x[1]=radius*TMath::Sin(phi);
418       GetCorrection(x,roc,dx);
419       Float_t r0=TMath::Sqrt((x[0]      )*(x[0]      )+(x[1]      )*(x[1]      ));
420       Float_t phi0=TMath::ATan2(x[1]      ,x[0]      );
421       Float_t phi1=TMath::ATan2(x[1]+dx[1],x[0]+dx[0]);
422       
423       Float_t dphi=phi1-phi0;
424       if (dphi<TMath::Pi()) dphi+=TMath::TwoPi();
425       if (dphi>TMath::Pi()) dphi-=TMath::TwoPi();
426       
427       h->SetBinContent(iz,ir,r0*dphi);
428     }
429   }
430   return h;
431 }
432
433 TH2F* AliTPCCorrection::CreateHistoDZinZR(Float_t phi,Int_t nz,Int_t nr) {
434   //
435   // Simple plot functionality.
436   // Returns a 2d hisogram which represents the corrections in longitudinal direction (dz) 
437   // in respect to angle phi within the ZR plane.
438   // The histogramm has nx times ny entries. 
439   //
440   TH2F *h=CreateTH2F("dz_zr",GetTitle(),"z [cm]","r [cm]","dz [cm]",
441                      nz,-250.,250.,nr,85.,250.);
442   Float_t x[3],dx[3];
443   for (Int_t ir=1;ir<=nr;++ir) {
444     Float_t radius=h->GetYaxis()->GetBinCenter(ir);
445     x[0]=radius*TMath::Cos(phi);
446     x[1]=radius*TMath::Sin(phi);
447     for (Int_t iz=1;iz<=nz;++iz) {
448       x[2]=h->GetXaxis()->GetBinCenter(iz);
449       Int_t roc=x[2]>0.?0:18; // FIXME
450       GetCorrection(x,roc,dx);
451       h->SetBinContent(iz,ir,dx[2]);
452     }
453   }
454   return h;
455
456 }
457
458
459 TH2F* AliTPCCorrection::CreateTH2F(const char *name,const char *title,
460                                    const char *xlabel,const char *ylabel,const char *zlabel,
461                                   Int_t nbinsx,Double_t xlow,Double_t xup,
462                                   Int_t nbinsy,Double_t ylow,Double_t yup) {
463   //
464   // Helper function to create a 2d histogramm of given size
465   //
466   
467   TString hname=name;
468   Int_t i=0;
469   if (gDirectory) {
470     while (gDirectory->FindObject(hname.Data())) {
471       hname =name;
472       hname+="_";
473       hname+=i;
474       ++i;
475     }
476   }
477   TH2F *h=new TH2F(hname.Data(),title,
478                    nbinsx,xlow,xup,
479                    nbinsy,ylow,yup);
480   h->GetXaxis()->SetTitle(xlabel);
481   h->GetYaxis()->SetTitle(ylabel);
482   h->GetZaxis()->SetTitle(zlabel);
483   h->SetStats(0);
484   return h;
485 }
486
487 // Simple Interpolation functions: e.g. with bi(tri)cubic interpolations (not yet in TH2 and TH3)
488
489 void AliTPCCorrection::Interpolate2DEdistortion( const Int_t order, const Double_t r, const Double_t z, 
490                                                   const Double_t er[kNZ][kNR], Double_t &erValue ) {
491   //
492   // Interpolate table - 2D interpolation
493   //
494   Double_t saveEr[5] = {0,0,0,0,0};
495
496   Search( kNZ,   fgkZList,  z,   fJLow   ) ;
497   Search( kNR,   fgkRList,  r,   fKLow   ) ;
498   if ( fJLow < 0 ) fJLow = 0 ;   // check if out of range
499   if ( fKLow < 0 ) fKLow = 0 ;
500   if ( fJLow + order  >=    kNZ - 1 ) fJLow =   kNZ - 1 - order ;
501   if ( fKLow + order  >=    kNR - 1 ) fKLow =   kNR - 1 - order ;
502
503   for ( Int_t j = fJLow ; j < fJLow + order + 1 ; j++ ) {
504       saveEr[j-fJLow]     = Interpolate( &fgkRList[fKLow], &er[j][fKLow], order, r )   ;
505   }
506   erValue = Interpolate( &fgkZList[fJLow], saveEr, order, z )   ;
507
508 }
509
510 void AliTPCCorrection::Interpolate3DEdistortion( const Int_t order, const Double_t r, const Float_t phi, const Double_t z, 
511                                                  const Double_t er[kNZ][kNPhi][kNR], const Double_t ephi[kNZ][kNPhi][kNR], const Double_t ez[kNZ][kNPhi][kNR],
512                                                  Double_t &erValue, Double_t &ephiValue, Double_t &ezValue) {
513   //
514   // Interpolate table - 3D interpolation
515   //
516   
517   Double_t saveEr[5]= {0,0,0,0,0};
518   Double_t savedEr[5]= {0,0,0,0,0} ;
519
520   Double_t saveEphi[5]= {0,0,0,0,0};
521   Double_t savedEphi[5]= {0,0,0,0,0} ;
522
523   Double_t saveEz[5]= {0,0,0,0,0};
524   Double_t savedEz[5]= {0,0,0,0,0} ;
525
526   Search( kNZ,   fgkZList,   z,   fILow   ) ;
527   Search( kNPhi, fgkPhiList, z,   fJLow   ) ;
528   Search( kNR,   fgkRList,   r,   fKLow   ) ;
529
530   if ( fILow < 0 ) fILow = 0 ;   // check if out of range
531   if ( fJLow < 0 ) fJLow = 0 ;
532   if ( fKLow < 0 ) fKLow = 0 ;
533
534   if ( fILow + order  >=    kNZ - 1 ) fILow =   kNZ - 1 - order ;
535   if ( fJLow + order  >=  kNPhi - 1 ) fJLow = kNPhi - 1 - order ;
536   if ( fKLow + order  >=    kNR - 1 ) fKLow =   kNR - 1 - order ;
537
538   for ( Int_t i = fILow ; i < fILow + order + 1 ; i++ ) {
539     for ( Int_t j = fJLow ; j < fJLow + order + 1 ; j++ ) {
540       saveEr[j-fJLow]     = Interpolate( &fgkRList[fKLow], &er[i][j][fKLow], order, r )   ;
541       saveEphi[j-fJLow]   = Interpolate( &fgkRList[fKLow], &ephi[i][j][fKLow], order, r ) ;
542       saveEz[j-fJLow]     = Interpolate( &fgkRList[fKLow], &ez[i][j][fKLow], order, r )   ;
543     }
544     savedEr[i-fILow]     = Interpolate( &fgkPhiList[fJLow], saveEr, order, phi )   ; 
545     savedEphi[i-fILow]   = Interpolate( &fgkPhiList[fJLow], saveEphi, order, phi ) ; 
546     savedEz[i-fILow]     = Interpolate( &fgkPhiList[fJLow], saveEz, order, phi )   ; 
547   }
548   erValue     = Interpolate( &fgkZList[fILow], savedEr, order, z )    ;
549   ephiValue   = Interpolate( &fgkZList[fILow], savedEphi, order, z )  ;
550   ezValue     = Interpolate( &fgkZList[fILow], savedEz, order, z )    ;
551
552 }
553
554 Double_t AliTPCCorrection::Interpolate2DTable( const Int_t order, const Double_t x, const Double_t y, 
555                                               const Int_t nx,  const Int_t ny, const Double_t xv[], const Double_t yv[], 
556                                               const TMatrixD &array ) {
557   //
558   // Interpolate table (TMatrix format) - 2D interpolation
559   //
560
561   static  Int_t jlow = 0, klow = 0 ;
562   Double_t saveArray[5] = {0,0,0,0,0} ;
563
564   Search( nx,  xv,  x,   jlow  ) ;
565   Search( ny,  yv,  y,   klow  ) ;
566   if ( jlow < 0 ) jlow = 0 ;   // check if out of range
567   if ( klow < 0 ) klow = 0 ;
568   if ( jlow + order  >=    nx - 1 ) jlow =   nx - 1 - order ;
569   if ( klow + order  >=    ny - 1 ) klow =   ny - 1 - order ;
570
571   for ( Int_t j = jlow ; j < jlow + order + 1 ; j++ )
572     {
573       Double_t *ajkl = &((TMatrixD&)array)(j,klow);
574       saveArray[j-jlow]  = Interpolate( &yv[klow], ajkl , order, y )   ;
575     }
576
577   return( Interpolate( &xv[jlow], saveArray, order, x ) )   ;
578
579 }
580
581 Double_t AliTPCCorrection::Interpolate3DTable( const Int_t order, const Double_t x,   const Double_t y,   const Double_t z,
582                                               const Int_t  nx,    const Int_t  ny,    const Int_t  nz,
583                                               const Double_t xv[], const Double_t yv[], const Double_t zv[],
584                                               TMatrixD **arrayofArrays ) {
585   //
586   // Interpolate table (TMatrix format) - 3D interpolation
587   //
588
589   static  Int_t ilow = 0, jlow = 0, klow = 0 ;
590   Double_t saveArray[5]= {0,0,0,0,0};
591   Double_t savedArray[5]= {0,0,0,0,0} ;
592
593   Search( nx, xv, x, ilow   ) ;
594   Search( ny, yv, y, jlow   ) ;
595   Search( nz, zv, z, klow   ) ;  
596
597   if ( ilow < 0 ) ilow = 0 ;   // check if out of range
598   if ( jlow < 0 ) jlow = 0 ;
599   if ( klow < 0 ) klow = 0 ;
600
601   if ( ilow + order  >=    nx - 1 ) ilow =   nx - 1 - order ;
602   if ( jlow + order  >=    ny - 1 ) jlow =   ny - 1 - order ;
603   if ( klow + order  >=    nz - 1 ) klow =   nz - 1 - order ;
604
605   for ( Int_t k = klow ; k < klow + order + 1 ; k++ )
606     {
607       TMatrixD &table = *arrayofArrays[k] ;
608       for ( Int_t i = ilow ; i < ilow + order + 1 ; i++ )
609         {
610           saveArray[i-ilow] = Interpolate( &yv[jlow], &table(i,jlow), order, y )   ;
611         }
612       savedArray[k-klow] = Interpolate( &xv[ilow], saveArray, order, x )   ; 
613     }
614   return( Interpolate( &zv[klow], savedArray, order, z ) )   ;
615
616 }
617
618
619 Double_t AliTPCCorrection::Interpolate( const Double_t xArray[], const Double_t yArray[], 
620                                        const Int_t order, const Double_t x ) {
621   //
622   // Interpolate function Y(x) using linear (order=1) or quadratic (order=2) interpolation.
623   //
624
625   Double_t y ;
626   if ( order == 2 ) {                // Quadratic Interpolation = 2 
627     y  = (x-xArray[1]) * (x-xArray[2]) * yArray[0] / ( (xArray[0]-xArray[1]) * (xArray[0]-xArray[2]) ) ; 
628     y += (x-xArray[2]) * (x-xArray[0]) * yArray[1] / ( (xArray[1]-xArray[2]) * (xArray[1]-xArray[0]) ) ; 
629     y += (x-xArray[0]) * (x-xArray[1]) * yArray[2] / ( (xArray[2]-xArray[0]) * (xArray[2]-xArray[1]) ) ; 
630   } else {                           // Linear Interpolation = 1
631     y  = yArray[0] + ( yArray[1]-yArray[0] ) * ( x-xArray[0] ) / ( xArray[1] - xArray[0] ) ;
632   }
633
634   return (y);
635
636 }
637
638
639 void AliTPCCorrection::Search( const Int_t n, const Double_t xArray[], const Double_t x, Int_t &low ) {
640   //
641   // Search an ordered table by starting at the most recently used point
642   //
643
644   Long_t middle, high ;
645   Int_t  ascend = 0, increment = 1 ;
646
647   if ( xArray[n-1] >= xArray[0] ) ascend = 1 ;  // Ascending ordered table if true
648   
649   if ( low < 0 || low > n-1 ) { 
650     low = -1 ; high = n ; 
651   } else {                                            // Ordered Search phase
652     if ( (Int_t)( x >= xArray[low] ) == ascend )  {
653       if ( low == n-1 ) return ;          
654       high = low + 1 ;
655       while ( (Int_t)( x >= xArray[high] ) == ascend ) {
656         low = high ;
657         increment *= 2 ;
658         high = low + increment ;
659         if ( high > n-1 )  {  high = n ; break ;  }
660       }
661     } else {
662       if ( low == 0 )  {  low = -1 ;  return ;  }
663       high = low - 1 ;
664       while ( (Int_t)( x < xArray[low] ) == ascend ) {
665         high = low ;
666         increment *= 2 ;
667         if ( increment >= high )  {  low = -1 ;  break ;  }
668         else  low = high - increment ;
669       }
670     }
671   }
672   
673   while ( (high-low) != 1 ) {                     // Binary Search Phase
674     middle = ( high + low ) / 2 ;
675     if ( (Int_t)( x >= xArray[middle] ) == ascend )
676       low = middle ;
677     else
678       high = middle ;
679   }
680   
681   if ( x == xArray[n-1] ) low = n-2 ;
682   if ( x == xArray[0]   ) low = 0 ;
683   
684 }
685
686 void AliTPCCorrection::InitLookUpfulcrums() {
687   //
688   // Initialization of interpolation points - for main look up table
689   //   (course grid in the middle, fine grid on the borders)
690   //
691
692   AliTPCROC * roc = AliTPCROC::Instance();
693   const Double_t rLow =  TMath::Floor(roc->GetPadRowRadii(0,0))-1; // first padRow plus some margin 
694
695   // fulcrums in R
696   fgkRList[0] = rLow;
697   for (Int_t i = 1; i<kNR; i++) {
698     fgkRList[i] = fgkRList[i-1] + 3.5;     // 3.5 cm spacing    
699     if (fgkRList[i]<90 ||fgkRList[i]>245) 
700        fgkRList[i] = fgkRList[i-1] + 0.5; // 0.5 cm spacing
701     else if (fgkRList[i]<100 || fgkRList[i]>235) 
702        fgkRList[i] = fgkRList[i-1] + 1.5;  // 1.5 cm spacing
703     else if (fgkRList[i]<120 || fgkRList[i]>225) 
704        fgkRList[i] = fgkRList[i-1] + 2.5;  // 2.5 cm spacing
705   }
706
707   // fulcrums in Z
708   fgkZList[0] = -249.5;
709   fgkZList[kNZ-1] = 249.5;
710   for (Int_t j = 1; j<kNZ/2; j++) {
711     fgkZList[j] = fgkZList[j-1];
712     if      (TMath::Abs(fgkZList[j])< 0.15)
713       fgkZList[j] = fgkZList[j-1] + 0.09; // 0.09 cm spacing
714     else if(TMath::Abs(fgkZList[j])< 0.6)
715       fgkZList[j] = fgkZList[j-1] + 0.4; // 0.4 cm spacing
716     else if      (TMath::Abs(fgkZList[j])< 2.5 || TMath::Abs(fgkZList[j])>248) 
717       fgkZList[j] = fgkZList[j-1] + 0.5; // 0.5 cm spacing
718     else if (TMath::Abs(fgkZList[j])<10 || TMath::Abs(fgkZList[j])>235) 
719       fgkZList[j] = fgkZList[j-1] + 1.5;  // 1.5 cm spacing
720     else if (TMath::Abs(fgkZList[j])<25 || TMath::Abs(fgkZList[j])>225) 
721       fgkZList[j] = fgkZList[j-1] + 2.5;  // 2.5 cm spacing
722     else 
723       fgkZList[j] = fgkZList[j-1] + 4;  // 4 cm spacing
724
725     fgkZList[kNZ-j-1] = -fgkZList[j];
726   }
727   
728   // fulcrums in phi
729   for (Int_t k = 0; k<kNPhi; k++) 
730     fgkPhiList[k] = TMath::TwoPi()*k/(kNPhi-1);    
731   
732   
733 }
734
735
736 void AliTPCCorrection::PoissonRelaxation2D(TMatrixD &arrayV, TMatrixD &chargeDensity, 
737                                            TMatrixD &arrayErOverEz, TMatrixD &arrayDeltaEz, 
738                                            const Int_t rows, const Int_t columns, const Int_t iterations,
739                                            const Bool_t rocDisplacement ) {
740   //
741   // Solve Poisson's Equation by Relaxation Technique in 2D (assuming cylindrical symmetry)
742   //
743   // Solve Poissons equation in a cylindrical coordinate system. The arrayV matrix must be filled with the 
744   // boundary conditions on the first and last rows, and the first and last columns.  The remainder of the 
745   // array can be blank or contain a preliminary guess at the solution.  The Charge density matrix contains 
746   // the enclosed spacecharge density at each point. The charge density matrix can be full of zero's if 
747   // you wish to solve Laplaces equation however it should not contain random numbers or you will get 
748   // random numbers back as a solution. 
749   // Poisson's equation is solved by iteratively relaxing the matrix to the final solution.  In order to 
750   // speed up the convergence to the best solution, this algorithm does a binary expansion of the solution 
751   // space.  First it solves the problem on a very sparse grid by skipping rows and columns in the original 
752   // matrix.  Then it doubles the number of points and solves the problem again.  Then it doubles the 
753   // number of points and solves the problem again.  This happens several times until the maximum number
754   // of points has been included in the array.  
755   //
756   // NOTE: In order for this algorithmto work, the number of rows and columns must be a power of 2 plus one.
757   // So rows == 2**M + 1 and columns == 2**N + 1.  The number of rows and columns can be different.
758   // 
759   // NOTE: rocDisplacement is used to include (or ignore) the ROC misalignment in the dz calculation
760   //
761   // Original code by Jim Thomas (STAR TPC Collaboration)
762   //
763
764   Double_t ezField = (fgkCathodeV-fgkGG)/fgkTPCZ0; // = ALICE Electric Field (V/cm) Magnitude ~ -400 V/cm; 
765
766   const Float_t  gridSizeR   =  (fgkOFCRadius-fgkIFCRadius) / (rows-1) ;
767   const Float_t  gridSizeZ   =  fgkTPCZ0 / (columns-1) ;
768   const Float_t  ratio       =  gridSizeR*gridSizeR / (gridSizeZ*gridSizeZ) ;
769
770   TMatrixD  arrayEr(rows,columns) ;
771   TMatrixD  arrayEz(rows,columns) ;
772
773   //Check that number of rows and columns is suitable for a binary expansion
774   
775   if ( !IsPowerOfTwo(rows-1) ) {
776     AliError("PoissonRelaxation - Error in the number of rows. Must be 2**M - 1");
777     return;
778   }
779   if ( !IsPowerOfTwo(columns-1) ) {
780     AliError("PoissonRelaxation - Error in the number of columns. Must be 2**N - 1");
781     return;
782   }
783   
784   // Solve Poisson's equation in cylindrical coordinates by relaxation technique
785   // Allow for different size grid spacing in R and Z directions
786   // Use a binary expansion of the size of the matrix to speed up the solution of the problem
787   
788   Int_t iOne = (rows-1)/4 ;
789   Int_t jOne = (columns-1)/4 ;
790   // Solve for N in 2**N, add one.
791   Int_t loops = 1 + (int) ( 0.5 + TMath::Log2( (double) TMath::Max(iOne,jOne) ) ) ;  
792
793   for ( Int_t count = 0 ; count < loops ; count++ ) { 
794     // Loop while the matrix expands & the resolution increases.
795
796     Float_t tempGridSizeR = gridSizeR * iOne ;
797     Float_t tempRatio     = ratio * iOne * iOne / ( jOne * jOne ) ;
798     Float_t tempFourth    = 1.0 / (2.0 + 2.0*tempRatio) ;
799     
800     // Do this the standard C++ way to avoid gcc extensions for Float_t coef1[rows]
801     std::vector<float> coef1(rows) ;  
802     std::vector<float> coef2(rows) ;  
803
804     for ( Int_t i = iOne ; i < rows-1 ; i+=iOne ) {
805        Float_t radius = fgkIFCRadius + i*gridSizeR ;
806       coef1[i] = 1.0 + tempGridSizeR/(2*radius);
807       coef2[i] = 1.0 - tempGridSizeR/(2*radius);
808     }
809     
810     TMatrixD sumChargeDensity(rows,columns) ;
811
812     for ( Int_t i = iOne ; i < rows-1 ; i += iOne ) {
813       Float_t radius = fgkIFCRadius + iOne*gridSizeR ;
814       for ( Int_t j = jOne ; j < columns-1 ; j += jOne ) {
815         if ( iOne == 1 && jOne == 1 ) sumChargeDensity(i,j) = chargeDensity(i,j) ;
816         else {        
817           // Add up all enclosed charge density contributions within 1/2 unit in all directions
818           Float_t weight = 0.0 ;
819           Float_t sum    = 0.0 ;
820           sumChargeDensity(i,j) = 0.0 ;
821           for ( Int_t ii = i-iOne/2 ; ii <= i+iOne/2 ; ii++ ) {
822             for ( Int_t jj = j-jOne/2 ; jj <= j+jOne/2 ; jj++ ) {
823               if ( ii == i-iOne/2 || ii == i+iOne/2 || jj == j-jOne/2 || jj == j+jOne/2 ) weight = 0.5 ;
824               else
825                 weight = 1.0 ;
826               // Note that this is cylindrical geometry
827               sumChargeDensity(i,j) += chargeDensity(ii,jj)*weight*radius ;  
828               sum += weight*radius ;
829             }
830           }
831           sumChargeDensity(i,j) /= sum ;
832         }
833         sumChargeDensity(i,j) *= tempGridSizeR*tempGridSizeR; // just saving a step later on
834        }
835     }
836
837     for ( Int_t k = 1 ; k <= iterations; k++ ) {               
838       // Solve Poisson's Equation
839       // Over-relaxation index, must be >= 1 but < 2.  Arrange for it to evolve from 2 => 1 
840       // as interations increase.
841       Float_t overRelax   = 1.0 + TMath::Sqrt( TMath::Cos( (k*TMath::PiOver2())/iterations ) ) ; 
842       Float_t overRelaxM1 = overRelax - 1.0 ;
843       Float_t overRelaxtempFourth, overRelaxcoef5 ;
844       overRelaxtempFourth = overRelax * tempFourth ;
845       overRelaxcoef5 = overRelaxM1 / overRelaxtempFourth ; 
846
847       for ( Int_t i = iOne ; i < rows-1 ; i += iOne ) {
848         for ( Int_t j = jOne ; j < columns-1 ; j += jOne ) {
849
850           arrayV(i,j) = (   coef2[i]       *   arrayV(i-iOne,j)
851                           + tempRatio      * ( arrayV(i,j-jOne) + arrayV(i,j+jOne) )
852                           - overRelaxcoef5 *   arrayV(i,j) 
853                           + coef1[i]       *   arrayV(i+iOne,j) 
854                           + sumChargeDensity(i,j) 
855                         ) * overRelaxtempFourth;
856         }
857       }
858
859       if ( k == iterations ) {    
860         // After full solution is achieved, copy low resolution solution into higher res array
861         for ( Int_t i = iOne ; i < rows-1 ; i += iOne ) {
862           for ( Int_t j = jOne ; j < columns-1 ; j += jOne ) {
863
864             if ( iOne > 1 ) {              
865               arrayV(i+iOne/2,j)                    =  ( arrayV(i+iOne,j) + arrayV(i,j)     ) / 2 ;
866               if ( i == iOne )  arrayV(i-iOne/2,j) =  ( arrayV(0,j)       + arrayV(iOne,j) ) / 2 ;
867             }
868             if ( jOne > 1 ) {
869               arrayV(i,j+jOne/2)                    =  ( arrayV(i,j+jOne) + arrayV(i,j) )     / 2 ;
870               if ( j == jOne )  arrayV(i,j-jOne/2) =  ( arrayV(i,0)       + arrayV(i,jOne) ) / 2 ;
871             }
872             if ( iOne > 1 && jOne > 1 ) {
873               arrayV(i+iOne/2,j+jOne/2) =  ( arrayV(i+iOne,j+jOne) + arrayV(i,j) ) / 2 ;
874               if ( i == iOne ) arrayV(i-iOne/2,j-jOne/2) =   ( arrayV(0,j-jOne) + arrayV(iOne,j) ) / 2 ;
875               if ( j == jOne ) arrayV(i-iOne/2,j-jOne/2) =   ( arrayV(i-iOne,0) + arrayV(i,jOne) ) / 2 ;
876               // Note that this leaves a point at the upper left and lower right corners uninitialized. 
877               // -> Not a big deal.
878             }
879
880           }
881         }
882       }
883
884     }
885
886     iOne = iOne / 2 ; if ( iOne < 1 ) iOne = 1 ;
887     jOne = jOne / 2 ; if ( jOne < 1 ) jOne = 1 ;
888
889     sumChargeDensity.Clear();
890   }      
891
892   // Differentiate V(r) and solve for E(r) using special equations for the first and last rows
893   for ( Int_t j = 0 ; j < columns ; j++ ) {       
894     for ( Int_t i = 1 ; i < rows-1 ; i++ ) arrayEr(i,j) = -1 * ( arrayV(i+1,j) - arrayV(i-1,j) ) / (2*gridSizeR) ;
895     arrayEr(0,j)      =  -1 * ( -0.5*arrayV(2,j) + 2.0*arrayV(1,j) - 1.5*arrayV(0,j) ) / gridSizeR ;  
896     arrayEr(rows-1,j) =  -1 * ( 1.5*arrayV(rows-1,j) - 2.0*arrayV(rows-2,j) + 0.5*arrayV(rows-3,j) ) / gridSizeR ; 
897   }
898
899   // Differentiate V(z) and solve for E(z) using special equations for the first and last columns
900   for ( Int_t i = 0 ; i < rows ; i++) {
901     for ( Int_t j = 1 ; j < columns-1 ; j++ ) arrayEz(i,j) = -1 * ( arrayV(i,j+1) - arrayV(i,j-1) ) / (2*gridSizeZ) ;
902     arrayEz(i,0)         =  -1 * ( -0.5*arrayV(i,2) + 2.0*arrayV(i,1) - 1.5*arrayV(i,0) ) / gridSizeZ ;  
903     arrayEz(i,columns-1) =  -1 * ( 1.5*arrayV(i,columns-1) - 2.0*arrayV(i,columns-2) + 0.5*arrayV(i,columns-3) ) / gridSizeZ ; 
904   }
905   
906   for ( Int_t i = 0 ; i < rows ; i++) {
907     // Note: go back and compare to old version of this code.  See notes below.
908     // JT Test ... attempt to divide by real Ez not Ez to first order
909     for ( Int_t j = 0 ; j < columns ; j++ ) {
910       arrayEz(i,j) += ezField;
911       // This adds back the overall Z gradient of the field (main E field component)
912     } 
913     // Warning: (-=) assumes you are using an error potetial without the overall Field included
914   }                                 
915   
916   // Integrate Er/Ez from Z to zero
917   for ( Int_t j = 0 ; j < columns ; j++ )  {      
918     for ( Int_t i = 0 ; i < rows ; i++ ) {
919       
920       Int_t index = 1 ;   // Simpsons rule if N=odd.  If N!=odd then add extra point by trapezoidal rule.  
921       arrayErOverEz(i,j) = 0.0 ;
922       arrayDeltaEz(i,j) = 0.0 ;
923       
924       for ( Int_t k = j ; k < columns ; k++ ) {
925         arrayErOverEz(i,j)  +=  index*(gridSizeZ/3.0)*arrayEr(i,k)/arrayEz(i,k) ;
926         arrayDeltaEz(i,j)   +=  index*(gridSizeZ/3.0)*(arrayEz(i,k)-ezField) ;
927         if ( index != 4 )  index = 4; else index = 2 ;
928       }
929       if ( index == 4 ) {
930         arrayErOverEz(i,j)  -=  (gridSizeZ/3.0)*arrayEr(i,columns-1)/arrayEz(i,columns-1) ;
931         arrayDeltaEz(i,j)   -=  (gridSizeZ/3.0)*(arrayEz(i,columns-1)-ezField) ;
932       }
933       if ( index == 2 ) {
934         arrayErOverEz(i,j)  +=  (gridSizeZ/3.0) * ( 0.5*arrayEr(i,columns-2)/arrayEz(i,columns-2) 
935                                                     -2.5*arrayEr(i,columns-1)/arrayEz(i,columns-1));
936         arrayDeltaEz(i,j)   +=  (gridSizeZ/3.0) * ( 0.5*(arrayEz(i,columns-2)-ezField) 
937                                                     -2.5*(arrayEz(i,columns-1)-ezField));
938       }
939       if ( j == columns-2 ) {
940         arrayErOverEz(i,j) =  (gridSizeZ/3.0) * ( 1.5*arrayEr(i,columns-2)/arrayEz(i,columns-2)
941                                                   +1.5*arrayEr(i,columns-1)/arrayEz(i,columns-1) ) ;
942         arrayDeltaEz(i,j)  =  (gridSizeZ/3.0) * ( 1.5*(arrayEz(i,columns-2)-ezField)
943                                                   +1.5*(arrayEz(i,columns-1)-ezField) ) ;
944       }
945       if ( j == columns-1 ) {
946         arrayErOverEz(i,j) =  0.0 ;
947         arrayDeltaEz(i,j)  =  0.0 ;
948       }
949     }
950   }
951   
952   // calculate z distortion from the integrated Delta Ez residuals
953   // and include the aquivalence (Volt to cm) of the ROC shift !!
954
955   for ( Int_t j = 0 ; j < columns ; j++ )  {      
956     for ( Int_t i = 0 ; i < rows ; i++ ) {
957
958       // Scale the Ez distortions with the drift velocity pertubation -> delivers cm
959       arrayDeltaEz(i,j) = arrayDeltaEz(i,j)*fgkdvdE;
960
961       // ROC Potential in cm aquivalent
962       Double_t dzROCShift =  arrayV(i, columns -1)/ezField;  
963       if ( rocDisplacement ) arrayDeltaEz(i,j) = arrayDeltaEz(i,j) + dzROCShift;  // add the ROC misaligment
964
965     }
966   }
967  
968   arrayEr.Clear();
969   arrayEz.Clear();
970
971 }
972
973 void AliTPCCorrection::PoissonRelaxation3D( TMatrixD**arrayofArrayV, TMatrixD**arrayofChargeDensities, 
974                     TMatrixD**arrayofEroverEz, TMatrixD**arrayofEPhioverEz, TMatrixD**arrayofDeltaEz,
975                     const Int_t rows, const Int_t columns,  const Int_t phislices, 
976                     const Float_t deltaphi, const Int_t iterations, const Int_t symmetry,
977                     Bool_t rocDisplacement  ) {
978   //
979   // 3D - Solve Poisson's Equation in 3D by Relaxation Technique
980   //
981   //    NOTE: In order for this algorith to work, the number of rows and columns must be a power of 2 plus one.  
982   //    The number of rows and COLUMNS can be different.
983   //
984   //    ROWS       ==  2**M + 1  
985   //    COLUMNS    ==  2**N + 1  
986   //    PHISLICES  ==  Arbitrary but greater than 3
987   //
988   //    DeltaPhi in Radians
989   //
990   //    SYMMETRY = 0 if no phi symmetries, and no phi boundary conditions
991   //             = 1 if we have reflection symmetry at the boundaries (eg. sector symmetry or half sector symmetries).
992   //
993   // NOTE: rocDisplacement is used to include (or ignore) the ROC misalignment in the dz calculation
994
995   const Double_t ezField = (fgkCathodeV-fgkGG)/fgkTPCZ0; // = ALICE Electric Field (V/cm) Magnitude ~ -400 V/cm; 
996
997   const Float_t  gridSizeR   =  (fgkOFCRadius-fgkIFCRadius) / (rows-1) ;
998   const Float_t  gridSizePhi =  deltaphi ;
999   const Float_t  gridSizeZ   =  fgkTPCZ0 / (columns-1) ;
1000   const Float_t  ratioPhi    =  gridSizeR*gridSizeR / (gridSizePhi*gridSizePhi) ;
1001   const Float_t  ratioZ      =  gridSizeR*gridSizeR / (gridSizeZ*gridSizeZ) ;
1002
1003   TMatrixD arrayE(rows,columns) ;
1004
1005   // Check that the number of rows and columns is suitable for a binary expansion
1006   if ( !IsPowerOfTwo((rows-1))    ) {  
1007     AliError("Poisson3DRelaxation - Error in the number of rows. Must be 2**M - 1"); 
1008     return; }
1009   if ( !IsPowerOfTwo((columns-1)) ) { 
1010     AliError("Poisson3DRelaxation - Error in the number of columns. Must be 2**N - 1");
1011     return; }
1012   if ( phislices <= 3   )  { 
1013     AliError("Poisson3DRelaxation - Error in the number of phislices. Must be larger than 3");
1014     return; }
1015   if  ( phislices > 1000 ) { 
1016     AliError("Poisson3D  phislices > 1000 is not allowed (nor wise) ");  
1017     return; }  
1018   
1019   // Solve Poisson's equation in cylindrical coordinates by relaxation technique
1020   // Allow for different size grid spacing in R and Z directions
1021   // Use a binary expansion of the matrix to speed up the solution of the problem
1022
1023   Int_t loops, mplus, mminus, signplus, signminus  ;
1024   Int_t ione = (rows-1)/4 ;
1025   Int_t jone = (columns-1)/4 ;
1026   loops = TMath::Max(ione, jone) ;      // Calculate the number of loops for the binary expansion
1027   loops = 1 + (int) ( 0.5 + TMath::Log2((double)loops) ) ;  // Solve for N in 2**N
1028
1029   TMatrixD* arrayofSumChargeDensities[1000] ;    // Create temporary arrays to store low resolution charge arrays
1030
1031   for ( Int_t i = 0 ; i < phislices ; i++ ) { arrayofSumChargeDensities[i] = new TMatrixD(rows,columns) ; }
1032
1033   for ( Int_t count = 0 ; count < loops ; count++ ) {      // START the master loop and do the binary expansion
1034    
1035     Float_t  tempgridSizeR   =  gridSizeR  * ione ;
1036     Float_t  tempratioPhi    =  ratioPhi * ione * ione ; // Used tobe divided by ( m_one * m_one ) when m_one was != 1
1037     Float_t  tempratioZ      =  ratioZ   * ione * ione / ( jone * jone ) ;
1038
1039     std::vector<float> coef1(rows) ;  // Do this the standard C++ way to avoid gcc extensions for Float_t coef1[rows]
1040     std::vector<float> coef2(rows) ;  // Do this the standard C++ way to avoid gcc extensions for Float_t coef1[rows]
1041     std::vector<float> coef3(rows) ;  // Do this the standard C++ way to avoid gcc extensions for Float_t coef1[rows]
1042     std::vector<float> coef4(rows) ;  // Do this the standard C++ way to avoid gcc extensions for Float_t coef1[rows]
1043
1044     for ( Int_t i = ione ; i < rows-1 ; i+=ione )  {
1045       Float_t radius = fgkIFCRadius + i*gridSizeR ;
1046       coef1[i] = 1.0 + tempgridSizeR/(2*radius);
1047       coef2[i] = 1.0 - tempgridSizeR/(2*radius);
1048       coef3[i] = tempratioPhi/(radius*radius);
1049       coef4[i] = 0.5 / (1.0 + tempratioZ + coef3[i]);
1050     }
1051
1052     for ( Int_t m = 0 ; m < phislices ; m++ ) {
1053       TMatrixD &chargeDensity    = *arrayofChargeDensities[m] ;
1054       TMatrixD &sumChargeDensity = *arrayofSumChargeDensities[m] ;
1055       for ( Int_t i = ione ; i < rows-1 ; i += ione ) {
1056         Float_t radius = fgkIFCRadius + i*gridSizeR ;
1057         for ( Int_t j = jone ; j < columns-1 ; j += jone ) {
1058           if ( ione == 1 && jone == 1 ) sumChargeDensity(i,j) = chargeDensity(i,j) ;
1059           else {           // Add up all enclosed charge density contributions within 1/2 unit in all directions
1060             Float_t weight = 0.0 ;
1061             Float_t sum    = 0.0 ;
1062             sumChargeDensity(i,j) = 0.0 ;
1063             for ( Int_t ii = i-ione/2 ; ii <= i+ione/2 ; ii++ ) {
1064               for ( Int_t jj = j-jone/2 ; jj <= j+jone/2 ; jj++ ) {
1065                 if ( ii == i-ione/2 || ii == i+ione/2 || jj == j-jone/2 || jj == j+jone/2 ) weight = 0.5 ;
1066                 else
1067                   weight = 1.0 ; 
1068                 sumChargeDensity(i,j) += chargeDensity(ii,jj)*weight*radius ;  
1069                 sum += weight*radius ;
1070               }
1071             }
1072             sumChargeDensity(i,j) /= sum ;
1073           }
1074           sumChargeDensity(i,j) *= tempgridSizeR*tempgridSizeR; // just saving a step later on
1075         }
1076       }
1077     }
1078
1079     for ( Int_t k = 1 ; k <= iterations; k++ ) {
1080
1081       // over-relaxation index, >= 1 but < 2
1082       Float_t overRelax   = 1.0 + TMath::Sqrt( TMath::Cos( (k*TMath::PiOver2())/iterations ) ) ; 
1083       Float_t overRelaxM1 = overRelax - 1.0 ;
1084
1085       std::vector<float> overRelaxcoef4(rows) ;  // Do this the standard C++ way to avoid gcc extensions
1086       std::vector<float> overRelaxcoef5(rows) ;  // Do this the standard C++ way to avoid gcc extensions
1087
1088       for ( Int_t i = ione ; i < rows-1 ; i+=ione ) { 
1089         overRelaxcoef4[i] = overRelax * coef4[i] ;
1090         overRelaxcoef5[i] = overRelaxM1 / overRelaxcoef4[i] ; 
1091       }
1092
1093       for ( Int_t m = 0 ; m < phislices ; m++ ) {
1094
1095         mplus  = m + 1;   signplus  = 1 ; 
1096         mminus = m - 1 ;  signminus = 1 ;
1097         if (symmetry==1) {  // Reflection symmetry in phi (e.g. symmetry at sector boundaries, or half sectors, etc.)
1098           if ( mplus  > phislices-1 ) mplus  = phislices - 2 ;
1099           if ( mminus < 0 )           mminus = 1 ;
1100         }
1101         else if (symmetry==-1) {   // Anti-symmetry in phi
1102           if ( mplus  > phislices-1 ) { mplus  = phislices - 2 ; signplus  = -1 ; }
1103           if ( mminus < 0 )           { mminus = 1 ;             signminus = -1 ; } 
1104         }
1105                 else { // No Symmetries in phi, no boundaries, the calculation is continuous across all phi
1106           if ( mplus  > phislices-1 ) mplus  = m + 1 - phislices ;
1107           if ( mminus < 0 )           mminus = m - 1 + phislices ;
1108         }
1109         TMatrixD& arrayV    =  *arrayofArrayV[m] ;
1110         TMatrixD& arrayVP   =  *arrayofArrayV[mplus] ;
1111         TMatrixD& arrayVM   =  *arrayofArrayV[mminus] ;
1112         TMatrixD& sumChargeDensity =  *arrayofSumChargeDensities[m] ;
1113
1114         for ( Int_t i = ione ; i < rows-1 ; i+=ione )  {
1115           for ( Int_t j = jone ; j < columns-1 ; j+=jone ) {
1116
1117             arrayV(i,j) = (   coef2[i]          *   arrayV(i-ione,j)
1118                             + tempratioZ        * ( arrayV(i,j-jone)  +  arrayV(i,j+jone) )
1119                             - overRelaxcoef5[i] *   arrayV(i,j) 
1120                             + coef1[i]          *   arrayV(i+ione,j)  
1121                             + coef3[i]          * ( signplus*arrayVP(i,j)       +  signminus*arrayVM(i,j) )
1122                             + sumChargeDensity(i,j) 
1123                           ) * overRelaxcoef4[i] ;     
1124             // Note: over-relax the solution at each step.  This speeds up the convergance.
1125
1126           }
1127         }
1128
1129         if ( k == iterations ) {   // After full solution is achieved, copy low resolution solution into higher res array
1130           for ( Int_t i = ione ; i < rows-1 ; i+=ione )  {
1131             for ( Int_t j = jone ; j < columns-1 ; j+=jone ) {
1132               
1133               if ( ione > 1 ) {              
1134                 arrayV(i+ione/2,j)                    =  ( arrayV(i+ione,j) + arrayV(i,j)     ) / 2 ;
1135                 if ( i == ione )  arrayV(i-ione/2,j) =  ( arrayV(0,j)       + arrayV(ione,j) ) / 2 ;
1136               }
1137               if ( jone > 1 ) {
1138                 arrayV(i,j+jone/2)                    =  ( arrayV(i,j+jone) + arrayV(i,j) )     / 2 ;
1139                 if ( j == jone )  arrayV(i,j-jone/2) =  ( arrayV(i,0)       + arrayV(i,jone) ) / 2 ;
1140               }
1141               if ( ione > 1 && jone > 1 ) {
1142                 arrayV(i+ione/2,j+jone/2) =  ( arrayV(i+ione,j+jone) + arrayV(i,j) ) / 2 ;
1143                 if ( i == ione ) arrayV(i-ione/2,j-jone/2) =   ( arrayV(0,j-jone) + arrayV(ione,j) ) / 2 ;
1144                 if ( j == jone ) arrayV(i-ione/2,j-jone/2) =   ( arrayV(i-ione,0) + arrayV(i,jone) ) / 2 ;
1145                 // Note that this leaves a point at the upper left and lower right corners uninitialized. Not a big deal.
1146               }
1147             }       
1148           }
1149         }
1150
1151       }
1152     }      
1153
1154     ione = ione / 2 ; if ( ione < 1 ) ione = 1 ;
1155     jone = jone / 2 ; if ( jone < 1 ) jone = 1 ;
1156
1157   }
1158   
1159   //Differentiate V(r) and solve for E(r) using special equations for the first and last row
1160   //Integrate E(r)/E(z) from point of origin to pad plane
1161
1162   for ( Int_t m = 0 ; m < phislices ; m++ ) {
1163     TMatrixD& arrayV    =  *arrayofArrayV[m] ;
1164     TMatrixD& eroverEz  =  *arrayofEroverEz[m] ;
1165     
1166     for ( Int_t j = columns-1 ; j >= 0 ; j-- ) {  // Count backwards to facilitate integration over Z
1167       
1168       // Differentiate in R
1169       for ( Int_t i = 1 ; i < rows-1 ; i++ )  arrayE(i,j) = -1 * ( arrayV(i+1,j) - arrayV(i-1,j) ) / (2*gridSizeR) ;
1170       arrayE(0,j)      =  -1 * ( -0.5*arrayV(2,j) + 2.0*arrayV(1,j) - 1.5*arrayV(0,j) ) / gridSizeR ;  
1171       arrayE(rows-1,j) =  -1 * ( 1.5*arrayV(rows-1,j) - 2.0*arrayV(rows-2,j) + 0.5*arrayV(rows-3,j) ) / gridSizeR ; 
1172       // Integrate over Z
1173       for ( Int_t i = 0 ; i < rows ; i++ ) {
1174         Int_t index = 1 ;   // Simpsons rule if N=odd.  If N!=odd then add extra point by trapezoidal rule.  
1175         eroverEz(i,j) = 0.0 ;
1176         for ( Int_t k = j ; k < columns ; k++ ) {
1177           
1178           eroverEz(i,j)  +=  index*(gridSizeZ/3.0)*arrayE(i,k)/(-1*ezField) ;
1179           if ( index != 4 )  index = 4; else index = 2 ;
1180         }
1181         if ( index == 4 ) eroverEz(i,j)  -=  (gridSizeZ/3.0)*arrayE(i,columns-1)/ (-1*ezField) ;
1182         if ( index == 2 ) eroverEz(i,j)  +=  
1183           (gridSizeZ/3.0)*(0.5*arrayE(i,columns-2)-2.5*arrayE(i,columns-1))/(-1*ezField) ;
1184         if ( j == columns-2 ) eroverEz(i,j) =  
1185           (gridSizeZ/3.0)*(1.5*arrayE(i,columns-2)+1.5*arrayE(i,columns-1))/(-1*ezField) ;
1186         if ( j == columns-1 ) eroverEz(i,j) =  0.0 ;
1187       }
1188     }
1189     // if ( m == 0 ) { TCanvas*  c1 =  new TCanvas("erOverEz","erOverEz",50,50,840,600) ;  c1 -> cd() ;
1190     // eroverEz.Draw("surf") ; } // JT test
1191   }
1192   
1193   //Differentiate V(r) and solve for E(phi) 
1194   //Integrate E(phi)/E(z) from point of origin to pad plane
1195
1196   for ( Int_t m = 0 ; m < phislices ; m++ ) {
1197     
1198     mplus  = m + 1;   signplus  = 1 ; 
1199     mminus = m - 1 ;  signminus = 1 ; 
1200     if (symmetry==1) { // Reflection symmetry in phi (e.g. symmetry at sector boundaries, or half sectors, etc.)
1201       if ( mplus  > phislices-1 ) mplus  = phislices - 2 ;
1202       if ( mminus < 0 )           mminus = 1 ;
1203     }
1204     else if (symmetry==-1) {       // Anti-symmetry in phi
1205       if ( mplus  > phislices-1 ) { mplus  = phislices - 2 ;  signplus  = -1 ; }
1206       if ( mminus < 0 )           { mminus = 1 ;                    signminus = -1 ; } 
1207     }
1208     else { // No Symmetries in phi, no boundaries, the calculations is continuous across all phi
1209       if ( mplus  > phislices-1 ) mplus  = m + 1 - phislices ;
1210       if ( mminus < 0 )           mminus = m - 1 + phislices ;
1211     }
1212     TMatrixD &arrayVP     =  *arrayofArrayV[mplus] ;
1213     TMatrixD &arrayVM     =  *arrayofArrayV[mminus] ;
1214     TMatrixD &ePhioverEz  =  *arrayofEPhioverEz[m] ;
1215     for ( Int_t j = columns-1 ; j >= 0 ; j-- ) { // Count backwards to facilitate integration over Z
1216       // Differentiate in Phi
1217       for ( Int_t i = 0 ; i < rows ; i++ ) {
1218         Float_t radius = fgkIFCRadius + i*gridSizeR ;
1219         arrayE(i,j) = -1 * (signplus * arrayVP(i,j) - signminus * arrayVM(i,j) ) / (2*radius*gridSizePhi) ;
1220       }
1221       // Integrate over Z
1222       for ( Int_t i = 0 ; i < rows ; i++ ) {
1223         Int_t index = 1 ;   // Simpsons rule if N=odd.  If N!=odd then add extra point by trapezoidal rule.  
1224         ePhioverEz(i,j) = 0.0 ;
1225         for ( Int_t k = j ; k < columns ; k++ ) {
1226           
1227           ePhioverEz(i,j)  +=  index*(gridSizeZ/3.0)*arrayE(i,k)/(-1*ezField) ;
1228           if ( index != 4 )  index = 4; else index = 2 ;
1229         }
1230         if ( index == 4 ) ePhioverEz(i,j)  -=  (gridSizeZ/3.0)*arrayE(i,columns-1)/ (-1*ezField) ;
1231         if ( index == 2 ) ePhioverEz(i,j)  +=  
1232           (gridSizeZ/3.0)*(0.5*arrayE(i,columns-2)-2.5*arrayE(i,columns-1))/(-1*ezField) ;
1233         if ( j == columns-2 ) ePhioverEz(i,j) =  
1234           (gridSizeZ/3.0)*(1.5*arrayE(i,columns-2)+1.5*arrayE(i,columns-1))/(-1*ezField) ;
1235         if ( j == columns-1 ) ePhioverEz(i,j) =  0.0 ;
1236       }
1237     }
1238     // if ( m == 5 ) { TCanvas* c2 =  new TCanvas("arrayE","arrayE",50,50,840,600) ;  c2 -> cd() ;
1239     // arrayE.Draw("surf") ; } // JT test
1240   }
1241   
1242
1243   // Differentiate V(r) and solve for E(z) using special equations for the first and last row
1244   // Integrate (E(z)-Ezstd) from point of origin to pad plane
1245   
1246   for ( Int_t m = 0 ; m < phislices ; m++ ) {
1247     TMatrixD& arrayV   =  *arrayofArrayV[m] ;
1248     TMatrixD& deltaEz  =  *arrayofDeltaEz[m] ;
1249     
1250     // Differentiate V(z) and solve for E(z) using special equations for the first and last columns
1251     for ( Int_t i = 0 ; i < rows ; i++) {
1252       for ( Int_t j = 1 ; j < columns-1 ; j++ ) arrayE(i,j) = -1 * ( arrayV(i,j+1) - arrayV(i,j-1) ) / (2*gridSizeZ) ;
1253       arrayE(i,0)         =  -1 * ( -0.5*arrayV(i,2) + 2.0*arrayV(i,1) - 1.5*arrayV(i,0) ) / gridSizeZ ;  
1254       arrayE(i,columns-1) =  -1 * ( 1.5*arrayV(i,columns-1) - 2.0*arrayV(i,columns-2) + 0.5*arrayV(i,columns-3) ) / gridSizeZ ; 
1255     }
1256     
1257     for ( Int_t j = columns-1 ; j >= 0 ; j-- ) {  // Count backwards to facilitate integration over Z
1258       // Integrate over Z
1259       for ( Int_t i = 0 ; i < rows ; i++ ) {
1260         Int_t index = 1 ;   // Simpsons rule if N=odd.  If N!=odd then add extra point by trapezoidal rule.  
1261         deltaEz(i,j) = 0.0 ;
1262         for ( Int_t k = j ; k < columns ; k++ ) {
1263           deltaEz(i,j)  +=  index*(gridSizeZ/3.0)*arrayE(i,k) ;
1264           if ( index != 4 )  index = 4; else index = 2 ;
1265         }
1266         if ( index == 4 ) deltaEz(i,j)  -=  (gridSizeZ/3.0)*arrayE(i,columns-1) ;
1267         if ( index == 2 ) deltaEz(i,j)  +=  
1268           (gridSizeZ/3.0)*(0.5*arrayE(i,columns-2)-2.5*arrayE(i,columns-1)) ;
1269         if ( j == columns-2 ) deltaEz(i,j) =  
1270           (gridSizeZ/3.0)*(1.5*arrayE(i,columns-2)+1.5*arrayE(i,columns-1)) ;
1271         if ( j == columns-1 ) deltaEz(i,j) =  0.0 ;
1272       }
1273     }
1274     // if ( m == 0 ) { TCanvas*  c1 =  new TCanvas("erOverEz","erOverEz",50,50,840,600) ;  c1 -> cd() ;
1275     // eroverEz.Draw("surf") ; } // JT test
1276     
1277     // calculate z distortion from the integrated Delta Ez residuals
1278     // and include the aquivalence (Volt to cm) of the ROC shift !!
1279     
1280     for ( Int_t j = 0 ; j < columns ; j++ )  {    
1281       for ( Int_t i = 0 ; i < rows ; i++ ) {
1282         
1283         // Scale the Ez distortions with the drift velocity pertubation -> delivers cm
1284         deltaEz(i,j) = deltaEz(i,j)*fgkdvdE;
1285         
1286         // ROC Potential in cm aquivalent
1287         Double_t dzROCShift =  arrayV(i, columns -1)/ezField;  
1288         if ( rocDisplacement ) deltaEz(i,j) = deltaEz(i,j) + dzROCShift;  // add the ROC misaligment
1289         
1290       }
1291     }
1292
1293   } // end loop over phi
1294   
1295  
1296
1297   for ( Int_t k = 0 ; k < phislices ; k++ )
1298     {
1299       arrayofSumChargeDensities[k]->Delete() ;
1300     }
1301   
1302
1303
1304   arrayE.Clear();
1305 }
1306
1307
1308 Int_t AliTPCCorrection::IsPowerOfTwo(Int_t i) const {
1309   //
1310   // Helperfunction: Check if integer is a power of 2
1311   //
1312   Int_t j = 0;
1313   while( i > 0 ) { j += (i&1) ; i = (i>>1) ; }
1314   if ( j == 1 ) return(1) ;  // True
1315   return(0) ;                // False
1316 }
1317
1318
1319 AliExternalTrackParam * AliTPCCorrection::FitDistortedTrack(AliExternalTrackParam & trackIn, Double_t refX, Int_t dir, TTreeSRedirector * const pcstream){
1320   //
1321   // Fit the track parameters - without and with distortion
1322   // 1. Space points in the TPC are simulated along the trajectory  
1323   // 2. Space points distorted
1324   // 3. Fits  the non distorted and distroted track to the reference plane at refX
1325   // 4. For visualization and debugging  purposes the space points and tracks can be stored  in the tree - using the TTreeSRedirector functionality 
1326   //
1327   // trackIn   - input track parameters
1328   // refX     - reference X to fit the track
1329   // dir      - direction - out=1 or in=-1
1330   // pcstream -  debug streamer to check the results
1331   //
1332   // see AliExternalTrackParam.h documentation:
1333   // track1.fP[0] - local y (rphi)
1334   // track1.fP[1] - z 
1335   // track1.fP[2] - sinus of local inclination angle
1336   // track1.fP[3] - tangent of deep angle
1337   // track1.fP[4] - 1/pt
1338
1339   AliTPCROC * roc = AliTPCROC::Instance();
1340   const Int_t    npoints0=roc->GetNRows(0)+roc->GetNRows(36);
1341   const Double_t kRTPC0  =roc->GetPadRowRadii(0,0);
1342   const Double_t kRTPC1  =roc->GetPadRowRadii(36,roc->GetNRows(36)-1);
1343   const Double_t kMaxSnp = 0.85;  
1344   const Double_t kSigmaY=0.1;
1345   const Double_t kSigmaZ=0.1;
1346   const Double_t kMaxR=500;
1347   const Double_t kMaxZ=500;
1348   const Double_t kMass = TDatabasePDG::Instance()->GetParticle("pi+")->Mass();
1349   Int_t npoints1=0;
1350   Int_t npoints2=0;
1351
1352   AliExternalTrackParam  track(trackIn); // 
1353   // generate points
1354   AliTrackPointArray pointArray0(npoints0);
1355   AliTrackPointArray pointArray1(npoints0);
1356   Double_t xyz[3];
1357   if (!AliTrackerBase::PropagateTrackToBxByBz(&track,kRTPC0,kMass,3,kTRUE,kMaxSnp)) return 0;
1358   //
1359   // simulate the track
1360   Int_t npoints=0;
1361   Float_t covPoint[6]={0,0,0, kSigmaY*kSigmaY,0,kSigmaZ*kSigmaZ};  //covariance at the local frame
1362   for (Double_t radius=kRTPC0; radius<kRTPC1; radius++){
1363     if (!AliTrackerBase::PropagateTrackToBxByBz(&track,radius,kMass,3,kTRUE,kMaxSnp)) return 0;
1364     track.GetXYZ(xyz);
1365     xyz[0]+=gRandom->Gaus(0,0.00005);
1366     xyz[1]+=gRandom->Gaus(0,0.00005);
1367     xyz[2]+=gRandom->Gaus(0,0.00005);
1368     if (TMath::Abs(track.GetZ())>kMaxZ) break;
1369     if (TMath::Abs(track.GetX())>kMaxR) break;
1370     AliTrackPoint pIn0;                               // space point          
1371     AliTrackPoint pIn1;
1372     Int_t sector= (xyz[2]>0)? 0:18;
1373     pointArray0.GetPoint(pIn0,npoints);
1374     pointArray1.GetPoint(pIn1,npoints);
1375     Double_t alpha = TMath::ATan2(xyz[1],xyz[0]);
1376     Float_t distPoint[3]={xyz[0],xyz[1],xyz[2]};
1377     DistortPoint(distPoint, sector);
1378     pIn0.SetXYZ(xyz[0], xyz[1],xyz[2]);
1379     pIn1.SetXYZ(distPoint[0], distPoint[1],distPoint[2]);
1380     //
1381     track.Rotate(alpha);
1382     AliTrackPoint prot0 = pIn0.Rotate(alpha);   // rotate to the local frame - non distoted  point
1383     AliTrackPoint prot1 = pIn1.Rotate(alpha);   // rotate to the local frame -     distorted point
1384     prot0.SetXYZ(prot0.GetX(),prot0.GetY(), prot0.GetZ(),covPoint);
1385     prot1.SetXYZ(prot1.GetX(),prot1.GetY(), prot1.GetZ(),covPoint);
1386     pIn0=prot0.Rotate(-alpha);                       // rotate back to global frame
1387     pIn1=prot1.Rotate(-alpha);                       // rotate back to global frame
1388     pointArray0.AddPoint(npoints, &pIn0);      
1389     pointArray1.AddPoint(npoints, &pIn1);
1390     npoints++;
1391     if (npoints>=npoints0) break;
1392   }
1393   if (npoints<npoints0/2) return 0;
1394   //
1395   // refit track
1396   //
1397   AliExternalTrackParam *track0=0;
1398   AliExternalTrackParam *track1=0;
1399   AliTrackPoint   point1,point2,point3;
1400   if (dir==1) {  //make seed inner
1401     pointArray0.GetPoint(point1,1);
1402     pointArray0.GetPoint(point2,30);
1403     pointArray0.GetPoint(point3,60);
1404   }
1405   if (dir==-1){ //make seed outer
1406     pointArray0.GetPoint(point1,npoints-60);
1407     pointArray0.GetPoint(point2,npoints-30);
1408     pointArray0.GetPoint(point3,npoints-1);
1409   }  
1410   track0 = AliTrackerBase::MakeSeed(point1, point2, point3);
1411   track1 = AliTrackerBase::MakeSeed(point1, point2, point3);
1412
1413   for (Int_t jpoint=0; jpoint<npoints; jpoint++){
1414     Int_t ipoint= (dir>0) ? jpoint: npoints-1-jpoint;
1415     //
1416     AliTrackPoint pIn0;
1417     AliTrackPoint pIn1;
1418     pointArray0.GetPoint(pIn0,ipoint);
1419     pointArray1.GetPoint(pIn1,ipoint);
1420     AliTrackPoint prot0 = pIn0.Rotate(track0->GetAlpha());   // rotate to the local frame - non distoted  point
1421     AliTrackPoint prot1 = pIn1.Rotate(track1->GetAlpha());   // rotate to the local frame -     distorted point
1422     //
1423     if (!AliTrackerBase::PropagateTrackToBxByBz(track0,prot0.GetX(),kMass,3,kFALSE,kMaxSnp)) break;
1424     if (!AliTrackerBase::PropagateTrackToBxByBz(track1,prot0.GetX(),kMass,3,kFALSE,kMaxSnp)) break;
1425     if (TMath::Abs(track0->GetZ())>kMaxZ) break;
1426     if (TMath::Abs(track0->GetX())>kMaxR) break;
1427     if (TMath::Abs(track1->GetZ())>kMaxZ) break;
1428     if (TMath::Abs(track1->GetX())>kMaxR) break;
1429
1430     track.GetXYZ(xyz);  // distorted track also propagated to the same reference radius
1431     //
1432     Double_t pointPos[2]={0,0};
1433     Double_t pointCov[3]={0,0,0};
1434     pointPos[0]=prot0.GetY();//local y
1435     pointPos[1]=prot0.GetZ();//local z
1436     pointCov[0]=prot0.GetCov()[3];//simay^2
1437     pointCov[1]=prot0.GetCov()[4];//sigmayz
1438     pointCov[2]=prot0.GetCov()[5];//sigmaz^2
1439     if (!track0->Update(pointPos,pointCov)) break;
1440     //
1441     Double_t deltaX=prot1.GetX()-prot0.GetX();   // delta X 
1442     Double_t deltaYX=deltaX*TMath::Tan(TMath::ASin(track1->GetSnp()));  // deltaY due  delta X
1443     Double_t deltaZX=deltaX*track1->GetTgl();                           // deltaZ due  delta X
1444
1445     pointPos[0]=prot1.GetY()-deltaYX;//local y is sign correct? should be minus
1446     pointPos[1]=prot1.GetZ()-deltaZX;//local z is sign correct? should be minus
1447     pointCov[0]=prot1.GetCov()[3];//simay^2
1448     pointCov[1]=prot1.GetCov()[4];//sigmayz
1449     pointCov[2]=prot1.GetCov()[5];//sigmaz^2
1450     if (!track1->Update(pointPos,pointCov)) break;
1451     npoints1++;
1452     npoints2++;
1453   }
1454   if (npoints2<npoints)  return 0;
1455   AliTrackerBase::PropagateTrackToBxByBz(track0,refX,kMass,2.,kTRUE,kMaxSnp);
1456   track1->Rotate(track0->GetAlpha());
1457   AliTrackerBase::PropagateTrackToBxByBz(track1,refX,kMass,2.,kFALSE,kMaxSnp);
1458
1459   if (pcstream) (*pcstream)<<Form("fitDistort%s",GetName())<<
1460     "point0.="<<&pointArray0<<   //  points
1461     "point1.="<<&pointArray1<<   //  distorted points
1462     "trackIn.="<<&track<<       //  original track
1463     "track0.="<<track0<<         //  fitted track
1464     "track1.="<<track1<<         //  fitted distorted track
1465     "\n";
1466   new(&trackIn) AliExternalTrackParam(*track0);
1467   delete track0;
1468   return track1;
1469 }
1470
1471
1472
1473
1474
1475 TTree* AliTPCCorrection::CreateDistortionTree(Double_t step){
1476   //
1477   // create the distortion tree on a mesh with granularity given by step
1478   // return the tree with distortions at given position 
1479   // Map is created on the mesh with given step size
1480   //
1481   TTreeSRedirector *pcstream = new TTreeSRedirector(Form("correction%s.root",GetName()));
1482   Float_t xyz[3];
1483   for (Double_t x= -250; x<250; x+=step){
1484     for (Double_t y= -250; y<250; y+=step){
1485       Double_t r    = TMath::Sqrt(x*x+y*y);
1486       if (r<80) continue;
1487       if (r>250) continue;      
1488       for (Double_t z= -250; z<250; z+=step){
1489         Int_t roc=(z>0)?0:18;
1490         xyz[0]=x;
1491         xyz[1]=y;
1492         xyz[2]=z;
1493         Double_t phi  = TMath::ATan2(y,x);
1494         DistortPoint(xyz,roc);
1495         Double_t r1    = TMath::Sqrt(xyz[0]*xyz[0]+xyz[1]*xyz[1]);
1496         Double_t phi1  = TMath::ATan2(xyz[1],xyz[0]);
1497         if ((phi1-phi)>TMath::Pi()) phi1-=TMath::Pi();
1498         if ((phi1-phi)<-TMath::Pi()) phi1+=TMath::Pi();
1499         Double_t dx = xyz[0]-x;
1500         Double_t dy = xyz[1]-y;
1501         Double_t dz = xyz[2]-z;
1502         Double_t dr=r1-r;
1503         Double_t drphi=(phi1-phi)*r;
1504         (*pcstream)<<"distortion"<<
1505           "x="<<x<<           // original position        
1506           "y="<<y<<
1507           "z="<<z<<
1508           "r="<<r<<
1509           "phi="<<phi<<   
1510           "x1="<<xyz[0]<<      // distorted position
1511           "y1="<<xyz[1]<<
1512           "z1="<<xyz[2]<<
1513           "r1="<<r1<<
1514           "phi1="<<phi1<<
1515           //
1516           "dx="<<dx<<          // delta position
1517           "dy="<<dy<<
1518           "dz="<<dz<<
1519           "dr="<<dr<<
1520           "drphi="<<drphi<<
1521           "\n";
1522       }
1523     }   
1524   }
1525   delete pcstream;
1526   TFile f(Form("correction%s.root",GetName()));
1527   TTree * tree = (TTree*)f.Get("distortion");
1528   TTree * tree2= tree->CopyTree("1");
1529   tree2->SetName(Form("dist%s",GetName()));
1530   tree2->SetDirectory(0);
1531   delete tree;
1532   return tree2;
1533 }
1534
1535
1536
1537
1538 void AliTPCCorrection::MakeTrackDistortionTree(TTree *tinput, Int_t dtype, Int_t ptype, const TObjArray * corrArray, Int_t step, Bool_t debug ){
1539   //
1540   // Make a fit tree:
1541   // For each partial correction (specified in array) and given track topology (phi, theta, snp, refX)
1542   // calculates partial distortions
1543   // Partial distortion is stored in the resulting tree
1544   // Output is storred in the file distortion_<dettype>_<partype>.root
1545   // Partial  distortion is stored with the name given by correction name
1546   //
1547   //
1548   // Parameters of function:
1549   // input     - input tree
1550   // dtype     - distortion type 0 - ITSTPC,  1 -TPCTRD, 2 - TPCvertex 
1551   // ppype     - parameter type
1552   // corrArray - array with partial corrections
1553   // step      - skipe entries  - if 1 all entries processed - it is slow
1554   // debug     0 if debug on also space points dumped - it is slow
1555
1556   const Double_t kMaxSnp = 0.85;  
1557   const Double_t kMass = TDatabasePDG::Instance()->GetParticle("pi+")->Mass();
1558   //  const Double_t kB2C=-0.299792458e-3;
1559   const Int_t kMinEntries=50; 
1560   Double_t phi,theta, snp, mean,rms, entries;
1561   tinput->SetBranchAddress("theta",&theta);
1562   tinput->SetBranchAddress("phi", &phi);
1563   tinput->SetBranchAddress("snp",&snp);
1564   tinput->SetBranchAddress("mean",&mean);
1565   tinput->SetBranchAddress("rms",&rms);
1566   tinput->SetBranchAddress("entries",&entries);
1567   TTreeSRedirector *pcstream = new TTreeSRedirector(Form("distortion%d_%d.root",dtype,ptype));
1568   //
1569   Int_t nentries=tinput->GetEntries();
1570   Int_t ncorr=corrArray->GetEntries();
1571   Double_t corrections[100]={0}; //
1572   Double_t tPar[5];
1573   Double_t cov[15]={0,0,0,0,0,0,0,0,0,0,0,0,0,0};
1574   Double_t refX=0;
1575   Int_t dir=0;
1576   if (dtype==0) {refX=85.; dir=-1;}
1577   if (dtype==1) {refX=275.; dir=1;}
1578   if (dtype==2) {refX=85.; dir=-1;}
1579   if (dtype==3) {refX=360.; dir=-1;}
1580   //
1581   for (Int_t ientry=0; ientry<nentries; ientry+=step){
1582     tinput->GetEntry(ientry);
1583     if (TMath::Abs(snp)>kMaxSnp) continue;
1584     tPar[0]=0;
1585     tPar[1]=theta*refX;
1586     tPar[2]=snp;
1587     tPar[3]=theta;
1588     tPar[4]=(gRandom->Rndm()-0.5)*0.02;  // should be calculated - non equal to 0
1589     Double_t bz=AliTrackerBase::GetBz();
1590     if (refX>10. && TMath::Abs(bz)>0.1 )  tPar[4]=snp/(refX*bz*kB2C*2);
1591     tPar[4]+=(gRandom->Rndm()-0.5)*0.02;
1592     AliExternalTrackParam track(refX,phi,tPar,cov);
1593     Double_t xyz[3];
1594     track.GetXYZ(xyz);
1595     Int_t id=0;
1596     Double_t dRrec=0; // dummy value - needed for points - e.g for laser
1597     if (ptype==4 &&bz<0) mean*=-1;  // interpret as curvature
1598     (*pcstream)<<"fit"<<
1599       "bz="<<bz<<         // magnetic filed used
1600       "dtype="<<dtype<<   // detector match type
1601       "ptype="<<ptype<<   // parameter type
1602       "theta="<<theta<<   // theta
1603       "phi="<<phi<<       // phi 
1604       "snp="<<snp<<       // snp
1605       "mean="<<mean<<     // mean dist value
1606       "rms="<<rms<<       // rms
1607       "gx="<<xyz[0]<<         // global position at reference
1608       "gy="<<xyz[1]<<         // global position at reference
1609       "gz="<<xyz[2]<<         // global position at reference   
1610       "dRrec="<<dRrec<<      // delta Radius in reconstruction
1611       "id="<<id<<             // track id
1612       "entries="<<entries;// number of entries in bin
1613     //
1614     for (Int_t icorr=0; icorr<ncorr; icorr++) {
1615       AliTPCCorrection *corr = (AliTPCCorrection*)corrArray->At(icorr);
1616       corrections[icorr]=0;
1617       if (entries>kMinEntries){
1618         AliExternalTrackParam trackIn(refX,phi,tPar,cov);
1619         AliExternalTrackParam *trackOut = 0;
1620         if (debug) trackOut=corr->FitDistortedTrack(trackIn, refX, dir,pcstream);
1621         if (!debug) trackOut=corr->FitDistortedTrack(trackIn, refX, dir,0);
1622         if (dtype==0) {refX=85.; dir=-1;}
1623         if (dtype==1) {refX=275.; dir=1;}
1624         if (dtype==2) {refX=0; dir=-1;}
1625         if (dtype==3) {refX=360.; dir=-1;}
1626         //
1627         if (trackOut){
1628           AliTrackerBase::PropagateTrackToBxByBz(&trackIn,refX,kMass,3,kTRUE,kMaxSnp);
1629           trackOut->Rotate(trackIn.GetAlpha());
1630           trackOut->PropagateTo(trackIn.GetX(),AliTrackerBase::GetBz());
1631           //
1632           corrections[icorr]= trackOut->GetParameter()[ptype]-trackIn.GetParameter()[ptype];
1633           delete trackOut;      
1634         }else{
1635           corrections[icorr]=0;
1636         }
1637         if (ptype==4 &&bz<0) corrections[icorr]*=-1;  // interpret as curvature
1638       }      
1639       Double_t dRdummy=0;
1640       (*pcstream)<<"fit"<<
1641         Form("%s=",corr->GetName())<<corrections[icorr]<<   // dump correction value
1642         Form("dR%s=",corr->GetName())<<dRdummy;   // dump dummy correction value not needed for tracks 
1643                                                   // for points it is neccessary
1644     }
1645     (*pcstream)<<"fit"<<"\n";
1646   }
1647   delete pcstream;
1648 }
1649
1650
1651
1652 void AliTPCCorrection::MakeLaserDistortionTree(TTree* tree, TObjArray *corrArray, Int_t itype){
1653   //
1654   // Make a laser fit tree for global minimization
1655   //
1656   const Double_t cutErrY=0.1;
1657   const Double_t cutErrZ=0.1;
1658   const Double_t kEpsilon=0.00000001;
1659   TVectorD *vecdY=0;
1660   TVectorD *vecdZ=0;
1661   TVectorD *veceY=0;
1662   TVectorD *veceZ=0;
1663   AliTPCLaserTrack *ltr=0;
1664   AliTPCLaserTrack::LoadTracks();
1665   tree->SetBranchAddress("dY.",&vecdY);
1666   tree->SetBranchAddress("dZ.",&vecdZ);
1667   tree->SetBranchAddress("eY.",&veceY);
1668   tree->SetBranchAddress("eZ.",&veceZ);
1669   tree->SetBranchAddress("LTr.",&ltr);
1670   Int_t entries= tree->GetEntries();
1671   TTreeSRedirector *pcstream= new TTreeSRedirector("distortion4_0.root");
1672   Double_t bz=AliTrackerBase::GetBz();
1673   // 
1674
1675   for (Int_t ientry=0; ientry<entries; ientry++){
1676     tree->GetEntry(ientry);
1677     if (!ltr->GetVecGX()){
1678       ltr->UpdatePoints();
1679     }
1680     TVectorD * delta= (itype==0)? vecdY:vecdZ;
1681     TVectorD * err= (itype==0)? veceY:veceZ;
1682     
1683     for (Int_t irow=0; irow<159; irow++){
1684       Int_t nentries = 1000;
1685       if (veceY->GetMatrixArray()[irow]>cutErrY||veceZ->GetMatrixArray()[irow]>cutErrZ) nentries=0;
1686       if (veceY->GetMatrixArray()[irow]<kEpsilon||veceZ->GetMatrixArray()[irow]<kEpsilon) nentries=0;
1687       Int_t dtype=4;
1688       Double_t phi   =(*ltr->GetVecPhi())[irow];
1689       Double_t theta =ltr->GetTgl();
1690       Double_t mean=delta->GetMatrixArray()[irow];
1691       Double_t gx=0,gy=0,gz=0;
1692       Double_t snp = (*ltr->GetVecP2())[irow];
1693       Double_t rms = 0.1+err->GetMatrixArray()[irow];
1694       gx = (*ltr->GetVecGX())[irow];
1695       gy = (*ltr->GetVecGY())[irow];
1696       gz = (*ltr->GetVecGZ())[irow];
1697       Int_t bundle= ltr->GetBundle();
1698       Double_t dRrec=0;
1699       //
1700       // get delta R used in reconstruction
1701       AliTPCcalibDB*  calib=AliTPCcalibDB::Instance();  
1702       AliTPCCorrection * correction = calib->GetTPCComposedCorrection();
1703       const AliTPCRecoParam * recoParam = calib->GetTransform()->GetCurrentRecoParam();
1704       Double_t xyz0[3]={gx,gy,gz};
1705       Double_t oldR=TMath::Sqrt(gx*gx+gy*gy);
1706       //
1707       // old ExB correction 
1708       //      
1709       if(recoParam&&recoParam->GetUseExBCorrection()) { 
1710         Double_t xyz1[3]={gx,gy,gz};
1711         calib->GetExB()->Correct(xyz0,xyz1);
1712         Double_t newR=TMath::Sqrt(xyz1[0]*xyz1[0]+xyz1[1]*xyz1[1]);
1713         dRrec=oldR-newR;
1714       } 
1715       if(recoParam&&recoParam->GetUseComposedCorrection()&&correction) {
1716         Float_t xyz1[3]={gx,gy,gz};
1717         Int_t sector=(gz>0)?0:18;
1718         correction->CorrectPoint(xyz1, sector);
1719         Double_t newR=TMath::Sqrt(xyz1[0]*xyz1[0]+xyz1[1]*xyz1[1]);
1720         dRrec=oldR-newR;
1721       } 
1722
1723
1724       (*pcstream)<<"fit"<<
1725         "bz="<<bz<<         // magnetic filed used
1726         "dtype="<<dtype<<   // detector match type
1727         "ptype="<<itype<<   // parameter type
1728         "theta="<<theta<<   // theta
1729         "phi="<<phi<<       // phi 
1730         "snp="<<snp<<       // snp
1731         "mean="<<mean<<     // mean dist value
1732         "rms="<<rms<<       // rms
1733         "gx="<<gx<<         // global position
1734         "gy="<<gy<<         // global position
1735         "gz="<<gz<<         // global position
1736         "dRrec="<<dRrec<<      // delta Radius in reconstruction
1737         "id="<<bundle<<     //bundle
1738         "entries="<<nentries;// number of entries in bin
1739       //
1740       //    
1741       Double_t ky = TMath::Tan(TMath::ASin(snp));
1742       Int_t ncorr = corrArray->GetEntries();
1743       Double_t r0   = TMath::Sqrt(gx*gx+gy*gy);
1744       Double_t phi0 = TMath::ATan2(gy,gx);
1745       Double_t distortions[1000]={0};
1746       Double_t distortionsR[1000]={0};
1747       for (Int_t icorr=0; icorr<ncorr; icorr++) {
1748         AliTPCCorrection *corr = (AliTPCCorrection*)corrArray->At(icorr);
1749         Float_t distPoint[3]={gx,gy,gz}; 
1750         Int_t sector= (gz>0)? 0:18;
1751         if (r0>80){
1752           corr->DistortPoint(distPoint, sector);
1753         }
1754         // Double_t value=distPoint[2]-gz;
1755         if (itype==0){
1756           Double_t r1   = TMath::Sqrt(distPoint[0]*distPoint[0]+distPoint[1]*distPoint[1]);
1757           Double_t phi1 = TMath::ATan2(distPoint[1],distPoint[0]);
1758           Double_t drphi= r0*(phi1-phi0);
1759           Double_t dr   = r1-r0;
1760           distortions[icorr]  = drphi-ky*dr;
1761           distortionsR[icorr] = dr;
1762         }
1763         (*pcstream)<<"fit"<<
1764           Form("%s=",corr->GetName())<<distortions[icorr]<<    // dump correction value
1765           Form("dR%s=",corr->GetName())<<distortionsR[icorr];   // dump correction R  value
1766       }
1767       (*pcstream)<<"fit"<<"\n";
1768     }
1769   }
1770   delete pcstream;
1771 }
1772
1773
1774
1775 void   AliTPCCorrection::MakeDistortionMap(THnSparse * his0, TTreeSRedirector * const pcstream, const char* hname, Int_t run){
1776   //
1777   // make a distortion map out ou fthe residual histogram
1778   // Results are written to the debug streamer - pcstream
1779   // Parameters:
1780   //   his0       - input (4D) residual histogram
1781   //   pcstream   - file to write the tree
1782   //   run        - run number
1783   // marian.ivanov@cern.ch
1784   const Int_t kMinEntries=50;
1785   Int_t nbins1=his0->GetAxis(1)->GetNbins();
1786   Int_t first1=his0->GetAxis(1)->GetFirst();
1787   Int_t last1 =his0->GetAxis(1)->GetLast();
1788   //
1789   Double_t bz=AliTrackerBase::GetBz();
1790   Int_t idim[4]={0,1,2,3};
1791   for (Int_t ibin1=first1; ibin1<last1; ibin1++){   //axis 1 - theta
1792     //
1793     his0->GetAxis(1)->SetRange(TMath::Max(ibin1,1),TMath::Min(ibin1,nbins1));
1794     Double_t       x1= his0->GetAxis(1)->GetBinCenter(ibin1);
1795     THnSparse * his1 = his0->Projection(4,idim);  // projected histogram according range1
1796     Int_t nbins3     = his1->GetAxis(3)->GetNbins();
1797     Int_t first3     = his1->GetAxis(3)->GetFirst();
1798     Int_t last3      = his1->GetAxis(3)->GetLast();
1799     //
1800
1801     for (Int_t ibin3=first3-1; ibin3<last3; ibin3+=1){   // axis 3 - local angle
1802       his1->GetAxis(3)->SetRange(TMath::Max(ibin3-1,1),TMath::Min(ibin3+1,nbins3));
1803       Double_t      x3= his1->GetAxis(3)->GetBinCenter(ibin3);
1804       if (ibin3<first3) {
1805         his1->GetAxis(3)->SetRangeUser(-1,1);
1806         x3=0;
1807       }
1808       THnSparse * his3= his1->Projection(4,idim);         //projected histogram according selection 3
1809       Int_t nbins2    = his3->GetAxis(2)->GetNbins();
1810       Int_t first2    = his3->GetAxis(2)->GetFirst();
1811       Int_t last2     = his3->GetAxis(2)->GetLast();
1812       //
1813       for (Int_t ibin2=first2; ibin2<last2; ibin2+=1){
1814         his3->GetAxis(2)->SetRange(TMath::Max(ibin2-1,1),TMath::Min(ibin2+1,nbins2));
1815         Double_t x2= his3->GetAxis(2)->GetBinCenter(ibin2);
1816         TH1 * hisDelta = his3->Projection(0);
1817         //
1818         Double_t entries = hisDelta->GetEntries();
1819         Double_t mean=0, rms=0;
1820         if (entries>kMinEntries){
1821           mean    = hisDelta->GetMean(); 
1822           rms = hisDelta->GetRMS(); 
1823         }
1824         (*pcstream)<<hname<<
1825           "run="<<run<<
1826           "bz="<<bz<<
1827           "theta="<<x1<<
1828           "phi="<<x2<<
1829           "snp="<<x3<<
1830           "entries="<<entries<<
1831           "mean="<<mean<<
1832           "rms="<<rms<<
1833           "\n";
1834         delete hisDelta;
1835         printf("%f\t%f\t%f\t%f\t%f\n",x1,x3,x2, entries,mean);
1836       }
1837       delete his3;
1838     }
1839     delete his1;
1840   }
1841 }
1842
1843
1844
1845
1846
1847 void AliTPCCorrection::StoreInOCDB(Int_t startRun, Int_t endRun, const char *comment){
1848   //
1849   // Store object in the OCDB
1850   // By default the object is stored in the current directory 
1851   // default comment consit of user name and the date
1852   //
1853   TString ocdbStorage="";
1854   ocdbStorage+="local://"+gSystem->GetFromPipe("pwd")+"/OCDB";
1855   AliCDBMetaData *metaData= new AliCDBMetaData();
1856   metaData->SetObjectClassName("AliTPCCorrection");
1857   metaData->SetResponsible("Marian Ivanov");
1858   metaData->SetBeamPeriod(1);
1859   metaData->SetAliRootVersion("05-25-01"); //root version
1860   TString userName=gSystem->GetFromPipe("echo $USER");
1861   TString date=gSystem->GetFromPipe("date");
1862
1863   if (!comment) metaData->SetComment(Form("Space point distortion calibration\n User: %s\n Data%s",userName.Data(),date.Data()));
1864   if (comment) metaData->SetComment(comment);
1865   AliCDBId* id1=NULL;
1866   id1=new AliCDBId("TPC/Calib/Correction", startRun, endRun);
1867   AliCDBStorage* gStorage = AliCDBManager::Instance()->GetStorage(ocdbStorage);
1868   gStorage->Put(this, (*id1), metaData);
1869 }
1870
1871
1872 void AliTPCCorrection::FastSimDistortedVertex(Double_t orgVertex[3], Int_t nTracks, AliESDVertex &aV, AliESDVertex &avOrg, AliESDVertex &cV, AliESDVertex &cvOrg, TTreeSRedirector * const pcstream, Double_t etaCuts){
1873   //
1874   // Fast method to simulate the influence of the given distortion on the vertex reconstruction
1875   //
1876
1877   AliMagF* magF= (AliMagF*)TGeoGlobalMagField::Instance()->GetField();
1878   if (!magF) AliError("Magneticd field - not initialized");
1879   Double_t bz = magF->SolenoidField(); //field in kGauss
1880   printf("bz: %lf\n",bz);
1881   AliVertexerTracks *vertexer = new AliVertexerTracks(bz); // bz in kGauss
1882
1883   TObjArray   aTrk;              // Original Track array of Aside
1884   TObjArray   daTrk;             // Distorted Track array of A side
1885   UShort_t    *aId = new UShort_t[nTracks];      // A side Track ID
1886   TObjArray   cTrk;               
1887   TObjArray   dcTrk;
1888   UShort_t    *cId = new UShort_t [nTracks];
1889   Int_t id=0; 
1890   Double_t mass = TDatabasePDG::Instance()->GetParticle("pi+")->Mass();
1891   TF1 fpt("fpt",Form("x*(1+(sqrt(x*x+%f^2)-%f)/([0]*[1]))^(-[0])",mass,mass),0.4,10);
1892   fpt.SetParameters(7.24,0.120);
1893   fpt.SetNpx(10000);
1894   for(Int_t nt=0; nt<nTracks; nt++){
1895     Double_t phi = gRandom->Uniform(0.0, 2*TMath::Pi());
1896     Double_t eta = gRandom->Uniform(-etaCuts, etaCuts);
1897     Double_t pt = fpt.GetRandom(); // momentum for f1
1898     //   printf("phi %lf  eta %lf pt %lf\n",phi,eta,pt);
1899     Short_t sign=1;
1900     if(gRandom->Rndm() < 0.5){
1901       sign =1;
1902     }else{
1903       sign=-1;
1904     }
1905
1906     Double_t theta = 2*TMath::ATan(TMath::Exp(-eta))-TMath::Pi()/2.;
1907     Double_t pxyz[3];
1908     pxyz[0]=pt*TMath::Cos(phi);
1909     pxyz[1]=pt*TMath::Sin(phi);
1910     pxyz[2]=pt*TMath::Tan(theta);
1911     Double_t cv[21]={0};
1912     AliExternalTrackParam *t= new AliExternalTrackParam(orgVertex, pxyz, cv, sign);
1913
1914     Double_t refX=1.;
1915     Int_t dir=-1;
1916     AliExternalTrackParam *td = FitDistortedTrack(*t, refX, dir,  NULL);
1917     if (!td) continue;
1918     if (pcstream) (*pcstream)<<"track"<<
1919       "eta="<<eta<<
1920       "theta="<<theta<<
1921       "tOrig.="<<t<<
1922       "td.="<<td<<
1923       "\n";
1924     if(( eta>0.07 )&&( eta<etaCuts )) { // - log(tan(0.5*theta)), theta = 0.5*pi - ATan(5.0/80.0)
1925       if (td){
1926         daTrk.AddLast(td);
1927         aTrk.AddLast(t);
1928         Int_t nn=aTrk.GetEntriesFast();
1929         aId[nn]=id;
1930       }
1931     }else if(( eta<-0.07 )&&( eta>-etaCuts )){
1932       if (td){
1933         dcTrk.AddLast(td);
1934         cTrk.AddLast(t);
1935         Int_t nn=cTrk.GetEntriesFast();
1936         cId[nn]=id;
1937       }
1938     }
1939     id++;  
1940   }// end of track loop
1941
1942   vertexer->SetTPCMode();
1943   vertexer->SetConstraintOff();
1944
1945   aV = *((AliESDVertex*)vertexer->FindPrimaryVertex(&daTrk,aId));  
1946   avOrg = *((AliESDVertex*)vertexer->FindPrimaryVertex(&aTrk,aId));
1947   cV = *((AliESDVertex*)vertexer->FindPrimaryVertex(&dcTrk,cId));  
1948   cvOrg = *((AliESDVertex*)vertexer->FindPrimaryVertex(&cTrk,cId));
1949   if (pcstream) (*pcstream)<<"vertex"<<
1950     "x="<<orgVertex[0]<<
1951     "y="<<orgVertex[1]<<
1952     "z="<<orgVertex[2]<<
1953     "av.="<<&aV<<              // distorted vertex A side
1954     "cv.="<<&cV<<              // distroted vertex C side
1955     "avO.="<<&avOrg<<         // original vertex A side
1956     "cvO.="<<&cvOrg<<
1957     "\n";
1958   delete []aId;
1959   delete []cId;
1960 }
1961
1962 void AliTPCCorrection::AddVisualCorrection(AliTPCCorrection* corr, Int_t position){
1963   //
1964   // make correction available for visualization using 
1965   // TFormula, TFX and TTree::Draw 
1966   // important in order to check corrections and also compute dervied variables 
1967   // e.g correction partial derivatives
1968   //
1969   // NOTE - class is not owner of correction
1970   //     
1971   if (!fgVisualCorrection) fgVisualCorrection=new TObjArray;
1972   if (position!=0&&position>=fgVisualCorrection->GetEntriesFast())
1973     fgVisualCorrection->Expand(position*2);
1974   fgVisualCorrection->AddAt(corr, position);
1975 }
1976
1977
1978
1979 Double_t AliTPCCorrection::GetCorrSector(Double_t sector, Double_t r, Double_t kZ, Int_t axisType, Int_t corrType){
1980   //
1981   // calculate the correction at given position - check the geffCorr
1982   //
1983   if (!fgVisualCorrection) return 0;
1984   AliTPCCorrection *corr = (AliTPCCorrection*)fgVisualCorrection->At(corrType);
1985   if (!corr) return 0;
1986
1987   Double_t phi=sector*TMath::Pi()/9.;
1988   Double_t gx = r*TMath::Cos(phi);
1989   Double_t gy = r*TMath::Sin(phi);
1990   Double_t gz = r*kZ;
1991   Int_t nsector=(gz>0) ? 0:18; 
1992   //
1993   //
1994   //
1995   Float_t distPoint[3]={gx,gy,gz};
1996   corr->DistortPoint(distPoint, nsector);
1997   Double_t r0=TMath::Sqrt(gx*gx+gy*gy);
1998   Double_t r1=TMath::Sqrt(distPoint[0]*distPoint[0]+distPoint[1]*distPoint[1]);
1999   Double_t phi0=TMath::ATan2(gy,gx);
2000   Double_t phi1=TMath::ATan2(distPoint[1],distPoint[0]);
2001   if (axisType==0) return r1-r0;
2002   if (axisType==1) return (phi1-phi0)*r0;
2003   if (axisType==2) return distPoint[2]-gz;
2004   return phi1-phi0;
2005 }
2006
2007 Double_t AliTPCCorrection::GetCorrXYZ(Double_t gx, Double_t gy, Double_t gz, Int_t axisType, Int_t corrType){
2008   //
2009   // return correction at given x,y,z
2010   // 
2011   if (!fgVisualCorrection) return 0;
2012   AliTPCCorrection *corr = (AliTPCCorrection*)fgVisualCorrection->At(corrType);
2013   if (!corr) return 0;
2014   Double_t phi0= TMath::ATan2(gy,gx);
2015   Int_t nsector=(gz>0) ? 0:18; 
2016   Float_t distPoint[3]={gx,gy,gz};
2017   corr->DistortPoint(distPoint, nsector);
2018   Double_t r0=TMath::Sqrt(gx*gx+gy*gy);
2019   Double_t r1=TMath::Sqrt(distPoint[0]*distPoint[0]+distPoint[1]*distPoint[1]);
2020   Double_t phi1=TMath::ATan2(distPoint[1],distPoint[0]);
2021   if (axisType==0) return r1-r0;
2022   if (axisType==1) return (phi1-phi0)*r0;
2023   if (axisType==2) return distPoint[2]-gz;
2024   return phi1-phi0;
2025 }