]> git.uio.no Git - u/mrichter/AliRoot.git/blob - TRD/AliTRDCalibra.cxx
b25b43d699e7580c69877e3fa9ccf5f88499637c
[u/mrichter/AliRoot.git] / TRD / AliTRDCalibra.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 /* $Id$ */
17
18 /////////////////////////////////////////////////////////////////////////////////
19 //                                                                             
20 // AliTRDCalibra                                                               
21 //                                                                             
22 // This class is for the TRD calibration of the relative gain factor, the drift velocity,
23 // the time 0 and the pad response function.        
24 // It can be used for the calibration per chamber but also per group of pads and eventually per pad.
25 // The user has to choose with the functions SetNz and SetNrphi the precision of the calibration. 
26 //Begin_Html
27 /*
28 <br>
29 <CENTER>
30 <TABLE border=1>
31 <TR><TD><center>Nz</center></TD><TD><center> 0 </center></TD><TD><center> 1 </center></TD><TD><center> 2 </center></TD><TD><center> 3 </center></TD><TD><center> 4 </center></TD></TR>
32 <TR><TD><CENTER>group of row pads per detector</CENTER></TD><TD><CENTER>1</CENTER></TD><TD><CENTER>2</CENTER></TD><TD><CENTER>4</CENTER></TD><TD><CENTER>6(chamb2)<br> 8(others chambers)</CENTER></TD><TD><CENTER>12 (chamb2)<br> 16 (chamb0)</CENTER></TD></TR>
33 <TR><TD><CENTER>row pads per group</CENTER></TD><TD><CENTER>12 (chamb2)<br> 16 (chamb0)</CENTER></TD><TD><CENTER>6 (chamb2)<br> 8 (chamb0)</CENTER></TD><TD><CENTER>3 (chamb2)<br> 4 (chamb0)</CENTER></TD><TD><CENTER>2</CENTER></TD><TD><CENTER>1</CENTER></TD></TR>
34 <TR><TD><CENTER>~distance [cm]</CENTER></TD><TD><CENTER>106 (chamb2)<br> 130 (chamb0)</CENTER></TD><TD><CENTER>53 (chamb2)<br> 65 (chamb0)</CENTER></TD><TD><CENTER>26.5 (chamb2)<br> 32.5 (chamb0)</CENTER></TD><TD><CENTER>17 (chamb2)<br> 17 (chamb0)</CENTER></TD><TD><CENTER>9 (chamb2)<br> 9 (chamb0)</CENTER></TD></TR>
35 <CAPTION>In the z direction</CAPTION>
36 </TABLE>
37 </CENTER>
38 <CENTER>
39 <br>
40 <TABLE border=1>
41 <TR><TD><center>Nrphi</center></TD><TD><center> 0 </center></TD><TD><center> 1 </center></TD><TD><center> 2 </center></TD><TD><center> 3 </center></TD><TD><center> 4 </center></TD><TD><center> 5 </center></TD><TD><center> 6 </center></TD></TR>
42 <TR><TD><CENTER>group of col pads per detector</CENTER></TD><TD><CENTER>1</CENTER></TD><TD><CENTER>2</CENTER></TD><TD><CENTER>4</CENTER></TD><TD><CENTER>8</CENTER></TD><TD><CENTER>16</CENTER></TD><TD><center>36</center></TD><TD><center>144</center></TD></TR>
43 <TR><TD><CENTER>col pads per group</CENTER></TD><TD><CENTER>144</CENTER></TD><TD><CENTER>72</CENTER></TD><TD><CENTER>36</CENTER></TD><TD><CENTER>18</CENTER></TD><TD><CENTER>9</CENTER></TD><TD><center>4</center></TD><TD><center>1</center></TD></TR>
44 <TR><TD><CENTER>~distance [cm]</CENTER></TD><TD><CENTER>113.4</CENTER></TD><TD><CENTER>56.7</CENTER></TD><TD><CENTER>25.3</CENTER></TD><TD><CENTER>14.3</CENTER></TD><TD><CENTER>7.25</CENTER></TD><TD><center>3.2</center></TD><TD><center>0.8</center></TD></TR>
45 <CAPTION>In the rphi direction</CAPTION>
46 </TABLE>
47 </CENTER>
48 <br>
49 */
50 //End_Html 
51 //
52 // Fill histograms or vectors
53 //----------------------------
54 //   
55 // 2D Histograms (Histo2d) or vectors (Vector2d), then converted in Trees, will be filled
56 // from RAW DATA in a run or from reconstructed TRD tracks during the offline tracking 
57 // in the function "FollowBackProlongation" (AliTRDtracker)
58 // Per default the functions to fill are off.                                   
59 //
60 //Begin_Html
61 /*
62 Example of 2D histos for the relative gain (left) and the drift velocity (right) calibration of the sector 13 <br>
63 <center>
64 <img src="./gif/2dhisto.gif" width="600" height="350"><br>
65 </center>
66 */
67 //End_Html    
68 //
69 // Fit the histograms to find the coefficients 
70 //---------------------------------------------
71 //
72 // These 2D histograms or vectors (first converted in 1D histos) will be fitted  
73 // if they have enough entries, otherwise the (default) value of the choosen database 
74 // will be put. For the relative gain calibration the resulted factors will be globally 
75 // normalized to the gain factors of the choosen database. It unables to precise     
76 // previous calibration procedure.
77 // The function SetDebug enables the user to see:                                     
78 // _fDebug = 0: nothing, only the values are written in the tree if wanted
79 // _fDebug = 1: a comparaison of the coefficients found and the default values 
80 //              in the choosen database.
81 //              fCoef , histogram of the coefs as function of the calibration group number
82 //              fDelta , histogram of the relative difference of the coef with the default
83 //                        value in the database as function of the calibration group number
84 //              fError , dirstribution of this relative difference
85 // _fDebug = 2: only the fit of the choosen calibration group fFitVoir (SetFitVoir)
86 // _fDebug = 3: The coefficients in the choosen detector fDet (SetDet) as function of the
87 //              pad row and col number
88 // _fDebug = 4; The coeffcicients in the choosen detector fDet (SetDet) like in the 3 but with
89 //              also the comparaison histograms of the 1 for this detector
90 //
91 //Begin_Html
92 /*
93 Example of fCoef for the relative gain calibration of the sector 13 <br>
94 <center>
95 <img src="./gif/coef.gif"  width="400" height="460">
96 </center><br>
97 Example of fDelta (right) and fError (left) for the relative gain calibration of the sector 13 <br>
98 <center>
99 <img src="./gif/detlaerror.gif"  width="550" height="380"><br>
100 </center>
101 */
102 //End_Html 
103 //                            
104 // Author:
105 //   R. Bailhache (R.Bailhache@gsi.de)
106 //                            
107 //////////////////////////////////////////////////////////////////////////////////////
108
109 #include <TTree.h>
110 #include <TLine.h>
111 #include <TH1I.h>
112 #include <TStyle.h>
113 #include <TProfile2D.h>
114 #include <TFile.h>
115 #include <TCanvas.h>
116 #include <TGraphErrors.h>
117 #include <TGraph.h>
118 #include <TObjArray.h>
119 #include <TChain.h>
120 #include <TH1.h>
121 #include <TH1I.h>
122 #include <TH1F.h>
123 #include <TF1.h>
124 #include <TH2F.h>
125 #include <TAxis.h>
126 #include <TStopwatch.h>
127 #include <TMath.h>
128 #include <TLegend.h>
129 #include <TDirectory.h>
130 #include <TROOT.h>
131
132 #include "AliLog.h"
133 #include "AliCDBManager.h"
134 #include "AliRun.h"
135 #include "AliRunLoader.h"
136 #include "AliLoader.h"
137 #include "AliRawReaderFile.h"
138 #include "AliRawReader.h"
139
140 #include "AliTRDCalibra.h"
141 #include "AliTRDcalibDB.h"
142 #include "AliTRDCommonParam.h"
143 #include "AliTRDmcmTracklet.h"
144 #include "AliTRDpadPlane.h"
145 #include "AliTRDcluster.h"
146 #include "AliTRDtrack.h"
147 #include "AliTRDdigit.h"
148 #include "AliTRDdigitsManager.h"
149 #include "AliTRD.h"
150 #include "AliTRDgeometry.h"
151 #include "./Cal/AliTRDCalROC.h"
152 #include "./Cal/AliTRDCalPad.h"
153 #include "./Cal/AliTRDCalDet.h"
154 #include "AliTRDrawData.h"
155
156 ClassImp(AliTRDCalibra)
157
158 AliTRDCalibra* AliTRDCalibra::fgInstance = 0;
159 Bool_t AliTRDCalibra::fgTerminated = kFALSE;
160
161 //_____________singleton implementation_________________________________________________
162 AliTRDCalibra *AliTRDCalibra::Instance()
163 {
164   //
165   // Singleton implementation
166   //
167
168   if (fgTerminated != kFALSE) {
169     return 0;
170   }
171
172   if (fgInstance == 0) {
173     fgInstance = new AliTRDCalibra();
174   }
175
176   return fgInstance;
177
178 }
179
180 //______________________________________________________________________________________
181 void AliTRDCalibra::Terminate()
182 {
183   //
184   // Singleton implementation
185   // Deletes the instance of this class
186   //
187
188   fgTerminated = kTRUE;
189
190   if (fgInstance != 0) {
191     delete fgInstance;
192     fgInstance = 0;
193   }
194
195 }
196
197 //______________________________________________________________________________________
198 AliTRDCalibra::AliTRDCalibra()
199   :TObject()
200   ,fMITracking(kFALSE)
201   ,fMcmTracking(kFALSE)
202   ,fMcmCorrectAngle(kFALSE)
203   ,fCH2dOn(kFALSE)
204   ,fPH2dOn(kFALSE)
205   ,fPRF2dOn(kFALSE)
206   ,fHisto2d(kFALSE)
207   ,fVector2d(kFALSE)
208   ,fRelativeScale(0)
209   ,fCountRelativeScale(0)
210   ,fRelativeScaleAuto(kFALSE)
211   ,fThresholdDigit(0)
212   ,fThresholdClusterPRF1(0.0)
213   ,fThresholdClusterPRF2(0.0)
214   ,fCenterOfflineCluster(kFALSE)
215   ,fTraMaxPad(kFALSE)
216   ,fWriteNameCoef(0)
217   ,fWriteName(0)
218   ,fFitPHOn(kFALSE)
219   ,fFitPHPeriode(0)
220   ,fBeginFitCharge(0.0)
221   ,fRangeFitPRF(0.0)
222   ,fMeanChargeOn(kFALSE)
223   ,fFitChargeBisOn(kFALSE)
224   ,fT0Shift(0.0)
225   ,fAccCDB(kFALSE)
226   ,fNumberFit(0)
227   ,fNumberEnt(0)
228   ,fStatisticMean(0.0)
229   ,fDebug(0)
230   ,fFitVoir(0)
231   ,fPRF(0)
232   ,fGain(0)
233   ,fT0(0)
234   ,fVdrift(0)
235   ,fVdriftDetector(0)
236   ,fVdriftPad(0x0)
237   ,fT0Detector(0)
238   ,fT0Pad(0x0)
239   ,fPRFDetector(0)
240   ,fPRFPad(0x0)
241   ,fCoefCH(0x0)
242   ,fDetectorAliTRDtrack(kFALSE)
243   ,fChamberAliTRDtrack(-1)
244   ,fDetectorPreviousTrack(-1)
245   ,fGoodTrack(kTRUE)
246   ,fAmpTotal(0x0)
247   ,fPHPlace(0x0)
248   ,fPHValue(0x0)
249   ,fNumberClusters(0)
250   ,fProcent(0.0)
251   ,fDifference(0)
252   ,fNumberTrack(0)
253   ,fCoefPRFE(0)
254   ,fCoefPRFDB(0)
255   ,fTimeMax(0)
256   ,fSf(0.0)
257   ,fScaleFitFactor(0.0)
258   ,fMinEntries(0)
259   ,fEntriesCurrent(0)
260   ,fL3P0(0.0)
261   ,fL3P2(0.0)
262   ,fG3P2(0.0)
263   ,fVectorPH(0)
264   ,fPlaPH(0)
265   ,fNumberBinCharge(0)
266   ,fVectorCH(0)
267   ,fPlaCH(0)
268   ,fVectorFitCH(0)
269   ,fNumberBinPRF(0)
270   ,fVectorPRF(0)
271   ,fPlaPRF(0)
272   ,fPH2d(0x0)
273   ,fPRF2d(0x0)
274   ,fCH2d(0x0)
275   ,fRebin(0)
276 {
277   //
278   // Default constructor
279   //
280
281   for (Int_t i = 0; i < 3; i++) {
282     fNz[i]    = 0;
283     fNrphi[i] = 0;
284   }
285
286   for (Int_t k = 0; k < 3; k++) {
287     fNtotal[k]    = 0;
288     fDetChamb2[k] = 0;
289     fDetChamb0[k] = 0;
290   }
291
292   // Write
293   for (Int_t i = 0; i < 3; i++) {
294     fWriteCoef[i] = kFALSE;
295     fWrite[i]     = kFALSE;
296   }
297
298   // Debug Mode
299   for (Int_t k = 0; k < 3; k++) {
300     fDet[k] = 0;
301   }
302
303   for (Int_t i = 0; i < 3; i++) {
304     fPhd[i] = 0.0;
305   }
306
307   // Init
308   Init();
309   
310 }
311
312 //______________________________________________________________________________________
313 AliTRDCalibra::AliTRDCalibra(const AliTRDCalibra &c)
314   :TObject(c)
315   ,fMITracking(kFALSE)
316   ,fMcmTracking(kFALSE)
317   ,fMcmCorrectAngle(kFALSE)
318   ,fCH2dOn(kFALSE)
319   ,fPH2dOn(kFALSE)
320   ,fPRF2dOn(kFALSE)
321   ,fHisto2d(kFALSE)
322   ,fVector2d(kFALSE)
323   ,fRelativeScale(0)
324   ,fCountRelativeScale(0)
325   ,fRelativeScaleAuto(kFALSE)
326   ,fThresholdDigit(0)
327   ,fThresholdClusterPRF1(0.0)
328   ,fThresholdClusterPRF2(0.0)
329   ,fCenterOfflineCluster(kFALSE)
330   ,fTraMaxPad(kFALSE)
331   ,fWriteNameCoef(0)
332   ,fWriteName(0)
333   ,fFitPHOn(kFALSE)
334   ,fFitPHPeriode(0)
335   ,fBeginFitCharge(0.0)
336   ,fRangeFitPRF(0.0)
337   ,fMeanChargeOn(kFALSE)
338   ,fFitChargeBisOn(kFALSE)
339   ,fT0Shift(0.0)
340   ,fAccCDB(kFALSE)
341   ,fNumberFit(0)
342   ,fNumberEnt(0)
343   ,fStatisticMean(0.0)
344   ,fDebug(0)
345   ,fFitVoir(0)
346   ,fPRF(0)
347   ,fGain(0)
348   ,fT0(0)
349   ,fVdrift(0)
350   ,fVdriftDetector(0)
351   ,fVdriftPad(0x0)
352   ,fT0Detector(0)
353   ,fT0Pad(0x0)
354   ,fPRFDetector(0)
355   ,fPRFPad(0x0)
356   ,fCoefCH(0x0)
357   ,fDetectorAliTRDtrack(kFALSE)
358   ,fChamberAliTRDtrack(-1)
359   ,fDetectorPreviousTrack(-1)
360   ,fGoodTrack(kTRUE)
361   ,fAmpTotal(0x0)
362   ,fPHPlace(0x0)
363   ,fPHValue(0x0)
364   ,fNumberClusters(0)
365   ,fProcent(0.0)
366   ,fDifference(0)
367   ,fNumberTrack(0)
368   ,fCoefPRFE(0)
369   ,fCoefPRFDB(0)
370   ,fTimeMax(0)
371   ,fSf(0.0)
372   ,fScaleFitFactor(0.0)
373   ,fMinEntries(0)
374   ,fEntriesCurrent(0)
375   ,fL3P0(0.0)
376   ,fL3P2(0.0)
377   ,fG3P2(0.0)
378   ,fVectorPH(0)
379   ,fPlaPH(0)
380   ,fNumberBinCharge(0)
381   ,fVectorCH(0)
382   ,fPlaCH(0)
383   ,fVectorFitCH(0)
384   ,fNumberBinPRF(0)
385   ,fVectorPRF(0)
386   ,fPlaPRF(0)
387   ,fPH2d(0x0)
388   ,fPRF2d(0x0)
389   ,fCH2d(0x0)
390   ,fRebin(0)
391 {
392   //
393   // Copy constructor
394   //
395
396 }
397
398 //____________________________________________________________________________________
399 AliTRDCalibra::~AliTRDCalibra()
400 {
401   //
402   // AliTRDCalibra destructor
403   //
404
405   ClearHistos();
406   ClearTree();
407
408 }
409
410 //_____________________________________________________________________________
411 void AliTRDCalibra::Destroy() 
412 {
413   //
414   // Delete instance 
415   //
416
417   if (fgInstance) {
418     delete fgInstance;
419     fgInstance = 0x0;
420   }
421
422 }
423
424 //_____________________________________________________________________________
425 void AliTRDCalibra::ClearHistos() 
426 {
427   //
428   // Delete the histos
429   //
430
431   if (fPH2d) {
432     delete fPH2d;
433     fPH2d  = 0x0;
434   }
435   if (fCH2d) {
436     delete fCH2d;
437     fCH2d  = 0x0;
438   }
439   if (fPRF2d) {
440     delete fPRF2d;
441     fPRF2d = 0x0;
442   }
443
444 }
445
446 //_____________________________________________________________________________
447 void AliTRDCalibra::ClearTree() 
448 {
449   //
450   // Delete the trees
451   //
452   
453   if (fPRF) {
454     delete fPRF;
455     fPRF    = 0x0;
456   }
457   if (fGain) {
458     delete fGain;
459     fGain   = 0x0;
460   }
461   if (fT0) {
462     delete fT0;
463     fT0     = 0x0;
464   }
465   if (fVdrift) {
466     delete fVdrift;
467     fVdrift = 0x0;
468   }
469
470 }
471
472 //_____________________________________________________________________________
473 void AliTRDCalibra::Init() 
474 {
475   //
476   // Init some default values
477   //
478
479   // How to fill the 2D
480   fThresholdDigit       = 5;
481   fThresholdClusterPRF1 = 2.0;
482   fThresholdClusterPRF2 = 3.0;
483   
484   // Store the Info
485   fNumberBinCharge      = 100;
486   fNumberBinPRF         = 20;
487   
488   // Write
489   fWriteName            = "TRD.calibration.root";
490   fWriteNameCoef        = "TRD.coefficient.root";
491   
492   // Fit
493   fFitPHPeriode         = 1;
494   fBeginFitCharge       = 3.5;
495   fRangeFitPRF          = 0.5;
496   fMinEntries           = 800;
497   fT0Shift              = 0.143397;
498   
499   // Internal variables
500   
501   // Fill the 2D histos in the offline tracking
502   fDetectorPreviousTrack = -1;
503   fChamberAliTRDtrack    = -1;
504   fGoodTrack             = kTRUE;
505
506   fProcent               = 6.0;
507   fDifference            = 17;
508   fNumberClusters        = 18;
509   fNumberTrack           = 0;
510   fNumberUsedCh[0]       = 0;
511   fNumberUsedCh[1]       = 0;
512   fNumberUsedPh[0]       = 0;
513   fNumberUsedPh[1]       = 0;
514   
515   // Variables in the loop
516   for (Int_t k = 0; k < 4; k++) {
517     fChargeCoef[k] = 1.0;
518     fVdriftCoef[k] = 1.5;
519     fT0Coef[k]     = -1.0;
520   }
521   for (Int_t i = 0; i < 2; i++) {
522     fPRFCoef[i]    = -1.0;
523   }
524   
525   // Pad calibration
526   for (Int_t i = 0; i < 3; i++) {
527     fRowMin[i]    = -1;
528     fRowMax[i]    = -1;
529     fColMax[i]    = -1;
530     fColMin[i]    = -1;
531     fNnZ[i]       = -1;
532     fNnRphi[i]    = -1;
533     fNfragZ[i]    = -1;
534     fNfragRphi[i] = -1;
535     fXbins[i]     = -1;
536   }
537   
538   // Local database to be changed
539   fRebin = 1;
540   
541 }
542
543 //____________Functions fit Online CH2d________________________________________
544 Bool_t AliTRDCalibra::FitCHOnline(TH2I *ch)
545 {
546   //
547   // Fit the 1D histos, projections of the 2D ch on the Xaxis, for each
548   // calibration group normalized the resulted coefficients (to 1 normally)
549   // and write the results in a tree
550   //
551    
552   // Number of Xbins (detectors or groups of pads)
553   TAxis   *xch     = ch->GetXaxis();
554   Int_t    nbins   = xch->GetNbins();
555   TAxis   *yph     = ch->GetYaxis();
556   Int_t    nybins  = yph->GetNbins();
557   if (!InitFit(nbins,0)) {
558     return kFALSE;
559   }
560   fStatisticMean = 0.0;
561   fNumberFit     = 0;
562   fNumberEnt     = 0;
563
564   // For memory
565   if (fVectorCH) {
566     fVectorCH->Clear();
567   }
568   if (fPlaCH) {
569     fPlaCH->Clear();
570   }
571   
572   // Init fCountDet and fCount
573   InitfCountDetAndfCount(0);
574   
575   // Beginning of the loop betwwen dect1 and dect2
576   for (Int_t idect = fDect1[0]; idect < fDect2[0]; idect++) {
577
578     TH1I *projch = (TH1I *) ch->ProjectionY("projch",idect+1,idect+1,(Option_t *)"e");
579     projch->SetDirectory(0);
580
581     // Determination of fNnZ, fNnRphi, fNfragZ and fNfragRphi
582     UpdatefCountDetAndfCount(idect,0);
583     
584     // Reconstruction of the row and pad group: rowmin, row max ...
585     ReconstructFitRowMinRowMax(idect, 0);
586     
587     // Number of entries for this calibration group
588     Double_t nentries = 0.0;
589     for (Int_t k = 0; k < nybins; k++) {
590       nentries += ch->GetBinContent(ch->GetBin(idect+1,k+1));
591     }
592     if (nentries > 0) {
593       fNumberEnt++;
594     }
595
596     // Rebin and statistic stuff
597     // Rebin
598     if (fRebin > 1) {
599       projch = ReBin((TH1I *) projch);
600     }
601     // This detector has not enough statistics or was off
602     if (nentries < fMinEntries) {
603       // Fill with the default infos
604       NotEnoughStatistic(idect,0);
605       // Memory!!!
606       if (fDebug != 2) {
607         delete projch;
608       }
609       continue;
610     }
611     
612     // Statistics of the group fitted
613     AliInfo(Form("For the group number %d there are %f stats",idect,nentries));
614     fStatisticMean += nentries;
615     fNumberFit++; 
616     
617     // Method Mean and fit
618     // idect is egal for fDebug = 0 and 2, only to fill the hist 
619     FitCH((TH1 *) projch,(Int_t) (idect-fDect1[0]));
620     // Method fit bis
621     // idect is egal for fDebug = 0 and 2, only to fill the hist
622     if (fFitChargeBisOn) { 
623       FitBisCH((TH1 *) projch,(Int_t) (idect-fDect1[0]));
624     }
625     
626     // Visualise the detector for fDebug 3 or 4
627     // Here is the reconstruction of the pad and row group is used!
628     if (fDebug >= 3) {
629       FillCoefChargeDB();
630     }
631     // Fill Infos Fit
632     FillInfosFit(idect,0);
633     
634     // Memory!!!
635     if (fDebug != 2) {
636       delete projch;
637     }
638     
639   } // Boucle object
640
641   // Normierungcharge
642   if (fDebug != 2) {
643     NormierungCharge();
644   }
645   
646   // Plot
647   // 0 no plot, 1 and 4 error plot, 3 and 4 DB plot
648   if ((fDebug == 1) || 
649       (fDebug == 4)) {
650     PlotWriteCH();
651   }
652   if ((fDebug == 4) || 
653       (fDebug == 3)) {
654     PlotCHDB();
655   }
656
657   // Mean Statistic
658   if (fNumberFit > 0) {
659     AliInfo(Form("There is a mean statistic of: %d",(Int_t) fStatisticMean/fNumberFit));
660     fStatisticMean = fStatisticMean / fNumberFit;
661   }
662   else {
663     AliInfo("There is no fit!");
664   }
665   
666   // Write the things!
667   ConvertVectorFitCHTree();
668   if (fWriteCoef[0]) {
669     WriteFitInfos(0);       
670   }
671
672   return kTRUE;
673   
674 }
675
676 //____________Functions fit Online CH2d________________________________________
677 Bool_t AliTRDCalibra::FitCHOnline()
678 {
679   //
680   // Reconstruct a 1D histo from the vectorCH for each calibration group,
681   // fit the histo, normalized the resulted coefficients (to 1 normally)
682   // and write the results in a tree
683   //
684
685   // Number of Xbins (detectors or groups of pads)
686   if (!InitFit(0,0)) {
687     return kFALSE;
688   }
689   fStatisticMean = 0.0;
690   fNumberFit     = 0;
691   fNumberEnt     = 0;
692  
693   // Init fCountDet and fCount
694   InitfCountDetAndfCount(0);
695
696   // Beginning of the loop between dect1 and dect2
697   for (Int_t idect = fDect1[0]; idect < fDect2[0]; idect++) {
698     
699     // Search if the group is in the VectorCH
700     Int_t place = SearchInVector(idect,0);
701        
702     // Is in
703     TH1F *projch = 0x0;
704     TString name("CH");
705     name += idect;
706     if (place != -1) {
707       // Variable
708       AliTRDCTInfo *fCHInfo = new AliTRDCTInfo();
709       // Retrieve
710       fCHInfo = ((AliTRDCTInfo *) fVectorCH->At(place));
711       projch  = ConvertVectorCTHisto(fCHInfo,(const char *) name);
712       projch->SetDirectory(0);
713       delete fCHInfo;
714     }
715
716     // Determination of fNnZ, fNnRphi, fNfragZ and fNfragRphi
717     UpdatefCountDetAndfCount(idect,0);
718     
719     // Reconstruction of the row and pad group: rowmin, row max ...
720     ReconstructFitRowMinRowMax(idect,0);
721     
722     // Number of entries
723     Double_t nentries = 0.0;
724     if (projch) {
725       for (Int_t k = 0; k < fNumberBinCharge; k++) {
726         nentries += projch->GetBinContent(k+1);
727       }
728     }
729     if (nentries > 0) {
730       fNumberEnt++;
731     }
732   
733     // Rebin and statistic stuff
734     // Rebin
735     if ((fRebin >  1) && 
736         (place != -1)) {
737       projch = ReBin((TH1F *) projch);
738     }
739
740     // This detector has not enough statistics or was not found in VectorCH
741     if ((place == -1) || 
742         ((place != -1) && 
743          (nentries < fMinEntries))) {
744       
745       // Fill with the default infos
746       NotEnoughStatistic(idect,0);
747
748       // Memory!!!
749       if (fDebug != 2) {
750         delete projch;
751       }     
752       
753       continue;
754
755     }
756
757     // Statistic of the histos fitted
758     AliInfo(Form("For the group number %d there are %f stats",idect,nentries));
759     fNumberFit++;
760     fStatisticMean += nentries;
761     
762     // Method Mean and fit
763     // idect is egal for fDebug = 0 and 2, only to fill the hist 
764     FitCH((TH1 *) projch,(Int_t) (idect-fDect1[0]));
765     
766     // Method fit bis
767     // idect is egal for fDebug = 0 and 2, only to fill the hist
768     if (fFitChargeBisOn) { 
769       FitBisCH((TH1 *) projch,(Int_t) (idect-fDect1[0]));
770     }
771     
772     // Visualise the detector for fDebug 3 or 4
773     // Here is the reconstruction of the pad and row group is used!
774     if (fDebug >= 3) {
775       FillCoefChargeDB();
776     }
777     
778     // Fill Infos Fit
779     FillInfosFit(idect,0); 
780     
781     // Memory!!!
782     if (fDebug != 2) {
783       delete projch;
784     }
785     
786   } // Boucle object
787
788   // Normierungcharge
789   if (fDebug != 2) {
790     NormierungCharge();
791   }
792
793   
794   // Plot
795   // 0 no plot, 1 and 4 error plot, 3 and 4 DB plot
796   if ((fDebug == 1) || 
797       (fDebug == 4)){
798     PlotWriteCH();
799   }
800   if((fDebug == 4) || 
801      (fDebug == 3)){
802     PlotCHDB();
803   }
804   
805   // Mean Statistics
806   if (fNumberFit > 0) {
807     AliInfo(Form("There is a mean statistic of: %d",(Int_t) fStatisticMean / fNumberFit));
808     fStatisticMean = fStatisticMean / fNumberFit;
809   }
810   else {
811     AliInfo("There is no fit!");
812   }
813   
814   // Write the things!
815   ConvertVectorFitCHTree();
816   if (fWriteCoef[0]) {
817     WriteFitInfos(0);      
818   }
819
820   return kTRUE;
821   
822 }
823
824 //____________Functions fit Online CH2d________________________________________
825 Bool_t AliTRDCalibra::FitCHOnline(TTree *tree)
826 {
827   //
828   // Look if the calibration group can be found in the tree, if yes take the
829   // histo, fit it, normalized the resulted coefficients (to 1 normally) and
830   // write the results in a tree
831   //
832    
833   // Number of Xbins (detectors or groups of pads)
834   if (!InitFit(0,0)) {
835     return kFALSE;
836   }
837   fStatisticMean = 0.0;
838   fNumberFit     = 0;
839   fNumberEnt     = 0;
840   
841   // For memory
842   if (fVectorCH) {
843     fVectorCH->Clear();
844   }
845   if (fPlaCH) {
846     fPlaCH->Clear();
847   }
848    
849   // Init fCountDet and fCount
850   InitfCountDetAndfCount(0);
851   TH1F      *projch      = 0x0;
852   tree->SetBranchAddress("histo",&projch);
853   TObjArray *vectorplace = ConvertTreeVector(tree);
854
855   // Beginning of the loop between dect1 and dect2
856   for (Int_t idect = fDect1[0]; idect < fDect2[0]; idect++) {
857     
858     //Search if the group is in the VectorCH
859     Int_t place = SearchInTreeVector(vectorplace,idect);
860     
861     // Is in
862     if (place != -1) {
863       // Variable
864       tree->GetEntry(place);
865     }
866     
867     // Determination of fNnZ, fNnRphi, fNfragZ and fNfragRphi
868     UpdatefCountDetAndfCount(idect,0);
869     
870     // Reconstruction of the row and pad group: rowmin, row max ...
871     ReconstructFitRowMinRowMax(idect,0);
872     
873     // Number of entries
874     Double_t nentries = 0.0;
875     if (projch) {
876       for (Int_t k = 0; k < projch->GetXaxis()->GetNbins(); k++) {
877         nentries += projch->GetBinContent(k+1);
878       }
879     } 
880     if (nentries > 0) {
881       fNumberEnt++;   
882     }
883
884     // Rebin and statistic stuff
885     // Rebin
886     if ((fRebin  >  1) && 
887         (place  != -1)) {
888       projch = ReBin((TH1F *) projch);
889     }
890
891     // This detector has not enough statistics or was not found in VectorCH
892     if((place == -1) || 
893        ((place    !=          -1) && 
894         (nentries  < fMinEntries))) {
895       
896       // Fill with the default infos
897       NotEnoughStatistic(idect,0);
898       
899       continue;
900
901     }
902     
903     // Statistics of the group fitted
904     AliInfo(Form("For the group number %d there are %f stats",idect,nentries));
905     fNumberFit++;
906     fStatisticMean += nentries;
907    
908     // Method Mean and fit
909     // idect is egal for fDebug = 0 and 2, only to fill the hist 
910     FitCH((TH1 *) projch,(Int_t) (idect-fDect1[0]));
911
912     // Method fit bis
913     // idect is egal for fDebug = 0 and 2, only to fill the hist
914     if (fFitChargeBisOn) { 
915       FitBisCH((TH1 *) projch,(Int_t) (idect-fDect1[0]));
916     }
917
918     // Visualise the detector for fDebug 3 or 4
919     // Here is the reconstruction of the pad and row group is used!
920     if (fDebug >= 3) {
921       FillCoefChargeDB();
922     }    
923
924     // Fill Infos Fit
925     FillInfosFit(idect,0); 
926     
927   } // Boucle object
928
929   // Normierungcharge
930   if (fDebug != 2) {
931     NormierungCharge();
932   }
933
934  
935   // Plot
936   // 0 no plot, 1 and 4 error plot, 3 and 4 DB plot
937   if ((fDebug == 1) || 
938       (fDebug == 4)){
939     PlotWriteCH();
940   }
941   if ((fDebug == 4) || 
942       (fDebug == 3)){
943     PlotCHDB();
944   }
945
946   // Mean Statistic
947   if (fNumberFit > 0) {
948     AliInfo(Form("There is a mean statistic of: %d",(Int_t) fStatisticMean / fNumberFit));
949     fStatisticMean = fStatisticMean / fNumberFit;
950   }
951   else {
952     AliInfo("There is no fit!");
953   }
954
955   // Write the things!
956   ConvertVectorFitCHTree();
957   if (fWriteCoef[0]) {
958     WriteFitInfos(0);      
959   }
960
961   return kTRUE;
962   
963 }
964
965 //________________functions fit Online PH2d____________________________________
966 Bool_t AliTRDCalibra::FitPHOnline(TProfile2D *ph)
967 {
968   //
969   // Take the 1D profiles (average pulse height), projections of the 2D PH
970   // on the Xaxis, for each calibration group
971   // Fit or use the slope of the average pulse height to reconstruct the
972   // drift velocity write the results in a tree
973   // A first calibration of T0 is also made  using the same method (slope method)
974   //
975  
976   // Number of Xbins (detectors or groups of pads)
977   TAxis   *xph     = ph->GetXaxis();
978   TAxis   *yph     = ph->GetYaxis();
979   Int_t    nbins   = xph->GetNbins();
980   Int_t    nybins  = yph->GetNbins();
981   if (!InitFit(nbins,1)) {
982     return kFALSE;
983   }
984   fStatisticMean = 0.0;
985   fNumberFit     = 0;
986   fNumberEnt     = 0;
987
988   // For memory
989   if (fVectorPH) {
990     fVectorPH->Clear();
991   }
992   if (fPlaPH) {
993     fPlaPH->Clear();
994   }
995
996   // Init fCountDet and fCount
997   InitfCountDetAndfCount(1);
998   
999   // Beginning of the loop
1000   for (Int_t idect = fDect1[1]; idect < fDect2[1]; idect++) {
1001       
1002     TH1D *projph = (TH1D *) ph->ProjectionY("projph",idect+1,idect+1,(Option_t *) "e");
1003     projph->SetDirectory(0); 
1004
1005     // Number of entries for this calibration group
1006     Double_t nentries = 0;
1007     for (Int_t k = 0; k < nybins; k++) {
1008       nentries += ph->GetBinEntries(ph->GetBin(idect+1,k+1));
1009     }
1010     if (nentries > 0) {
1011       fNumberEnt++;
1012     }  
1013
1014     // Determination of fNnZ, fNnRphi, fNfragZ and fNfragRphi
1015     UpdatefCountDetAndfCount(idect,1);
1016
1017     // Reconstruction of the row and pad group: rowmin, row max ...
1018     ReconstructFitRowMinRowMax(idect,1);
1019     
1020     // Rebin and statistic stuff
1021     // This detector has not enough statistics or was off
1022     if (nentries  < fMinEntries) {
1023       
1024       // Fill with the default values
1025       NotEnoughStatistic(idect,1);     
1026       
1027       // Memory!!!
1028       if (fDebug != 2) {
1029         delete projph;
1030       }
1031            
1032       continue;
1033
1034     }
1035     
1036     // Statistics of the histos fitted
1037     AliInfo(Form("For the group number %d there are %f stats",idect,nentries));
1038     fNumberFit++;
1039     fStatisticMean += nentries;
1040     
1041     // Calcul of "real" coef
1042     CalculVdriftCoefMean(fCountDet[1],(Int_t) (idect - fDect1[1]));
1043     CalculT0CoefMean(fCountDet[1],(Int_t) (idect - fDect1[1]));
1044     
1045     // Method Mean and fit
1046     // idect is egal for fDebug = 0 and 2, only to fill the hist 
1047     FitPente((TH1 *) projph,(Int_t) (idect - fDect1[1]));
1048
1049     // Method fit bis
1050     // idect is egal for fDebug = 0 and 2, only to fill the hist
1051     if (fFitPHOn) { 
1052       FitPH((TH1 *) projph,(Int_t) (idect - fDect1[1]));
1053     }
1054      
1055     // Visualise the detector for fDebug 3 or 4
1056     // Here is the reconstruction of the pad and row group is used!
1057     if (fDebug >= 3) {
1058       FillCoefVdriftDB();
1059       FillCoefT0DB();
1060     }
1061
1062     // Fill the tree if end of a detector or only the pointer to the branch!!!
1063     FillInfosFit(idect,1);
1064     
1065     // Memory!!!
1066     if (fDebug != 2) {
1067       delete projph;
1068     }
1069   
1070   } // Boucle object
1071
1072   
1073   // Plot
1074   // 0 no plot, 1 and 4 error plot, 3 and 4 DB plot
1075   if ((fDebug == 1) || 
1076       (fDebug == 4)) {
1077     PlotWritePH();
1078     PlotWriteT0();
1079   }
1080   if ((fDebug == 4) || 
1081       (fDebug == 3)) {
1082     PlotPHDB();
1083     PlotT0DB();
1084   }
1085
1086   // Mean Statistic
1087   if (fNumberFit > 0) {
1088     AliInfo(Form("There is a mean statistic of: %d",(Int_t) fStatisticMean / fNumberFit));
1089     fStatisticMean = fStatisticMean / fNumberFit;
1090   }
1091   else {
1092     AliInfo("There is no fit!");
1093   }
1094
1095   // Write the things!
1096   if(fWriteCoef[1]) {
1097     WriteFitInfos(1);
1098   }
1099
1100   return kTRUE;
1101   
1102 }
1103
1104 //____________Functions fit Online PH2d________________________________________
1105 Bool_t AliTRDCalibra::FitPHOnline()
1106 {
1107   //
1108   // Reconstruct the average pulse height from the vectorPH for each
1109   // calibration group
1110   // Fit or use the slope of the average pulse height to reconstruct the
1111   // drift velocity write the results in a tree
1112   // A first calibration of T0 is also made  using the same method (slope method)
1113   //
1114    
1115   // Number of Xbins (detectors or groups of pads)
1116   if (!InitFit(0,1)) {
1117     return kFALSE;
1118   }
1119   fStatisticMean = 0.0;
1120   fNumberFit     = 0;
1121   fNumberEnt     = 0;
1122
1123   // Init fCountDet and fCount
1124   InitfCountDetAndfCount(1);
1125
1126   // Beginning of the loop
1127   for (Int_t idect = fDect1[1]; idect < fDect2[1]; idect++) {
1128
1129     // Search if the group is in the VectorCH
1130     Int_t place = SearchInVector(idect,1);
1131     
1132     // Is in
1133     TH1F    *projph = 0x0;
1134     TString name("PH");
1135     name += idect;
1136     if (place != -1) {
1137       //Entries
1138       fNumberEnt++;
1139       // Variable
1140       AliTRDPInfo *fPHInfo = new AliTRDPInfo();
1141       // Retrieve
1142       fPHInfo = (AliTRDPInfo *) fVectorPH->At(place);
1143       projph  = CorrectTheError((TGraphErrors *) ConvertVectorPHisto(fPHInfo,(const char *) name));
1144       projph->SetDirectory(0);
1145       delete fPHInfo;
1146     }
1147
1148     // Determination of fNnZ, fNnRphi, fNfragZ and fNfragRphi
1149     UpdatefCountDetAndfCount(idect,1);
1150     
1151     // Reconstruction of the row and pad group: rowmin, row max ...
1152     ReconstructFitRowMinRowMax(idect,1);
1153
1154     // Rebin and statistic stuff
1155     // This detector has not enough statistics or was off
1156     if ((place == -1) || 
1157         ((place           !=          -1) && 
1158          (fEntriesCurrent <  fMinEntries))) {
1159       
1160       // Fill with the default values
1161       NotEnoughStatistic(idect,1);
1162
1163       // Memory!!!
1164       if (fDebug != 2) {
1165         delete projph;
1166       }
1167
1168       continue;
1169
1170     }
1171
1172     // Statistic of the histos fitted
1173     AliInfo(Form("For the group number %d there are %d stats",idect,fEntriesCurrent));
1174     fNumberFit++;
1175     fStatisticMean += fEntriesCurrent;
1176
1177     // Calcul of "real" coef
1178     CalculVdriftCoefMean(fCountDet[1],(Int_t) (idect - fDect1[1]));
1179     CalculT0CoefMean(fCountDet[1],(Int_t) (idect - fDect1[1]));
1180
1181     // Method Mean and fit
1182     // idect is egal for fDebug = 0 and 2, only to fill the hist 
1183     FitPente((TH1 *) projph,(Int_t) (idect - fDect1[1]));
1184
1185     // Method fit bis
1186     // idect is egal for fDebug = 0 and 2, only to fill the hist
1187     if (fFitPHOn) { 
1188       FitPH((TH1 *) projph,(Int_t) (idect - fDect1[1]));
1189     }
1190   
1191     // Visualise the detector for fDebug 3 or 4
1192     // Here is the reconstruction of the pad and row group is used!
1193     if (fDebug >= 3) {
1194       FillCoefVdriftDB();
1195       FillCoefT0DB();
1196     }
1197     
1198     // Fill the tree if end of a detector or only the pointer to the branch!!!
1199     FillInfosFit(idect,1);
1200     
1201     // Memory!!!
1202     if (fDebug != 2) {
1203       delete projph;
1204     }
1205     
1206   } // Boucle object
1207   
1208   
1209   // Plot
1210   // 0 no plot, 1 and 4 error plot, 3 and 4 DB plot
1211   if ((fDebug == 1) || 
1212       (fDebug == 4)) {
1213     PlotWritePH();
1214     PlotWriteT0();
1215   }
1216   if ((fDebug == 4) || 
1217       (fDebug == 3)) {
1218     PlotPHDB();
1219     PlotT0DB();
1220   }
1221   
1222   // Mean Statistic
1223   if (fNumberFit > 0) {
1224     AliInfo(Form("There is a mean statistic of: %d",(Int_t) fStatisticMean / fNumberFit));
1225     fStatisticMean = fStatisticMean / fNumberFit;
1226   }
1227   else {
1228     AliInfo("There is no fit!");
1229   }
1230   
1231   // Write the things!
1232   if (fWriteCoef[1]) {
1233     WriteFitInfos(1);
1234   }
1235
1236   return kTRUE;
1237   
1238 }
1239
1240 //____________Functions fit Online PH2d________________________________________
1241 Bool_t AliTRDCalibra::FitPHOnline(TTree *tree)
1242 {
1243   //
1244   // Look if the calibration group can be found in the tree, if yes take the
1245   // histo, fit it, and write the results in a tree
1246   // A first calibration of T0 is also made  using the same method (slope method)
1247   //
1248    
1249   // Number of Xbins (detectors or groups of pads)
1250   if (!InitFit(0,1)) {
1251     return kFALSE;
1252   }
1253   fStatisticMean = 0.0;
1254   fNumberFit     = 0;
1255   fNumberEnt     = 0;
1256
1257   // For memory
1258   if (fVectorPH) {
1259     fVectorPH->Clear();
1260   }
1261   if (fPlaPH) {
1262     fPlaPH->Clear();
1263   }
1264
1265   // Init fCountDet and fCount
1266   InitfCountDetAndfCount(1);
1267   TGraphErrors *projphtree  = 0x0;
1268   tree->SetBranchAddress("histo",&projphtree);
1269   TObjArray    *vectorplace = ConvertTreeVector(tree);
1270   
1271   // Beginning of the loop
1272   for (Int_t idect = fDect1[1]; idect < fDect2[1]; idect++) {
1273
1274     // Search if the group is in the VectorCH
1275     Int_t place = SearchInTreeVector(vectorplace,idect);
1276     
1277     TH1F *projph = 0x0;
1278     // Is in
1279     if (place != -1) {
1280       //Entries
1281       fNumberEnt++;
1282       // Variable
1283       tree->GetEntry(place);
1284       projph = CorrectTheError(projphtree);
1285     }
1286     
1287     // Determination of fNnZ, fNnRphi, fNfragZ and fNfragRphi
1288     UpdatefCountDetAndfCount(idect,1);
1289
1290     // Reconstruction of the row and pad group: rowmin, row max ...
1291     ReconstructFitRowMinRowMax(idect,1);
1292
1293     // Rebin and statistic stuff
1294     // This detector has not enough statistics or was off
1295     if((place == -1) || 
1296        ((place           !=         -1) && 
1297         (fEntriesCurrent < fMinEntries))) {
1298       
1299       // Fill with the default values
1300       NotEnoughStatistic(idect,1);
1301       
1302       // Memory!!!
1303       if (fDebug != 2) {
1304         delete projph;
1305       }
1306       
1307       continue;
1308
1309     }
1310     
1311     // Statistics of the histos fitted
1312     AliInfo(Form("For the group number %d there are %d stats",idect,fEntriesCurrent));
1313     fNumberFit++;
1314     fStatisticMean += fEntriesCurrent;
1315
1316     // Calcul of "real" coef
1317     CalculVdriftCoefMean(fCountDet[1],(Int_t) (idect - fDect1[1]));
1318     CalculT0CoefMean(fCountDet[1],(Int_t) (idect - fDect1[1]));
1319     
1320     // Method Mean and fit
1321     // idect is egal for fDebug = 0 and 2, only to fill the hist 
1322     FitPente((TH1 *) projph,(Int_t) (idect - fDect1[1]));
1323     // Method fit bis
1324     // idect is egal for fDebug = 0 and 2, only to fill the hist
1325     if (fFitPHOn) { 
1326       FitPH((TH1 *) projph,(Int_t) (idect - fDect1[1]));
1327     }
1328   
1329     // Visualise the detector for fDebug 3 or 4
1330     // Here is the reconstruction of the pad and row group is used!
1331     if (fDebug >= 3) {
1332       FillCoefVdriftDB();
1333       FillCoefT0DB();
1334     }
1335
1336     // Fill the tree if end of a detector or only the pointer to the branch!!!
1337     FillInfosFit(idect,1);
1338
1339     // Memory!!!
1340     if (fDebug != 2) {
1341       delete projph;
1342     }
1343        
1344   } // Boucle object
1345  
1346   // Plot
1347   // 0 no plot, 1 and 4 error plot, 3 and 4 DB plot
1348   if ((fDebug == 1) || 
1349       (fDebug == 4)){
1350     PlotWritePH();
1351     PlotWriteT0();
1352   }
1353   if ((fDebug == 4) || 
1354       (fDebug == 3)){
1355     PlotPHDB();
1356     PlotT0DB();
1357   }
1358
1359   // Mean Statistics
1360   if (fNumberFit > 0) {
1361     AliInfo(Form("There is a mean statistic of: %d",(Int_t) fStatisticMean / fNumberFit));
1362     fStatisticMean = fStatisticMean / fNumberFit;
1363   }
1364   else {
1365     AliInfo("There is no fit!");
1366   }
1367   
1368   // Write the things!
1369   if (fWriteCoef[1]) {
1370     WriteFitInfos(1);
1371   }
1372
1373   return kTRUE;
1374   
1375 }
1376
1377 //____________Functions fit Online PRF2d_______________________________________
1378 Bool_t AliTRDCalibra::FitPRFOnline(TProfile2D *prf)
1379 {
1380   //
1381   // Take the 1D profiles (pad response function), projections of the 2D PRF
1382   // on the Xaxis, for each calibration group
1383   // Fit with a gaussian to reconstruct the sigma of the pad response function
1384   // write the results in a tree
1385   //
1386
1387   // Number of Xbins (detectors or groups of pads)
1388   TAxis   *xprf    = prf->GetXaxis();
1389   TAxis   *yprf    = prf->GetYaxis();
1390   Int_t    nybins  = yprf->GetNbins();
1391   Int_t    nbins   = xprf->GetNbins();
1392   if (!InitFit(nbins,2)) {
1393     return kFALSE;
1394   }
1395   fStatisticMean = 0.0;
1396   fNumberFit     = 0;
1397   fNumberEnt     = 0;
1398
1399   // For memory
1400   if (fVectorPRF) {
1401     fVectorPRF->Clear();
1402   }
1403   if (fPlaPRF) {
1404     fPlaPRF->Clear();
1405   }
1406   
1407   // Init fCountDet and fCount
1408   InitfCountDetAndfCount(2);
1409   
1410   // Beginning of the loop
1411   for (Int_t idect = fDect1[2]; idect < fDect2[2]; idect++) {
1412
1413     TH1D *projprf = (TH1D *) prf->ProjectionY("projprf",idect+1,idect+1,(Option_t *) "e");
1414     projprf->SetDirectory(0);
1415     
1416     // Number of entries for this calibration group
1417     Double_t nentries = 0;
1418     for (Int_t k = 0; k < nybins; k++) {
1419       nentries += prf->GetBinEntries(prf->GetBin(idect+1,k+1));
1420     }
1421     if(nentries > 0) fNumberEnt++;
1422     
1423     // Determination of fNnZ, fNnRphi, fNfragZ and fNfragRphi
1424     UpdatefCountDetAndfCount(idect,2);
1425     
1426     // Reconstruction of the row and pad group: rowmin, row max ...
1427     ReconstructFitRowMinRowMax(idect,2);
1428     
1429     // Rebin and statistic stuff
1430     // This detector has not enough statistics or was off
1431     if (nentries < fMinEntries) {
1432       
1433       // Fill with the default values
1434       NotEnoughStatistic(idect,2);
1435       
1436       // Memory!
1437       if (fDebug != 2) {
1438         delete projprf;
1439       }
1440       
1441       continue;
1442
1443     }
1444     
1445     // Statistics of the histos fitted
1446     AliInfo(Form("For the group number %d there are %f stats",idect,nentries));
1447     fNumberFit++;
1448     fStatisticMean += nentries;
1449     
1450     // Calcul of "real" coef
1451     if ((fDebug == 1) || 
1452         (fDebug == 4)) {
1453       CalculPRFCoefMean(fCountDet[2],(Int_t) (idect - fDect1[2]));
1454     }
1455     
1456     // Method Mean and fit
1457     // idect is egal for fDebug = 0 and 2, only to fill the hist 
1458     FitPRF((TH1 *) projprf,(Int_t) (idect - fDect1[2]));
1459     
1460     // Visualise the detector for fDebug 3 or 4
1461     // Here is the reconstruction of the pad and row group is used!
1462     if (fDebug >= 3) {
1463       FillCoefPRFDB();
1464     }
1465
1466     // Fill the tree if end of a detector or only the pointer to the branch!!!
1467     FillInfosFit(idect,2);
1468     
1469     // Memory!!!
1470     if (fDebug != 2) {
1471       delete projprf;
1472     }
1473     
1474   } // Boucle object
1475  
1476   // Plot
1477   // No plot, 1 and 4 error plot, 3 and 4 DB plot
1478   if ((fDebug == 1) || 
1479       (fDebug == 4)) {
1480     PlotWritePRF();
1481   }
1482   if ((fDebug == 4) || 
1483       (fDebug == 3)){
1484     PlotPRFDB();
1485   }
1486
1487   // Mean Statistic
1488   if (fNumberFit > 0) {
1489     AliInfo(Form("There is a mean statistic of: %d",(Int_t) fStatisticMean / fNumberFit));
1490     fStatisticMean = fStatisticMean / fNumberFit;
1491   }
1492   else {
1493     AliInfo("There is no fit!");
1494   }
1495
1496   // Write the things!
1497   if (fWriteCoef[2]) {
1498     WriteFitInfos(2);
1499   }
1500
1501   return kTRUE;
1502   
1503 }
1504
1505 //____________Functions fit Online PRF2d_______________________________________
1506 Bool_t AliTRDCalibra::FitPRFOnline(TTree *tree)
1507 {
1508   //
1509   // Look if the calibration group can be found in the tree, if yes take
1510   // the histo, fit it, and write the results in a tree
1511   //
1512   
1513   // Number of Xbins (detectors or groups of pads)
1514   if (!InitFit(0,2)) {
1515     return kFALSE;
1516   }
1517   fStatisticMean = 0.0;
1518   fNumberFit     = 0;
1519   fNumberEnt     = 0;
1520
1521   // For memory
1522   if (fVectorPRF) {
1523     fVectorPRF->Clear();
1524   }
1525   if (fPlaPRF) {
1526     fPlaPRF->Clear();
1527   }
1528
1529   // Init fCountDet and fCount
1530   InitfCountDetAndfCount(2);
1531   TGraphErrors *projprftree = 0x0;
1532   tree->SetBranchAddress("histo",&projprftree);
1533   TObjArray    *vectorplace = ConvertTreeVector(tree);
1534
1535   // Beginning of the loop
1536   for (Int_t idect = fDect1[2]; idect < fDect2[2]; idect++) {
1537
1538     // Search if the group is in the VectorCH
1539     Int_t place = SearchInTreeVector(vectorplace,idect);
1540     
1541     // Is in   
1542     TH1F *projprf = 0x0;
1543     if (place != -1) {
1544       //Entries
1545       fNumberEnt++;
1546       // Variable
1547       tree->GetEntry(place);
1548       projprf = CorrectTheError(projprftree);
1549     }
1550
1551     // Determination of fNnZ, fNnRphi, fNfragZ and fNfragRphi
1552     UpdatefCountDetAndfCount(idect,2);
1553
1554     // Reconstruction of the row and pad group: rowmin, row max ...
1555     ReconstructFitRowMinRowMax(idect,2);
1556
1557     // Rebin and statistic stuff
1558     // This detector has not enough statistics or was off
1559     if ((place == -1) ||
1560         ((place           !=          -1) &&
1561          (fEntriesCurrent  < fMinEntries))) {
1562       
1563       // Fill with the default values
1564       NotEnoughStatistic(idect,2);
1565       
1566       // Memory!!!
1567       if (fDebug != 2) {
1568         delete projprf;
1569       }
1570       
1571       continue;
1572
1573     }
1574
1575     // Statistics of the histos fitted
1576     AliInfo(Form("For the group number %d there are %d stats",idect,fEntriesCurrent));
1577     fNumberFit++;
1578     fStatisticMean += fEntriesCurrent;
1579         
1580     // Calcul of "real" coef
1581     if ((fDebug == 1) || 
1582         (fDebug == 4)){
1583       CalculPRFCoefMean(fCountDet[2],(Int_t) (idect - fDect1[2]));
1584     }
1585     
1586     // Method Mean and fit
1587     // idect is egal for fDebug = 0 and 2, only to fill the hist 
1588     FitPRF((TH1 *) projprf,(Int_t) (idect - fDect1[2]));
1589     // Visualise the detector for fDebug 3 or 4
1590     // Here is the reconstruction of the pad and row group is used!
1591     if (fDebug >= 3) {
1592       FillCoefPRFDB();
1593     }
1594     // Fill the tree if end of a detector or only the pointer to the branch!!!
1595     FillInfosFit(idect,2);
1596
1597     // Memory!!!
1598     if (fDebug != 2) {
1599       delete projprf;
1600     }                
1601     
1602   } // Boucle object
1603   
1604   // Plot
1605   // No plot, 1 and 4 error plot, 3 and 4 DB plot
1606   if ((fDebug == 1) || 
1607       (fDebug == 4)){
1608     PlotWritePRF();
1609   }
1610   if ((fDebug == 4) || 
1611       (fDebug == 3)){
1612     PlotPRFDB();
1613   }
1614   
1615   // Mean Statistics
1616   if (fNumberFit > 0) {
1617     AliInfo(Form("There is a mean statistic of: %d",(Int_t) fStatisticMean / fNumberFit));
1618     fStatisticMean = fStatisticMean / fNumberFit;
1619   }
1620   else {
1621     AliInfo("There is no fit!");
1622   }
1623
1624   // Write the things!
1625   if (fWriteCoef[2]) {
1626     WriteFitInfos(2);
1627   }
1628
1629   return kTRUE;
1630   
1631 }
1632
1633 //____________Functions fit Online PRF2d_______________________________________
1634 Bool_t AliTRDCalibra::FitPRFOnline()
1635 {
1636   //
1637   // Reconstruct the 1D histo (pad response function) from the vectorPRD for
1638   // each calibration group
1639   // Fit with a gaussian to reconstruct the sigma of the pad response function
1640   // write the results in a tree
1641   //
1642   
1643   // Number of Xbins (detectors or groups of pads)
1644   if (!InitFit(0,2)) {
1645     return kFALSE;
1646   }
1647   fStatisticMean = 0.0;
1648   fNumberFit     = 0;
1649   fNumberEnt     = 0;
1650
1651   // Init fCountDet and fCount
1652   InitfCountDetAndfCount(2);
1653
1654   // Beginning of the loop
1655   for (Int_t idect = fDect1[2]; idect < fDect2[2]; idect++) {
1656
1657     // Search if the group is in the VectorCH
1658     Int_t place = SearchInVector(idect,2);
1659     
1660     // Is in
1661     TH1F   *projprf = 0x0;
1662     TString name("PRF");
1663     name += idect;
1664     if (place != -1) {
1665       //Entries
1666       fNumberEnt++;
1667       // Variable
1668       AliTRDPInfo *fPRFInfo = new AliTRDPInfo();
1669       // Retrieve
1670       fPRFInfo = (AliTRDPInfo *) fVectorPRF->At(place);
1671       projprf = CorrectTheError((TGraphErrors *) ConvertVectorPHisto(fPRFInfo,(const char *)name));
1672       projprf->SetDirectory(0);
1673       delete fPRFInfo;
1674     }
1675
1676     // Determination of fNnZ, fNnRphi, fNfragZ and fNfragRphi
1677     UpdatefCountDetAndfCount(idect,2);
1678
1679     // Reconstruction of the row and pad group: rowmin, row max ...
1680     ReconstructFitRowMinRowMax(idect,2);
1681
1682     // Rebin and statistic stuff
1683     // This detector has not enough statistics or was off
1684     if ((place == -1) ||
1685         ((place           != -1) &&
1686          (fEntriesCurrent < fMinEntries))) {
1687
1688       // Fill with the default values
1689       NotEnoughStatistic(idect,2);
1690
1691       // Memory
1692       if (fDebug != 2) {
1693         delete projprf;
1694       }
1695
1696       continue;
1697
1698     }
1699
1700     // Statistic of the histos fitted
1701     AliInfo(Form("For the group number %d there are %d stats", idect,fEntriesCurrent));
1702     fNumberFit++;
1703     fStatisticMean += fEntriesCurrent;
1704
1705     // Calcul of "real" coef
1706     if ((fDebug == 1) || 
1707         (fDebug == 4)) {
1708       CalculPRFCoefMean(fCountDet[2],(Int_t) (idect-fDect1[2]));
1709     }
1710
1711     // Method Mean and fit
1712     // idect is egal for fDebug = 0 and 2, only to fill the hist 
1713     FitPRF((TH1 *) projprf,(Int_t) (idect-fDect1[2]));
1714     // Visualise the detector for fDebug 3 or 4
1715     // Here is the reconstruction of the pad and row group is used!
1716     if (fDebug >= 3) {
1717       FillCoefPRFDB();
1718     }
1719     // Fill the tree if end of a detector or only the pointer to the branch!!!
1720     FillInfosFit(idect,2);
1721                     
1722     // Memory!!!
1723     if (fDebug != 2) {
1724       delete projprf;
1725     }
1726     
1727   } // Boucle object
1728
1729   // Plot
1730   // No plot, 1 and 4 error plot, 3 and 4 DB plot
1731   if ((fDebug == 1) || 
1732       (fDebug == 4)) {
1733     PlotWritePRF();
1734   }
1735   if ((fDebug == 4) || 
1736       (fDebug == 3)) {
1737     PlotPRFDB();
1738   }
1739
1740   // Mean Statistics
1741   if (fNumberFit > 0) {
1742     AliInfo(Form("There is a mean statistic of: %d",(Int_t) fStatisticMean / fNumberFit));
1743   }
1744   else {
1745     AliInfo("There is no fit!");
1746   }
1747
1748   // Write the things!
1749   if (fWriteCoef[2]) {
1750     WriteFitInfos(2);
1751   }
1752
1753   return kTRUE;
1754   
1755 }
1756
1757 //____________Functions for initialising the AliTRDCalibra in the code_________
1758 Bool_t AliTRDCalibra::Init2Dhistos()
1759 {
1760   //
1761   // For the offline tracking
1762   // This function will be called in the function AliReconstruction::Run() 
1763   // Init the calibration mode (Nz, Nrphi), the 2D histograms if fHisto2d = kTRUE, 
1764   //
1765
1766   // DB Setting
1767   // Get cal
1768   AliTRDcalibDB *cal = AliTRDcalibDB::Instance();
1769   if (!cal) {
1770     AliInfo("Could not get calibDB");
1771     return kFALSE;
1772   }
1773   AliTRDCommonParam *parCom = AliTRDCommonParam::Instance();
1774   if (!parCom) {
1775     AliInfo("Could not get CommonParam");
1776     return kFALSE;
1777   }
1778
1779   // Some parameters
1780   fTimeMax = cal->GetNumberOfTimeBins();
1781   fSf      = parCom->GetSamplingFrequency();
1782   if (fRelativeScaleAuto) {
1783     fRelativeScale = 0;
1784   }
1785   else {
1786     fRelativeScale = 20;
1787   }
1788
1789   // Create the 2D histos corresponding to the pad groupCalibration mode
1790   if (fCH2dOn) {
1791
1792     AliInfo(Form("The pad calibration mode for the relative gain calibration: Nz %d, and Nrphi %d"
1793                 ,fNz[0]
1794                 ,fNrphi[0]));
1795     
1796     // Calcul the number of Xbins
1797     fNtotal[0] = 0;
1798     ModePadCalibration(2,0);
1799     ModePadFragmentation(0,2,0,0);
1800     fDetChamb2[0] = fNfragZ[0] * fNfragRphi[0];
1801     if (fDebug == 4) {
1802       AliInfo(Form("For the chamber 2: %d",fDetChamb2[0]));
1803     }
1804     fNtotal[0] += 6 * 18 * fDetChamb2[0];
1805     ModePadCalibration(0,0);
1806     ModePadFragmentation(0,0,0,0);
1807     fDetChamb0[0] = fNfragZ[0] * fNfragRphi[0];
1808     if (fDebug == 4) {
1809       AliInfo(Form("For the other chamber 0: %d",fDetChamb0[0]));
1810     }
1811     fNtotal[0] += 6 * 4 * 18 * fDetChamb0[0];
1812     AliInfo(Form("Total number of Xbins: %d",fNtotal[0]));
1813
1814     // Create the 2D histo
1815     if (fHisto2d) {
1816       CreateCH2d(fNtotal[0]);
1817     }
1818     if (fVector2d) {
1819       fVectorCH = new TObjArray();
1820       fPlaCH    = new TObjArray();
1821     }
1822
1823     // Variable
1824     fAmpTotal = new Float_t[TMath::Max(fDetChamb2[0],fDetChamb0[0])];
1825     for (Int_t k = 0; k < TMath::Max(fDetChamb2[0],fDetChamb0[0]); k++) {
1826       fAmpTotal[k] = 0.0;
1827     } 
1828
1829   }
1830
1831   if (fPH2dOn) {
1832
1833     AliInfo(Form("The pad calibration mode for the drift velocity calibration: Nz %d, and Nrphi %d"
1834                 ,fNz[1]
1835                 ,fNrphi[1]));
1836     
1837     // Calcul the number of Xbins
1838     fNtotal[1] = 0;
1839     ModePadCalibration(2,1);
1840     ModePadFragmentation(0,2,0,1);
1841     fDetChamb2[1] = fNfragZ[1]*fNfragRphi[1];
1842     if (fDebug == 4) {
1843       AliInfo(Form("For the chamber 2: %d",fDetChamb2[1]));
1844     }
1845     fNtotal[1] += 6 * 18 * fDetChamb2[1];
1846     ModePadCalibration(0,1);
1847     ModePadFragmentation(0,0,0,1);
1848     fDetChamb0[1] = fNfragZ[1] * fNfragRphi[1];
1849     if (fDebug == 4) {
1850       AliInfo(Form("For the chamber 0: %d",fDetChamb0[1]));
1851     }
1852     fNtotal[1] += 6 * 4 * 18 * fDetChamb0[1];
1853     AliInfo(Form("Total number of Xbins: %d",fNtotal[1]));
1854
1855     // Create the 2D histo
1856     if (fHisto2d) {
1857       CreatePH2d(fNtotal[1]);
1858     }
1859     if (fVector2d) {
1860       fVectorPH = new TObjArray();
1861       fPlaPH    = new TObjArray();
1862     }
1863    
1864     // Variable
1865     fPHPlace = new Short_t[fTimeMax];
1866     for (Int_t k = 0; k < fTimeMax; k++) {
1867       fPHPlace[k] = -1;
1868     } 
1869     fPHValue = new Float_t[fTimeMax];
1870     for (Int_t k = 0; k < fTimeMax; k++) {
1871       fPHValue[k] = -1.0;
1872     }
1873
1874   }
1875
1876   if (fPRF2dOn) {
1877
1878     AliInfo(Form("The pad calibration mode for the PRF calibration: Nz %d, and Nrphi %d"
1879                 ,fNz[2]
1880                 ,fNrphi[2]));
1881     
1882     // Calcul the number of Xbins
1883     fNtotal[2] = 0;
1884     ModePadCalibration(2,2);
1885     ModePadFragmentation(0,2,0,2);
1886     fDetChamb2[2] = fNfragZ[2] * fNfragRphi[2];
1887     if (fDebug == 4) {
1888       AliInfo(Form("For the chamber 2: %d",fDetChamb2[2]));
1889     }
1890     fNtotal[2] += 6 * 18 * fDetChamb2[2];
1891     ModePadCalibration(0,2);
1892     ModePadFragmentation(0,0,0,2);
1893     fDetChamb0[2] = fNfragZ[2] * fNfragRphi[2];
1894     if (fDebug == 4) {
1895       AliInfo(Form("For the chamber 0: %d",fDetChamb0[2]));
1896     }
1897     fNtotal[2] += 6 * 4 * 18 * fDetChamb0[2];
1898     AliInfo(Form("Total number of Xbins: %d",fNtotal[2]));
1899
1900     // Create the 2D histo
1901     if (fHisto2d) {
1902       CreatePRF2d(fNtotal[2]);
1903     }
1904     if (fVector2d) {
1905       fVectorPRF = new TObjArray();
1906       fPlaPRF    = new TObjArray();
1907     }
1908   
1909   }
1910
1911   return kTRUE;
1912
1913 }
1914
1915 //____________Functions for filling the histos in the code_____________________
1916
1917 //____________Offine tracking in the AliTRDtracker_____________________________
1918 Bool_t AliTRDCalibra::ResetTrack()
1919 {
1920   //
1921   // For the offline tracking
1922   // This function will be called in the function
1923   // AliTRDtracker::FollowBackPropagation() at the beginning 
1924   // Reset the parameter to know we have a new TRD track
1925   //
1926   
1927   fDetectorAliTRDtrack = kFALSE;
1928   return kTRUE;
1929
1930 }
1931
1932 //____________Offline tracking in the AliTRDtracker____________________________
1933 Bool_t AliTRDCalibra::UpdateHistograms(AliTRDcluster *cl, AliTRDtrack *t)
1934 {
1935   //
1936   // For the offline tracking
1937   // This function will be called in the function
1938   // AliTRDtracker::FollowBackPropagation() in the loop over the clusters
1939   // of TRD tracks 
1940   // Fill the 2D histos or the vectors with the info of the clusters at
1941   // the end of a detectors if the track is "good"
1942   //
1943
1944   // Get the parameter object
1945   AliTRDCommonParam *parCom = AliTRDCommonParam::Instance();
1946   if (!parCom) {
1947     AliInfo("Could not get CommonParam");
1948     return kFALSE;
1949   }
1950
1951   // Get the parameter object
1952   AliTRDcalibDB     *cal    = AliTRDcalibDB::Instance();
1953   if (!cal) {
1954     AliInfo("Could not get calibDB");
1955     return kFALSE;
1956   }
1957  
1958   // Localisation of the detector
1959   Int_t detector = cl->GetDetector();
1960   Int_t chamber  = GetChamber(detector);
1961   Int_t plane    = GetPlane(detector);
1962
1963   // Fill the infos for the previous clusters if not the same
1964   // detector anymore or if not the same track
1965   if (((detector != fDetectorPreviousTrack) || (!fDetectorAliTRDtrack)) && 
1966       (fDetectorPreviousTrack != -1)) {
1967
1968     fNumberTrack++;   
1969     
1970     // If the same track, then look if the previous detector is in
1971     // the same plane, if yes: not a good track
1972     if (fDetectorAliTRDtrack && 
1973         (GetPlane(detector) <= GetPlane(fDetectorPreviousTrack))) {
1974       fGoodTrack = kFALSE;
1975     }
1976
1977     // Fill only if the track doesn't touch a masked pad or doesn't
1978     // appear in the middle (fGoodTrack)
1979     if (fGoodTrack) {
1980
1981       // Gain calibration
1982       if (fCH2dOn) {
1983         FillTheInfoOfTheTrackCH();
1984       }
1985
1986       // PH calibration
1987       if (fPH2dOn) {
1988         FillTheInfoOfTheTrackPH();    
1989       }
1990     
1991     } // if a good track
1992     
1993     ResetfVariables();
1994    
1995   } // Fill at the end the charge
1996   
1997   // Calcul the position of the detector
1998   if (detector != fDetectorPreviousTrack) {
1999     LocalisationDetectorXbins(detector);
2000   }
2001
2002   // Reset the good track for the PRF
2003   Bool_t good = kTRUE;
2004   
2005   // Localisation of the cluster
2006   Double_t pos[3] = { 0.0, 0.0, 0.0 };
2007   pos[0] = cl->GetX();
2008   pos[1] = cl->GetY();
2009   pos[2] = cl->GetZ();
2010   Int_t    time   = cl->GetLocalTimeBin();
2011   
2012   // Reset the detector
2013   fDetectorPreviousTrack = detector;
2014   fDetectorAliTRDtrack   = kTRUE;
2015   
2016   // Position of the cluster
2017   AliTRDpadPlane *padplane = parCom->GetPadPlane(plane,chamber);
2018   Int_t    row        = padplane->GetPadRowNumber(pos[2]);
2019   Double_t offsetz    = padplane->GetPadRowOffset(row,pos[2]);
2020   Double_t offsettilt = padplane->GetTiltOffset(offsetz);
2021   Int_t    col        = padplane->GetPadColNumber(pos[1] + offsettilt,offsetz);
2022   
2023   // See if we are not near a masked pad
2024   if (!IsPadOn(detector,col,row)) {
2025     good       = kFALSE;
2026     fGoodTrack = kFALSE;
2027   }
2028
2029   if (col > 0) {
2030     if (!IsPadOn(detector,col-1,row)) {
2031       fGoodTrack = kFALSE;
2032       good       = kFALSE;
2033     }
2034   }
2035
2036   if (col < 143) {
2037     if (!IsPadOn(detector,col+1,row)) {
2038       fGoodTrack = kFALSE;
2039       good       = kFALSE;
2040     }
2041   }
2042
2043   // Row of the cluster and position in the pad groups
2044   Int_t posr[3] = { 0, 0, 0 };
2045   if ((fCH2dOn)  && (fNnZ[0] != 0)) {
2046     posr[0] = (Int_t) row / fNnZ[0];
2047   }
2048   if ((fPH2dOn)  && (fNnZ[1] != 0)) {
2049     posr[1] = (Int_t) row / fNnZ[1];
2050   }
2051   if ((fPRF2dOn) && (fNnZ[2] != 0)) {
2052     posr[2] = (Int_t) row / fNnZ[2];
2053   }  
2054       
2055   // Col of the cluster and position in the pad groups
2056   Int_t posc[3] = { 0, 0, 0 };
2057   if ((fCH2dOn)  && (fNnRphi[0] != 0)) {
2058     posc[0] = (Int_t) col / fNnRphi[0];
2059   }
2060   if ((fPH2dOn)  && (fNnRphi[1] != 0)) {
2061     posc[1] = (Int_t) col / fNnRphi[1];
2062   }
2063   if ((fPRF2dOn) && (fNnRphi[2] != 0)) {
2064     posc[2] = (Int_t) col / fNnRphi[2];
2065   }
2066
2067   // Charge in the cluster
2068   // For the moment take the abs
2069   Float_t  q       = TMath::Abs(cl->GetQ());
2070   Short_t *signals = cl->GetSignals();
2071
2072   // Correction due to the track angle
2073   Float_t correction    = 1.0;
2074   Float_t normalisation = 6.67;
2075   if ((q >0) && (t->GetNdedx() > 0)) {
2076     correction = t->GetClusterdQdl((t->GetNdedx() - 1)) / (q * normalisation);
2077   }
2078
2079   // Fill the fAmpTotal with the charge
2080   if (fCH2dOn) {
2081     if (!fTraMaxPad){ 
2082       fAmpTotal[(Int_t) (posc[0]*fNfragZ[0]+posr[0])] += q * correction;
2083     }
2084     else {
2085       fAmpTotal[(Int_t) (posc[0]*fNfragZ[0]+posr[0])] += ((Float_t) signals[3]) * correction;
2086     }
2087   }
2088
2089   // Fill the fPHPlace and value
2090   if (fPH2dOn) {
2091     fPHPlace[time] = posc[1]*fNfragZ[1]+posr[1];
2092     if (!fTraMaxPad) {
2093       fPHValue[time] = q * correction;
2094     }
2095     else {
2096       fPHValue[time] = ((Float_t) signals[3]) * correction;
2097     }
2098   }
2099
2100   // Fill direct the PRF
2101   if ((fPRF2dOn) && (good)) {
2102
2103     Float_t yminus  = 0.0;
2104     Float_t xcenter = 0.0;
2105     Float_t ycenter = 0.0;
2106     Float_t ymax    = 0.0;
2107     Bool_t  echec   = kFALSE;
2108     
2109     if ((cl->From3pad()) && (!cl->IsUsed())) { 
2110          
2111       // Center 3 balanced
2112       if ((((Float_t) signals[3]) > fThresholdClusterPRF2) && 
2113           (((Float_t) signals[2]) > fThresholdClusterPRF2) && 
2114           (((Float_t) signals[4]) > fThresholdClusterPRF2) && 
2115           (((Float_t) signals[1]) < fThresholdClusterPRF1) && 
2116           (((Float_t) signals[5]) < fThresholdClusterPRF1) && 
2117           ((((Float_t) signals[2])*((Float_t) signals[4])/(((Float_t) signals[3])*((Float_t) signals[3]))) < 0.06)) {
2118         // Col correspond to signals[3]
2119         if (fCenterOfflineCluster) {
2120           xcenter = cl->GetCenter();
2121         }
2122         else {
2123           // Security of the denomiateur is 0
2124           if ((((Float_t) (((Float_t) signals[3]) * ((Float_t) signals[3]))) / 
2125                            ((Float_t) (((Float_t) signals[2]) * ((Float_t) signals[4])))) != 1.0) {
2126             xcenter = 0.5 * (TMath::Log((Float_t) (((Float_t) signals[4]) / ((Float_t) signals[2]))))
2127                           / (TMath::Log(((Float_t) (((Float_t) signals[3]) * ((Float_t) signals[3]))) 
2128                                       / ((Float_t) (((Float_t) signals[2]) * ((Float_t) signals[4])))));
2129           }
2130           else {
2131             xcenter = -100.0;
2132           }
2133         }
2134         if ((xcenter > -0.5) && (xcenter < 0.5)) {
2135           ycenter = (Float_t) (((Float_t) signals[3]) 
2136                             / (((Float_t) signals[2]) + ((Float_t) signals[3]) + (((Float_t) signals[4]))));
2137           yminus  = (Float_t) (((Float_t) signals[2]) 
2138                             / (((Float_t) signals[2]) + ((Float_t) signals[3]) + (((Float_t) signals[4]))));
2139           ymax    = (Float_t) (((Float_t) signals[4]) 
2140                             / (((Float_t) signals[2]) + ((Float_t) signals[3]) + (((Float_t) signals[4]))));
2141           if ((TMath::Abs(((Float_t) signals[2]) + ((Float_t) signals[3]) + (((Float_t) signals[4])) - q) < 10.0)) {
2142             echec = kTRUE;
2143           }
2144         }
2145       }
2146       
2147       // Fill only if it is in the drift region!
2148       if ((((Float_t) (((Float_t) time) / fSf)) > 0.3) && (echec)) {
2149         if (fHisto2d) {
2150           fPRF2d->Fill((fXbins[2]+posc[2]*fNfragZ[2]+posr[2]+0.5),xcenter,ycenter);
2151           if (xcenter < 0.0) {
2152             fPRF2d->Fill((fXbins[2]+posc[2]*fNfragZ[2]+posr[2]+0.5),-(xcenter+1.0),yminus);
2153           }
2154           if (xcenter > 0.0) {
2155             fPRF2d->Fill((fXbins[2]+posc[2]*fNfragZ[2]+posr[2]+0.5),1.0-xcenter,ymax);
2156           }
2157         }
2158         if (fVector2d) {
2159           UpdateVectorPRF(fXbins[2]+posc[2]*fNfragZ[2]+posr[2],xcenter,ycenter);
2160           if (xcenter < 0.0) {
2161             UpdateVectorPRF(fXbins[2]+posc[2]*fNfragZ[2]+posr[2],-(xcenter+1.0),yminus);
2162           }
2163           if (xcenter > 0.0) {
2164             UpdateVectorPRF(fXbins[2]+posc[2]*fNfragZ[2]+posr[2],1.0-xcenter,ymax);
2165           }
2166         }
2167       } // If in the drift region
2168
2169     } // Cluster isole
2170
2171   } // PRF2dOn  
2172   
2173   return kTRUE;
2174   
2175 }
2176
2177 //____________Online trackling in AliTRDtrigger________________________________
2178 Bool_t AliTRDCalibra::UpdateHistogramcm(AliTRDmcmTracklet *trk)
2179 {
2180   //
2181   // For the tracking
2182   // This function will be called in the function AliTRDtrigger::TestTracklet
2183   // before applying the pt cut on the tracklets 
2184   // Fill the infos for the tracklets fTrkTest if the tracklets is "good"
2185   //
2186   
2187   // Localisation of the Xbins involved
2188   Int_t idect = trk->GetDetector();
2189   LocalisationDetectorXbins(idect);
2190
2191   // Get the parameter object
2192   AliTRDcalibDB *cal = AliTRDcalibDB::Instance();
2193   if (!cal) {
2194     AliInfo("Could not get calibDB");
2195     return kFALSE;
2196   }
2197    
2198   // Reset
2199   ResetfVariables();
2200
2201   // Row of the tracklet and position in the pad groups
2202   Int_t row     = trk->GetRow();
2203   Int_t posr[3] = { 0, 0, 0 };
2204   if ((fCH2dOn)  && (fNnZ[0] != 0)) {
2205     posr[0] = (Int_t) row / fNnZ[0];
2206   }
2207   if ((fPH2dOn)  && (fNnZ[1] != 0)) {
2208     posr[1] = (Int_t) row / fNnZ[1];
2209   }
2210   if ((fPRF2dOn) && (fNnZ[2] != 0)) {
2211     posr[2] = (Int_t) row / fNnZ[2];
2212   }
2213  
2214   // Eventuelle correction due to track angle in z direction
2215   Float_t correction = 1.0;
2216   if (fMcmCorrectAngle) {
2217     Float_t z = trk->GetRowz();
2218     Float_t r = trk->GetTime0();
2219     correction = r / TMath::Sqrt((r*r+z*z));
2220   }
2221
2222   // Boucle sur les clusters
2223   // Condition on number of cluster: don't come from the middle of the detector
2224   if (trk->GetNclusters() >= fNumberClusters) {
2225
2226     for (Int_t icl = 0; icl < trk->GetNclusters(); icl++) {
2227
2228       Float_t amp[3] = { 0.0, 0.0, 0.0 };
2229       Int_t   time   = trk->GetClusterTime(icl);
2230       Int_t   col    = trk->GetClusterCol(icl);
2231             
2232       amp[0] = trk->GetClusterADC(icl)[0] * correction;
2233       amp[1] = trk->GetClusterADC(icl)[1] * correction;
2234       amp[2] = trk->GetClusterADC(icl)[2] * correction;
2235            
2236       if ((amp[0] < 0.0) || 
2237           (amp[1] < 0.0) || 
2238           (amp[2] < 0.0)) {
2239         continue;
2240       }
2241
2242       // Col of cluster and position in the pad groups
2243       Int_t posc[3] = { 0, 0, 0 };
2244       if ((fCH2dOn)  && (fNnRphi[0] != 0)) {
2245         posc[0] = (Int_t) col / fNnRphi[0];
2246       }
2247       if ((fPH2dOn)  && (fNnRphi[1] != 0)) {
2248         posc[1] = (Int_t) col / fNnRphi[1];
2249       }
2250       if ((fPRF2dOn) && (fNnRphi[2] != 0)) {
2251         posc[2] = (Int_t) col / fNnRphi[2];
2252       }
2253
2254       // See if we are not near a masked pad
2255       Bool_t good = kTRUE;
2256       if (!IsPadOn(idect,col,row)) {
2257         fGoodTrack = kFALSE;
2258         good       = kFALSE;
2259       }
2260
2261       if (col >   0) {
2262         if (!IsPadOn(idect,col-1,row)) {
2263           fGoodTrack = kFALSE;
2264           good       = kFALSE;
2265         }
2266       }
2267       
2268       if (col < 143) {
2269         if (!IsPadOn(idect,col+1,row)) {
2270           fGoodTrack = kFALSE;
2271           good       = kFALSE;
2272         }
2273       }
2274
2275       // Total spectrum
2276       if (fPH2dOn) {
2277         fPHPlace[time] = posc[1] * fNfragZ[1] + posr[1];
2278       }
2279
2280       if (!fTraMaxPad) {
2281         if (fCH2dOn) {
2282           fAmpTotal[(Int_t) (posc[0]*fNfragZ[0]+posr[0])] += (Float_t) (amp[0]+amp[1]+amp[2]);
2283         }
2284         if (fPH2dOn) {
2285           fPHValue[time] = (Float_t) (amp[0]+amp[1]+amp[2]);
2286         }
2287       }
2288       else {
2289         if (fCH2dOn) {
2290           fAmpTotal[(Int_t) (posc[0]*fNfragZ[0]+posr[0])] += (Float_t) amp[1];
2291         }
2292         if (fPH2dOn) {
2293           fPHValue[time] = amp[1];
2294         }
2295       }
2296             
2297       // Fill PRF direct
2298       if (fPRF2dOn && good) {
2299         if ((amp[0] > fThresholdClusterPRF2) && 
2300             (amp[1] > fThresholdClusterPRF2) && 
2301             (amp[2] > fThresholdClusterPRF2) && 
2302             ((amp[0]*amp[2]/(amp[1]*amp[1])) < 0.06)) {
2303           // Security of the denomiateur is 0
2304           if ((((Float_t) (((Float_t) amp[1]) * ((Float_t) amp[1]))) 
2305              / ((Float_t) (((Float_t) amp[0]) * ((Float_t) amp[2])))) != 1.0) {
2306             Float_t xcenter = 0.5 * (TMath::Log(amp[2] / amp[0]))
2307                                   / (TMath::Log((amp[1]*amp[1]) / (amp[0]*amp[2])));
2308             Float_t ycenter = amp[1] / (amp[0] + amp[1] + amp[2]);
2309             if ((xcenter > -0.5) && 
2310                 (xcenter <  0.5)) {
2311               Float_t yminus = amp[0] / (amp[0]+amp[1]+amp[2]);
2312               Float_t ymax   = amp[2] / (amp[0]+amp[1]+amp[2]);
2313               // Fill only if it is in the drift region!
2314               if (((Float_t) time / fSf) > 0.3) {
2315                 if (fHisto2d) {
2316                   fPRF2d->Fill((fXbins[2]+posc[2]*fNfragZ[2]+posr[2]+0.5),xcenter,ycenter);
2317                   if (xcenter < 0.0) {
2318                     fPRF2d->Fill((fXbins[2]+posc[2]*fNfragZ[2]+posr[2]+0.5),-(xcenter+1.0),yminus);
2319                   }
2320                   if (xcenter > 0.0) {
2321                     fPRF2d->Fill((fXbins[2]+posc[2]*fNfragZ[2]+posr[2]+0.5),(1.0-xcenter),ymax);
2322                   }
2323                 }
2324                 if (fVector2d) {
2325                   UpdateVectorPRF((fXbins[2]+posc[2]*fNfragZ[2]+posr[2]),xcenter,ycenter);
2326                   if (xcenter < 0.0) {
2327                     UpdateVectorPRF(fXbins[2]+posc[2]*fNfragZ[2]+posr[2],-(xcenter+1.0),yminus);
2328                   }
2329                   if (xcenter > 0.0) {
2330                     UpdateVectorPRF(fXbins[2]+posc[2]*fNfragZ[2]+posr[2],(1.0-xcenter),ymax);
2331                   }
2332                 }
2333               } 
2334             }
2335           }
2336         }
2337       }
2338       
2339     } // Boucle clusters
2340     
2341     // Fill the charge
2342     if (fCH2dOn && fGoodTrack) {
2343       FillTheInfoOfTheTrackCH();
2344     }
2345
2346     // PH calibration
2347     if (fPH2dOn && fGoodTrack) {
2348       FillTheInfoOfTheTrackPH();        
2349     }
2350         
2351   } // Condition on number of clusters
2352
2353   return kTRUE;
2354   
2355 }
2356
2357 //____________Functions for seeing if the pad is really okey___________________
2358
2359 //_____________________________________________________________________________
2360 Bool_t AliTRDCalibra::SetModeCalibrationFromTObject(TObject *object, Int_t i)
2361 {
2362   //
2363   // Set fNz[i] and fNrphi[i] of the AliTRDCalibra::Instance()
2364   // corresponding to the given TObject
2365   //
2366
2367   const char *nametitle = object->GetTitle();
2368
2369   // Some patterns
2370   const Char_t *patternz0    = "Nz0";
2371   const Char_t *patternz1    = "Nz1";
2372   const Char_t *patternz2    = "Nz2";
2373   const Char_t *patternz3    = "Nz3";
2374   const Char_t *patternz4    = "Nz4";
2375   const Char_t *patternrphi0 = "Nrphi0";
2376   const Char_t *patternrphi1 = "Nrphi1";
2377   const Char_t *patternrphi2 = "Nrphi2";
2378   const Char_t *patternrphi3 = "Nrphi3";
2379   const Char_t *patternrphi4 = "Nrphi4";
2380   const Char_t *patternrphi5 = "Nrphi5";
2381   const Char_t *patternrphi6 = "Nrphi6";
2382
2383   UShort_t testz    = 0;
2384   UShort_t testrphi = 0;
2385
2386   // Nz mode
2387   if (strstr(nametitle,patternz0)) {
2388     testz++;
2389     fNz[i] = 0;
2390   }
2391   if (strstr(nametitle,patternz1)) {
2392     testz++;
2393     fNz[i] = 1;
2394   }
2395   if (strstr(nametitle,patternz2)) {
2396     testz++;
2397     fNz[i] = 2;
2398   }
2399   if (strstr(nametitle,patternz3)) {
2400     testz++;
2401     fNz[i] = 3;
2402   }
2403   if (strstr(nametitle,patternz4)) {
2404     testz++;
2405     fNz[i] = 4;
2406   }
2407
2408   // Nrphi mode
2409   if (strstr(nametitle,patternrphi0)) {
2410     testrphi++;
2411     fNrphi[i] = 0;
2412   }
2413   if (strstr(nametitle,patternrphi1)) {
2414     testrphi++;
2415     fNrphi[i] = 1;
2416   }
2417   if (strstr(nametitle,patternrphi2)) {
2418     testrphi++;
2419     fNrphi[i] = 2;
2420   }
2421   if (strstr(nametitle,patternrphi3)) {
2422     testrphi++;
2423     fNrphi[i] = 3;
2424   }
2425   if (strstr(nametitle,patternrphi4)) {
2426     testrphi++;
2427     fNrphi[i] = 4;
2428   }
2429   if (strstr(nametitle,patternrphi5)) {
2430     testrphi++;
2431     fNrphi[i] = 5;
2432   }
2433   if (strstr(nametitle,patternrphi6)) {
2434     testrphi++;
2435     fNrphi[i] = 6;
2436   }
2437  
2438   // Look if all is okey
2439   if ((testz    == 1) && 
2440       (testrphi == 1)) {
2441     return kTRUE;
2442   }
2443   else {
2444     fNrphi[i] = 0;
2445     fNz[i]    = 0;
2446     return kFALSE;
2447   }
2448   
2449 }
2450
2451 //_____________________________________________________________________________
2452 Bool_t AliTRDCalibra::IsPadOn(Int_t detector, Int_t col, Int_t row) const
2453 {
2454   //
2455   // Look in the choosen database if the pad is On.
2456   // If no the track will be "not good"
2457   //
2458
2459   // Get the parameter object
2460   AliTRDcalibDB *cal = AliTRDcalibDB::Instance();
2461   if (!cal) {
2462     AliInfo("Could not get calibDB");
2463     return kFALSE;
2464   }
2465   
2466   if (!cal->IsChamberInstalled(detector)     || 
2467        cal->IsChamberMasked(detector)        ||
2468        cal->IsPadMasked(detector,col,row)) {
2469     return kFALSE;
2470   }
2471   else {
2472     return kTRUE;
2473   }
2474   
2475 }
2476
2477 //____________Functions for plotting the 2D____________________________________
2478
2479 //_____________________________________________________________________________
2480 void AliTRDCalibra::Plot2d()
2481 {
2482   //
2483   // Plot the 2D histos 
2484   //
2485  
2486   if (fCH2dOn) {
2487     PlotCH2d();
2488   }
2489   if (fPH2dOn) {
2490     PlotPH2d();
2491   }
2492   if (fPRF2dOn) {
2493     PlotPRF2d();
2494   }
2495
2496 }
2497
2498 //____________Writing the 2D___________________________________________________
2499
2500 //_____________________________________________________________________________
2501 Bool_t AliTRDCalibra::Write2d()
2502 {
2503   //
2504   // Write the 2D histograms or the vectors converted in trees in the file
2505   // "TRD.calibration.root" 
2506   //
2507   
2508   TFile *fout = TFile::Open(fWriteName,"RECREATE");
2509   // Check if the file could be opened
2510   if (!fout || !fout->IsOpen()) {
2511     AliInfo("No File found!");
2512     return kFALSE;
2513   }
2514   AliInfo(Form("Numbertrack: %d Numberusedch[0]: %d, Numberusedch[1]: %d Numberusedph[0]: %d, Numberusedph[1]: %d"
2515               ,fNumberTrack
2516               ,fNumberUsedCh[0]
2517               ,fNumberUsedCh[1]
2518               ,fNumberUsedPh[0]
2519               ,fNumberUsedPh[1]));
2520   
2521   TStopwatch stopwatch;
2522   stopwatch.Start();
2523   AliInfo("Write2d");
2524
2525   if ((fCH2dOn ) && (fWrite[0])) {
2526     if (fHisto2d) {
2527       fout->WriteTObject(fCH2d);
2528     }
2529     if (fVector2d) {
2530       TString name("Nz");
2531       name += fNz[0];
2532       name += "Nrphi";
2533       name += fNrphi[0];
2534       TTree *treeCH2d = ConvertVectorCTTreeHisto(fVectorCH,fPlaCH,"treeCH2d",(const char *) name);
2535       fout->WriteTObject(treeCH2d);
2536     }
2537   }
2538   if ((fPH2dOn ) && (fWrite[1])) {
2539     if (fHisto2d) {
2540       fout->WriteTObject(fPH2d);
2541     }
2542     if (fVector2d) {
2543       TString name("Nz");
2544       name += fNz[1];
2545       name += "Nrphi";
2546       name += fNrphi[1];
2547       TTree *treePH2d = ConvertVectorPTreeHisto(fVectorPH,fPlaPH,"treePH2d",(const char *) name);
2548       fout->WriteTObject(treePH2d);
2549     }
2550   }
2551   if ((fPRF2dOn ) && (fWrite[2])) {
2552     if (fHisto2d) {
2553       fout->WriteTObject(fPRF2d);
2554     }
2555     if (fVector2d) {
2556       TString name("Nz");
2557       name += fNz[2];
2558       name += "Nrphi";
2559       name += fNrphi[2];
2560       TTree *treePRF2d = ConvertVectorPTreeHisto(fVectorPRF,fPlaPRF,"treePRF2d",(const char *) name);
2561       fout->WriteTObject(treePRF2d);
2562     }
2563   }
2564   
2565   fout->Close();
2566   
2567   AliInfo(Form("Execution time Write2d: R:%.2fs C:%.2fs"
2568               ,stopwatch.RealTime(),stopwatch.CpuTime()));
2569
2570   return kTRUE;
2571   
2572 }
2573
2574 //_____________________________________________________________________________
2575 AliTRDCalDet *AliTRDCalibra::CreateDetObjectTree(TTree *tree, Int_t i)
2576 {
2577   //
2578   // It creates the AliTRDCalDet object from the tree of the coefficient
2579   // for the calibration i (i != 2)
2580   // It takes the mean value of the coefficients per detector 
2581   // This object has to be written in the database
2582   //
2583   
2584   // Create the DetObject
2585   AliTRDCalDet *object = 0x0;
2586   if (i == 0) {
2587     object = new AliTRDCalDet("ChamberGainFactor","GainFactor (detector value)");
2588   }
2589   if (i == 1) {
2590     object = new AliTRDCalDet("ChamberVdrift","TRD drift velocities (detector value)");
2591   }
2592   else {
2593     object = new AliTRDCalDet("ChamberT0","T0 (detector value)");
2594   }
2595   
2596   // Read the Tree
2597   Int_t   detector = -1;
2598   Float_t values[2304];
2599   tree->SetBranchAddress("detector",&detector);
2600   if (i == 0) {
2601     tree->SetBranchAddress("gainPad",values);
2602   }
2603   if (i == 1) {
2604     tree->SetBranchAddress("vdrift" ,values);
2605   }
2606   if (i == 3) {
2607     tree->SetBranchAddress("t0"     ,values);
2608   }
2609   
2610   // For calculating the mean
2611   Float_t mean            = 0.0;
2612   Int_t   nto             = 0;
2613   Int_t   numberofentries = tree->GetEntries();
2614   
2615   if (numberofentries != 540) {
2616     AliInfo("The tree is not complete");
2617   }
2618   
2619   for (Int_t det = 0; det < numberofentries; ++det) {
2620     tree->GetEntry(det);
2621     if (GetChamber(detector) == 2) {
2622       nto = 1728;
2623     }
2624     else {
2625       nto = 2304;
2626     }
2627     mean = 0.0;
2628     if(i != 3){
2629       for (Int_t k = 0; k < nto; k++) {
2630         mean += TMath::Abs(values[k]) / nto;  
2631       }
2632     }
2633     else {
2634       for (Int_t k = 0; k < nto; k++) {
2635         if(k == 0) mean = values[k];
2636         if(mean > values[k]) mean = values[k];
2637       }
2638     }
2639     object->SetValue(detector,mean);
2640   }
2641
2642   return object;
2643
2644 }
2645
2646 //_____________________________________________________________________________
2647 TObject *AliTRDCalibra::CreatePadObjectTree(TTree *tree, Int_t i
2648                                           , AliTRDCalDet *detobject)
2649 {
2650   //
2651   // It Creates the AliTRDCalPad object from the tree of the
2652   // coefficient for the calibration i (i != 2)
2653   // You need first to create the object for the detectors,
2654   // where the mean value is put.
2655   // This object has to be written in the database
2656   //
2657   
2658   // Create the DetObject
2659   AliTRDCalPad *object = 0x0;
2660   if (i == 0) {
2661     object = new AliTRDCalPad("GainFactor","GainFactor (local variations)");
2662   }
2663   if (i == 1) {
2664     object = new AliTRDCalPad("LocalVdrift","TRD drift velocities (local variations)");
2665   }
2666   else {
2667     object = new AliTRDCalPad("LocalT0","T0 (local variations)");
2668   }
2669   
2670   // Read the Tree
2671   Int_t   detector = -1;
2672   Float_t values[2304];
2673   tree->SetBranchAddress("detector",&detector);
2674   if (i == 0) {
2675     tree->SetBranchAddress("gainPad",values);
2676   }
2677   if (i == 1) {
2678     tree->SetBranchAddress("vdrift" ,values);
2679   }
2680   if (i == 3) {
2681     tree->SetBranchAddress("t0"     ,values);
2682   }
2683   
2684   // Variables
2685   Float_t mean            = 0.0;
2686   Int_t   numberofentries = tree->GetEntries();
2687   
2688   if (numberofentries != 540) {
2689     AliInfo("The tree is not complete");
2690   }
2691   
2692   for (Int_t det = 0; det < numberofentries; ++det) {
2693     tree->GetEntry(det);
2694     AliTRDCalROC *calROC = object->GetCalROC(detector);
2695     mean = detobject->GetValue(detector);
2696     if ((mean == 0) && (i != 3)) {
2697       continue;
2698     }
2699     Int_t rowMax = calROC->GetNrows();
2700     Int_t colMax = calROC->GetNcols();
2701     for (Int_t row = 0; row < rowMax; ++row) {
2702       for (Int_t col = 0; col < colMax; ++col) {
2703         if(i != 3) calROC->SetValue(col,row,TMath::Abs(values[(Int_t) (col*rowMax+row)])/mean);
2704         else calROC->SetValue(col,row,values[(Int_t) (col*rowMax+row)]-mean);
2705         
2706       } // Col
2707     } // Row
2708   }
2709
2710   return object;
2711
2712 }
2713
2714 //_____________________________________________________________________________
2715 TObject *AliTRDCalibra::CreatePadObjectTree(TTree *tree)
2716 {
2717   //
2718   // It Creates the AliTRDCalPad object from the tree of the
2719   // coefficient for the calibration PRF (i = 2)
2720   // This object has to be written in the database
2721   //
2722   
2723   // Create the DetObject
2724   AliTRDCalPad *object = new AliTRDCalPad("PRFWidth","PRFWidth");
2725
2726   // Read the Tree
2727   Int_t   detector = -1;
2728   Float_t values[2304];
2729   tree->SetBranchAddress("detector",&detector);
2730   tree->SetBranchAddress("width"   ,values);
2731    
2732   // Variables
2733   Int_t numberofentries = tree->GetEntries();
2734
2735   if (numberofentries != 540) {
2736     AliInfo("The tree is not complete");
2737   }
2738
2739   for (Int_t det = 0; det < numberofentries; ++det) {
2740     tree->GetEntry(det);
2741     AliTRDCalROC *calROC = object->GetCalROC(detector);
2742     Int_t rowMax = calROC->GetNrows();
2743     Int_t colMax = calROC->GetNcols();
2744     for (Int_t row = 0; row < rowMax; ++row) {
2745       for (Int_t col = 0; col < colMax; ++col) {
2746         calROC->SetValue(col,row,TMath::Abs(values[(Int_t) (col*rowMax+row)]));
2747       } // Col
2748     } // Row
2749   }
2750
2751   return object;
2752
2753 }
2754
2755 //_____________________________________________________________________________
2756 void AliTRDCalibra::SetRelativeScale(Float_t RelativeScale)
2757 {
2758   //
2759   // Set the factor that will divide the deposited charge
2760   // to fit in the histo range [0,300]
2761   //
2762  
2763   if (RelativeScale > 0.0) {
2764     fRelativeScale = RelativeScale;
2765   } 
2766   else {
2767     AliInfo("RelativeScale must be strict positif!");
2768   }
2769
2770
2771
2772 //_____________________________________________________________________________
2773 void AliTRDCalibra::SetNz(Int_t i, Short_t Nz)
2774 {
2775   //
2776   // Set the mode of calibration group in the z direction for the parameter i
2777   // 
2778
2779   if ((Nz >= 0) && 
2780       (Nz <  5)) {
2781     fNz[i] = Nz; 
2782   }
2783   else { 
2784     AliInfo("You have to choose between 0 and 4");
2785   }
2786
2787 }
2788
2789 //_____________________________________________________________________________
2790 void AliTRDCalibra::SetNrphi(Int_t i, Short_t Nrphi)
2791 {
2792   //
2793   // Set the mode of calibration group in the rphi direction for the parameter i
2794   //
2795  
2796   if ((Nrphi >= 0) && 
2797       (Nrphi <  7)) {
2798     fNrphi[i] = Nrphi; 
2799   }
2800   else {
2801     AliInfo("You have to choose between 0 and 6");
2802   }
2803
2804 }
2805
2806 //_____________________________________________________________________________
2807 void AliTRDCalibra::SetPeriodeFitPH(Int_t periodeFitPH)
2808
2809   //
2810   // Set FitPH if 1 then each detector will be fitted
2811   //
2812
2813   if (periodeFitPH > 0) {
2814     fFitPHPeriode   = periodeFitPH; 
2815   }
2816   else {
2817     AliInfo("periodeFitPH must be higher than 0!");
2818   }
2819
2820 }
2821
2822 //_____________________________________________________________________________
2823 void AliTRDCalibra::SetBeginFitCharge(Float_t beginFitCharge)
2824
2825   //
2826   // The fit of the deposited charge distribution begins at
2827   // histo->Mean()/beginFitCharge
2828   // You can here set beginFitCharge
2829   //
2830
2831   if (beginFitCharge > 0) {
2832     fBeginFitCharge = beginFitCharge; 
2833   }
2834   else {
2835     AliInfo("beginFitCharge must be strict positif!");
2836   }
2837
2838 }
2839
2840 //_____________________________________________________________________________
2841 void AliTRDCalibra::SetT0Shift(Float_t t0Shift) 
2842
2843   //
2844   // The t0 calculated with the maximum positif slope is shift from t0Shift
2845   // You can here set t0Shift
2846   //
2847
2848   if (t0Shift > 0) {
2849     fT0Shift = t0Shift; 
2850   } 
2851   else {
2852     AliInfo("t0Shift must be strict positif!");
2853   }
2854
2855 }
2856
2857 //_____________________________________________________________________________
2858 void AliTRDCalibra::SetRangeFitPRF(Float_t rangeFitPRF)
2859
2860   //
2861   // The fit of the PRF is from -rangeFitPRF to rangeFitPRF
2862   // You can here set rangeFitPRF
2863   //
2864
2865   if ((rangeFitPRF >    0) && 
2866       (rangeFitPRF <= 1.0)) {
2867     fRangeFitPRF = rangeFitPRF;
2868   } 
2869   else {
2870     AliInfo("rangeFitPRF must be between 0 and 1.0");
2871   }
2872
2873 }
2874
2875 //_____________________________________________________________________________
2876 void AliTRDCalibra::SetRebin(Short_t rebin)
2877
2878   //
2879   // Rebin with rebin time less bins the Ch histo
2880   // You can set here rebin that should divide the number of bins of CH histo
2881   //
2882
2883   if (rebin > 0) {
2884     fRebin = rebin; 
2885     AliInfo("You have to be sure that fRebin divides fNumberBinCharge used!");
2886   } 
2887   else {
2888     AliInfo("You have to choose a positiv value!");
2889   }
2890
2891 }
2892
2893 //_____________________________________________________________________________
2894 TTree *AliTRDCalibra::Sum2Trees(const Char_t *filename1
2895                               , const Char_t *filename2
2896                               , const Char_t *variablecali)
2897 {
2898   //
2899   // It returns the sum of two trees with the name variablecali
2900   // in the files filenam1 and filename2 equivalent of merging two 2D histos
2901   // The name of the resulting tree is the same as the two input trees
2902   // variablecali can be treeCH2d, treePH2d or treePRF2d 
2903   //
2904
2905   // Variables
2906   TChain    *treeChain   = new TChain(variablecali);
2907   TObjArray *vectorplace = new TObjArray();
2908   TObjArray *where       = new TObjArray();
2909   
2910   // First tree
2911   // Take the tree
2912   TFile *file1 = new TFile(filename1,"READ");
2913   TTree *tree1 = (TTree *) file1->Get(variablecali);
2914
2915   gDirectory = gROOT;
2916
2917   // Take the places
2918   vectorplace = ConvertTreeVector(tree1);
2919
2920   // Say where it is in tree 1
2921   for (Int_t jui = 0; jui < (Int_t) vectorplace->GetEntriesFast(); jui++) {
2922     AliTRDPlace *placejui = new AliTRDPlace();
2923     placejui->SetPlace(jui);
2924     TObjArray *chainplace = new TObjArray();
2925     chainplace->Add((TObject *) placejui);
2926     where->Add((TObject *) chainplace);
2927   }
2928
2929   // Add to the chain
2930   treeChain->Add(filename1);
2931   delete file1;
2932
2933   // Second tree
2934   // Take the tree
2935   TFile *file2 = new TFile(filename2,"READ");
2936   TTree *tree2 = (TTree *) file2->Get(variablecali);
2937
2938   gDirectory = gROOT;
2939
2940   // Take the places
2941   TObjArray *vector2 = ConvertTreeVector(tree2);
2942   Int_t j = treeChain->GetEntries();
2943
2944   for (Int_t jui = 0; jui < (Int_t) vector2->GetEntriesFast(); jui++) {
2945     // Search if already found
2946     Int_t place = SearchInTreeVector(vectorplace,((AliTRDPlace *) vector2->At(jui))->GetPlace());
2947     // Create a new element in the two std vectors
2948     if (place == -1) {
2949       AliTRDPlace *placejjui  = new AliTRDPlace();
2950       placejjui->SetPlace((j+jui));
2951       TObjArray   *chainplace = new TObjArray();
2952       chainplace->Add((TObject *) placejjui);
2953       vectorplace->Add((TObject *) (vector2->At(jui)));
2954       where->Add((TObject *) chainplace);
2955     }
2956     // Update the element at the place "place" in the std vector whereinthechain
2957     else {
2958       AliTRDPlace *placejjui  = new AliTRDPlace();
2959       placejjui->SetPlace((j+jui));
2960       TObjArray   *chainplace = ((TObjArray *) where->At(place));
2961       chainplace->Add((TObject *) placejjui);
2962       where->AddAt((TObject *) chainplace,place);
2963     }
2964   }
2965
2966   // Add to the Chain
2967   treeChain->Add(filename2);
2968   delete file2; 
2969
2970   // Take care of the profile
2971   const Char_t *pattern = "P";
2972   TTree *tree = 0x0;
2973
2974   if (!strstr(variablecali,pattern)) {
2975
2976     // Ready to read the chain
2977     TH1F *his = 0x0;
2978     treeChain->SetBranchAddress("histo",&his);
2979
2980     // Initialise the final tree
2981     Int_t group   = -1;
2982     TH1F *histsum = 0x0;
2983    
2984     tree = new TTree(variablecali,variablecali);
2985     tree->Branch("groupnumber",&group,"groupnumber/I");
2986     tree->Branch("histo","TH1F",&histsum,32000,0);
2987
2988     // Init histsum
2989     if (treeChain->GetEntries() < 1) {
2990       return tree1; 
2991     }
2992     
2993     for (Int_t h = 0; h < (Int_t) vectorplace->GetEntriesFast(); h++) {
2994       group = ((AliTRDPlace *) vectorplace->At(h))->GetPlace();
2995       TObjArray *chainplace = ((TObjArray *) where->At(h));
2996       treeChain->GetEntry(((AliTRDPlace *) chainplace->At(0))->GetPlace());
2997       //Init for the first time
2998       if (h == 0)  {
2999         histsum = new TH1F("","",his->GetXaxis()->GetNbins()
3000                                 ,his->GetXaxis()->GetBinLowEdge(1)
3001                                 ,his->GetXaxis()->GetBinUpEdge(his->GetXaxis()->GetNbins()));
3002         histsum->Sumw2();
3003       }
3004       // Reset for each new group
3005       histsum->SetEntries(0.0);
3006       for (Int_t l = 0; l <= histsum->GetXaxis()->GetNbins(); l++) {
3007         histsum->SetBinContent(l,0.0);
3008         histsum->SetBinError(l,0.0);
3009       }
3010       histsum->Add(his,1);
3011       if ((Int_t) chainplace->GetEntriesFast() > 1) {
3012         for (Int_t s = 1; s < (Int_t) chainplace->GetEntriesFast(); s++) {
3013           treeChain->GetEntry(((AliTRDPlace *) chainplace->At(s))->GetPlace());
3014           histsum->Add(his,1);
3015         }
3016       }
3017       tree->Fill();
3018     }
3019
3020   }
3021   else {
3022
3023     // Ready to read the chain
3024     TGraphErrors *his = 0x0;
3025     treeChain->SetBranchAddress("histo",&his);
3026     
3027     // Initialise the final tree
3028     Int_t         group   = -1;
3029     TGraphErrors *histsum = 0x0;
3030     Double_t     *xref    = 0x0;
3031   
3032     tree = new TTree(variablecali,variablecali);
3033     tree->Branch("groupnumber",&group,"groupnumber/I");
3034     tree->Branch("histo","TGraphErrors",&histsum,32000,0);
3035
3036     // Init histsum
3037     if (treeChain->GetEntries() < 1) {
3038       return tree1; 
3039     }
3040
3041     for (Int_t h = 0; h < (Int_t) vectorplace->GetEntriesFast(); h++) {
3042
3043       group = ((AliTRDPlace *) vectorplace->At(h))->GetPlace();
3044       TObjArray *chainplace = ((TObjArray *) where->At(h));
3045       treeChain->GetEntry(((AliTRDPlace *) chainplace->At(0))->GetPlace());
3046       //Init or reset for a new group
3047       Int_t nbins = his->GetN();
3048       Double_t *x;
3049       x    = new Double_t[nbins];
3050       xref = his->GetX();
3051       Double_t *ex;
3052       ex   = new Double_t[nbins];
3053       Double_t *y;
3054       y    = new Double_t[nbins];
3055       Double_t *ey;
3056       ey   = new Double_t[nbins];
3057      
3058       for (Int_t lo = 0; lo < nbins; lo++) {
3059         x[lo]  = xref[lo];
3060         ex[lo] = 0.0;
3061         y[lo]  = 0.0;
3062         ey[lo] = 0.0;
3063       }
3064       delete histsum;
3065       histsum = new TGraphErrors(nbins,x,y,ex,ey);
3066
3067       // Add the first
3068       histsum = AddProfiles(his,histsum);
3069       if ((Int_t) chainplace->GetEntriesFast() > 1) {
3070         for (Int_t s = 1; s < (Int_t) chainplace->GetEntriesFast(); s++) {
3071           treeChain->GetEntry(((AliTRDPlace *) chainplace->At(s))->GetPlace());
3072           histsum = AddProfiles(his,histsum);
3073         }
3074       }
3075
3076       tree->Fill();
3077
3078     }
3079
3080   }
3081     
3082   return tree;
3083
3084 }
3085
3086 //____________Function fill 2D for the moment out of the code__________________
3087
3088 //____________Function fill 2D all objects from digits_________________________
3089 Bool_t AliTRDCalibra::Create2DDiSimOnline(Int_t iev1, Int_t iev2)
3090 {
3091   //
3092   // Only for simulations, after the simulation, create the 2D histos
3093   // from the digits stored in the file "TRD.Digits.root" 
3094   // Only for CH and PH
3095   //
3096   
3097   const Int_t kNplan = 6;
3098   const Int_t kNcham = 5;
3099
3100   // RunLoader and so on
3101   if (gAlice) {
3102     delete gAlice->GetRunLoader();
3103     delete gAlice;
3104     gAlice = 0;
3105   }
3106  
3107   AliRunLoader *rl = AliRunLoader::Open("galice.root");
3108   if (!rl) {
3109     return kFALSE;
3110   }
3111
3112   rl->LoadgAlice();
3113   gAlice = rl->GetAliRun();
3114   if (!gAlice) {
3115     return kFALSE;
3116   }
3117
3118   // Import the Trees for the event nEvent in the file
3119   rl->LoadKinematics();
3120   rl->GetEvent(0);
3121   rl->LoadHeader();
3122   
3123   AliLoader *loader = rl->GetLoader("TRDLoader");
3124   if (!loader) {
3125     AliInfo("No TRDLLoader found!");
3126     return kFALSE;
3127   }
3128
3129   // Get the pointer to the TRD detector 
3130   AliTRD *trd = (AliTRD *) gAlice->GetDetector("TRD");
3131   if (!trd) {
3132     AliInfo("No TRD detector found");
3133     return kFALSE;
3134   }
3135
3136   // Get the pointer to the geometry object
3137   AliTRDgeometry *geo;
3138   if (trd) {
3139     geo = trd->GetGeometry();
3140   }
3141   else {
3142     AliInfo("No TRD geometry found");
3143     return kFALSE;
3144   }
3145
3146   // DB Setting
3147   AliCDBManager *man = AliCDBManager::Instance();
3148   if (!man) {
3149     AliInfo("Could not get CDB Manager");
3150     return kFALSE;
3151   }
3152  
3153   // Get the parameter object
3154   AliTRDCommonParam *parCom = AliTRDCommonParam::Instance();
3155   if (!parCom) {
3156     AliInfo("Could not get CommonParam");
3157     return kFALSE;
3158   }
3159   AliTRDcalibDB     *cal    = AliTRDcalibDB::Instance();
3160   if (!cal) {
3161     AliInfo("Could not get calibDB");
3162     return kFALSE;
3163   }
3164
3165   // Some parameters
3166   fTimeMax = cal->GetNumberOfTimeBins();
3167   fSf      = (Float_t) parCom->GetSamplingFrequency();
3168   if (fRelativeScaleAuto) {
3169     fRelativeScale = 0;
3170   }
3171   else {
3172     if (fRelativeScale <= 0.0) {
3173       AliInfo("You have to set the relativescale factor per hand!");
3174       return kFALSE;
3175     }
3176   }
3177
3178   // Create the 2D histos corresponding to the pad group calibration mode
3179   if (fCH2dOn) {
3180
3181     AliInfo(Form("We will fill the CH2d histo with the pad calibration mode: Nz %d, and Nrphi %d"
3182                 ,fNz[0]
3183                 ,fNrphi[0]));
3184     
3185     // Calcul the number of Xbins
3186     fNtotal[0]    = 0;
3187     ModePadCalibration(2,0);
3188     ModePadFragmentation(0,2,0,0);
3189     fDetChamb2[0] = fNfragZ[0] * fNfragRphi[0];
3190     fNtotal[0]   += 6 * 18 * fDetChamb2[0];
3191     ModePadCalibration(0,0);
3192     ModePadFragmentation(0,0,0,0);
3193     fDetChamb0[0] = fNfragZ[0] * fNfragRphi[0];
3194     fNtotal[0]   += 6 * 4 * 18 * fDetChamb0[0];
3195     AliInfo(Form("Total number of Xbins: %d",fNtotal[0]));
3196
3197     // Create the 2D histo
3198     if (fHisto2d) {
3199       CreateCH2d(fNtotal[0]);
3200     }
3201     if (fVector2d) {
3202       fVectorCH = new TObjArray();
3203       fPlaCH    = new TObjArray();
3204     }
3205     
3206   }
3207   
3208   if (fPH2dOn) {
3209
3210     AliInfo(Form("We will fill the PH2d histo with the pad calibration mode: Nz %d, and Nrphi %d"
3211                 ,fNz[1]
3212                 ,fNrphi[1]));
3213     
3214     // Calcul the number of Xbins
3215     fNtotal[1]    = 0;
3216     ModePadCalibration(2,1);
3217     ModePadFragmentation(0,2,0,1);
3218     fDetChamb2[1] = fNfragZ[1] * fNfragRphi[1];
3219     fNtotal[1]   += 6 * 18 * fDetChamb2[1];
3220     ModePadCalibration(0,1);
3221     ModePadFragmentation(0,0,0,1);
3222     fDetChamb0[1] = fNfragZ[1] * fNfragRphi[1];
3223     fNtotal[1]   += 6 * 4 * 18 * fDetChamb0[1];
3224     AliInfo(Form("Total number of Xbins: %d",fNtotal[1]));
3225
3226     // Create the 2D histo
3227     if (fHisto2d) {
3228       CreatePH2d(fNtotal[1]);
3229     }
3230     if (fVector2d) {
3231       fVectorPH = new TObjArray();
3232       fPlaPH    = new TObjArray();
3233     }
3234
3235   }
3236
3237   loader->LoadDigits();
3238   AliInfo("LoadDigits ");
3239   AliTRDdigitsManager *digitsManager = new AliTRDdigitsManager();
3240
3241   //iev2 egal to the max if 0
3242   if (iev2 == 0) {
3243     iev2 = rl->GetNumberOfEvents();
3244     AliInfo(Form("Total number of events: %d",iev2));
3245   }
3246
3247   // Loop on event
3248   for (Int_t ievent = iev1; ievent < iev2; ievent++) {
3249     AliInfo(Form("Process event %d",ievent));
3250     rl->GetEvent(ievent);
3251     if (!loader->TreeD()) {
3252       AliInfo("loader Loading Digits ... ");
3253       loader->LoadDigits();
3254     }
3255     digitsManager->ReadDigits(loader->TreeD());
3256     AliInfo("digitsManager Read Digits Done");
3257     // Read the digits from the file
3258     if (!(digitsManager->ReadDigits(loader->TreeD()))) {
3259       return kFALSE;
3260     }
3261
3262     // Loop on detector
3263     for (Int_t iSect = 0; iSect < 18; iSect++) {
3264       for (Int_t iChamb = 0; iChamb < kNcham; iChamb++) {
3265         for (Int_t iPlane = 0; iPlane < kNplan; iPlane++) {
3266           
3267           // A little geometry:
3268           Int_t iDet   = geo->GetDetector(iPlane,iChamb,iSect);
3269           Int_t rowMax = parCom->GetRowMax(iPlane,iChamb,iSect);
3270           Int_t colMax = parCom->GetColMax(iPlane);
3271
3272           // Variables for the group
3273           LocalisationDetectorXbins(iDet);
3274
3275           // In the cas of charge
3276           Float_t *amptotal;
3277           amptotal = new Float_t[fNfragRphi[0]*fNfragZ[0]];
3278           if (fCH2dOn) {
3279             for (Int_t k = 0; k < fNfragRphi[0]*fNfragZ[0]; k++) {
3280               amptotal[k] = 0.0;
3281             }
3282           }
3283
3284           // Loop through the detector pixel
3285           for (Int_t time = 0; time < fTimeMax; time++) {
3286             for (Int_t  col = 0;  col <  colMax;  col++) {
3287               for (Int_t  row = 0;  row <  rowMax;  row++) {
3288
3289                 // Amplitude and position in pad group 
3290                 AliTRDdigit *digit   = digitsManager->GetDigit(row,col,time,iDet);
3291                 Int_t        amp     = digit->GetAmp();
3292                 Int_t        posr[2] = {0,0};
3293                 Int_t        posc[2] = {0,0};
3294                 if ((fCH2dOn) && 
3295                     (fNnZ[0]    != 0)) {
3296                   posr[0] = (Int_t) row / fNnZ[0];
3297                 }
3298                 if ((fCH2dOn) && 
3299                     (fNnRphi[0] != 0)) {
3300                   posc[0] = (Int_t) col / fNnRphi[0];
3301                 }
3302                 if ((fPH2dOn) && 
3303                     (fNnZ[1]    != 0)) {
3304                   posr[1] = (Int_t) row / fNnZ[1];
3305                 }
3306                 if ((fPH2dOn) && 
3307                     (fNnRphi[1] != 0)) {
3308                   posc[1] = (Int_t) col / fNnRphi[1];
3309                 }
3310
3311                 // Total spectrum
3312                 if (fCH2dOn) {
3313                   if (amp < fThresholdDigit) {
3314                     amp = 0;
3315                   }
3316                   amptotal[(Int_t) (posc[0]*fNfragZ[0]+posr[0])] += amp;
3317                 }
3318                 if (fPH2dOn) {
3319                   if (fHisto2d) {
3320                     fPH2d->Fill((fXbins[1]+posc[1]*fNfragZ[1]+posr[1])+0.5,(Float_t) time/fSf,(Double_t) amp);
3321                   }
3322                   if (fVector2d) {
3323                     UpdateVectorPH((fXbins[1]+posc[1]*fNfragZ[1]+posr[1]),time,(Double_t) amp);
3324                   }
3325                 }
3326              
3327                 // Memory stuff
3328                 delete digit;
3329
3330               } // Boucle row
3331             } // Boucle col
3332           } // Boucle time
3333
3334           if (fCH2dOn) {
3335
3336             // If automatic scale
3337             if ((fCountRelativeScale < 100) && (fRelativeScaleAuto)) {
3338               // Take only the one zone track
3339               for (Int_t k = 0; k < fNfragZ[0]*fNfragRphi[0]; k++) {
3340                 if ((fCountRelativeScale < 100) && (amptotal[k] > 2.0)) {
3341                   fRelativeScale += amptotal[k]*0.014*0.01;
3342                   fCountRelativeScale++;
3343                 }
3344               }
3345             }
3346             
3347             // We fill the CH2d after having scale with the first 100
3348             if ((fCountRelativeScale >= 100) && (fRelativeScaleAuto)) {
3349               // Case of
3350               for (Int_t k = 0; k < fNfragZ[0]*fNfragRphi[0]; k++) {
3351                 if (fHisto2d && 
3352                     (amptotal[k] > 0.0)) {
3353                   fCH2d->Fill(fXbins[0]+k+0.5,amptotal[k]/fRelativeScale);
3354                 }
3355                 if (fVector2d && 
3356                     (amptotal[k] > 0.0)) {
3357                   UpdateVectorCH(fXbins[0]+k ,amptotal[k]/fRelativeScale);
3358                 }
3359               }
3360             }
3361
3362             // No relative salce
3363             if (!fRelativeScaleAuto) {
3364               for (Int_t k = 0; k < fNfragZ[0]*fNfragRphi[0]; k++) {
3365                 if (fHisto2d && 
3366                     (amptotal[k] > 0.0)) {
3367                   fCH2d->Fill(fXbins[0]+k+0.5, amptotal[k]/fRelativeScale); 
3368                 }
3369                 if (fVector2d && 
3370                     (amptotal[k] > 0.0)) {
3371                   UpdateVectorCH(fXbins[0]+k, amptotal[k]/fRelativeScale);
3372                 }
3373               }
3374             }
3375
3376           }
3377
3378           delete amptotal;        
3379           
3380         } // Boucle chamber
3381       } // Boucle plane
3382     } // Boucle sect
3383     
3384     loader->UnloadDigits();  
3385     
3386   } // Boucle event
3387   
3388   if (fDebug == 1) {
3389     if (fPH2dOn && fHisto2d) {
3390       PlotPH2d();
3391     }
3392     if (fCH2dOn && fHisto2d) {
3393       PlotCH2d();
3394     }  
3395   }
3396   
3397   if (fWrite[0] || fWrite[1]) {
3398
3399     TFile *fout = TFile::Open(fWriteName,"RECREATE");
3400     // Check if the file could be opened
3401     if (!fout || !fout->IsOpen()) {
3402       AliInfo("<No File found!");
3403       return kFALSE;
3404     }
3405
3406     if (fCH2dOn && fHisto2d && fWrite[0]) {
3407       fout->WriteTObject(fCH2d);
3408     }
3409     if (fPH2dOn && fHisto2d && fWrite[1]) {
3410       fout->WriteTObject(fPH2d);
3411     }
3412
3413     if (fVector2d && fCH2dOn && fWrite[0]) {
3414       TString name("Nz");
3415       name += fNz[0];
3416       name += "Nrphi";
3417       name += fNrphi[0];
3418       TTree *treeCH2d = ConvertVectorCTTreeHisto(fVectorCH,fPlaCH,"treeCH2d",(const char *) name);
3419       fout->WriteTObject(treeCH2d);
3420     }
3421
3422     if (fVector2d && fPH2dOn && fWrite[1]) {
3423       TString name("Nz");
3424       name += fNz[1];
3425       name += "Nrphi";
3426       name += fNrphi[1];
3427       TTree *treePH2d = ConvertVectorPTreeHisto(fVectorPH,fPlaPH,"treePH2d",(const char *) name);
3428       fout->WriteTObject(treePH2d);
3429     }
3430
3431     fout->Close();
3432
3433   }
3434  
3435   return kTRUE;
3436
3437 }
3438
3439 //____________Function fill 2D all objects from Raw Data_______________________
3440 Bool_t AliTRDCalibra::Create2DRaDaOnline(Int_t iev1, Int_t iev2)
3441 {
3442   //
3443   // After having written the RAW DATA in the current directory, create the
3444   // 2D histos from these RAW DATA  
3445   // Only for CH and PH
3446   //
3447   
3448   const Int_t kNplan = 6;
3449   const Int_t kNcham = 5;
3450   TString dirname(".");
3451   
3452   // DB Setting
3453   AliCDBManager *man = AliCDBManager::Instance();
3454   if (!man) {
3455     AliInfo("Could not get CDB Manager");
3456     return kFALSE;
3457   }
3458
3459   // Get the parameter object
3460   AliTRDCommonParam *parCom = AliTRDCommonParam::Instance();
3461   if (!parCom) {
3462     AliInfo("Could not get CommonParam");
3463     return kFALSE;
3464   }
3465
3466   AliTRDcalibDB     *cal    = AliTRDcalibDB::Instance();
3467   if (!cal) {
3468     AliInfo("Could not get calibDB");
3469     return kFALSE;
3470   }
3471
3472   // Some parameters
3473   fTimeMax = cal->GetNumberOfTimeBins();
3474   fSf      = (Float_t) parCom->GetSamplingFrequency();
3475   if (fRelativeScaleAuto) {
3476     fRelativeScale = 0;
3477   }
3478   else {
3479     if (fRelativeScale <= 0.0) {
3480       AliInfo("You have to set the relativescale factor per hand!");
3481       return kFALSE;
3482     }
3483   }
3484
3485   // Create the 2D histo corresponding to the pad group calibration mode
3486   if (fCH2dOn) {
3487
3488     AliInfo(Form("We will fill the CH2d histo with the pad calibration mode: Nz %d, and Nrphi %d"
3489                 ,fNz[0]
3490                 ,fNrphi[0]));
3491     
3492     // Calcul the number of Xbins
3493     fNtotal[0]    = 0;
3494     ModePadCalibration(2,0);
3495     ModePadFragmentation(0,2,0,0);
3496     fDetChamb2[0] = fNfragZ[0] * fNfragRphi[0];
3497     fNtotal[0]   += 6 * 18 * fDetChamb2[0];
3498     ModePadCalibration(0,0);
3499     ModePadFragmentation(0,0,0,0);
3500     fDetChamb0[0] = fNfragZ[0] * fNfragRphi[0];
3501     fNtotal[0]   += 6 * 4 * 18 * fDetChamb0[0];
3502     AliInfo(Form("Total number of Xbins: %d",fNtotal[0]));
3503     
3504     // Create the 2D histo
3505     if (fHisto2d) {
3506       CreateCH2d(fNtotal[0]);
3507     }
3508     if (fVector2d) {
3509       fVectorCH = new TObjArray();
3510       fPlaCH    = new TObjArray();
3511     }
3512
3513   }
3514   
3515   if(fPH2dOn) {
3516
3517     AliInfo(Form("We will fill the PH2d histo with the pad calibration mode: Nz %d, and Nrphi %d"
3518                 ,fNz[1]
3519                 ,fNrphi[1]));
3520     
3521     // Calcul the number of Xbins
3522     fNtotal[1]    = 0;
3523     ModePadCalibration(2,1);
3524     ModePadFragmentation(0,2,0,1);
3525     fDetChamb2[1] = fNfragZ[1] * fNfragRphi[1];
3526     fNtotal[1]   += 6 * 18 * fDetChamb2[1];
3527     ModePadCalibration(0,1);
3528     ModePadFragmentation(0,0,0,1);
3529     fDetChamb0[1] = fNfragZ[1] * fNfragRphi[1];
3530     fNtotal[1]   += 6 * 4 * 18 * fDetChamb0[1];
3531     AliInfo(Form("Total number of Xbins: %d",fNtotal[1]));
3532
3533     // Create the 2D histo
3534     if (fHisto2d) {
3535       CreatePH2d(fNtotal[1]);
3536     }
3537     if (fVector2d){
3538       fVectorPH = new TObjArray();
3539       fPlaPH    = new TObjArray();
3540     }
3541
3542   }
3543    
3544   AliTRDrawData *rawdata = new AliTRDrawData();
3545   AliInfo("AliTRDrawData object created ");
3546   
3547   // Loop on events
3548   for (Int_t ievent = iev1; ievent < iev2; ievent++) {
3549    
3550     // AliRawReaderFile
3551     AliRawReaderFile *readerfile = new AliRawReaderFile(dirname,ievent);
3552     if (!readerfile) {
3553       AliInfo("No readerfile found!");
3554       return kFALSE;
3555     }
3556  
3557     AliTRDdigitsManager *digitsManager = rawdata->Raw2Digits((AliRawReader *) readerfile);
3558     if (!digitsManager) {
3559       AliInfo("No DigitsManager done!");
3560       return kFALSE;
3561     }
3562  
3563     // Loop on detectors
3564     for (Int_t iSect = 0; iSect < 18; iSect++) {
3565       for (Int_t iPlane = 0; iPlane < kNplan; iPlane++) {
3566         for (Int_t iChamb = 0; iChamb < kNcham; iChamb++) {
3567           
3568           // A little geometry:
3569           Int_t iDet   = AliTRDgeometry::GetDetector(iPlane,iChamb,iSect);
3570           Int_t rowMax = parCom->GetRowMax(iPlane,iChamb,iSect);
3571           Int_t colMax = parCom->GetColMax(iPlane);
3572
3573           // Variables for the group
3574           LocalisationDetectorXbins(iDet);
3575         
3576           // In the cas of charge
3577           Float_t *amptotal;
3578           amptotal = new Float_t[fNfragRphi[0]*fNfragZ[0]];
3579           if(fCH2dOn) {
3580             for (Int_t k = 0; k < fNfragRphi[0]*fNfragZ[0]; k++) {
3581               amptotal[k] = 0.0;
3582             }
3583           }
3584
3585           // Loop through the detector pixel
3586           for (Int_t time = 0; time < fTimeMax; time++) {
3587             for (Int_t  col = 0;  col <  colMax;  col++) {
3588               for (Int_t  row = 0;  row <  rowMax;  row++) {
3589
3590                 // Amplitude and position of the digit
3591                 AliTRDdigit *digit   = digitsManager->GetDigit(row,col,time,iDet);
3592                 Int_t        amp     = digit->GetAmp();
3593                 Int_t        posr[2] = { 0, 0 };
3594                 Int_t        posc[2] = { 0, 0 };
3595                 if ((fCH2dOn) && 
3596                     (fNnZ[0]    != 0)) {
3597                   posr[0] = (Int_t) row / fNnZ[0];
3598                 }
3599                 if ((fCH2dOn) && 
3600                     (fNnRphi[0] != 0)) {
3601                   posc[0] = (Int_t) col / fNnRphi[0];
3602                 }
3603                 if ((fPH2dOn) && 
3604                     (fNnZ[1]    != 0)) {
3605                   posr[1] = (Int_t) row / fNnZ[1];
3606                 }
3607                 if ((fPH2dOn) && 
3608                     (fNnRphi[1] != 0)) {
3609                   posc[1] = (Int_t) col / fNnRphi[1];
3610                 }
3611                 
3612                 // Total spectrum
3613                 if (fCH2dOn) {
3614                   if (amp < fThresholdDigit) {
3615                     amp = 0;
3616                   }
3617                   amptotal[(Int_t) (posc[0]*fNfragZ[0]+posr[0])] += amp;
3618                 }
3619
3620                 if (fPH2dOn ) {
3621                   if (fHisto2d) {
3622                     fPH2d->Fill((fXbins[1]+posc[1]*fNfragZ[1]+posr[1])+0.5,(Float_t)time/fSf,amp);
3623                   }
3624                   if (fVector2d) {
3625                     UpdateVectorPH(fXbins[1]+posc[1]*fNfragZ[1]+posr[1],time,amp);
3626                   }
3627                 }
3628
3629                 delete digit;
3630
3631               } // Boucle row
3632             } // Boucle col
3633           } // Boucle time
3634
3635           if (fCH2dOn) {
3636
3637             // If automatic scale
3638             if ((fCountRelativeScale < 100) && (fRelativeScaleAuto)) {
3639               // Take only the one zone track
3640               for (Int_t k = 0; k < fNfragZ[0]*fNfragRphi[0]; k++) {
3641                 if ((fCountRelativeScale < 100) && (amptotal[k] > 2.0)) {
3642                   fRelativeScale += amptotal[k] * 0.014 * 0.01;
3643                   fCountRelativeScale++;
3644                 }
3645               }
3646             }
3647             
3648             // We fill the CH2d after having scale with the first 100
3649             if ((fCountRelativeScale >= 100) && (fRelativeScaleAuto)) {
3650               // Case of
3651               for (Int_t k = 0; k < fNfragZ[0]*fNfragRphi[0]; k++) {
3652                 if (fHisto2d  && (amptotal[k] > 0.0)) {
3653                   fCH2d->Fill(fXbins[0]+k+0.5,amptotal[k]/fRelativeScale);
3654                 }
3655                 if (fVector2d && (amptotal[k] > 0.0)) {
3656                   UpdateVectorCH(fXbins[0]+k, amptotal[k]/fRelativeScale);
3657                 }
3658               }
3659             }
3660
3661             // No relative salce
3662             if (!fRelativeScaleAuto) {
3663               for (Int_t k = 0; k < fNfragZ[0]*fNfragRphi[0]; k++) {
3664                 if (fHisto2d  && 
3665                     (amptotal[k] > 0.0)) {
3666                   fCH2d->Fill(fXbins[0]+k+0.5,amptotal[k]/fRelativeScale); 
3667                 }
3668                 if (fVector2d && 
3669                     (amptotal[k] > 0.0)) {
3670                   UpdateVectorCH(fXbins[0]+k, amptotal[k]/fRelativeScale);
3671                 }
3672               }
3673             }
3674
3675           }
3676          
3677           delete amptotal;
3678           
3679         } // Boucle chamber
3680       } // Boucle plane
3681     } // Boucle sect
3682   
3683     delete digitsManager;
3684     delete readerfile;
3685
3686   } // Boucle event
3687   
3688   if (fDebug == 1) {
3689     if (fPH2dOn && fHisto2d) {
3690       PlotPH2d();
3691     }
3692     if (fCH2dOn && fHisto2d) {
3693       PlotCH2d();
3694     }
3695   }
3696
3697   if (fWrite[0] || fWrite[1]) {
3698     
3699     TFile *fout = TFile::Open(fWriteName,"UPDATE");
3700     // Check if the file could be opened
3701     if (!fout || !fout->IsOpen()) {
3702       AliInfo("<No File found!");
3703       return kFALSE;
3704     }
3705
3706     if (fCH2dOn && fHisto2d && fWrite[0]) {
3707       fout->WriteTObject(fCH2d);
3708     }
3709     if (fPH2dOn && fHisto2d && fWrite[1]) {
3710       fout->WriteTObject(fPH2d);
3711     }
3712
3713     if (fVector2d && fCH2dOn && fWrite[0]) {
3714       TString name("Nz");
3715       name += fNz[0];
3716       name += "Nrphi";
3717       name += fNrphi[0];
3718       TTree *treeCH2d = ConvertVectorCTTreeHisto(fVectorCH,fPlaCH,"treeCH2d",(const Char_t *) name);
3719       fout->WriteTObject(treeCH2d);
3720     }
3721
3722     if (fVector2d && fPH2dOn && fWrite[1]) {
3723       TString name("Nz");
3724       name += fNz[1];
3725       name += "Nrphi";
3726       name += fNrphi[1];
3727       TTree *treePH2d = ConvertVectorPTreeHisto(fVectorPH,fPlaPH,"treePH2d",(const Char_t *) name);
3728       fout->WriteTObject(treePH2d);
3729     }
3730   
3731   }
3732   
3733   return kTRUE;
3734
3735 }
3736
3737 //____________Pad Calibration Public___________________________________________
3738
3739 //____________Define the number of pads per group for one detector and one calibration
3740 void AliTRDCalibra::ModePadCalibration(Int_t iChamb, Int_t i)
3741 {
3742   //
3743   // Definition of the calibration mode
3744   // from Nz and Nrphi, the number of row and col pads per calibration groups are setted
3745   //
3746
3747
3748   fNnZ[i]    = 0;
3749   fNnRphi[i] = 0;
3750   
3751   if ((fNz[i] == 0) && (iChamb == 2)) {
3752     fNnZ[i] = 12;
3753   }
3754   if ((fNz[i] == 0) && (iChamb != 2)) {
3755     fNnZ[i] = 16;
3756   }  
3757   if ((fNz[i] == 1) && (iChamb == 2)) {
3758     fNnZ[i] = 6;
3759   }
3760   if ((fNz[i] == 1) && (iChamb != 2)) {
3761     fNnZ[i] = 8;
3762   }
3763   if ((fNz[i] == 2) && (iChamb == 2)) {
3764     fNnZ[i] = 3;
3765   }
3766   if ((fNz[i] == 2) && (iChamb != 2)) {
3767     fNnZ[i] = 4;
3768   }
3769   if (fNz[i] == 3) {
3770     fNnZ[i] = 2;
3771   }
3772   if (fNz[i] == 4) {
3773     fNnZ[i] = 1;
3774   }
3775    
3776   if (fNrphi[i] == 0) {
3777     fNnRphi[i] = 144;
3778   }
3779   if (fNrphi[i] == 1) {
3780     fNnRphi[i] = 72;
3781   } 
3782   if (fNrphi[i] == 2) {
3783     fNnRphi[i] = 36;
3784   } 
3785   if (fNrphi[i] == 3) {
3786     fNnRphi[i] = 18;
3787   } 
3788   if (fNrphi[i] == 4) {
3789     fNnRphi[i] = 9;
3790   } 
3791   if (fNrphi[i] == 5) {
3792     fNnRphi[i] = 4;
3793   } 
3794   if (fNrphi[i] == 6) {
3795     fNnRphi[i] = 1;
3796   } 
3797
3798 }
3799
3800 //____________Define the number of pad groups in one detector for one calibration
3801 Bool_t AliTRDCalibra::ModePadFragmentation(Int_t iPlane,Int_t iChamb, Int_t iSect, Int_t i)
3802 {
3803   //
3804   // Definition of the calibration mode
3805   // From the number of row and col pads per calibration groups the
3806   // number of calibration groups are setted
3807   //
3808
3809   fNfragZ[i]    = 0;
3810   fNfragRphi[i] = 0;
3811   
3812   AliTRDCommonParam *parCom = AliTRDCommonParam::Instance();
3813   if (!parCom) {
3814     AliInfo("Could not get CommonParam Manager");
3815     return kFALSE;
3816   }
3817
3818   // A little geometry:
3819   Int_t rowMax = parCom->GetRowMax(iPlane,iChamb,iSect);
3820   Int_t colMax = parCom->GetColMax(iPlane);
3821   
3822   // The fragmentation
3823   if (fNnZ[i]    != 0) {
3824     fNfragZ[i]    = (Int_t) rowMax / fNnZ[i];
3825   }
3826
3827   if (fNnRphi[i] != 0) {
3828     fNfragRphi[i] = (Int_t) colMax / fNnRphi[i];
3829   }
3830
3831   return kTRUE;
3832
3833 }
3834
3835 //____________Protected Functions______________________________________________
3836 //____________Create the 2D histo to be filled online__________________________
3837 //
3838
3839 //_____________________________________________________________________________
3840 void AliTRDCalibra::CreatePRF2d(Int_t nn)
3841 {
3842   //
3843   // Create the 2D histos
3844   //
3845
3846   TString name("Nz");
3847   name += fNz[2];
3848   name += "Nrphi";
3849   name += fNrphi[2];
3850
3851   fPRF2d = new TProfile2D("PRF2d",(const Char_t *) name
3852                                  ,nn,0,nn,fNumberBinPRF,-1.0,1.0);
3853   fPRF2d->SetXTitle("Det/pad groups");
3854   fPRF2d->SetYTitle("Position x/W [pad width units]");
3855   fPRF2d->SetZTitle("Q_{i}/Q_{total}");
3856   fPRF2d->SetStats(0);
3857
3858 }
3859
3860 //_____________________________________________________________________________
3861 void AliTRDCalibra::CreatePH2d(Int_t nn)
3862 {
3863   //
3864   // Create the 2D histos
3865   //
3866
3867   TString name("Nz");
3868   name += fNz[1];
3869   name += "Nrphi";
3870   name += fNrphi[1];
3871
3872   fPH2d = new TProfile2D("PH2d",(const Char_t *) name
3873                                ,nn,0,nn,fTimeMax
3874                                ,-0.5/fSf,(Float_t) (fTimeMax-0.5)/fSf);
3875   fPH2d->SetXTitle("Det/pad groups");
3876   fPH2d->SetYTitle("time [#mus]");
3877   fPH2d->SetZTitle("<PH> [a.u.]");
3878   fPH2d->SetStats(0);
3879
3880 }
3881
3882 //_____________________________________________________________________________
3883 void AliTRDCalibra::CreateCH2d(Int_t nn)
3884 {
3885   //
3886   // Create the 2D histos
3887   //
3888
3889   TString name("Nz");
3890   name += fNz[0];
3891   name += "Nrphi";
3892   name += fNrphi[0];
3893
3894   fCH2d = new TH2I("CH2d",(const Char_t *) name
3895                          ,nn,0,nn,fNumberBinCharge,0,300);
3896   fCH2d->SetXTitle("Det/pad groups");
3897   fCH2d->SetYTitle("charge deposit [a.u]");
3898   fCH2d->SetZTitle("counts");
3899   fCH2d->SetStats(0);
3900   fCH2d->Sumw2();
3901
3902 }
3903
3904 //____________Offine tracking in the AliTRDtracker_____________________________
3905 void AliTRDCalibra::FillTheInfoOfTheTrackCH()
3906 {
3907   //
3908   // For the offline tracking or mcm tracklets
3909   // This function will be called in the functions UpdateHistogram... 
3910   // to fill the info of a track for the relativ gain calibration
3911   //
3912         
3913   Int_t nb =  0; // Nombre de zones traversees
3914   Int_t fd = -1; // Premiere zone non nulle
3915   
3916   
3917   // See if the track goes through different zones
3918   for (Int_t k = 0; k < fNfragZ[0]*fNfragRphi[0]; k++) {
3919     if (fAmpTotal[k] > 0.0) {
3920       nb++;
3921       if (nb == 1) {
3922         fd = k;
3923       }
3924     }
3925   }
3926  
3927   // If automatic scale
3928   if ((fCountRelativeScale < 100) && (fRelativeScaleAuto)) {
3929     // Take only the one zone track
3930     if (nb == 1) {
3931       fRelativeScale += fAmpTotal[fd] * 0.014 * 0.01;
3932       fCountRelativeScale++;
3933     }
3934   }
3935
3936   // We fill the CH2d after having scale with the first 100
3937   if ((fCountRelativeScale >= 100) && (fRelativeScaleAuto)) {
3938     // Case of track with only one zone
3939     if (nb == 1) {
3940       if (fHisto2d) {
3941         fCH2d->Fill(fXbins[0]+fd+0.5,fAmpTotal[fd]/fRelativeScale);
3942       }
3943       if (fVector2d) {
3944         UpdateVectorCH(fXbins[0]+fd,fAmpTotal[fd]/fRelativeScale);
3945       }
3946     } // Case 1 zone
3947     // Case of track with two zones
3948     if (nb == 2) {
3949       // Two zones voisines sinon rien!
3950       if ((fAmpTotal[fd]   > 0.0) && 
3951           (fAmpTotal[fd+1] > 0.0)) {
3952         // One of the two very big
3953         if (fAmpTotal[fd] > fProcent*fAmpTotal[fd+1]) {
3954           if (fHisto2d) {
3955             fCH2d->Fill(fXbins[0]+fd+0.5,fAmpTotal[fd]/fRelativeScale);
3956           }
3957           if (fVector2d) {
3958             UpdateVectorCH(fXbins[0]+fd,fAmpTotal[fd]/fRelativeScale);
3959           }
3960         }
3961         if (fAmpTotal[fd+1] > fProcent*fAmpTotal[fd])  {
3962           if (fHisto2d) {
3963             fCH2d->Fill(fXbins[0]+fd+1.5,fAmpTotal[fd+1]/fRelativeScale);
3964           }
3965           if (fVector2d) {
3966             UpdateVectorCH(fXbins[0]+fd,fAmpTotal[fd+1]/fRelativeScale);
3967           }
3968         }
3969       }
3970     } // Case 2 zones
3971   }
3972
3973   // Fill with no automatic scale
3974   if (!fRelativeScaleAuto) {
3975     // Case of track with only one zone
3976     if (nb == 1) {
3977       fNumberUsedCh[0]++;
3978       if (fHisto2d) {
3979         fCH2d->Fill(fXbins[0]+fd+0.5,fAmpTotal[fd]/fRelativeScale);
3980       }
3981       if (fVector2d) {
3982         UpdateVectorCH(fXbins[0]+fd,fAmpTotal[fd]/fRelativeScale);
3983       }
3984     } // Case 1 zone
3985     // Case of track with two zones
3986     if (nb == 2) {
3987       // Two zones voisines sinon rien!
3988       // Case 1
3989       if ((fAmpTotal[fd]   > 0.0) && 
3990           (fAmpTotal[fd+1] > 0.0)) {
3991         // One of the two very big
3992         if (fAmpTotal[fd] > fProcent*fAmpTotal[fd+1]) {
3993           if (fHisto2d) {
3994             fCH2d->Fill(fXbins[0]+fd+0.5,fAmpTotal[fd]/fRelativeScale);
3995           }
3996           if (fVector2d) {
3997             UpdateVectorCH(fXbins[0]+fd,fAmpTotal[fd]/fRelativeScale);
3998           }
3999           fNumberUsedCh[1]++;
4000         }
4001         if (fAmpTotal[fd+1] > fProcent*fAmpTotal[fd]) {
4002           if (fHisto2d) {
4003             fCH2d->Fill(fXbins[0]+fd+1.5,fAmpTotal[fd+1]/fRelativeScale);
4004           }
4005           if (fVector2d) {
4006             UpdateVectorCH(fXbins[0]+fd+1,fAmpTotal[fd+1]/fRelativeScale);
4007           }
4008           fNumberUsedCh[1]++;
4009         }
4010       }
4011       // Case 2
4012       if (fNfragZ[0] > 1) {
4013         if (fAmpTotal[fd] > 0.0) {
4014           if ((fd+fNfragZ[0]) < (fNfragZ[0]*fNfragRphi[0])) {
4015             if (fAmpTotal[fd+fNfragZ[0]] > 0.0) {
4016               // One of the two very big
4017               if (fAmpTotal[fd] > fProcent*fAmpTotal[fd+fNfragZ[0]]) {
4018                 if (fHisto2d) {
4019                   fCH2d->Fill(fXbins[0]+fd+0.5,fAmpTotal[fd]/fRelativeScale);
4020                 }
4021                 if (fVector2d) {
4022                   UpdateVectorCH(fXbins[0]+fd,fAmpTotal[fd]/fRelativeScale);
4023                 }
4024                 fNumberUsedCh[1]++;
4025               }
4026               if (fAmpTotal[fd+fNfragZ[0]] > fProcent*fAmpTotal[fd]) {
4027                 if (fHisto2d) {
4028                   fCH2d->Fill(fXbins[0]+fd+fNfragZ[0]+0.5,fAmpTotal[fd+fNfragZ[0]]/fRelativeScale);
4029                 }
4030                 fNumberUsedCh[1]++;
4031                 if (fVector2d) {
4032                   UpdateVectorCH(fXbins[0]+fd+fNfragZ[0],fAmpTotal[fd+fNfragZ[0]]/fRelativeScale);
4033                 }
4034               }
4035             }
4036           }
4037         }
4038       }
4039     } // Case 2 zones
4040
4041   }
4042
4043 }
4044
4045 //____________Offine tracking in the AliTRDtracker_____________________________
4046 void AliTRDCalibra::ResetfVariables()
4047 {
4048   //
4049   // Reset values of fAmpTotal, fPHValue and fPHPlace for
4050   // the updateHistogram... functions
4051   //
4052
4053   // Reset the good track
4054   fGoodTrack = kTRUE;
4055   
4056   // Reset the fAmpTotal where we put value
4057   if (fCH2dOn) {
4058     for (Int_t k = 0; k < fNfragZ[0]*fNfragRphi[0]; k++) {
4059       fAmpTotal[k] = 0.0;
4060     }
4061   }
4062   
4063   // Reset the fPHValue
4064   if (fPH2dOn) {
4065     for (Int_t k = 0; k < fTimeMax; k++) {
4066       fPHValue[k] = -1.0;
4067       fPHPlace[k] = -1;
4068     }
4069   }
4070
4071 }
4072
4073 //____________Offine tracking in the AliTRDtracker_____________________________
4074 void AliTRDCalibra::FillTheInfoOfTheTrackPH()
4075 {
4076   //
4077   // For the offline tracking or mcm tracklets
4078   // This function will be called in the functions UpdateHistogram... 
4079   // to fill the info of a track for the drift velocity  calibration
4080   //
4081     
4082   Int_t nb  =  1; // Nombre de zones traversees 1, 2 ou plus de 3
4083   Int_t fd1 = -1; // Premiere zone non nulle
4084   Int_t fd2 = -1; // Deuxieme zone non nulle
4085   Int_t k1  = -1; // Debut de la premiere zone
4086   Int_t k2  = -1; // Debut de la seconde zone
4087
4088   // See if the track goes through different zones
4089   for (Int_t k = 0; k < fTimeMax; k++) {
4090     if (fPHValue[k] > 0.0) {
4091       if (fd1 == -1) {
4092         fd1 = fPHPlace[k];
4093         k1  = k;              
4094       }
4095       if (fPHPlace[k] != fd1) {
4096         if (fd2 == -1) {
4097           k2  = k;
4098           fd2 = fPHPlace[k];
4099           nb  = 2;
4100         }
4101         if (fPHPlace[k] != fd2) {
4102           nb = 3;
4103         }
4104       }
4105     }
4106   }
4107   
4108   // Fill 
4109   // Case of track with only one zone
4110   if (nb == 1) {
4111     fNumberUsedPh[0]++;
4112     for (Int_t i = 0; i < fTimeMax; i++) {
4113       if (fPHValue[i] > 0.0) {
4114         if (fHisto2d) {
4115           fPH2d->Fill((fXbins[1]+fPHPlace[i])+0.5,(Float_t) i/fSf,(Float_t) fPHValue[i]);
4116         }
4117         if (fDebug == 13) {
4118           AliInfo(Form("WRITE nb %d ,place final: %d, fPHPlace[i]: %d, i: %d, fPHValue[i]: %f"
4119                       ,nb,fXbins[1]+fPHPlace[i],fPHPlace[i],i,fPHValue[i]));
4120         }
4121         if (fVector2d) {
4122           UpdateVectorPH(fXbins[1]+fPHPlace[i],i,fPHValue[i]);
4123         }
4124       }
4125     }
4126   } // Case 1 zone
4127   // Case of track with two zones
4128   if (nb == 2) {
4129     // Two zones voisines sinon rien!
4130     // Case 1
4131     if ((fd1 == fd2+1) || 
4132         (fd2 == fd1+1)) {
4133       // One of the two fast all the think
4134       if (k2 > (k1+fDifference)) {
4135         fNumberUsedPh[1]++;
4136         for (Int_t i = k1; i < k2; i++) {
4137           if (fPHValue[i] > 0.0) {
4138             if (fHisto2d) {
4139               fPH2d->Fill((fXbins[1]+fPHPlace[i])+0.5,(Float_t) i/fSf,(Float_t) fPHValue[i]);
4140             }
4141             if (fVector2d) {
4142               UpdateVectorPH(fXbins[1]+fPHPlace[i],i,fPHValue[i]);
4143             }
4144           }
4145         }
4146       }
4147       if ((k2+fDifference) < fTimeMax) {
4148         fNumberUsedPh[1]++;
4149         for (Int_t i = k2; i < fTimeMax; i++) {
4150           if (fPHValue[i] > 0.0) {
4151             if (fHisto2d) {
4152               fPH2d->Fill((fXbins[1]+fPHPlace[i])+0.5,(Float_t) i/fSf,(Float_t) fPHValue[i]);
4153             }
4154             if (fVector2d) {
4155               UpdateVectorPH(fXbins[1]+fPHPlace[i],i,fPHValue[i]);
4156             }
4157           }
4158         }
4159       }
4160     }
4161     // Two zones voisines sinon rien!
4162     if (fNfragZ[1] > 1) {
4163       // Case 2
4164       if ((fd1+fNfragZ[1]) < (fNfragZ[1]*fNfragRphi[1])) {
4165         if (fd2 == (fd1+fNfragZ[1])) {
4166           // One of the two fast all the think
4167           if (k2 > (k1+fDifference)) {
4168             fNumberUsedPh[1]++;
4169             for (Int_t i = k1; i < k2; i++) {
4170               if (fPHValue[i] > 0.0) {
4171                 if (fHisto2d) {
4172                   fPH2d->Fill((fXbins[1]+fPHPlace[i])+0.5,(Float_t) i/fSf,(Float_t) fPHValue[i]);
4173                 }
4174                 if (fVector2d) {
4175                   UpdateVectorPH(fXbins[1]+fPHPlace[i],i,fPHValue[i]);
4176                 }
4177               }
4178             }
4179           }
4180           if ((k2+fDifference) < fTimeMax) {
4181             fNumberUsedPh[1]++;
4182             for (Int_t i = k2; i < fTimeMax; i++) {
4183               if (fPHValue[i] > 0.0) {
4184                 if (fHisto2d) {
4185                   fPH2d->Fill((fXbins[1]+fPHPlace[i])+0.5,(Float_t) i/fSf,(Float_t) fPHValue[i]);
4186                 }
4187                 if (fVector2d) {
4188                   UpdateVectorPH(fXbins[1]+fPHPlace[i],i,fPHValue[i]);
4189                 }
4190               }
4191             }
4192           }
4193         }
4194       }
4195       // Two zones voisines sinon rien!
4196       // Case 3
4197       if ((fd1 - fNfragZ[1]) >= 0) {
4198         if (fd2 == (fd1 - fNfragZ[1])) {
4199           // One of the two fast all the think
4200           if (k2 > (k1 + fDifference)) {
4201             fNumberUsedPh[1]++;
4202             for (Int_t i = k1; i < k2; i++) {
4203               if (fPHValue[i] > 0.0) {
4204                 if (fHisto2d) {
4205                   fPH2d->Fill((fXbins[1]+fPHPlace[i])+0.5,(Float_t) i/fSf,(Float_t) fPHValue[i]);
4206                 }
4207                 if (fVector2d) {
4208                   UpdateVectorPH(fXbins[1]+fPHPlace[i],i,fPHValue[i]);
4209                 }
4210               }
4211             }
4212           }
4213           if ((k2+fDifference) < fTimeMax) {
4214             fNumberUsedPh[1]++;
4215             for (Int_t i = k2; i < fTimeMax; i++) {
4216               if (fPHValue[i] > 0.0) {
4217                 if (fHisto2d) {
4218                   fPH2d->Fill((fXbins[1]+fPHPlace[i])+0.5,(Float_t) i/fSf,(Float_t) fPHValue[i]);
4219                 }
4220                 if (fVector2d) {
4221                   UpdateVectorPH(fXbins[1]+fPHPlace[i],i,fPHValue[i]);
4222                 }
4223               }
4224             }
4225           }
4226         }
4227       }
4228     }
4229
4230   } // case 2 zones
4231
4232 }
4233
4234 //____________Set the pad calibration variables for the detector_______________
4235 Bool_t AliTRDCalibra::LocalisationDetectorXbins(Int_t detector)
4236 {
4237   //
4238   // For the detector calcul the first Xbins and set the number of row
4239   // and col pads per calibration groups, the number of calibration
4240   // groups in the detector.
4241   //
4242   
4243   // first Xbins of the detector
4244   if (fCH2dOn) {
4245     CalculXBins(detector,0);
4246   }
4247   if (fPH2dOn) {
4248     CalculXBins(detector,1);
4249   }
4250   if (fPRF2dOn) {
4251     CalculXBins(detector,2);
4252   }
4253
4254   // fragmentation of idect
4255   for (Int_t i = 0; i < 3; i++) {
4256     ModePadCalibration((Int_t) GetChamber(detector),i);
4257     ModePadFragmentation((Int_t) GetPlane(detector)
4258                        , (Int_t) GetChamber(detector)
4259                        , (Int_t) GetSector(detector),i);
4260   }
4261   
4262   return kTRUE;
4263
4264 }
4265
4266 //____________Plot the 2D histos filled Online_________________________________
4267
4268 //_____________________________________________________________________________
4269 void AliTRDCalibra::PlotPH2d()
4270 {
4271   //
4272   // Plot the 2D histo 
4273   //
4274
4275   TCanvas *cph2d = new TCanvas("cph2d","",50,50,600,800);
4276   cph2d->cd();
4277   fPH2d->Draw("LEGO");
4278
4279 }
4280
4281 //_____________________________________________________________________________
4282 void AliTRDCalibra::PlotCH2d()
4283 {
4284   //
4285   // Plot the 2D histos
4286   //
4287
4288   TCanvas *cch2d = new TCanvas("cch2d","",50,50,600,800);
4289   cch2d->cd();
4290   fCH2d->Draw("LEGO");
4291   
4292 }
4293
4294 //_____________________________________________________________________________
4295 void AliTRDCalibra::PlotPRF2d()
4296 {
4297   //
4298   // Plot the 2D histos
4299   //
4300
4301   TCanvas *cPRF2d = new TCanvas("cPRF2d","",50,50,600,800);
4302   cPRF2d->cd();
4303   fPRF2d->Draw("LEGO");
4304       
4305 }
4306
4307 //____________Fit______________________________________________________________
4308
4309 //____________Create histos if fDebug == 1 or fDebug >= 3______________________
4310
4311 //_____________________________________________________________________________
4312 void AliTRDCalibra::InitArrayFitPH()
4313 {
4314   //
4315   // Initialise fCoefVdrift[3] and fCoefVdriftE[2] to the right dimension
4316   //
4317   
4318   Int_t nbins = fDect2[1]-fDect1[1];
4319
4320   //Init the pointer to nbins
4321   fCoefVdrift[0] = new Double_t[nbins];
4322   fCoefVdrift[1] = new Double_t[nbins];
4323   fCoefVdrift[2] = new Double_t[nbins];
4324   
4325   fCoefVdriftE[0] = new Double_t[nbins];
4326   fCoefVdriftE[1] = new Double_t[nbins];
4327
4328   for(Int_t k = 0; k < nbins; k++){
4329     fCoefVdriftE[0][k] = 0.0;
4330     fCoefVdriftE[1][k] = 0.0;
4331   }
4332  
4333 }
4334
4335 //_____________________________________________________________________________
4336 void AliTRDCalibra::InitArrayFitT0()
4337 {
4338   //
4339   // Initialise fCoefT0[3] and fCoefT0E[2] to the right dimension
4340   //
4341   
4342   Int_t nbins = fDect2[1]-fDect1[1];
4343
4344   //Init the pointer to nbins
4345   fCoefT0[0] = new Double_t[nbins];
4346   fCoefT0[1] = new Double_t[nbins];
4347   fCoefT0[2] = new Double_t[nbins];
4348   
4349   fCoefT0E[0] = new Double_t[nbins];
4350   fCoefT0E[1] = new Double_t[nbins];
4351
4352   for(Int_t k = 0; k < nbins; k++){
4353     fCoefT0E[0][k] = 0.0;
4354     fCoefT0E[1][k] = 0.0;
4355   }
4356  
4357 }
4358
4359 //_____________________________________________________________________________
4360 void AliTRDCalibra::InitArrayFitCH()
4361 {
4362   //
4363   // Initialise fCoefCharge[4] and fCoefChargeE[3] to the right dimension
4364   //
4365
4366   Int_t nbins = fDect2[0]-fDect1[0];
4367
4368   //Init the pointer to nbins
4369   fCoefCharge[0] = new Double_t[nbins];
4370   fCoefCharge[1] = new Double_t[nbins];
4371   fCoefCharge[2] = new Double_t[nbins];
4372   fCoefCharge[3] = new Double_t[nbins];
4373
4374   fCoefChargeE[0] = new Double_t[nbins];
4375   fCoefChargeE[1] = new Double_t[nbins];
4376   fCoefChargeE[2] = new Double_t[nbins];
4377
4378   for(Int_t k = 0; k < nbins; k++){
4379     fCoefChargeE[0][k] = 0.0;
4380     fCoefChargeE[1][k] = 0.0;
4381     fCoefChargeE[2][k] = 0.0;
4382   }
4383
4384   
4385 }
4386
4387 //_____________________________________________________________________________
4388 void AliTRDCalibra::InitArrayFitPRF()
4389 {
4390   //
4391   // Initialise fCoefPRF[2] and fCoefPRFE to the right dimension
4392   //
4393
4394   Int_t nbins = fDect2[2]-fDect1[2];
4395
4396   //Init the pointer to nbins
4397   fCoefPRF[0] = new Double_t[nbins];
4398   fCoefPRF[1] = new Double_t[nbins];
4399   
4400   fCoefPRFE = new Double_t[nbins];
4401  
4402   for(Int_t k = 0; k < nbins; k++){
4403     fCoefPRFE[k] = 0.0;
4404   }
4405   
4406 }
4407
4408 //_____________________________________________________________________________
4409 void AliTRDCalibra::CreateFitHistoPRFDB(Int_t rowMax, Int_t colMax)
4410 {
4411   //
4412   // Create the histos for fDebug = 3 and fDebug = 4 (Fit functions)
4413   //
4414
4415   fCoefPRFDB = new TH2F("coefPRF","",rowMax,0,rowMax,colMax,0,colMax);
4416
4417   fCoefPRFDB->SetStats(0);
4418   fCoefPRFDB->SetXTitle("row Number");
4419   fCoefPRFDB->SetYTitle("col Number");
4420   fCoefPRFDB->SetZTitle("PRF width [pad width units]");
4421
4422   fCoefPRFDB->SetFillColor(6);
4423   fCoefPRFDB->SetLineColor(6);
4424
4425 }
4426
4427 //_____________________________________________________________________________
4428 void AliTRDCalibra::CreateFitHistoCHDB(Int_t rowMax, Int_t colMax)
4429 {
4430   //
4431   // Create the histos for fDebug = 3 and fDebug = 4 (Fit functions)
4432   //
4433
4434   fCoefChargeDB[0] = new TH2F("coefchargedb0","",rowMax,0,rowMax,colMax,0,colMax);
4435   fCoefChargeDB[1] = new TH2F("coefchargedb1","",rowMax,0,rowMax,colMax,0,colMax);
4436   fCoefChargeDB[2] = new TH2F("coefchargedb2","",rowMax,0,rowMax,colMax,0,colMax);
4437
4438   fCoefChargeDB[0]->SetStats(0);
4439   fCoefChargeDB[1]->SetStats(0);
4440   fCoefChargeDB[2]->SetStats(0);
4441   fCoefChargeDB[0]->SetXTitle("row Number");
4442   fCoefChargeDB[0]->SetYTitle("col Number");
4443   fCoefChargeDB[1]->SetXTitle("row Number");
4444   fCoefChargeDB[1]->SetYTitle("col Number");
4445   fCoefChargeDB[2]->SetXTitle("row Number");
4446   fCoefChargeDB[2]->SetYTitle("col Number");
4447   fCoefChargeDB[0]->SetZTitle("f_{g} Fit method");
4448   fCoefChargeDB[1]->SetZTitle("f_{g} Mean method");
4449   fCoefChargeDB[2]->SetZTitle("f_{g} Fitbis method");
4450
4451   fCoefChargeDB[0]->SetFillColor(6);
4452   fCoefChargeDB[0]->SetLineColor(6);
4453   fCoefChargeDB[0]->SetLineColor(6);
4454   fCoefChargeDB[1]->SetFillColor(2);
4455   fCoefChargeDB[1]->SetLineColor(2);
4456   fCoefChargeDB[1]->SetLineColor(2);
4457   fCoefChargeDB[2]->SetFillColor(8);
4458   fCoefChargeDB[2]->SetLineColor(8);
4459   fCoefChargeDB[2]->SetLineColor(8);
4460
4461 }
4462
4463 //_____________________________________________________________________________
4464 void AliTRDCalibra::CreateFitHistoPHDB(Int_t rowMax, Int_t colMax)
4465 {
4466   //
4467   // Create the histos for fDebug = 3 and fDebug = 4 (Fit functions)
4468   //
4469
4470   fCoefVdriftDB[0] = new TH2F("coefvdriftdb0","",rowMax,0,rowMax,colMax,0,colMax);
4471   fCoefVdriftDB[1] = new TH2F("coefvdriftdb1","",rowMax,0,rowMax,colMax,0,colMax);
4472   
4473   fCoefVdriftDB[0]->SetStats(0);
4474   fCoefVdriftDB[1]->SetStats(0);
4475   fCoefVdriftDB[0]->SetXTitle("row Number");
4476   fCoefVdriftDB[0]->SetYTitle("col Number");
4477   fCoefVdriftDB[1]->SetXTitle("row Number");
4478   fCoefVdriftDB[1]->SetYTitle("col Number");
4479   fCoefVdriftDB[0]->SetZTitle("v_{drift} Fit method");
4480   fCoefVdriftDB[1]->SetZTitle("v_{drift} slope method");
4481   
4482   fCoefVdriftDB[0]->SetFillColor(6);
4483   fCoefVdriftDB[0]->SetLineColor(6);
4484   fCoefVdriftDB[0]->SetLineColor(6);
4485   fCoefVdriftDB[1]->SetFillColor(2);
4486   fCoefVdriftDB[1]->SetLineColor(2);
4487   fCoefVdriftDB[1]->SetLineColor(2);
4488
4489 }
4490
4491 //_____________________________________________________________________________
4492 void AliTRDCalibra::CreateFitHistoT0DB(Int_t rowMax, Int_t colMax)
4493 {
4494   //
4495   // Create the histos for fDebug = 3 and fDebug = 4 (Fit functions)
4496   //
4497
4498   fCoefT0DB[0] = new TH2F("coefT0db0","",rowMax,0,rowMax,colMax,0,colMax);
4499   fCoefT0DB[1] = new TH2F("coefT0db1","",rowMax,0,rowMax,colMax,0,colMax);
4500   
4501   fCoefT0DB[0]->SetStats(0);
4502   fCoefT0DB[1]->SetStats(0);
4503   fCoefT0DB[0]->SetXTitle("row Number");
4504   fCoefT0DB[0]->SetYTitle("col Number");
4505   fCoefT0DB[1]->SetXTitle("row Number");
4506   fCoefT0DB[1]->SetYTitle("col Number");
4507   fCoefT0DB[0]->SetZTitle("t0 Fit method");
4508   fCoefT0DB[1]->SetZTitle("t0 slope method");
4509   
4510   fCoefT0DB[0]->SetFillColor(6);
4511   fCoefT0DB[0]->SetLineColor(6);
4512   fCoefT0DB[0]->SetLineColor(6);
4513   fCoefT0DB[1]->SetFillColor(2);
4514   fCoefT0DB[1]->SetLineColor(2);
4515   fCoefT0DB[1]->SetLineColor(2);
4516   
4517 }
4518
4519 //_____________________________________________________________________________
4520 Bool_t AliTRDCalibra::FillVectorFitCH(Int_t countdet)
4521 {
4522   //
4523   // For the Fit functions fill the vector FitCH special for the gain calibration
4524   //
4525
4526   AliTRDFitCHInfo *fitCHInfo = new AliTRDFitCHInfo();
4527
4528   Int_t ntotal = 1;
4529   if (GetChamber(countdet) == 2) {
4530     ntotal = 1728;
4531   }
4532   else {
4533     ntotal = 2304;
4534   }
4535
4536   Float_t *coef = new Float_t[ntotal];
4537   for (Int_t i = 0; i < ntotal; i++) {
4538     coef[i] = fCoefCH[i];
4539   }
4540
4541   Int_t detector = countdet;
4542   // Set
4543   fitCHInfo->SetCoef(coef);
4544   fitCHInfo->SetDetector(detector);
4545   fVectorFitCH->Add((TObject *) fitCHInfo);
4546
4547   return kTRUE;
4548
4549 }
4550
4551 //____________Functions for initialising the AliTRDCalibra in the code_________
4552 Bool_t AliTRDCalibra::InitFit(Int_t nbins, Int_t i)
4553 {
4554   //
4555   // Init the calibration mode (Nz, Nrphi), the histograms for
4556   // debugging the fit methods if fDebug > 0, 
4557   //
4558
4559   gStyle->SetPalette(1);
4560   gStyle->SetOptStat(1111);
4561   gStyle->SetPadBorderMode(0);
4562   gStyle->SetCanvasColor(10);
4563   gStyle->SetPadLeftMargin(0.13);
4564   gStyle->SetPadRightMargin(0.01);
4565
4566   // Get the parameter object
4567   AliTRDCommonParam *parCom = AliTRDCommonParam::Instance();
4568   if (!parCom) {
4569     AliInfo("Could not get CommonParam");
4570     return kFALSE;
4571   }
4572
4573   // Mode groups of pads: the total number of bins!
4574   Int_t numberofbinsexpected = 0;
4575   ModePadCalibration(2,i);
4576   ModePadFragmentation(0,2,0,i);
4577   fDetChamb2[i] = fNfragZ[i] * fNfragRphi[i];
4578   if (fDebug == 1) {
4579     AliInfo(Form("For the chamber 2: %d",fDetChamb2[i]));
4580   }
4581   numberofbinsexpected += 6 * 18 * fDetChamb2[i];
4582   ModePadCalibration(0,i);
4583   ModePadFragmentation(0,0,0,i);
4584   fDetChamb0[i] = fNfragZ[i] * fNfragRphi[i];
4585   if (fDebug == 1) {
4586     AliInfo(Form("For the other chamber 0: %d",fDetChamb0[i]));
4587   }
4588   numberofbinsexpected += 6 * 4 * 18 * fDetChamb0[i];
4589   
4590   // Quick verification that we have the good pad calibration mode if 2D histos!
4591   if (nbins != 0) {
4592     if (numberofbinsexpected != nbins) {
4593       AliInfo("It doesn't correspond to the mode of pad group calibration!");
4594       return kFALSE;
4595     }
4596   }
4597
4598   // Security for fDebug 3 and 4
4599   if ((fDebug >= 3) && 
4600       ((fDet[0] >  5) || 
4601        (fDet[1] >  4) || 
4602        (fDet[2] > 17))) {
4603     AliInfo("This detector doesn't exit!");
4604     return kFALSE;
4605   }
4606
4607   // Determine fDet1 and fDet2
4608   fDect1[i] = -1;
4609   fDect2[i] = -1;
4610   if (fDebug == 2) {
4611     fDect1[i] = fFitVoir;
4612     fDect2[i] = fDect1[i] +1;
4613   }
4614   if (fDebug <= 1) {
4615     fDect1[i] = 0;
4616     fDect2[i] = numberofbinsexpected;
4617   }
4618   if (fDebug >= 3) {
4619     CalculXBins(AliTRDgeometry::GetDetector(fDet[0],fDet[1],fDet[2]),i);
4620     fDect1[i] = fXbins[i];
4621     CalculXBins((AliTRDgeometry::GetDetector(fDet[0],fDet[1],fDet[2])+1),i);
4622     fDect2[i] = fXbins[i];
4623   }
4624
4625   // Create the histos for debugging
4626   // CH
4627   if (i == 0) {
4628     
4629     gDirectory = gROOT;
4630     // Init the VectorFitCH
4631     fVectorFitCH = new TObjArray();
4632     fCoefCH      = new Float_t[2304];
4633     for (Int_t k = 0; k < 2304; k++) {
4634       fCoefCH[k] = 0.0;    
4635     }
4636     fScaleFitFactor = 0.0;
4637
4638     // Number of Xbins(detectors or groups of pads) if Vector2d
4639     // Quick verification that we are not out of range!
4640     if (fVectorCH && fPlaCH) {
4641       if ((nbins                            == 0) && 
4642           (fVectorCH->GetEntriesFast()      >  0) && 
4643           ((Int_t) fPlaCH->GetEntriesFast() >  0)) {
4644         if ((Int_t) fVectorCH->GetEntriesFast() > numberofbinsexpected) {
4645           AliInfo("ch doesn't correspond to the mode of pad group calibration!");
4646           return kFALSE;
4647         }
4648         if ((Int_t) fVectorCH->GetEntriesFast() != (Int_t) fPlaCH->GetEntriesFast()) {
4649           AliInfo("VectorCH doesn't correspond to PlaCH!");
4650           return kFALSE;
4651         }
4652       }
4653     }
4654
4655     //
4656     // Debugging: Create the histos
4657     //
4658
4659     // fDebug == 0 nothing
4660     
4661     // fDebug == 1 
4662     if (fDebug == 1) {
4663       InitArrayFitCH();
4664     }
4665
4666     // fDebug == 2 and fFitVoir no histo
4667     if (fDebug == 2) {
4668       if (fFitVoir < numberofbinsexpected) {
4669         AliInfo(Form("We will see the fit of the object %d",fFitVoir));
4670       }
4671       else {
4672         AliInfo("fFitVoir is out of range of the histo!");
4673         return kFALSE;
4674       }
4675     }
4676
4677     // fDebug == 3  or 4 and fDet
4678     if (fDebug >= 3) {
4679       if ((fNz[0] == 0) && (fNrphi[0] == 0)) {
4680         AliInfo("Do you really want to see one detector without pad groups?");
4681         return kFALSE;
4682       }
4683       else {
4684         AliInfo(Form("You will see the detector: iPlane %d, iChamb %d, iSect %d"
4685                     ,fDet[0],fDet[1],fDet[2]));
4686         // A little geometry:
4687         Int_t rowMax = parCom->GetRowMax(fDet[0],fDet[1],fDet[2]);
4688         Int_t colMax = parCom->GetColMax(fDet[0]);
4689         // Create the histos to visualise
4690         CreateFitHistoCHDB(rowMax,colMax);
4691         if (fDebug == 4) {
4692           InitArrayFitCH();
4693         }
4694       }
4695     }
4696
4697   }
4698     
4699   // PH and T0
4700   if (i == 1) {
4701     
4702     // Number of Xbins (detectors or groups of pads) if vector2d
4703     // Quick verification that we are not out of range!
4704     if (fVectorPH && fPlaPH) {
4705       if ((nbins == 0) && 
4706           (fVectorPH->GetEntriesFast()      > 0) && 
4707           ((Int_t) fPlaPH->GetEntriesFast() > 0)) {
4708         if ((Int_t) fVectorPH->GetEntriesFast() > numberofbinsexpected) {
4709           AliInfo("ph doesn't correspond to the mode of pad group calibration!");
4710           return kFALSE;
4711         }
4712         if ((Int_t) fVectorPH->GetEntriesFast() != (Int_t) fPlaPH->GetEntriesFast()) {
4713           AliInfo("VectorPH doesn't correspond to PlaPH!");
4714           return kFALSE;
4715         }
4716       }
4717     }
4718         
4719     // Init tree
4720     InitTreePH();
4721     InitTreeT0();    
4722
4723     //
4724     // Debugging: Create the histos
4725     //
4726
4727     // fDebug == 0 nothing
4728     
4729     // fDebug == 1 
4730     if (fDebug == 1) {
4731       // Create the histos replique de ph
4732       InitArrayFitPH();
4733       InitArrayFitT0();
4734     }
4735
4736     // fDebug == 2 and fFitVoir no histo
4737     if (fDebug == 2) {
4738       if (fFitVoir < numberofbinsexpected) {
4739         AliInfo(Form("We will see the fit of the object %d",fFitVoir));
4740       }
4741       else {
4742         AliInfo("fFitVoir is out of range of the histo!");
4743         return kFALSE;
4744       }
4745     }
4746
4747     // fDebug == 3  or 4 and fDet
4748     if (fDebug >= 3) {
4749       if ((fNz[1]    == 0) && 
4750           (fNrphi[1] == 0)) {
4751         AliInfo("Do you really want to see one detector without pad groups?");
4752         return kFALSE;
4753       }
4754       else  {
4755         AliInfo(Form("You will see the detector: iPlane %d, iChamb %d, iSect %d"
4756                     ,fDet[0],fDet[1],fDet[2]));
4757         // A little geometry:
4758         Int_t rowMax = parCom->GetRowMax(fDet[0],fDet[1],fDet[2]);
4759         Int_t colMax = parCom->GetColMax(fDet[0]);
4760         // Create the histos to visualise
4761         CreateFitHistoPHDB(rowMax,colMax);
4762         CreateFitHistoT0DB(rowMax,colMax);
4763         if (fDebug == 4) {
4764           InitArrayFitPH();
4765           InitArrayFitT0();
4766         }
4767       }
4768     }
4769
4770   }
4771
4772   // PRF
4773   if (i == 2) {
4774     
4775     // Number of Xbins(detectors or groups of pads) if vector2d
4776     if (fVectorPRF && fPlaPRF){
4777       if ((nbins == 0) && 
4778           (fVectorPRF->GetEntriesFast() > 0) && 
4779           (fPlaPRF->GetEntriesFast()    > 0)) {
4780         // Quick verification that we are not out of range!
4781         if ((Int_t) fVectorPRF->GetEntriesFast() > numberofbinsexpected) {
4782           AliInfo("ch doesn't correspond to the mode of pad group calibration!");
4783           return kFALSE;
4784         }
4785         if ((Int_t) fVectorPRF->GetEntriesFast() != (Int_t) fPlaPRF->GetEntriesFast()) {
4786           AliInfo("VectorPRF doesn't correspond to PlaCH!");
4787           return kFALSE;
4788         }
4789       }
4790     }
4791     
4792     // Init tree
4793     InitTreePRF();
4794
4795     //
4796     // Debugging: Create the histos
4797     //
4798
4799     // fDebug == 0 nothing
4800
4801     // fDebug == 1 
4802     if (fDebug == 1) {
4803       // Create the histos replique de ch
4804       InitArrayFitPRF();
4805     }
4806     
4807     // fDebug == 2 and fFitVoir no histo
4808     if (fDebug == 2) {
4809       if (fFitVoir < numberofbinsexpected) {
4810         AliInfo(Form("We will see the fit of the object %d",fFitVoir));
4811       }
4812       else {
4813         AliInfo("fFitVoir is out of range of the histo!");
4814         return kFALSE;
4815       }
4816     }
4817
4818     // fDebug == 3  or 4 and fDet
4819     if (fDebug >= 3) {
4820       if ((fNz[2]    == 0) && 
4821           (fNrphi[2] == 0)) {
4822         AliInfo("Do you really want to see one detector without pad groups?");
4823         return kFALSE;
4824       }
4825       else {
4826         AliInfo(Form("You will see the detector: iPlane %d, iChamb %d, iSect %d"
4827                     ,fDet[0],fDet[1],fDet[2]));
4828         // A little geometry:
4829         Int_t rowMax = parCom->GetRowMax(fDet[0],fDet[1],fDet[2]);
4830         Int_t colMax = parCom->GetColMax(fDet[0]);
4831         // Create the histos to visualise
4832         CreateFitHistoPRFDB(rowMax,colMax);
4833         if (fDebug == 4) {
4834           InitArrayFitPRF();
4835         }
4836       }
4837     }
4838
4839   }
4840
4841   return kTRUE;
4842   
4843 }
4844
4845 //____________Functions for initialising the AliTRDCalibra in the code_________
4846 void AliTRDCalibra::InitfCountDetAndfCount(Int_t i)
4847 {
4848   //
4849   // Init the current detector where we are fCountDet and the
4850   // next fCount for the functions Fit... 
4851   //
4852   
4853   // Loop on the Xbins of ch!!
4854   fCountDet[i] = -1; // Current detector
4855   fCount[i]    =  0; // To find the next detector
4856   
4857   // If fDebug >= 3
4858   if (fDebug >= 3) {
4859
4860     // Set countdet to the detector
4861     fCountDet[i] = AliTRDgeometry::GetDetector(fDet[0],fDet[1],fDet[2]);
4862         
4863     // Determination of fNnZ, fNnRphi, fNfragZ and fNfragRphi
4864     ModePadCalibration(fDet[1],i);
4865     ModePadFragmentation(fDet[0],fDet[1],fDet[2],i);
4866     
4867     // Set counter to write at the end of the detector
4868     fCount[i] = fDect1[i] + fNfragZ[i]*fNfragRphi[i];
4869
4870   }
4871
4872 }
4873
4874 //____________Functions for initialising the AliTRDCalibra in the code_________
4875 void AliTRDCalibra::UpdatefCountDetAndfCount(Int_t idect, Int_t i)
4876 {
4877   //
4878   // See if we are in a new detector and update the
4879   // variables fNfragZ and fNfragRphi if yes 
4880   //
4881
4882   // Determination of fNnZ, fNnRphi, fNfragZ and fNfragRphi
4883   // If fDebug == 1 or 0
4884   if ((fDebug == 0) || 
4885       (fDebug == 1)) {
4886
4887     if (fCount[i] == idect) {
4888       
4889       // On en est au detector
4890       fCountDet[i] += 1;
4891       
4892       // Determination of fNnZ, fNnRphi, fNfragZ and fNfragRphi
4893       ModePadCalibration((Int_t) GetChamber(fCountDet[i]),i);
4894       ModePadFragmentation((Int_t) GetPlane(fCountDet[i])
4895                           ,(Int_t) GetChamber(fCountDet[i])
4896                           ,(Int_t) GetSector(fCountDet[i]),i);
4897
4898       // Set for the next detector
4899       fCount[i] += fNfragZ[i]*fNfragRphi[i];
4900
4901     }
4902
4903   }
4904
4905 }
4906
4907 //____________Functions for initialising the AliTRDCalibra in the code_________
4908 void AliTRDCalibra::ReconstructFitRowMinRowMax(Int_t idect, Int_t i)
4909 {
4910   //
4911   // Reconstruct the min pad row, max pad row, min pad col and
4912   // max pad col of the calibration group for the Fit functions
4913   //
4914
4915   if (fDebug <  2) {
4916     ReconstructionRowPadGroup((Int_t) (idect-(fCount[i]-(fNfragZ[i]*fNfragRphi[i]))),i);
4917   }
4918   if (fDebug >= 3) {
4919     ReconstructionRowPadGroup((Int_t) (idect-fDect1[i]),i);
4920   }
4921
4922 }
4923
4924 //____________Functions for initialising the AliTRDCalibra in the code_________
4925 Bool_t AliTRDCalibra::NotEnoughStatistic(Int_t idect, Int_t i)
4926 {
4927   //
4928   // For the case where there are not enough entries in the histograms
4929   // of the calibration group, the value present in the choosen database
4930   // will be put. A negativ sign enables to know that a fit was not possible.
4931   //
4932   
4933   // Get the parameter object
4934   AliTRDCommonParam *parCom = AliTRDCommonParam::Instance();
4935   if (!parCom) {
4936     AliInfo("Could not get CommonParam Manager");
4937     return kFALSE;
4938   }
4939   
4940   // Get cal
4941   AliTRDcalibDB     *cal    = AliTRDcalibDB::Instance();
4942   if (!cal) {
4943     AliInfo("Could not get calibDB");
4944     return kFALSE;
4945   }
4946
4947   if (fDebug != 2) {
4948     AliInfo(Form("The element %d in this detector %d has not enough statistic to be fitted"
4949                 ,idect-(fCount[i]-(fNfragZ[i]*fNfragRphi[i])),fCountDet[i]));
4950   }
4951   if (fDebug == 2) {
4952     AliInfo("The element has not enough statistic to be fitted");
4953   }
4954
4955   if ((i == 0) && (fDebug != 2)) {
4956     
4957     // Calcul the coef from the database choosen
4958     CalculChargeCoefMean(fCountDet[0],(Int_t) (idect-fDect1[0]),kFALSE);
4959     
4960     // Fill the coefCH[2304] with negative value to say: not fitted
4961     for (Int_t k = fRowMin[0]; k < fRowMax[0]; k++) {
4962       for (Int_t j = fColMin[0]; j < fColMax[0]; j++) {
4963         if (GetChamber(fCountDet[0]) == 2) {
4964           fCoefCH[(Int_t)(j*12+k)] = -TMath::Abs(fChargeCoef[3]);
4965         }
4966         if (GetChamber(fCountDet[0]) != 2) {
4967           fCoefCH[(Int_t)(j*16+k)] = -TMath::Abs(fChargeCoef[3]);
4968         }
4969       }
4970     }
4971
4972     // Put the default value negative 
4973     if ((fDebug == 1) || 
4974         (fDebug == 4)) {
4975
4976       if (fFitChargeBisOn) {
4977         fCoefCharge[2][idect-fDect1[0]]=-TMath::Abs(fChargeCoef[3]);
4978       }
4979       if (fMeanChargeOn) {
4980         fCoefCharge[1][idect-fDect1[0]]=-TMath::Abs(fChargeCoef[3]);
4981       }
4982
4983       fCoefCharge[0][idect-fDect1[0]]=-TMath::Abs(fChargeCoef[3]);
4984
4985     }
4986       
4987     // End of one detector
4988     if ((idect == (fCount[0]-1))) {
4989       FillVectorFitCH((Int_t) fCountDet[0]);
4990       // Reset
4991       for (Int_t k = 0; k < 2304; k++) {
4992         fCoefCH[k] = 0.0;
4993       }
4994     }
4995
4996   }
4997   
4998   if ((i == 1) && (fDebug != 2)) {
4999
5000     CalculVdriftCoefMean(fCountDet[1],(Int_t) (idect-fDect1[1]));
5001     CalculT0CoefMean(fCountDet[1],(Int_t) (idect-fDect1[1]));
5002
5003     // Put the default value (time0 can be negativ, so we stay with + )
5004     if ((fDebug == 1) || 
5005         (fDebug == 4)) {
5006
5007       if (fFitPHOn) {
5008         fCoefVdrift[0][(idect-fDect1[1])] = -fVdriftCoef[2];
5009         fCoefT0[0][(idect-fDect1[1])] = fT0Coef[2];
5010       }
5011
5012       fCoefVdrift[1][(idect-fDect1[1])] = -fVdriftCoef[2];
5013       fCoefT0[1][(idect-fDect1[1])] = fT0Coef[2];
5014
5015     }
5016     
5017     // Put the default value
5018     if (fDebug >= 3) {
5019       fVdriftCoef[0] = fVdriftCoef[2];
5020       fVdriftCoef[1] = fVdriftCoef[2];
5021       FillCoefVdriftDB();
5022       fT0Coef[0]     = fT0Coef[2];
5023       fT0Coef[1]     = fT0Coef[2];
5024       FillCoefT0DB();
5025     }
5026
5027     // Fill the tree if end of a detector.
5028     // The pointer to the branch stays with the default value negative!!!
5029     // PH
5030     // Pointer to the branch
5031     for (Int_t k = fRowMin[1]; k < fRowMax[1]; k++) {
5032       for (Int_t j = fColMin[1]; j < fColMax[1]; j++) {
5033         if (GetChamber(fCountDet[1]) == 2) {
5034           fVdriftPad[(Int_t)(j*12+k)] = -TMath::Abs(fVdriftCoef[2]);
5035         }
5036         if (GetChamber(fCountDet[1]) != 2) {
5037           fVdriftPad[(Int_t)(j*16+k)] = -TMath::Abs(fVdriftCoef[2]);
5038         }
5039       }
5040     }
5041
5042     // End of one detector
5043     if ((idect == (fCount[1]-1)) && (fDebug != 2)) {
5044       FillTreeVdrift((Int_t) fCountDet[1]);
5045     }
5046
5047     // T0
5048     // Fill the tree if end of a detector.
5049     // The pointer to the branch stays with the default value positive!!!
5050     // Pointer to the branch
5051     for (Int_t k = fRowMin[1]; k < fRowMax[1]; k++) {
5052       for (Int_t j = fColMin[1]; j < fColMax[1]; j++) {
5053         if (GetChamber(fCountDet[1]) == 2) {
5054           fT0Pad[(Int_t)(j*12+k)] = fT0Coef[2];
5055         }
5056         if (GetChamber(fCountDet[1]) != 2) {
5057           fT0Pad[(Int_t)(j*16+k)] = fT0Coef[2];
5058         }
5059       }
5060     }
5061
5062     // End of one detector
5063     if ((idect == (fCount[1]-1)) && (fDebug != 2)) {
5064       FillTreeT0((Int_t) fCountDet[1]);
5065     }
5066
5067   }
5068
5069   if ((i == 2) && (fDebug != 2)) {
5070
5071     CalculPRFCoefMean(fCountDet[2],(Int_t) (idect-fDect1[2]));
5072       
5073     if ((fDebug == 1) || 
5074         (fDebug == 4)) {
5075       fCoefPRF[0][(idect-fDect1[2])] = -fPRFCoef[1];
5076     }
5077
5078     if (fDebug >= 3){
5079       fPRFCoef[0] = fPRFCoef[1];
5080       FillCoefPRFDB();
5081     }
5082
5083     // Fill the tree if end of a detector.
5084     // The pointer to the branch stays with the default value 1.5!!!
5085     // Pointer to the branch
5086     for (Int_t k = fRowMin[2]; k < fRowMax[2]; k++) {
5087       for (Int_t j = fColMin[2]; j < fColMax[2]; j++) {
5088         if((parCom->GetColMax(GetPlane(fCountDet[2])) != (j+1)) && (j != 0)){
5089           if (GetChamber(fCountDet[2]) == 2) {
5090             fPRFPad[(Int_t)(j*12+k)] = -fPRFCoef[1];
5091           }
5092           if (GetChamber(fCountDet[2]) != 2) {
5093             fPRFPad[(Int_t)(j*16+k)] = -fPRFCoef[1];
5094           }
5095         }
5096         else {
5097           if (fAccCDB) {
5098             if (GetChamber(fCountDet[2]) == 2) {
5099               fPRFPad[(Int_t)(j*12+k)] = -((Float_t) cal->GetPRFWidth(fCountDet[2],j,k));
5100             }
5101             if (GetChamber(fCountDet[2]) != 2) {
5102               fPRFPad[(Int_t)(j*16+k)] = -((Float_t) cal->GetPRFWidth(fCountDet[2],j,k));
5103             }
5104           }
5105           if (!fAccCDB) {
5106             if (GetChamber(fCountDet[2]) == 2) {
5107               fPRFPad[(Int_t)(j*12+k)] = -((Float_t) GetPRFDefault(GetPlane(fCountDet[2])));
5108              }
5109             if (GetChamber(fCountDet[2]) != 2) {
5110               fPRFPad[(Int_t)(j*16+k)] = -((Float_t) GetPRFDefault(GetPlane(fCountDet[2])));
5111             }
5112           }
5113         }
5114       }
5115     }
5116
5117     // End of one detector
5118     if ((idect == (fCount[2]-1)) && (fDebug != 2)) {
5119       FillTreePRF((Int_t) fCountDet[2]);
5120     }
5121
5122   }
5123   
5124   return kTRUE;
5125
5126 }
5127
5128 //____________Functions for initialising the AliTRDCalibra in the code_________
5129 Bool_t AliTRDCalibra::FillInfosFit(Int_t idect, Int_t i)
5130 {
5131   //
5132   // Fill the coefficients found with the fits or other
5133   // methods from the Fit functions
5134   //
5135
5136   // Get the parameter object
5137   AliTRDCommonParam *parCom = AliTRDCommonParam::Instance();
5138   if (!parCom) {
5139     AliInfo("Could not get CommonParam Manager");
5140     return kFALSE;
5141   }
5142
5143   // Get cal
5144   AliTRDcalibDB     *cal    = AliTRDcalibDB::Instance();
5145   if (!cal) {
5146     AliInfo("Could not get calibDB");
5147     return kFALSE;
5148   }
5149
5150   if ((i == 0) && (fDebug != 2)) {
5151     // Fill the coefCH[2304] with fChargeCoef[0]
5152     // that would be negativ only if the fit failed totally
5153     for (Int_t k = fRowMin[0]; k < fRowMax[0]; k++) {
5154       for (Int_t j = fColMin[0]; j < fColMax[0]; j++) {
5155         if (GetChamber(fCountDet[0]) == 2) {
5156           fCoefCH[(Int_t)(j*12+k)] = fChargeCoef[0];
5157         }
5158         if (GetChamber(fCountDet[0]) != 2) {
5159           fCoefCH[(Int_t)(j*16+k)] = fChargeCoef[0];
5160         }
5161       }
5162     }                
5163     // End of one detector
5164     if ((idect == (fCount[0]-1))) {
5165       FillVectorFitCH((Int_t) fCountDet[0]);
5166       // Reset
5167       for (Int_t k = 0; k < 2304; k++) {
5168         fCoefCH[k] = 0.0;
5169       }
5170     }
5171   }
5172
5173   if ((i == 1) && (fDebug != 2)) {
5174
5175     // PH
5176     // Pointer to the branch: fVdriftCoef[1] will ne negativ only if the fit failed totally 
5177     for (Int_t k = fRowMin[1]; k < fRowMax[1]; k++) {
5178       for (Int_t j = fColMin[1]; j < fColMax[1]; j++) {
5179         if (GetChamber(fCountDet[1]) == 2) {
5180           fVdriftPad[(Int_t)(j*12+k)]=fVdriftCoef[1];
5181         }
5182         if (GetChamber(fCountDet[1]) != 2) {
5183           fVdriftPad[(Int_t)(j*16+k)]=fVdriftCoef[1];
5184         }
5185       }
5186     }                
5187     // End of one detector
5188     if ((idect == (fCount[1]-1)) && (fDebug != 2)) {
5189       FillTreeVdrift((Int_t) fCountDet[1]);
5190     }
5191
5192     // T0
5193     // Pointer to the branch: fT0Coef[1] will ne negativ only if the fit failed totally 
5194     for (Int_t k = fRowMin[1]; k < fRowMax[1]; k++) {
5195       for (Int_t j = fColMin[1]; j < fColMax[1]; j++) {
5196         if (GetChamber(fCountDet[1]) == 2) {
5197           fT0Pad[(Int_t)(j*12+k)]=fT0Coef[1];
5198         }
5199         if (GetChamber(fCountDet[1]) != 2) {
5200           fT0Pad[(Int_t)(j*16+k)]=fT0Coef[1];
5201         }
5202       }
5203     }                
5204     // End of one detector
5205     if ((idect == (fCount[1]-1)) && (fDebug != 2)) {
5206       FillTreeT0((Int_t) fCountDet[1]);
5207     }
5208
5209   }
5210
5211   if ((i == 2) && (fDebug != 2)) {
5212     // Pointer to the branch
5213     for (Int_t k = fRowMin[2]; k < fRowMax[2]; k++) {
5214       for (Int_t j = fColMin[2]; j < fColMax[2]; j++) {
5215         if ((parCom->GetColMax(GetPlane(fCountDet[2])) != (j+1)) && (j != 0)) {
5216           if (GetChamber(fCountDet[2]) == 2) {
5217             fPRFPad[(Int_t)(j*12+k)] = fPRFCoef[0];
5218           }
5219           if (GetChamber(fCountDet[2]) != 2) {
5220             fPRFPad[(Int_t)(j*16+k)] = fPRFCoef[0];
5221           }
5222         }
5223         else {
5224           if (fAccCDB) {
5225             if (GetChamber(fCountDet[2]) == 2) {
5226               fPRFPad[(Int_t)(j*12+k)] = (Float_t) cal->GetPRFWidth(fCountDet[2],j,k);
5227             }
5228             if (GetChamber(fCountDet[2]) != 2) {
5229               fPRFPad[(Int_t)(j*16+k)] = (Float_t) cal->GetPRFWidth(fCountDet[2],j,k);
5230             }
5231           }
5232           if (!fAccCDB) {
5233             if (GetChamber(fCountDet[2]) == 2) {
5234               fPRFPad[(Int_t)(j*12+k)] = (Float_t) GetPRFDefault(GetPlane(fCountDet[2]));
5235             }
5236             if (GetChamber(fCountDet[2]) != 2) {
5237               fPRFPad[(Int_t)(j*16+k)] = (Float_t) GetPRFDefault(GetPlane(fCountDet[2])); 
5238             }
5239           }
5240         }
5241       }
5242     }
5243     // End of one detector
5244     if ((idect == (fCount[2]-1)) && (fDebug != 2)) {
5245       FillTreePRF((Int_t) fCountDet[2]);
5246     }
5247   }
5248
5249   return kTRUE;
5250
5251 }
5252
5253 //____________Functions for initialising the AliTRDCalibra in the code_________
5254 Bool_t AliTRDCalibra::WriteFitInfos(Int_t i)
5255 {
5256   //
5257   // In the case the user wants to write a file with a tree of the found
5258   // coefficients for the calibration before putting them in the database
5259   //
5260
5261   TFile *fout = TFile::Open(fWriteNameCoef,"UPDATE");
5262   // Check if the file could be opened
5263   if (!fout || !fout->IsOpen()) {
5264     AliInfo("No File found!");
5265     return kFALSE;
5266   }
5267
5268   if ((i == 0) && (fDebug != 2)) {
5269     // The DB stuff
5270     if ((fDebug == 4) || 
5271         (fDebug == 3)) {
5272       WriteCHDB(fout);
5273     }
5274     // The tree
5275     fout->WriteTObject(fGain,fGain->GetName(),(Option_t *) "writedelete");
5276   }
5277
5278   if ((i == 1) && (fDebug != 2)) {
5279     // The DB stuff
5280     if ((fDebug == 4) || 
5281         (fDebug == 3)) {
5282       WritePHDB(fout);
5283     }
5284     // The tree
5285     fout->WriteTObject(fVdrift,fVdrift->GetName(),(Option_t *) "writedelete");
5286     // The DB stuff
5287     if ((fDebug == 4) || 
5288         (fDebug == 3)) {
5289       WriteT0DB(fout);
5290     }
5291     // The tree
5292     fout->WriteTObject(fT0,fT0->GetName(),(Option_t *) "writedelete");
5293   }
5294
5295   if ((i == 2) && (fDebug != 2)) {
5296     // The DB stuff
5297     if ((fDebug == 4) || 
5298         (fDebug == 3)) {
5299       WritePRFDB(fout);
5300     }
5301     // The tree
5302     fout->WriteTObject(fPRF,fPRF->GetName(),(Option_t *) "writedelete");
5303   }
5304
5305   fout->Close();
5306
5307   return kTRUE;
5308
5309 }
5310
5311 //
5312 //____________Fill Coef DB in case of visualisation of one detector____________
5313 //
5314
5315 //_____________________________________________________________________________
5316 void AliTRDCalibra::FillCoefVdriftDB()
5317 {
5318   //
5319   // Fill the histos for fDebug = 3 and fDebug = 4 to visualise the detector
5320   //
5321  
5322   for (Int_t row = fRowMin[1]; row < fRowMax[1]; row++) {
5323     for (Int_t col = fColMin[1]; col < fColMax[1]; col++) {
5324       fCoefVdriftDB[1]->SetBinContent(row+1,col+1,TMath::Abs(fVdriftCoef[1]));
5325       if (fFitPHOn ) {
5326         fCoefVdriftDB[0]->SetBinContent(row+1,col+1,TMath::Abs(fVdriftCoef[0]));
5327       }
5328     }
5329   }
5330
5331 }
5332
5333 //_____________________________________________________________________________
5334 void AliTRDCalibra::FillCoefT0DB()
5335 {
5336   //
5337   // Fill the histos for fDebug = 3 and fDebug = 4 to visualise the detector
5338   //
5339  
5340   for (Int_t row = fRowMin[1]; row < fRowMax[1]; row++) {
5341     for (Int_t col = fColMin[1]; col < fColMax[1]; col++) {
5342       fCoefT0DB[1]->SetBinContent(row+1,col+1,TMath::Abs(fT0Coef[1]));
5343       if (fFitPHOn) {
5344         fCoefT0DB[0]->SetBinContent(row+1,col+1,TMath::Abs(fT0Coef[0]));
5345       }
5346     }
5347   }
5348
5349 }
5350
5351 //_____________________________________________________________________________
5352 void AliTRDCalibra::FillCoefChargeDB()
5353 {
5354   //
5355   // Fill the histos for fDebug = 3 and fDebug = 4 to visualise the detector
5356   //
5357
5358   for (Int_t row = fRowMin[0]; row < fRowMax[0]; row++) {
5359     for (Int_t col = fColMin[0]; col < fColMax[0]; col++) {
5360       if (fMeanChargeOn) {
5361         fCoefChargeDB[1]->SetBinContent(row+1,col+1,TMath::Abs(fChargeCoef[1]));
5362       }
5363       if (fFitChargeBisOn) {
5364         fCoefChargeDB[2]->SetBinContent(row+1,col+1,TMath::Abs(fChargeCoef[2]));
5365       }
5366       fCoefChargeDB[0]->SetBinContent(row+1,col+1,TMath::Abs(fChargeCoef[0]));
5367     }
5368   }
5369
5370 }
5371
5372 //_____________________________________________________________________________
5373 void AliTRDCalibra::FillCoefPRFDB()
5374 {
5375   //
5376   // Fill the histos for fDebug = 3 and fDebug = 4 to visualise the detector
5377   //
5378
5379   for (Int_t row = fRowMin[2]; row < fRowMax[2]; row++) {
5380     for (Int_t col = fColMin[2]; col < fColMax[2]; col++) {
5381       fCoefPRFDB->SetBinContent(row+1,col+1,fPRFCoef[0]);
5382     }
5383   }
5384
5385 }
5386
5387 //
5388 //____________Plot histos CoefPRF....__________________________________________
5389 //
5390
5391 //_____________________________________________________________________________
5392 void AliTRDCalibra::PlotWriteCH()
5393 {
5394   //
5395   // Scale the coefficients to one, create the graph errors and write them if wanted
5396   //
5397
5398   //TObjArray of the grapherrors and so on
5399   TObjArray *listofgraphs = new TObjArray(); 
5400
5401   Int_t nbins = fDect2[0]-fDect1[0];
5402
5403   //Scale the coefs
5404
5405   //counter
5406   Int_t counter[3];
5407   counter[0] = 0;
5408   counter[1] = 0;
5409   counter[2] = 0;
5410   Double_t sum = 0.0;
5411   Double_t scale = 1.0; 
5412
5413   // Scale the histo
5414   Double_t *xValuesFitted = new Double_t[nbins];
5415   Double_t *xValuesFittedMean = new Double_t[nbins];
5416   Double_t *xValuesFittedBis =  new Double_t[nbins];
5417   for(Int_t k = 0; k < nbins; k ++){
5418     xValuesFitted[k] = -1;
5419     xValuesFittedMean[k] = -1;
5420     xValuesFittedBis[k] = -1;
5421   }
5422
5423   for(Int_t l = 0; l < nbins; l++){
5424     if(fCoefCharge[0][l] > 0){
5425       fCoefCharge[0][l]=fCoefCharge[0][l]*fScaleFitFactor;
5426       fCoefChargeE[0][l]=fCoefChargeE[0][l]*fScaleFitFactor;
5427       xValuesFitted[counter[0]]=l;
5428       counter[0]++;
5429     }
5430   }
5431   if(fMeanChargeOn){
5432     sum = 0.0;
5433     for(Int_t l = 0; l < nbins; l++){
5434       if(fCoefCharge[1][l] > 0){
5435         sum += fCoefCharge[1][l];
5436         xValuesFittedMean[counter[1]]= l;
5437         counter[1]++;
5438       }
5439     }
5440     scale = 1.0;
5441     if(sum > 0.0) scale = counter[1]/sum;
5442     for(Int_t l = 0; l < nbins; l++){
5443       if(fCoefCharge[1][l] > 0){
5444         fCoefCharge[1][l]=fCoefCharge[1][l]*scale;
5445         fCoefChargeE[1][l]=fCoefChargeE[1][l]*scale;
5446       }
5447     }
5448   }
5449   if(fFitChargeBisOn){
5450     sum = 0.0;
5451     for(Int_t l = 0; l < nbins; l++){
5452       if(fCoefCharge[2][l] > 0){
5453         fCoefCharge[2][l]=fCoefCharge[2][l]*fScaleFitFactor;
5454         fCoefChargeE[2][l]=fCoefChargeE[2][l]*fScaleFitFactor;
5455         sum += fCoefCharge[2][l];
5456         xValuesFittedBis[counter[2]]= l;
5457         counter[2]++;
5458       }
5459     }
5460     scale = 1.0;
5461     if(sum > 0.0) scale = counter[2]/sum;
5462     for(Int_t l = 0; l < nbins; l++){
5463       if(fCoefCharge[2][l] > 0){
5464         fCoefCharge[2][l]=fCoefCharge[2][l]*scale;
5465         fCoefChargeE[2][l]=fCoefChargeE[2][l]*scale;
5466         if(fCoefCharge[2][l] > 1.0) printf("for the group %d, I have the coef %f with the error %f\n",l,fCoefCharge[2][l],fCoefChargeE[2][l]);
5467       }
5468     }
5469   }
5470   
5471   //Create the X and Xerror
5472   Double_t *xValues = new Double_t[nbins];
5473   Double_t *xValuesE = new Double_t[nbins];
5474   for(Int_t k = 0; k < nbins; k ++){
5475     xValues[k] = k;
5476     xValuesE[k] = 0.0;
5477   }
5478
5479   //Create the graph erros and plot them
5480   TGraph *graphCharge3  = new TGraph(nbins,xValues,fCoefCharge[3]);
5481   graphCharge3->SetName("coefcharge3");
5482   graphCharge3->SetTitle("");
5483   graphCharge3->GetXaxis()->SetTitle("Det/Pad groups");
5484   graphCharge3->GetYaxis()->SetTitle("gain factor");
5485   graphCharge3->SetLineColor(4);
5486   listofgraphs->Add((TObject *)graphCharge3);
5487   TGraphErrors *graphCharge0  = new TGraphErrors(nbins,xValues,fCoefCharge[0],xValuesE,fCoefChargeE[0]);
5488   graphCharge0->SetName("coefcharge0");
5489   graphCharge0->SetTitle("");
5490   graphCharge0->GetXaxis()->SetTitle("Det/Pad groups");
5491   graphCharge0->GetYaxis()->SetTitle("gain factor");
5492   graphCharge0->SetMarkerColor(6);
5493   graphCharge0->SetLineColor(6);
5494   graphCharge0->SetMarkerStyle(26);
5495   listofgraphs->Add((TObject *)graphCharge0);
5496   TCanvas *cch1 = new TCanvas("cch1","",50,50,600,800);
5497   cch1->cd();
5498   TLegend *legch1 = new TLegend(0.4,0.6,0.89,0.89);
5499   legch1->AddEntry(graphCharge3,"f_{g} simulated","l");
5500   legch1->AddEntry(graphCharge0,"f_{g} fit","p");
5501   graphCharge0->Draw("AP");
5502   //graphCharge3->Draw("AL");
5503   if (fMeanChargeOn) {
5504     TGraphErrors *graphCharge1  = new TGraphErrors(nbins,xValues,fCoefCharge[1],xValuesE,fCoefChargeE[1]);
5505     graphCharge1->SetName("coefcharge1");
5506     graphCharge1->GetXaxis()->SetTitle("Det/Pad groups");
5507     graphCharge1->GetYaxis()->SetTitle("gain factor");
5508     graphCharge1->SetTitle("");
5509     graphCharge1->SetMarkerColor(2);
5510     graphCharge1->SetLineColor(2);
5511     graphCharge1->SetMarkerStyle(24);
5512     legch1->AddEntry(graphCharge1,"f_{g} mean","p");
5513     graphCharge1->Draw("P");
5514     listofgraphs->Add((TObject *)graphCharge1);
5515   } 
5516   if (fFitChargeBisOn ) {
5517     TGraphErrors *graphCharge2  = new TGraphErrors(nbins,xValues,fCoefCharge[2],xValuesE,fCoefChargeE[2]);
5518     graphCharge2->SetName("coefcharge2");
5519     graphCharge2->SetTitle("");
5520     graphCharge2->GetXaxis()->SetTitle("Det/Pad groups");
5521     graphCharge2->GetYaxis()->SetTitle("gain factor");
5522     graphCharge2->SetMarkerColor(8);
5523     graphCharge2->SetLineColor(8);
5524     graphCharge2->SetMarkerStyle(25);
5525     legch1->AddEntry(graphCharge2,"f_{g} fitbis","p");
5526     graphCharge2->Draw("P");
5527     listofgraphs->Add((TObject *)graphCharge2);
5528   } 
5529   legch1->Draw("same");
5530
5531   
5532   //Create the arrays and the graphs for the delta
5533   TCanvas *cch2 = new TCanvas("cch2","",50,50,600,800);
5534   cch2->Divide(2,1);
5535   cch2->cd(2);
5536   Double_t *yValuesDelta = new Double_t[counter[0]];
5537   for(Int_t k = 0; k < counter[0]; k++){
5538     if(fCoefCharge[3][(Int_t)(xValuesFitted[k])] > 0.0) {
5539       yValuesDelta[k] = (fCoefCharge[0][(Int_t)xValuesFitted[k]]-fCoefCharge[3][(Int_t)xValuesFitted[k]])/fCoefCharge[3][(Int_t)xValuesFitted[k]];
5540     }
5541     else yValuesDelta[k] = 0.0;
5542   }
5543   TGraph *graphDeltaCharge0 = new TGraph(counter[0],&xValuesFitted[0],yValuesDelta);
5544   graphDeltaCharge0->SetName("deltacharge0");
5545   graphDeltaCharge0->GetXaxis()->SetTitle("Det/Pad groups");
5546   graphDeltaCharge0->GetYaxis()->SetTitle("#Deltag/g_{sim}");
5547   graphDeltaCharge0->SetMarkerColor(6);
5548   graphDeltaCharge0->SetTitle("");
5549   graphDeltaCharge0->SetLineColor(6);
5550   graphDeltaCharge0->SetMarkerStyle(26);
5551   listofgraphs->Add((TObject *)graphDeltaCharge0);
5552   TLegend *legch3 = new TLegend(0.4,0.6,0.89,0.89);
5553   legch3->AddEntry(graphDeltaCharge0,"fit","p");
5554   graphDeltaCharge0->Draw("AP");
5555   cch2->cd(1); 
5556   TH1I *histoErrorCharge0 = new TH1I("errorcharge0","",100  ,-0.3,0.3);
5557   histoErrorCharge0->SetXTitle("#Deltag/g_{sim}");
5558   histoErrorCharge0->SetYTitle("counts"); 
5559   histoErrorCharge0->SetLineColor(6);
5560   histoErrorCharge0->SetLineStyle(1);
5561   histoErrorCharge0->SetStats(0);
5562   for(Int_t k = 0; k < counter[0]; k++){
5563     histoErrorCharge0->Fill(yValuesDelta[k]);
5564   }
5565   TLegend *legch2 = new TLegend(0.4,0.6,0.89,0.89);
5566   legch2->AddEntry(histoErrorCharge0,"f_{g} fit","l");
5567   histoErrorCharge0->Draw();
5568   listofgraphs->Add((TObject *)histoErrorCharge0); 
5569   if (fMeanChargeOn) {
5570     cch2->cd(2);
5571     Double_t *yValuesDeltaMean = new Double_t[counter[1]];
5572     for(Int_t k = 0; k < counter[1]; k++){
5573       if(fCoefCharge[3][(Int_t)xValuesFittedMean[k]] > 0.0) {
5574         yValuesDeltaMean[k] = (fCoefCharge[1][(Int_t)xValuesFittedMean[k]]-fCoefCharge[3][(Int_t)xValuesFittedMean[k]])/fCoefCharge[3][(Int_t)xValuesFittedMean[k]];
5575       }
5576       else yValuesDeltaMean[k] = 0.0;
5577     }
5578     TGraph *graphDeltaCharge1 = new TGraph(counter[1],&xValuesFittedMean[0],yValuesDeltaMean);
5579     graphDeltaCharge1->SetName("deltacharge1");
5580     graphDeltaCharge1->GetXaxis()->SetTitle("Det/Pad groups");
5581     graphDeltaCharge1->GetYaxis()->SetTitle("#Deltag/g_{sim}");
5582     graphDeltaCharge1->SetMarkerColor(2);
5583     graphDeltaCharge1->SetMarkerStyle(24);
5584     graphDeltaCharge1->SetLineColor(2);
5585     graphDeltaCharge1->SetTitle("");
5586     legch3->AddEntry(graphDeltaCharge1,"mean","p");
5587     graphDeltaCharge1->Draw("P");
5588     listofgraphs->Add((TObject *)graphDeltaCharge1);
5589     cch2->cd(1);
5590     TH1I *histoErrorCharge1 = new TH1I("errorcharge1","",100  ,-0.3,0.3);
5591     histoErrorCharge1->SetXTitle("#Deltag/g_{sim}");
5592     histoErrorCharge1->SetYTitle("counts");
5593     histoErrorCharge1->SetLineColor(2);
5594     histoErrorCharge1->SetLineStyle(2);
5595     histoErrorCharge1->SetStats(0); 
5596     for(Int_t k = 0; k < counter[1]; k++){
5597       histoErrorCharge1->Fill(yValuesDeltaMean[k]);
5598     }
5599     legch2->AddEntry(histoErrorCharge1,"f_{g} mean","l");
5600     histoErrorCharge1->Draw("same");
5601     listofgraphs->Add((TObject *)histoErrorCharge1);
5602   }
5603   
5604   if (fFitChargeBisOn) {
5605     cch2->cd(2);
5606     Double_t *yValuesDeltaBis = new Double_t[counter[2]];
5607     for(Int_t k = 0; k < counter[2]; k++){
5608       if(fCoefCharge[3][(Int_t)xValuesFittedBis[k]] > 0.0) {
5609         yValuesDeltaBis[k] = (fCoefCharge[2][(Int_t)xValuesFittedBis[k]]-fCoefCharge[3][(Int_t)xValuesFittedBis[k]])/fCoefCharge[3][(Int_t)xValuesFittedBis[k]];
5610       }
5611       else yValuesDeltaBis[k] = 0.0;
5612     }
5613     TGraph *graphDeltaCharge2 = new TGraph(counter[2],&xValuesFittedBis[0],yValuesDeltaBis);
5614     graphDeltaCharge2->SetName("deltacharge2");
5615     graphDeltaCharge2->GetXaxis()->SetTitle("Det/Pad groups");
5616     graphDeltaCharge2->GetYaxis()->SetTitle("#Deltag/g_{sim}");
5617     graphDeltaCharge2->SetMarkerColor(8);
5618     graphDeltaCharge2->SetLineColor(8);
5619     graphDeltaCharge2->SetMarkerStyle(25);
5620     legch3->AddEntry(graphDeltaCharge2,"fit","p");
5621     graphDeltaCharge2->SetTitle("");
5622     graphDeltaCharge2->Draw("P");
5623     listofgraphs->Add((TObject *)graphDeltaCharge2);
5624     cch2->cd(1);
5625     TH1I *histoErrorCharge2 = new TH1I("errorcharge2","",100  ,-0.3,0.3);
5626     histoErrorCharge2->SetXTitle("#Deltag/g_{sim}");
5627     histoErrorCharge2->SetYTitle("counts"); 
5628     histoErrorCharge2->SetLineColor(8);
5629     histoErrorCharge2->SetLineStyle(5);
5630     histoErrorCharge2->SetLineWidth(3);
5631     histoErrorCharge2->SetStats(0);
5632     for(Int_t k = 0; k < counter[2]; k++){
5633       histoErrorCharge2->Fill(yValuesDeltaBis[k]);
5634     }
5635     legch2->AddEntry(histoErrorCharge2,"f_{g} fitbis","l");
5636     histoErrorCharge2->Draw("same");
5637     listofgraphs->Add((TObject *)histoErrorCharge2);
5638   }
5639   cch2->cd(2);
5640   legch3->Draw("same");
5641   cch2->cd(1);
5642   legch2->Draw("same");
5643
5644
5645   //Write if wanted
5646   if (fWriteCoef[0]){
5647     TFile *fout = TFile::Open(fWriteNameCoef,"UPDATE");
5648     // Check if the file could be opened
5649     if (!fout || !fout->IsOpen()) {
5650       AliInfo("No File found!");
5651     }
5652     
5653     else{
5654       for(Int_t k = 0; k < listofgraphs->GetEntriesFast(); k++){
5655         fout->WriteTObject((TObject *) listofgraphs->At(k),((TObject *)listofgraphs->At(k))->GetName(),(Option_t *) "OverWrite");
5656       }
5657     }
5658     fout->Close();
5659   }
5660     
5661 }
5662
5663 //_____________________________________________________________________________
5664 void AliTRDCalibra::PlotWritePH()
5665 {
5666   //
5667   // create the graph errors and write them if wanted
5668   //
5669
5670   //TObjArray of the grapherrors and so on
5671   TObjArray *listofgraphs = new TObjArray(); 
5672
5673   Int_t nbins = fDect2[1]-fDect1[1];
5674
5675   //See the number of fitted for delta
5676   
5677   //counter
5678   Int_t counter[2];
5679   counter[0] = 0;
5680   counter[1] = 0;
5681
5682   Double_t *xValuesFitted = new Double_t[nbins];
5683   Double_t *xValuesFittedPH = new Double_t[nbins];
5684   for(Int_t k = 0; k < nbins; k ++){
5685     xValuesFitted[k] = -1;
5686     xValuesFittedPH[k] = -1;
5687   }
5688
5689   for(Int_t l = 0; l < nbins; l++){
5690     if(fCoefVdrift[1][l] > 0){
5691       xValuesFitted[counter[1]]=l;
5692       counter[1]++;
5693     }
5694   }
5695   if(fFitPHOn){
5696     for(Int_t l = 0; l < nbins; l++){
5697       if(fCoefVdrift[0][l] > 0){
5698         xValuesFittedPH[counter[0]]= l;
5699         counter[0]++;
5700       }
5701     }
5702   }
5703
5704
5705   //Create the X and Xerror
5706   Double_t *xValues = new Double_t[nbins];
5707   Double_t *xValuesE = new Double_t[nbins];
5708   for(Int_t k = 0; k < nbins; k ++){
5709     xValues[k] = k;
5710     xValuesE[k] = 0.0;
5711   }
5712
5713   //Create the graph erros and plot them
5714   TGraph *graphVdrift2  = new TGraph(nbins,xValues,fCoefVdrift[2]);
5715   graphVdrift2->SetName("coefvdrift2");
5716   graphVdrift2->SetTitle("");
5717   graphVdrift2->GetXaxis()->SetTitle("Det/Pad groups");
5718   graphVdrift2->GetYaxis()->SetTitle("Vdrift [cm/#mus]");
5719   graphVdrift2->SetLineColor(4);
5720   listofgraphs->Add((TObject *)graphVdrift2);
5721   TGraphErrors *graphVdrift1  = new TGraphErrors(nbins,xValues,fCoefVdrift[1],xValuesE,fCoefVdriftE[1]);
5722   graphVdrift1->SetName("coefvdrift1");
5723   graphVdrift1->SetTitle("");
5724   graphVdrift1->GetXaxis()->SetTitle("Det/Pad groups");
5725   graphVdrift1->GetYaxis()->SetTitle("Vdrift [cm/#mus]");
5726   graphVdrift1->SetMarkerColor(6);
5727   graphVdrift1->SetLineColor(6);
5728   graphVdrift1->SetMarkerStyle(26);
5729   listofgraphs->Add((TObject *)graphVdrift1);
5730   TCanvas *cph1 = new TCanvas("cph1","",50,50,600,800);
5731   cph1->cd();
5732   TLegend *legph1 = new TLegend(0.4,0.6,0.89,0.89);
5733   legph1->AddEntry(graphVdrift2,"Vdrift simulated","l");
5734   legph1->AddEntry(graphVdrift1,"Vdrift fit","p");
5735   graphVdrift2->Draw("AL");
5736   graphVdrift1->Draw("P");
5737   if (fFitPHOn) {
5738     TGraphErrors *graphVdrift0  = new TGraphErrors(nbins,xValues,fCoefVdrift[0],xValuesE,fCoefVdriftE[0]);
5739     graphVdrift0->SetName("coefVdrift0");
5740     graphVdrift0->GetXaxis()->SetTitle("Det/Pad groups");
5741     graphVdrift0->GetYaxis()->SetTitle("Vdrift [cm/#mus]");
5742     graphVdrift0->SetTitle("");
5743     graphVdrift0->SetMarkerColor(2);
5744     graphVdrift0->SetLineColor(2);
5745     graphVdrift0->SetMarkerStyle(24);
5746     legph1->AddEntry(graphVdrift0,"v_{fit PH}","p");
5747     graphVdrift0->Draw("P");
5748     listofgraphs->Add((TObject *)graphVdrift0);
5749   } 
5750   legph1->Draw("same");
5751
5752   
5753   //Create the arrays and the graphs for the delta
5754   TCanvas *cph2 = new TCanvas("cph2","",50,50,600,800);
5755   cph2->Divide(2,1);
5756   cph2->cd(2);
5757   Double_t *yValuesDelta = new Double_t[counter[1]];
5758   for(Int_t k = 0; k < counter[1]; k++){
5759     if(fCoefVdrift[2][(Int_t)(xValuesFitted[k])] > 0.0) {
5760       yValuesDelta[k] = (fCoefVdrift[1][(Int_t)xValuesFitted[k]]-fCoefVdrift[2][(Int_t)xValuesFitted[k]])/fCoefVdrift[2][(Int_t)xValuesFitted[k]];
5761     }
5762     else yValuesDelta[k] = 0.0;
5763   }
5764   TGraph *graphDeltaVdrift1 = new TGraph(counter[1],&xValuesFitted[0],yValuesDelta);
5765   graphDeltaVdrift1->SetName("deltavdrift1");
5766   graphDeltaVdrift1->GetXaxis()->SetTitle("Det/Pad groups");
5767   graphDeltaVdrift1->GetYaxis()->SetTitle("#Deltav/v_{sim}");
5768   graphDeltaVdrift1->SetMarkerColor(6);
5769   graphDeltaVdrift1->SetTitle("");
5770   graphDeltaVdrift1->SetLineColor(6);
5771   graphDeltaVdrift1->SetMarkerStyle(26);
5772   listofgraphs->Add((TObject *)graphDeltaVdrift1);
5773   TLegend *legph3 = new TLegend(0.4,0.6,0.89,0.89);
5774   legph3->AddEntry(graphDeltaVdrift1,"v_{slope method}","p");
5775   graphDeltaVdrift1->Draw("AP");
5776   cph2->cd(1); 
5777   TH1I *histoErrorVdrift1 = new TH1I("errorvdrift1","",100  ,-0.05,0.05);
5778   histoErrorVdrift1->SetXTitle("#Deltav/v_{sim}");
5779   histoErrorVdrift1->SetYTitle("counts"); 
5780   histoErrorVdrift1->SetLineColor(6);
5781   histoErrorVdrift1->SetLineStyle(1);
5782   histoErrorVdrift1->SetStats(0);
5783   for(Int_t k = 0; k < counter[1]; k++){
5784     histoErrorVdrift1->Fill(yValuesDelta[k]);
5785   }
5786   TLegend *legph2 = new TLegend(0.4,0.6,0.89,0.89);
5787   legph2->AddEntry(histoErrorVdrift1,"v_{slope method}","l");
5788   histoErrorVdrift1->Draw();
5789   listofgraphs->Add((TObject *)histoErrorVdrift1); 
5790   if (fFitPHOn) {
5791     cph2->cd(2);
5792     Double_t *yValuesDeltaPH = new Double_t[counter[0]];
5793     for(Int_t k = 0; k < counter[0]; k++){
5794       if(fCoefVdrift[2][(Int_t)xValuesFittedPH[k]] > 0.0) {
5795         yValuesDeltaPH[k] = (fCoefVdrift[0][(Int_t)xValuesFittedPH[k]]-fCoefVdrift[2][(Int_t)xValuesFittedPH[k]])/fCoefVdrift[2][(Int_t)xValuesFittedPH[k]];
5796       }
5797       else yValuesDeltaPH[k] = 0.0;
5798     }
5799     TGraph *graphDeltaVdrift0 = new TGraph(counter[0],&xValuesFittedPH[0],yValuesDeltaPH);
5800     graphDeltaVdrift0->SetName("deltavdrift0");
5801     graphDeltaVdrift0->GetXaxis()->SetTitle("Det/Pad groups");
5802     graphDeltaVdrift0->GetYaxis()->SetTitle("#Deltav/v_{sim}");
5803     graphDeltaVdrift0->SetMarkerColor(2);
5804     graphDeltaVdrift0->SetMarkerStyle(24);
5805     graphDeltaVdrift0->SetLineColor(2);
5806     graphDeltaVdrift0->SetTitle("");
5807     legph3->AddEntry(graphDeltaVdrift0,"v_{fit PH}","p");
5808     graphDeltaVdrift0->Draw("P");
5809     listofgraphs->Add((TObject *)graphDeltaVdrift0);
5810     cph2->cd(1);
5811     TH1I *histoErrorVdrift0 = new TH1I("errorvdrift0","",100  ,-0.05,0.05);
5812     histoErrorVdrift0->SetXTitle("#Deltav/v_{sim}");
5813     histoErrorVdrift0->SetYTitle("counts");
5814     histoErrorVdrift0->SetLineColor(2);
5815     histoErrorVdrift0->SetLineStyle(2);
5816     histoErrorVdrift0->SetStats(0); 
5817     for(Int_t k = 0; k < counter[0]; k++){
5818       histoErrorVdrift0->Fill(yValuesDeltaPH[k]);
5819     }
5820     legph2->AddEntry(histoErrorVdrift0,"v_{fit PH}","l");
5821     histoErrorVdrift0->Draw("same");
5822     listofgraphs->Add((TObject *)histoErrorVdrift0);
5823   }
5824   cph2->cd(2);
5825   legph3->Draw("same");
5826   cph2->cd(1);
5827   legph2->Draw("same");
5828
5829
5830   //Write if wanted
5831   if (fWriteCoef[1]){
5832     TFile *fout = TFile::Open(fWriteNameCoef,"UPDATE");
5833     // Check if the file could be opened
5834     if (!fout || !fout->IsOpen()) {
5835       AliInfo("No File found!");
5836     }
5837     
5838     else{
5839       for(Int_t k = 0; k < listofgraphs->GetEntriesFast(); k++){
5840         fout->WriteTObject((TObject *) listofgraphs->At(k),((TObject *)listofgraphs->At(k))->GetName(),(Option_t *) "OverWrite");
5841       }
5842     }
5843     fout->Close();
5844   }
5845
5846 }
5847
5848 //_____________________________________________________________________________
5849 void AliTRDCalibra::PlotWriteT0()
5850 {
5851   //
5852   // create the graph errors and write them if wanted
5853   //
5854
5855   //TObjArray of the grapherrors and so on
5856   TObjArray *listofgraphs = new TObjArray(); 
5857
5858   Int_t nbins = fDect2[1]-fDect1[1];
5859
5860   //See the number of fitted for delta: here T0 can be negative, we don't use the sign but the error
5861   //and the grapherrors of the coefficients contained the no fitted with error 0.0
5862   
5863   //counter
5864   Int_t counter[2];
5865   counter[0] = 0;
5866   counter[1] = 0;
5867
5868   Double_t *xValuesFitted = new Double_t[nbins];
5869   Double_t *xValuesFittedPH = new Double_t[nbins];
5870   for(Int_t k = 0; k < nbins; k ++){
5871     xValuesFitted[k] = -1;
5872     xValuesFittedPH[k] = -1;
5873   }
5874
5875   for(Int_t l = 0; l < nbins; l++){
5876     if(fCoefT0E[1][l] != 0.0){
5877       xValuesFitted[counter[1]]=l;
5878       counter[1]++;
5879     }
5880   }
5881   if(fFitPHOn){
5882     for(Int_t l = 0; l < nbins; l++){
5883       if(fCoefT0E[0][l] != 0.0){
5884         xValuesFittedPH[counter[0]]= l;
5885         counter[0]++;
5886       }
5887     }
5888   }
5889
5890
5891   //Create the X and Xerror
5892   Double_t *xValues = new Double_t[nbins];
5893   Double_t *xValuesE = new Double_t[nbins];
5894   for(Int_t k = 0; k < nbins; k ++){
5895     xValues[k] = k;
5896     xValuesE[k] = 0.0;
5897   }
5898
5899   //Create the graph erros and plot them
5900   TGraph *graphT02  = new TGraph(nbins,xValues,fCoefT0[2]);
5901   graphT02->SetName("coeft02");
5902   graphT02->SetTitle("");
5903   graphT02->GetXaxis()->SetTitle("Det/Pad groups");
5904   graphT02->GetYaxis()->SetTitle("T0 [time bins]");
5905   graphT02->SetLineColor(4);
5906   listofgraphs->Add((TObject *)graphT02);
5907   TGraphErrors *graphT01  = new TGraphErrors(nbins,xValues,fCoefT0[1],xValuesE,fCoefT0E[1]);
5908   graphT01->SetName("coeft01");
5909   graphT01->SetTitle("");
5910   graphT01->GetXaxis()->SetTitle("Det/Pad groups");
5911   graphT01->GetYaxis()->SetTitle("T0 [time bins]");
5912   graphT01->SetMarkerColor(6);
5913   graphT01->SetLineColor(6);
5914   graphT01->SetMarkerStyle(26);
5915   listofgraphs->Add((TObject *)graphT01);
5916   TCanvas *ct01 = new TCanvas("ct01","",50,50,600,800);
5917   ct01->cd();
5918   TLegend *legt01 = new TLegend(0.4,0.6,0.89,0.89);
5919   legt01->AddEntry(graphT02,"T0 simulated","l");
5920   legt01->AddEntry(graphT01,"T0 slope method","p");
5921   graphT02->Draw("AL");
5922   graphT01->Draw("P");
5923   if (fFitPHOn) {
5924     TGraphErrors *graphT00  = new TGraphErrors(nbins,xValues,fCoefT0[0],xValuesE,fCoefT0E[0]);
5925     graphT00->SetName("coeft00");
5926     graphT00->GetXaxis()->SetTitle("Det/Pad groups");
5927     graphT00->GetYaxis()->SetTitle("T0 [time bins]");
5928     graphT00->SetTitle("");
5929     graphT00->SetMarkerColor(2);
5930     graphT00->SetLineColor(2);
5931     graphT00->SetMarkerStyle(24);
5932     legt01->AddEntry(graphT00,"T0 fit","p");
5933     graphT00->Draw("P");
5934     listofgraphs->Add((TObject *)graphT00);
5935   } 
5936   legt01->Draw("same");
5937
5938   
5939   //Create the arrays and the graphs for the delta
5940   TCanvas *ct02 = new TCanvas("ct02","",50,50,600,800);
5941   ct02->Divide(2,1);
5942   ct02->cd(2);
5943   Double_t *yValuesDelta = new Double_t[counter[1]];
5944   for(Int_t k = 0; k < counter[1]; k++){
5945     yValuesDelta[k] = (fCoefT0[1][(Int_t)xValuesFitted[k]]-fCoefT0[2][(Int_t)xValuesFitted[k]]);
5946   }
5947   TGraph *graphDeltaT01 = new TGraph(counter[1],&xValuesFitted[0],yValuesDelta);
5948   graphDeltaT01->SetName("deltat01");
5949   graphDeltaT01->GetXaxis()->SetTitle("Det/Pad groups");
5950   graphDeltaT01->GetYaxis()->SetTitle("#Deltat0 [time bins]");
5951   graphDeltaT01->SetMarkerColor(6);
5952   graphDeltaT01->SetTitle("");
5953   graphDeltaT01->SetLineColor(6);
5954   graphDeltaT01->SetMarkerStyle(26);
5955   listofgraphs->Add((TObject *)graphDeltaT01);
5956   TLegend *legt03 = new TLegend(0.4,0.6,0.89,0.89);
5957   legt03->AddEntry(graphDeltaT01,"T0_{slope method}","p");
5958   graphDeltaT01->Draw("AP");
5959   ct02->cd(1); 
5960   TH1I *histoErrorT01 = new TH1I("errort01","",100  ,-0.05,0.05);
5961   histoErrorT01->SetXTitle("#Deltat0 [time bins]");
5962   histoErrorT01->SetYTitle("counts"); 
5963   histoErrorT01->SetLineColor(6);
5964   histoErrorT01->SetLineStyle(1);
5965   histoErrorT01->SetStats(0);
5966   for(Int_t k = 0; k < counter[1]; k++){
5967     histoErrorT01->Fill(yValuesDelta[k]);
5968   }
5969   TLegend *legt02 = new TLegend(0.4,0.6,0.89,0.89);
5970   legt02->AddEntry(histoErrorT01,"T0_{slope method}","l");
5971   histoErrorT01->Draw();
5972   listofgraphs->Add((TObject *)histoErrorT01); 
5973   if (fFitPHOn) {
5974     ct02->cd(2);
5975     Double_t *yValuesDeltaPH = new Double_t[counter[0]];
5976     for(Int_t k = 0; k < counter[0]; k++){
5977       yValuesDeltaPH[k] = (fCoefT0[0][(Int_t)xValuesFittedPH[k]]-fCoefT0[2][(Int_t)xValuesFittedPH[k]]);
5978     }
5979     TGraph *graphDeltaT00 = new TGraph(counter[0],&xValuesFittedPH[0],yValuesDeltaPH);
5980     graphDeltaT00->SetName("deltat00");
5981     graphDeltaT00->GetXaxis()->SetTitle("Det/Pad groups");
5982     graphDeltaT00->GetYaxis()->SetTitle("#Deltat0 [time bins]");
5983     graphDeltaT00->SetMarkerColor(2);
5984     graphDeltaT00->SetMarkerStyle(24);
5985     graphDeltaT00->SetLineColor(2);
5986     graphDeltaT00->SetTitle("");
5987     legt03->AddEntry(graphDeltaT00,"T0_{fit PH}","p");
5988     graphDeltaT00->Draw("P");
5989     listofgraphs->Add((TObject *)graphDeltaT00);
5990     ct02->cd(1);
5991     TH1I *histoErrorT00 = new TH1I("errort00","",100  ,-0.05,0.05);
5992     histoErrorT00->SetXTitle("#Deltat0 [time bins]");
5993     histoErrorT00->SetYTitle("counts");
5994     histoErrorT00->SetLineColor(2);
5995     histoErrorT00->SetLineStyle(2);
5996     histoErrorT00->SetStats(0); 
5997     for(Int_t k = 0; k < counter[0]; k++){
5998       histoErrorT00->Fill(yValuesDeltaPH[k]);
5999     }
6000     legt02->AddEntry(histoErrorT00,"T0_{fit PH}","l");
6001     histoErrorT00->Draw("same");
6002     listofgraphs->Add((TObject *)histoErrorT00);
6003   }
6004   ct02->cd(2);
6005   legt03->Draw("same");
6006   ct02->cd(1);
6007   legt02->Draw("same");
6008
6009
6010   //Write if wanted
6011   if (fWriteCoef[1]){
6012     TFile *fout = TFile::Open(fWriteNameCoef,"UPDATE");
6013     // Check if the file could be opened
6014     if (!fout || !fout->IsOpen()) {
6015       AliInfo("No File found!");
6016     }
6017     
6018     else{
6019       for(Int_t k = 0; k < listofgraphs->GetEntriesFast(); k++){
6020         fout->WriteTObject((TObject *) listofgraphs->At(k),((TObject *)listofgraphs->At(k))->GetName(),(Option_t *) "OverWrite");
6021       }
6022     }
6023     fout->Close();
6024   }  
6025
6026 }
6027
6028 //_____________________________________________________________________________
6029 void AliTRDCalibra::PlotWritePRF()
6030 {
6031   //
6032   // create the graph errors and write them if wanted
6033   //
6034
6035   //TObjArray of the grapherrors and so on
6036   TObjArray *listofgraphs = new TObjArray(); 
6037
6038   Int_t nbins = fDect2[2]-fDect1[2];
6039
6040   //See the number of fitted for delta
6041   
6042   //counter
6043   Int_t counter = 0;
6044
6045   Double_t *xValuesFitted = new Double_t[nbins];
6046   for(Int_t k = 0; k < nbins; k ++){
6047     xValuesFitted[k] = -1;
6048   }
6049
6050   for(Int_t l = 0; l < nbins; l++){
6051     if(fCoefPRF[0][l] > 0){
6052       xValuesFitted[counter]=l;
6053       counter++;
6054     }
6055   }
6056  
6057
6058
6059   //Create the X and Xerror
6060   Double_t *xValues = new Double_t[nbins];
6061   Double_t *xValuesE = new Double_t[nbins];
6062   for(Int_t k = 0; k < nbins; k ++){
6063     xValues[k] = k;
6064     xValuesE[k] = 0.0;
6065   }
6066
6067   //Create the graph erros and plot them
6068   TGraph *graphPRF1  = new TGraph(nbins,xValues,fCoefPRF[1]);
6069   graphPRF1->SetName("coefprf1");
6070   graphPRF1->SetTitle("");
6071   graphPRF1->GetXaxis()->SetTitle("Det/Pad groups");
6072   graphPRF1->GetYaxis()->SetTitle("PRF width [p.u]");
6073   graphPRF1->SetLineColor(4);
6074   graphPRF1->SetMarkerColor(4);
6075   graphPRF1->SetMarkerStyle(25);
6076   graphPRF1->SetMarkerSize(0.7);
6077   listofgraphs->Add((TObject *)graphPRF1);
6078   TGraphErrors *graphPRF0  = new TGraphErrors(nbins,xValues,fCoefPRF[0],xValuesE,fCoefPRFE);
6079   graphPRF0->SetName("coefprf0");
6080   graphPRF0->SetTitle("");
6081   graphPRF0->GetXaxis()->SetTitle("Det/Pad groups");
6082   graphPRF0->GetYaxis()->SetTitle("PRF Width [p.u]");
6083   graphPRF0->SetMarkerColor(6);
6084   graphPRF0->SetLineColor(6);
6085   graphPRF0->SetMarkerStyle(26);
6086   listofgraphs->Add((TObject *)graphPRF0);
6087   TCanvas *cprf1 = new TCanvas("cprf1","",50,50,600,800);
6088   cprf1->cd();
6089   TLegend *legprf1 = new TLegend(0.4,0.6,0.89,0.89);
6090   legprf1->AddEntry(graphPRF1,"PRF width simulated","p");
6091   legprf1->AddEntry(graphPRF0,"PRF fit","p");
6092   graphPRF1->Draw("AP");
6093   graphPRF0->Draw("P");
6094   legprf1->Draw("same");
6095
6096   
6097   //Create the arrays and the graphs for the delta
6098   TCanvas *cprf2 = new TCanvas("cprf2","",50,50,600,800);
6099   cprf2->Divide(2,1);
6100   cprf2->cd(2);
6101   Double_t *yValuesDelta = new Double_t[counter];
6102   for(Int_t k = 0; k < counter; k++){
6103     if(fCoefPRF[1][(Int_t)xValuesFitted[k]] > 0.0){
6104       yValuesDelta[k] = (fCoefPRF[0][(Int_t)xValuesFitted[k]]-fCoefPRF[1][(Int_t)xValuesFitted[k]])/(fCoefPRF[1][(Int_t)xValuesFitted[k]]);
6105     }
6106   }
6107   TGraph *graphDeltaPRF = new TGraph(counter,&xValuesFitted[0],yValuesDelta);
6108   graphDeltaPRF->SetName("deltaprf");
6109   graphDeltaPRF->GetXaxis()->SetTitle("Det/Pad groups");
6110   graphDeltaPRF->GetYaxis()->SetTitle("#Delta#sigma/#sigma_{sim}");
6111   graphDeltaPRF->SetMarkerColor(6);
6112   graphDeltaPRF->SetTitle("");
6113   graphDeltaPRF->SetLineColor(6);
6114   graphDeltaPRF->SetMarkerStyle(26);
6115   listofgraphs->Add((TObject *)graphDeltaPRF);
6116   TLegend *legprf3 = new TLegend(0.4,0.6,0.89,0.89);
6117   legprf3->AddEntry(graphDeltaPRF,"#sigma_{fit}","p");
6118   graphDeltaPRF->Draw("AP");
6119   cprf2->cd(1); 
6120   TH1I *histoErrorPRF = new TH1I("errorprf1","",100  ,-0.5,0.5);
6121   histoErrorPRF->SetXTitle("#Delta#sigma/#sigma_{sim}");
6122   histoErrorPRF->SetYTitle("counts"); 
6123   histoErrorPRF->SetLineColor(6);
6124   histoErrorPRF->SetLineStyle(1);
6125   histoErrorPRF->SetStats(0);
6126   for(Int_t k = 0; k < counter; k++){
6127     histoErrorPRF->Fill(yValuesDelta[k]);
6128   }
6129   TLegend *legprf2 = new TLegend(0.4,0.6,0.89,0.89);
6130   legprf2->AddEntry(histoErrorPRF,"#sigma_{fit}","l");
6131   histoErrorPRF->Draw();
6132   listofgraphs->Add((TObject *)histoErrorPRF); 
6133   cprf2->cd(2);
6134   legprf3->Draw("same");
6135   cprf2->cd(1);
6136   legprf2->Draw("same");
6137
6138
6139   //Write if wanted
6140   if (fWriteCoef[2]){
6141     TFile *fout = TFile::Open(fWriteNameCoef,"UPDATE");
6142     // Check if the file could be opened
6143     if (!fout || !fout->IsOpen()) {
6144       AliInfo("No File found!");
6145     }
6146     
6147     else{
6148       for(Int_t k = 0; k < listofgraphs->GetEntriesFast(); k++){
6149         fout->WriteTObject((TObject *) listofgraphs->At(k),((TObject *)listofgraphs->At(k))->GetName(),(Option_t *) "OverWrite");
6150       }
6151     }
6152     fout->Close();
6153   }  
6154   
6155 }
6156
6157 //
6158 //____________Plot histos DB___________________________________________________
6159 //
6160
6161 //_____________________________________________________________________________
6162 void AliTRDCalibra::PlotCHDB()
6163 {
6164   //
6165   // Plot the histos for fDebug = 3 and fDebug = 4 to visualise the detector
6166   //
6167
6168   TCanvas *cchdb = new TCanvas("cchdb","",50,50,600,800);
6169   if ((fFitChargeBisOn) && (fMeanChargeOn)) {
6170     cchdb->Divide(3,1);
6171     cchdb->cd(1);
6172     fCoefChargeDB[0]->Draw("LEGO");
6173     cchdb->cd(2);
6174     fCoefChargeDB[1]->Draw("LEGO");
6175     cchdb->cd(3);
6176     fCoefChargeDB[2]->Draw("LEGO");
6177   }
6178   if ((!fFitChargeBisOn) && (fMeanChargeOn)) {
6179     cchdb->Divide(2,1);
6180     cchdb->cd(1);
6181     fCoefChargeDB[0]->Draw("LEGO");
6182     cchdb->cd(2);
6183     fCoefChargeDB[1]->Draw("LEGO");
6184   }
6185   else {
6186     cchdb->cd();
6187     fCoefChargeDB[0]->Draw("LEGO");
6188   }
6189
6190 }
6191
6192 //_____________________________________________________________________________
6193 void AliTRDCalibra::PlotPHDB()
6194 {
6195   //
6196   // Plot the histos for fDebug = 3 and fDebug = 4 to visualise the detector
6197   //
6198
6199   TCanvas *cphdb = new TCanvas("cphdb","",50,50,600,800);
6200   if (fFitPHOn) {
6201     cphdb->Divide(2,1);
6202     cphdb->cd(1);
6203     fCoefVdriftDB[0]->Draw("LEGO");
6204     cphdb->cd(2);
6205     fCoefVdriftDB[1]->Draw("LEGO");
6206   }
6207   else {
6208     cphdb->cd();
6209     fCoefVdriftDB[1]->Draw("LEGO");
6210   }
6211
6212 }
6213
6214 //_____________________________________________________________________________
6215 void AliTRDCalibra::PlotT0DB()
6216 {
6217   //
6218   // Plot the histos for fDebug = 3 and fDebug = 4 to visualise the detector
6219   //
6220
6221   TCanvas *ct0db = new TCanvas("ct0db","",50,50,600,800);
6222   if (fFitPHOn ) {
6223     ct0db->Divide(2,1);
6224     ct0db->cd(1);
6225     fCoefT0DB[0]->Draw("LEGO");
6226     ct0db->cd(2);
6227     fCoefT0DB[1]->Draw("LEGO");
6228   }
6229   else {
6230     ct0db->cd();
6231     fCoefT0DB[1]->Draw("LEGO");
6232   }
6233
6234 }
6235
6236 //_____________________________________________________________________________
6237 void AliTRDCalibra::PlotPRFDB()
6238 {
6239   //
6240   // Plot the histos for fDebug = 3 and fDebug = 4 to visualise the detector
6241   //
6242
6243   TCanvas *cprfdb = new TCanvas("cprfdb","",50,50,600,800);
6244   cprfdb->cd();
6245   fCoefPRFDB->Draw("LEGO");
6246
6247 }
6248
6249 //
6250 //____________Write DB Histos__________________________________________________
6251 //
6252
6253 //_____________________________________________________________________________
6254 void AliTRDCalibra::WriteCHDB(TFile *fout)
6255 {
6256   //
6257   // If wanted, write the debug histos for fDebug = 3 and fDebug = 4
6258   //
6259
6260   fout->WriteTObject(fCoefChargeDB[0],fCoefChargeDB[0]->GetName(),(Option_t *) "OverWrite");
6261   if (fMeanChargeOn) {
6262     fout->WriteTObject(fCoefChargeDB[1],fCoefChargeDB[1]->GetName(),(Option_t *) "OverWrite");
6263   }
6264   if (fFitChargeBisOn ) {
6265     fout->WriteTObject(fCoefChargeDB[2],fCoefChargeDB[2]->GetName(),(Option_t *) "OverWrite");
6266   }
6267
6268 }
6269
6270 //_____________________________________________________________________________
6271 void AliTRDCalibra::WritePHDB(TFile *fout)
6272 {
6273   //
6274   // If wanted, write the debug histos for fDebug = 3 and fDebug = 4
6275   //
6276
6277   if (fFitPHOn) {
6278     fout->WriteTObject(fCoefVdriftDB[0],fCoefVdriftDB[0]->GetName(),(Option_t *) "OverWrite");
6279   }
6280   fout->WriteTObject(fCoefVdriftDB[1],fCoefVdriftDB[1]->GetName(),(Option_t *) "OverWrite");
6281
6282 }
6283
6284 //_____________________________________________________________________________
6285 void AliTRDCalibra::WriteT0DB(TFile *fout)
6286 {
6287   //
6288   // If wanted, write the debug histos for fDebug = 3 and fDebug = 4
6289   //
6290
6291   if (fFitPHOn) {
6292     fout->WriteTObject(fCoefT0DB[0],fCoefT0DB[0]->GetName(),(Option_t *) "OverWrite");
6293   }
6294   fout->WriteTObject(fCoefT0DB[1],fCoefT0DB[1]->GetName(),(Option_t *) "OverWrite");
6295
6296 }
6297
6298 //_____________________________________________________________________________
6299 void AliTRDCalibra::WritePRFDB(TFile *fout)
6300 {
6301   //
6302   // If wanted, write the debug histos for fDebug = 3 and fDebug = 4
6303   //
6304
6305   fout->WriteTObject(fCoefPRFDB,fCoefPRFDB->GetName(),(Option_t *) "OverWrite");
6306
6307 }
6308
6309 //
6310 //____________Calcul Coef Mean_________________________________________________
6311 //
6312
6313 //_____________________________________________________________________________
6314 Bool_t AliTRDCalibra::CalculT0CoefMean(Int_t dect, Int_t idect)
6315 {
6316   //
6317   // For the detector Dect calcul the mean time 0
6318   // for the calibration group idect from the choosen database
6319   //
6320
6321   AliTRDcalibDB *cal = AliTRDcalibDB::Instance();
6322   if (!cal) {
6323     AliInfo("Could not get calibDB  Manager");
6324     return kFALSE;
6325   }
6326
6327   fT0Coef[2] = 0.0;
6328
6329   if ((fDebug != 2) && fAccCDB) {
6330
6331     for (Int_t row = fRowMin[1]; row < fRowMax[1]; row++) {
6332       for (Int_t col = fColMin[1]; col < fColMax[1]; col++) {
6333         // Groups of pads
6334         if ((fNz[1]    > 0) && 
6335             (fNrphi[1] > 0)) {
6336           fT0Coef[2] += (Float_t) cal->GetT0(dect,col,row);
6337         }
6338         // Per detectors
6339         else {
6340           fT0Coef[2] += (Float_t) cal->GetT0Average(dect);
6341         }
6342       }
6343     }
6344
6345     fT0Coef[2] = fT0Coef[2] / ((fColMax[1]-fColMin[1])*(fRowMax[1]-fRowMin[1]));
6346     if ((fDebug == 1) || 
6347         (fDebug == 4)) {
6348       fCoefT0[2][idect] = fT0Coef[2];
6349     }
6350
6351   }
6352
6353   return kTRUE;
6354   
6355 }
6356
6357 //_____________________________________________________________________________
6358 Bool_t AliTRDCalibra::CalculChargeCoefMean(Int_t dect, Int_t idect, Bool_t vrai)
6359 {
6360   //
6361   // For the detector Dect calcul the mean gain factor
6362   // for the calibration group idect from the choosen database
6363   //
6364
6365   AliTRDcalibDB     *cal    = AliTRDcalibDB::Instance();
6366   if (!cal) {
6367     AliInfo("Could not get calibDB  Manager");
6368     return kFALSE;
6369   }
6370   AliTRDCommonParam *parCom = AliTRDCommonParam::Instance();
6371   if (!parCom) {
6372     AliInfo("Could not get CommonParam  Manager");
6373     return kFALSE;
6374   }
6375
6376   fChargeCoef[3] = 0.0;
6377
6378   if (fDebug != 2) {
6379
6380     for (Int_t row = fRowMin[0]; row < fRowMax[0]; row++) {
6381       for (Int_t col = fColMin[0]; col < fColMax[0]; col++) {
6382         // Groups of pads
6383         if ((fNz[0]    > 0) || 
6384             (fNrphi[0] > 0)) {
6385           if (fAccCDB) {
6386             fChargeCoef[3] += (Float_t) cal->GetGainFactor(dect,col,row);
6387           }
6388           if (vrai && fAccCDB) {
6389             fScaleFitFactor += (Float_t) cal->GetGainFactor(dect,col,row);
6390           }
6391           if (!fAccCDB) {
6392             fChargeCoef[3] += 1.0;
6393           }
6394           if (vrai && (!fAccCDB)) {
6395             fScaleFitFactor += 1.0;
6396           }
6397         }
6398         // Per detectors
6399         else {
6400           if (fAccCDB) {
6401             fChargeCoef[3] += (Float_t) cal->GetGainFactorAverage(dect);
6402           }
6403           if (vrai && fAccCDB) {
6404             fScaleFitFactor += ((Float_t) cal->GetGainFactorAverage(dect));
6405           }
6406           if (!fAccCDB) {
6407             fChargeCoef[3] += 1.0;
6408           }
6409           if (vrai && (!fAccCDB)) {
6410             fScaleFitFactor += 1.0;
6411           }
6412         }
6413       }
6414     }
6415
6416     fChargeCoef[3] = fChargeCoef[3] / ((fColMax[0]-fColMin[0])*(fRowMax[0]-fRowMin[0]));
6417     if ((fDebug == 1) || 
6418         (fDebug == 4)) {
6419       fCoefCharge[3][idect]=fChargeCoef[3];
6420     }
6421
6422   }
6423
6424   return kTRUE;
6425
6426 }
6427
6428 //_____________________________________________________________________________
6429 Bool_t AliTRDCalibra::CalculPRFCoefMean(Int_t dect, Int_t idect)
6430 {
6431   //
6432   // For the detector Dect calcul the mean sigma of pad response
6433   // function for the calibration group idect from the choosen database
6434   //
6435
6436   AliTRDcalibDB     *cal    = AliTRDcalibDB::Instance();
6437   if (!cal) {
6438     AliInfo("Could not get calibDB  Manager");
6439     return kFALSE;
6440   }
6441
6442   AliTRDCommonParam *parCom = AliTRDCommonParam::Instance();
6443   if (!parCom) {
6444     AliInfo("Could not get CommonParam  Manager");
6445     return kFALSE;
6446   }
6447
6448   fPRFCoef[1] = 0.0;
6449   Int_t cot = 0;
6450
6451   if (fDebug != 2) {
6452     
6453     for (Int_t row = fRowMin[2]; row < fRowMax[2]; row++) {
6454       for (Int_t col = fColMin[2]; col < fColMax[2]; col++) {
6455         if ((parCom->GetColMax(GetPlane(dect)) != (col+1)) && (col != 0)) {
6456           cot++;
6457           if (fAccCDB) {
6458             fPRFCoef[1] += (Float_t) cal->GetPRFWidth(dect,col,row);
6459           }
6460           if (!fAccCDB) {
6461             fPRFCoef[1] += GetPRFDefault(GetPlane(dect));
6462           }
6463         }
6464       }
6465     }
6466
6467     if (cot > 0) {
6468       fPRFCoef[1] = fPRFCoef[1]/cot;
6469       if ((fDebug == 1) ||
6470           (fDebug == 4)) {
6471         fCoefPRF[1][idect] = fPRFCoef[1];
6472       }
6473     }
6474     if (cot <= 0) {
6475       if ((fDebug == 1) ||
6476           (fDebug == 4)) {
6477         if (fAccCDB) {
6478           fCoefPRF[1][idect] = cal->GetPRFWidth(dect,fColMin[2],fRowMin[2]);
6479         }
6480         if (!fAccCDB) {
6481           fCoefPRF[1][idect] = GetPRFDefault(GetPlane(dect));
6482         }
6483       }
6484     }
6485
6486   }
6487
6488   return kTRUE;
6489   
6490 }
6491
6492 //_____________________________________________________________________________
6493 Bool_t AliTRDCalibra::CalculVdriftCoefMean(Int_t dect, Int_t idect)
6494 {
6495   //
6496   // For the detector dect calcul the mean drift velocity for the
6497   // calibration group idect from the choosen database
6498   //
6499
6500   AliTRDcalibDB *cal = AliTRDcalibDB::Instance();
6501   if (!cal) {
6502     AliInfo("Could not get calibDB  Manager");
6503     return kFALSE;
6504   }
6505
6506   fVdriftCoef[2] = 0.0;
6507
6508   if (fDebug != 2) {
6509     for (Int_t row = fRowMin[1]; row < fRowMax[1]; row++) {
6510       for (Int_t col = fColMin[1]; col < fColMax[1]; col++) {
6511         // Groups of pads
6512         if ((fNz[1]    > 0) || 
6513             (fNrphi[1] > 0)) {
6514           if (fAccCDB) {
6515             fVdriftCoef[2] += (Float_t) cal->GetVdrift(dect,col,row);
6516           }
6517           if (!fAccCDB) {
6518             fVdriftCoef[2] += 1.5;
6519           }
6520         }
6521         // Per detectors
6522         else {
6523           if (fAccCDB) {
6524             fVdriftCoef[2] += (Float_t) cal->GetVdriftAverage(dect);
6525           }
6526           if (!fAccCDB) {
6527             fVdriftCoef[2] += 1.5;
6528           }
6529         }
6530       }
6531     }
6532     fVdriftCoef[2] = fVdriftCoef[2] / ((fColMax[1]-fColMin[1])*(fRowMax[1]-fRowMin[1]));
6533     if ((fDebug == 1) || 
6534         (fDebug == 4)) {
6535       fCoefVdrift[2][idect] = fVdriftCoef[2];
6536     }
6537   }
6538
6539   return kTRUE;
6540   
6541 }
6542
6543 //_____________________________________________________________________________
6544 Float_t AliTRDCalibra::GetPRFDefault(Int_t plane) const
6545 {
6546   //
6547   // Default width of the PRF if there is no database as reference
6548   //
6549
6550   if (plane == 0) {
6551     return 0.515;
6552   }
6553   if (plane == 1) {
6554     return 0.502;
6555   }
6556   if (plane == 2) {
6557     return 0.491;
6558   }
6559   if (plane == 3) {
6560     return 0.481;
6561   }
6562   if (plane == 4) {
6563     return 0.471;
6564   }
6565   if (plane == 5) {
6566     return 0.463;
6567   }
6568   else {
6569     return 0.0;
6570   }
6571   
6572 }
6573
6574 //
6575 //____________Pad group calibration mode_______________________________________
6576 //
6577
6578 //_____________________________________________________________________________
6579 void AliTRDCalibra::ReconstructionRowPadGroup(Int_t idect, Int_t i)
6580 {
6581   //
6582   // For the calibration group idect in a detector calculate the
6583   // first and last row pad and col pad.
6584   // The pads in the interval will have the same calibrated coefficients
6585   //
6586
6587   Int_t posc = -1;
6588   Int_t posr = -1;
6589   fRowMin[i] = -1;
6590   fRowMax[i] = -1;
6591   fColMin[i] = -1;
6592   fColMax[i] = -1;
6593   
6594   if (fNfragZ[i]    != 0) {
6595     posc = (Int_t) idect / fNfragZ[i];
6596   }
6597   if (fNfragRphi[i] != 0) {
6598     posr = (Int_t) idect % fNfragZ[i];
6599   }
6600   fRowMin[i] = posr     * fNnZ[i];
6601   fRowMax[i] = (posr+1) * fNnZ[i];
6602   fColMin[i] = posc     * fNnRphi[i];
6603   fColMax[i] = (posc+1) * fNnRphi[i];
6604
6605 }
6606
6607 //_____________________________________________________________________________
6608 void AliTRDCalibra::CalculXBins(Int_t idect, Int_t i)
6609 {
6610   //
6611   // For the detector idect calcul the first Xbins
6612   //
6613
6614   fXbins[i] = 0;
6615   if (fDebug == 4) {
6616     AliInfo(Form("detector: %d", idect));
6617   }
6618
6619   // In which sector?
6620   Int_t sector = GetSector(idect);
6621   fXbins[i] += sector*(6*fDetChamb2[i]+6*4*fDetChamb0[i]);
6622  
6623   // In which chamber?
6624   Int_t chamber = GetChamber(idect);
6625   Int_t kc      = 0;
6626   while (kc < chamber) {
6627     if (kc == 2) {
6628       fXbins[i] += 6 * fDetChamb2[i];
6629     }
6630     else {
6631       fXbins[i] += 6 * fDetChamb0[i];
6632     }
6633     kc ++;
6634   }
6635   
6636   // In which plane?
6637   Int_t plane = GetPlane(idect);
6638   if (chamber == 2) {
6639     fXbins[i] += plane*fDetChamb2[i];
6640   }
6641   else {
6642     fXbins[i] += plane*fDetChamb0[i];
6643   }
6644  
6645 }
6646
6647 //_____________________________________________________________________________
6648 Int_t AliTRDCalibra::SearchInVector(Int_t group, Int_t i) const
6649 {
6650   //
6651   // Search if the calibration group "group" has already been
6652   // initialised by a previous track in the vector
6653   //
6654
6655   if (i == 0) {
6656     for (Int_t k = 0; k < (Int_t) fPlaCH->GetEntriesFast(); k++) {
6657       if (((AliTRDPlace *) fPlaCH->At(k))->GetPlace() == group) {
6658         return k;
6659       }
6660     }
6661     return -1;
6662   }
6663
6664   if (i == 1) {
6665     for (Int_t k = 0; k < (Int_t) fPlaPH->GetEntriesFast(); k++) {
6666       if (((AliTRDPlace *) fPlaPH->At(k))->GetPlace() == group) {
6667         return k;
6668       }
6669     }
6670     return -1;
6671   }
6672
6673   if (i == 2) {
6674     for (Int_t k = 0; k < (Int_t) fPlaPRF->GetEntriesFast(); k++) {
6675       if (((AliTRDPlace *) fPlaPRF->At(k))->GetPlace() == group) {
6676         return k;
6677       }
6678     }
6679     return -1;
6680   }
6681
6682   return -1;
6683
6684 }
6685
6686 //_____________________________________________________________________________
6687 Int_t AliTRDCalibra::SearchInTreeVector(TObjArray *vectorplace, Int_t group) const
6688 {
6689   //
6690   // Search if the calibration group "group" is present in the tree
6691   //
6692
6693   for (Int_t k = 0; k < (Int_t) vectorplace->GetEntriesFast(); k++) {
6694     if (((AliTRDPlace *) vectorplace->At(k))->GetPlace() == group) {
6695       return k;
6696     }
6697   }
6698
6699   return -1;
6700
6701 }
6702
6703 //_____________________________________________________________________________
6704 Int_t AliTRDCalibra::SearchBin(Float_t value, Int_t i) const
6705 {
6706   //
6707   // Search the bin
6708   //
6709
6710   Int_t reponse      = 0;
6711   Int_t fbinmin      = 0;
6712   Int_t fbinmax      = (Int_t) value;
6713   Int_t fNumberOfBin = -1;
6714
6715   // Charge
6716   if (i == 0) {
6717     fbinmax      = 300;
6718     fbinmin      = 0;
6719     fNumberOfBin = fNumberBinCharge;
6720   }
6721
6722   // PRF
6723   if (i == 2) {
6724     fbinmax      = 1;
6725     fbinmin      = -1;
6726     fNumberOfBin = fNumberBinPRF;
6727   }
6728
6729   // Return -1 if out
6730   if ((value >= fbinmax) || 
6731       (value <  fbinmin)) {
6732     return -1;
6733   }
6734   // Sinon
6735   else {
6736     reponse = (Int_t) ((fNumberOfBin*(value-fbinmin)) / (fbinmax-fbinmin));
6737   }
6738
6739   return reponse;
6740
6741 }
6742
6743 //_____________________________________________________________________________
6744 Bool_t AliTRDCalibra::UpdateVectorCH(Int_t group, Float_t value)
6745 {
6746   //
6747   // Fill the vector if a new calibration group "group" or update the
6748   // values of the calibration group "group" if already here  
6749   //
6750
6751   // Search bin
6752   Int_t bin = SearchBin(value,0);
6753   // Out
6754   if ((bin < 0) || (bin >= fNumberBinCharge)) {
6755     return kFALSE; 
6756   }
6757
6758   // Search place
6759   Int_t place = SearchInVector(group,0);
6760
6761   // New group
6762   if (place == -1) {
6763     AliTRDPlace *placegroup = new AliTRDPlace();
6764     placegroup->SetPlace(group);
6765     fPlaCH->Add((TObject *) placegroup);
6766     // Variable
6767     AliTRDCTInfo *fCHInfo = new AliTRDCTInfo();
6768     UShort_t *entries = new UShort_t[fNumberBinCharge];
6769     // Initialise first
6770     for(Int_t k = 0; k < fNumberBinCharge; k++) {
6771       entries[k] = 0;
6772     }
6773     // Add the value
6774     entries[bin]= 1;
6775     // Set
6776     fCHInfo->SetEntries(entries);
6777     // Set in the vector
6778     fVectorCH->Add((TObject *) fCHInfo);
6779   }
6780   // Group already exits
6781   else {
6782     // Variable
6783     AliTRDCTInfo *fCHInfo = new AliTRDCTInfo();
6784     // Retrieve
6785     fCHInfo = ((AliTRDCTInfo *) fVectorCH->At(place));
6786     UShort_t *entries = fCHInfo->GetEntries();
6787     // Add
6788     entries[bin]++;
6789     // Set
6790     fCHInfo->SetEntries(entries);
6791     // Update the vector
6792     fVectorCH->AddAt((TObject *) fCHInfo,place);
6793   }
6794
6795   return kTRUE;
6796
6797 }
6798
6799 //_____________________________________________________________________________
6800 Bool_t AliTRDCalibra::UpdateVectorPRF(Int_t group, Float_t x, Float_t y)
6801 {
6802   //
6803   // Fill the vector if a new calibration group "group" or update the
6804   // values of the calibration group "group" if already here  
6805   //
6806
6807   // Search bin
6808   Int_t bin = SearchBin(x,2);
6809   // Out
6810   if ((bin < 0) || (bin >= fNumberBinPRF)) {
6811     return kFALSE; 
6812   }
6813
6814   // Search place
6815   Int_t place = SearchInVector(group,2);
6816
6817   // New group
6818   if (place == -1) {
6819
6820     AliTRDPlace *placegroup = new AliTRDPlace();
6821     placegroup->SetPlace(group);
6822     fPlaPRF->Add((TObject *) placegroup);
6823     AliTRDPInfo *fPRFInfo = new AliTRDPInfo();
6824
6825     Float_t  *sum       = new Float_t[fNumberBinPRF];
6826     Float_t  *sumsquare = new Float_t[fNumberBinPRF];
6827     UShort_t *entries   = new UShort_t[fNumberBinPRF];
6828
6829     // Initialise first
6830     for (Int_t k = 0; k < fNumberBinPRF; k++) {
6831       sum[k]       = 0.0;
6832       sumsquare[k] = 0.0;
6833       entries[k]   = 0;
6834     }
6835
6836     // Add the value
6837     sum[bin]       += y;
6838     sumsquare[bin] += y*y;
6839     entries[bin]++;
6840
6841     // Set
6842     fPRFInfo->SetSum(sum);
6843     fPRFInfo->SetSumSquare(sumsquare);
6844     fPRFInfo->SetEntries(entries);
6845
6846     // Set in the vector
6847     fVectorPRF->Add((TObject *) fPRFInfo);
6848         
6849   }
6850   // Group already exits
6851   else {
6852
6853     AliTRDPInfo *fPRFInfo = new AliTRDPInfo();
6854     // Retrieve
6855     fPRFInfo = (AliTRDPInfo *) fVectorPRF->At(place);
6856
6857     Float_t  *sum       = fPRFInfo->GetSum();
6858     Float_t  *sumsquare = fPRFInfo->GetSumSquare();
6859     UShort_t *entries   = fPRFInfo->GetEntries();
6860
6861     // Add
6862     Double_t calcul       = (((Double_t) fPRFInfo->GetEntries()[bin])
6863                            * ((Double_t) fPRFInfo->GetSum()[bin]) + (Double_t) y)
6864                           / (((Double_t) fPRFInfo->GetEntries()[bin]) + 1);
6865     sum[bin]       = (Float_t) calcul;
6866     Double_t calculsquare = (((Double_t) fPRFInfo->GetSumSquare()[bin])
6867                            * ((Double_t) fPRFInfo->GetEntries()[bin]) + ((Double_t) y)*((Double_t) y))
6868                           / (((Double_t) fPRFInfo->GetEntries()[bin]) + 1);
6869     sumsquare[bin] = (Float_t) calculsquare;
6870     entries[bin]++;
6871
6872     // Set
6873     fPRFInfo->SetSum(sum);
6874     fPRFInfo->SetSumSquare(sumsquare);
6875     fPRFInfo->SetEntries(entries);
6876  
6877     // Update the vector
6878     fVectorPRF->AddAt((TObject *) fPRFInfo,place);
6879
6880   }
6881
6882   return kTRUE;
6883
6884 }
6885
6886 //_____________________________________________________________________________
6887 Bool_t AliTRDCalibra::UpdateVectorPH(Int_t group, Int_t time, Float_t value)
6888 {
6889   //
6890   // Fill the vector if a new calibration group "group" or update
6891   // the values of the calibration group "group" if already here  
6892   //
6893
6894   // Search bin
6895   Int_t bin = time;
6896   // Out
6897   if ((bin <         0) || 
6898       (bin >= fTimeMax)) {
6899     return kFALSE; 
6900   }
6901
6902   // Search place
6903   Int_t place = SearchInVector(group,1);
6904
6905   // New group
6906   if(place == -1){
6907
6908     AliTRDPlace *placegroup = new AliTRDPlace();
6909     placegroup->SetPlace(group);
6910     fPlaPH->Add((TObject *) placegroup);
6911     AliTRDPInfo *fPHInfo = new AliTRDPInfo();
6912
6913     Float_t  *sum       = new Float_t[fTimeMax];
6914     Float_t  *sumsquare = new Float_t[fTimeMax];
6915     UShort_t *entries   = new UShort_t[fTimeMax];
6916
6917     // Initialise first
6918     for (Int_t k = 0; k < fTimeMax; k++) {
6919       sum[k]       = 0.0;
6920       sumsquare[k] = 0.0;
6921       entries[k]   = 0;
6922     }
6923
6924     // Add the value
6925     sum[bin]       += value;
6926     sumsquare[bin] += value*value;
6927     entries[bin]++;
6928
6929     // Set
6930     fPHInfo->SetSum(sum);
6931     fPHInfo->SetSumSquare(sumsquare);
6932     fPHInfo->SetEntries(entries);
6933
6934     // Set in the vector
6935     fVectorPH->Add((TObject *) fPHInfo);
6936
6937   }
6938   // Group already exits
6939   else {
6940
6941     AliTRDPInfo *fPHInfo = new AliTRDPInfo();
6942     // Retrieve
6943     fPHInfo = (AliTRDPInfo *) fVectorPH->At(place);
6944
6945     Float_t  *sum       = fPHInfo->GetSum();
6946     Float_t  *sumsquare = fPHInfo->GetSumSquare();
6947     UShort_t *entries   = fPHInfo->GetEntries();
6948
6949     // Add
6950     Double_t calcul       = (((Double_t) fPHInfo->GetEntries()[bin])
6951                            * ((Double_t) fPHInfo->GetSum()[bin]) + (Double_t) value)
6952                           / (((Double_t) fPHInfo->GetEntries()[bin]) + 1);
6953     sum[bin]       = (Float_t) calcul;
6954     Double_t calculsquare = ((((Double_t) fPHInfo->GetSumSquare()[bin])
6955                             * ((Double_t) fPHInfo->GetEntries()[bin])) 
6956                           + (((Double_t) value) * ((Double_t)value))) 
6957                           / (((Double_t) fPHInfo->GetEntries()[bin]) + 1);
6958     sumsquare[bin] = (Float_t) calculsquare;
6959     entries[bin]++;
6960
6961     // Set
6962     fPHInfo->SetSum(sum);
6963     fPHInfo->SetSumSquare(sumsquare);
6964     fPHInfo->SetEntries(entries);
6965
6966     // Update the vector
6967     fVectorPH->AddAt((TObject *) fPHInfo,place);
6968
6969   }
6970
6971   return kTRUE;
6972
6973 }
6974   
6975 //_____________________________________________________________________________
6976 TGraphErrors *AliTRDCalibra::ConvertVectorPHisto(AliTRDPInfo *pInfo
6977                                                , const Char_t *name) const
6978 {
6979   //
6980   // Convert the PInfo in a 1D grapherror, name must contains "PRF"
6981   // if PRF calibration and not "PRF" for Vdrift calibration
6982   //
6983
6984   TGraphErrors *histo;
6985   const Char_t *pattern1 = "PRF";
6986
6987   // Axis
6988   Double_t *x;
6989   Double_t *y;
6990   Double_t *ex;
6991   Double_t *ey;
6992   Double_t step = 0.0;
6993   Double_t min  = 0.0;
6994
6995   // Ntimes
6996   Int_t ntimes = 0;
6997   if (strstr(name,pattern1)) {
6998     ntimes = fNumberBinPRF;
6999   }
7000   else {
7001     ntimes = fTimeMax;
7002   }
7003   x  = new Double_t[ntimes]; // Xaxis
7004   y  = new Double_t[ntimes]; // Mean
7005   ex = new Double_t[ntimes]; // Nentries
7006   ey = new Double_t[ntimes]; // Sum of square/nentries
7007
7008   // Init histo
7009   if (!strstr(name,pattern1)) {
7010     step = 1.0 / fSf;
7011     min  = 0.0;
7012   }
7013   else {
7014     step = (1.0 - (-1.0)) / fNumberBinPRF;
7015     min  = -1.0 + step / 2.0;
7016   }
7017
7018   // Fill histo
7019   for (Int_t k = 0; k < ntimes; k++) {
7020     x[k]  = min + k*step;
7021     y[k]  = 0.0;
7022     ex[k] = 0.0;
7023     ey[k] = 0.0;
7024     // Fill only if there is more than 0 something
7025     if (pInfo->GetEntries()[k] > 0) {
7026       ex[k] = pInfo->GetEntries()[k];
7027       y[k]  = pInfo->GetSum()[k];
7028       ey[k] =  pInfo->GetSumSquare()[k];
7029     }
7030   }
7031
7032   // Define the TGraphErrors
7033   histo = new TGraphErrors(ntimes,x,y,ex,ey);
7034   histo->SetTitle(name); 
7035   return histo;
7036
7037 }
7038  
7039 //_____________________________________________________________________________
7040 TH1F *AliTRDCalibra::ConvertVectorCTHisto(AliTRDCTInfo *cTInfo
7041                                         , const Char_t * name) const
7042 {
7043   //
7044   // Convert the CTInfo in a 1D histo
7045   //
7046
7047   TH1F *histo;
7048   
7049   Int_t     ntimes  = fNumberBinCharge;
7050   UShort_t *entries = cTInfo->GetEntries();
7051   
7052   // Init histo
7053   histo = new TH1F(name,name,fNumberBinCharge,0,300);
7054   histo->Sumw2();
7055   // Fill histo
7056   for (Int_t k = 0; k < ntimes; k++) {
7057     histo->SetBinContent(k+1,entries[k]);
7058     histo->SetBinError(k+1,TMath::Sqrt(TMath::Abs(entries[k])));
7059   }
7060   
7061   return histo;
7062
7063 }
7064
7065 //_____________________________________________________________________________
7066 TTree *AliTRDCalibra::ConvertVectorCTTreeHisto(TObjArray *vVectorCT
7067                                              , TObjArray *pPlaCT
7068                                              , const Char_t *name
7069                                              , const Char_t *nametitle) const
7070 {
7071   //
7072   // Convert the vector in a tree with two branchs: the group number
7073   // and the TH1F histo reconstructed from the vector
7074   //
7075
7076   // Size of the things
7077   Int_t ntotal = (Int_t) pPlaCT->GetEntriesFast();
7078   if (ntotal == 0) {
7079     AliInfo("nothing to write!");
7080     TTree *treeCT = new TTree(name,nametitle);
7081     return treeCT;
7082   }
7083   
7084   // Variable of the tree
7085   Int_t groupnumber = -1; // Group calibration
7086   TH1F      *histo = 0x0;
7087   TObjArray  vectorCT = *vVectorCT;
7088   TObjArray  plaCT    = *pPlaCT;
7089
7090   // Init the tree
7091   TTree *treeCT = new TTree(name,nametitle);
7092   treeCT->Branch("groupnumber",&groupnumber,"groupnumber/I");
7093   treeCT->Branch("histo","TH1F",&histo,32000,0);
7094
7095   // Fill
7096   Int_t k = 0;
7097   while (k < ntotal) {
7098     TString nome(name);
7099     groupnumber  = ((AliTRDPlace *) plaCT.At(0))->GetPlace();
7100     nome        += groupnumber;
7101     histo        = ConvertVectorCTHisto(((AliTRDCTInfo *) vectorCT.At(0)),nome);
7102     treeCT->Fill();
7103     vectorCT.RemoveAt(0);
7104     vectorCT.Compress();
7105     plaCT.RemoveAt(0);
7106     plaCT.Compress();
7107     k++;
7108   } 
7109
7110   return treeCT;
7111
7112 }
7113
7114 //_____________________________________________________________________________
7115 TTree *AliTRDCalibra::ConvertVectorPTreeHisto(TObjArray *vVectorP
7116                                             , TObjArray *pPlaP
7117                                             , const Char_t *name
7118                                             , const Char_t *nametitle) const
7119 {
7120   //
7121   // Convert the vector in a tree with two branchs: the group number
7122   // and the TGraphErrors histo reconstructed from the vector.
7123   // The name must contain "PRF" for PRF calibration and not "PRF"
7124   // for Vdrift calibration
7125   //
7126
7127   // Size of the things
7128   Int_t ntotal = (Int_t) pPlaP->GetEntriesFast();
7129   if (ntotal == 0) {
7130     AliInfo("nothing to write!");
7131     TTree *treeP = new TTree(name,nametitle);
7132     return treeP;
7133   }
7134
7135   // Variable of the tree
7136   Int_t groupnumber = -1; // Group calibration
7137   TGraphErrors *histo   = 0x0;
7138   TObjArray     vectorP = *vVectorP;
7139   TObjArray     plaP    = *pPlaP;
7140
7141   // Init the tree
7142   TTree *treeP = new TTree(name,nametitle);
7143   treeP->Branch("groupnumber",&groupnumber,"groupnumber/I");
7144   treeP->Branch("histo","TGraphErrors",&histo,32000,0);
7145
7146   // Fill
7147   Int_t k = 0;
7148   while (k < ntotal) {
7149     TString nome(name);
7150     groupnumber = ((AliTRDPlace *) plaP.At(0))->GetPlace();
7151     nome       += groupnumber;
7152     histo       = ConvertVectorPHisto((AliTRDPInfo *) vectorP.At(0),nome);
7153     treeP->Fill();
7154     vectorP.RemoveAt(0);
7155     vectorP.Compress();
7156     plaP.RemoveAt(0);
7157     plaP.Compress();
7158     k++;
7159   } 
7160
7161   return treeP;
7162
7163 }
7164
7165 //_____________________________________________________________________________
7166 TObjArray *AliTRDCalibra::ConvertTreeVector(TTree *tree) const
7167 {
7168   //
7169   // Convert the branch groupnumber of the tree taken from
7170   // TRD.calibration.root in case of vector method in a std::vector 
7171   // to be faster
7172   //
7173
7174   // Initialise
7175   TObjArray *vectorplace = new TObjArray();
7176   
7177   // Variable of the tree
7178   Int_t groupnumber = -1; // Group calibration
7179
7180   // Set the branch
7181   tree->SetBranchAddress("groupnumber",&groupnumber);
7182     
7183   // Fill
7184   Int_t ntotal = tree->GetEntries();
7185   for (Int_t k = 0; k < ntotal; k++) {
7186     tree->GetEntry(k);
7187     AliTRDPlace *placegroupnumber = new AliTRDPlace();
7188     placegroupnumber->SetPlace(groupnumber);
7189     vectorplace->Add((TObject *) placegroupnumber);
7190   }
7191   
7192   return vectorplace;
7193
7194 }
7195
7196 //_____________________________________________________________________________
7197 Bool_t AliTRDCalibra::MergeVectorCT(TObjArray *vVectorCT2, TObjArray *pPlaCT2)
7198 {
7199   //
7200   // Add the two vectors and place the result in the first
7201   //
7202
7203   if (((Int_t) pPlaCT2->GetEntriesFast()) != ((Int_t) vVectorCT2->GetEntriesFast())){
7204     AliInfo("VectorCT2 doesn't correspond to PlaCT2!");
7205     return kFALSE;
7206   }
7207  
7208   // CH case
7209   for (Int_t k = 0; k < (Int_t) fPlaCH->GetEntriesFast(); k++) {
7210     
7211     // Look if PlaCT1[k] it is also in the second vector
7212     Int_t place = -1;
7213     for (Int_t j = 0; j < (Int_t) pPlaCT2->GetEntriesFast(); j++) {
7214       if (((AliTRDPlace *) pPlaCT2->At(j))->GetPlace() == 
7215             ((AliTRDPlace *) fPlaCH->At(k))->GetPlace()) {
7216         place = j;
7217         break;
7218       }
7219     }
7220     
7221     // If not in the second vector nothing to do
7222
7223     // If in the second vector
7224     if (place != -1) {
7225       
7226       AliTRDCTInfo *fCTInfo = new AliTRDCTInfo();
7227       UShort_t *entries = new UShort_t[fNumberBinCharge];
7228       
7229       for (Int_t nu = 0; nu < fNumberBinCharge; nu++) {
7230         entries[nu] = ((AliTRDCTInfo *)  fVectorCH->At(((AliTRDPlace *) fPlaCH->At(k))->GetPlace()))->GetEntries()[nu]
7231                     + ((AliTRDCTInfo *) vVectorCT2->At(((AliTRDPlace *) fPlaCH->At(k))->GetPlace()))->GetEntries()[nu];
7232       }
7233       
7234       // Set
7235       fCTInfo->SetEntries(entries);
7236
7237       // Nothing to do on PlaCT1
7238       
7239       // Update the vector 
7240       fVectorCH->AddAt((TObject *) fCTInfo,((AliTRDPlace *) fPlaCH->At(k))->GetPlace());
7241
7242     }
7243     
7244   } 
7245  
7246   // And at the end the vector in CT2 but not in CH1
7247   for (Int_t k = 0; k < (Int_t) pPlaCT2->GetEntriesFast(); k++) {
7248     
7249     // Look if pPlaCT2[k] it is also in the second vector
7250     Int_t place = -1;
7251     for (Int_t j = 0; j < (Int_t) fPlaCH->GetEntriesFast(); j++) {
7252       if (((AliTRDPlace *) fPlaCH->At(j))->GetPlace() == ((AliTRDPlace *) pPlaCT2->At(k))->GetPlace()) {
7253         place = j;
7254         break;
7255       }
7256     }
7257
7258     // If not in the first vector
7259     if (place == -1) {
7260       
7261       AliTRDCTInfo *fCTInfo = new AliTRDCTInfo();     
7262       fCTInfo = ((AliTRDCTInfo *) vVectorCT2->At(((AliTRDPlace *) pPlaCT2->At(k))->GetPlace()));
7263       
7264       // Add at the end 
7265       fPlaCH->Add((TObject *) (pPlaCT2->At(k)));
7266       fVectorCH->Add((TObject *) fCTInfo);
7267
7268     }
7269     
7270   }
7271   
7272   return kTRUE;
7273   
7274 }
7275
7276 //_____________________________________________________________________________
7277 Bool_t AliTRDCalibra::MergeVectorP(TObjArray *vVectorP2
7278                                  , TObjArray *pPlaP2
7279                                  , Int_t i)
7280 {
7281   //
7282   // Add the two vectors and place the result in the first
7283   //
7284
7285   if (((Int_t) pPlaP2->GetEntriesFast()) != ((Int_t) vVectorP2->GetEntriesFast())) {
7286     AliInfo("VectorP2 doesn't correspond to PlaP2!");
7287     return kFALSE;
7288   }
7289
7290   // PH case
7291   if (i == 1) {
7292
7293      for (Int_t k = 0; k < (Int_t) fPlaPH->GetEntriesFast(); k++) {
7294        
7295        // Look if fPlaPH[k] it is also in the second vector
7296        Int_t place = -1;
7297        for (Int_t j = 0; j < (Int_t) pPlaP2->GetEntriesFast(); j++) {
7298          if (((AliTRDPlace *) pPlaP2->At(j))->GetPlace() == ((AliTRDPlace *) fPlaPH->At(k))->GetPlace()) {
7299            place = j;
7300            break;
7301          }
7302        }
7303        
7304        // If not in the second vector nothing to do
7305
7306        // If in the second vector
7307        if (place != -1) {
7308
7309          AliTRDPInfo *fPInfo = new AliTRDPInfo();
7310          UShort_t *entries   = new UShort_t[fTimeMax];
7311          Float_t  *sum       = new Float_t[fTimeMax];
7312          Float_t  *sumsquare = new Float_t[fTimeMax];
7313
7314          for (Int_t nu = 0; nu < fTimeMax; nu++) {
7315            
7316            entries[nu]   = ((AliTRDPInfo *) fVectorPH->At(((AliTRDPlace *) fPlaPH->At(k))->GetPlace()))->GetEntries()[nu]
7317                          + ((AliTRDPInfo *) vVectorP2->At(((AliTRDPlace *) fPlaPH->At(k))->GetPlace()))->GetEntries()[nu];
7318            
7319            Double_t calcul       = ((((Double_t) ((AliTRDPInfo *) fVectorPH->At(((AliTRDPlace *) fPlaPH->At(k))->GetPlace()))->GetSum()[nu])
7320                                    * ((Double_t) ((AliTRDPInfo *) fVectorPH->At(((AliTRDPlace *) fPlaPH->At(k))->GetPlace()))->GetEntries()[nu]))
7321                                   + (((Double_t) ((AliTRDPInfo *) vVectorP2->At(((AliTRDPlace *) fPlaPH->At(k))->GetPlace()))->GetSum()[nu])
7322                                    * ((Double_t) ((AliTRDPInfo *) vVectorP2->At(((AliTRDPlace *) fPlaPH->At(k))->GetPlace()))->GetEntries()[nu])))
7323                                  / ((Double_t) fPInfo->GetEntries()[nu]);
7324
7325            sum[nu]       = (Float_t) calcul;
7326            
7327            Double_t calculsquare = ((((Double_t) ((AliTRDPInfo *) fVectorPH->At(((AliTRDPlace *) fPlaPH->At(k))->GetPlace()))->GetSumSquare()[nu])
7328                                    * ((Double_t) ((AliTRDPInfo *) fVectorPH->At(((AliTRDPlace *) fPlaPH->At(k))->GetPlace()))->GetEntries()[nu]))
7329                                   + (((Double_t) ((AliTRDPInfo *) vVectorP2->At(((AliTRDPlace *) fPlaPH->At(k))->GetPlace()))->GetSumSquare()[nu])
7330                                    * ((Double_t) ((AliTRDPInfo *) vVectorP2->At(((AliTRDPlace *) fPlaPH->At(k))->GetPlace()))->GetEntries()[nu])))
7331                                  / ((Double_t) fPInfo->GetEntries()[nu]);
7332            
7333            
7334            sumsquare[nu] = calculsquare;
7335
7336          }
7337
7338          // Set
7339          fPInfo->SetSum(sum);
7340          fPInfo->SetSumSquare(sumsquare);
7341          fPInfo->SetEntries(entries);
7342          
7343          // Nothing to do on PlaCT1
7344          
7345          // Update the vector VectorCT1
7346          fVectorPH->AddAt((TObject *) fPInfo,((AliTRDPlace *) fPlaPH->At(k))->GetPlace());
7347          
7348        }
7349
7350      }
7351
7352      // And at the end the vector in P2 but not in CH1
7353      for (Int_t k = 0; k < (Int_t) pPlaP2->GetEntriesFast(); k++) {
7354        
7355        // Look if PlaCT2[k] it is also in the second vector
7356        Int_t place = -1;
7357        for (Int_t j = 0; j < (Int_t) fPlaPH->GetEntriesFast(); j++) {
7358          if (((AliTRDPlace *) fPlaPH->At(j))->GetPlace() == ((AliTRDPlace *) pPlaP2->At(k))->GetPlace()) {
7359            place = j;
7360            break;
7361          }
7362        }
7363        
7364        // If not in the first vector
7365        if (place == -1) {
7366                  
7367          AliTRDPInfo *fPInfo = new AliTRDPInfo();
7368          fPInfo = (AliTRDPInfo *) vVectorP2->At(((AliTRDPlace *) pPlaP2->At(k))->GetPlace());
7369          
7370          // Add at the end of CH1
7371          fPlaPH->Add(((TObject *) pPlaP2->At(k)));
7372          fVectorPH->Add((TObject *) fPInfo);
7373
7374        }
7375
7376      }
7377
7378    }
7379    
7380
7381    // PRF case
7382    if (i == 1) {
7383
7384      for (Int_t k = 0; k < (Int_t) fPlaPRF->GetEntriesFast(); k++) {
7385
7386        // Look if fPlaPRF[k] it is also in the second vector
7387        Int_t place = -1;
7388        for (Int_t j = 0; j < (Int_t) pPlaP2->GetEntriesFast(); j++) {
7389          if (((AliTRDPlace *) pPlaP2->At(j))->GetPlace() == ((AliTRDPlace *) fPlaPRF->At(k))->GetPlace()) {
7390            place = j;
7391            break;
7392          }
7393        }
7394
7395        // If not in the second vector nothing to do
7396
7397        // If in the second vector
7398        if (place != -1) {
7399         
7400          AliTRDPInfo *fPInfo = new AliTRDPInfo();
7401          UShort_t *entries   = new UShort_t[fNumberBinPRF];
7402          Float_t  *sum       = new Float_t[fNumberBinPRF];
7403          Float_t  *sumsquare = new Float_t[fNumberBinPRF];
7404
7405          for (Int_t nu = 0; nu < fNumberBinPRF; nu++) {
7406            
7407            entries[nu]           = ((AliTRDPInfo *) fVectorPRF->At(((AliTRDPlace *) fPlaPRF->At(k))->GetPlace()))->GetEntries()[nu]
7408                                  + ((AliTRDPInfo *)  vVectorP2->At(((AliTRDPlace *) fPlaPRF->At(k))->GetPlace()))->GetEntries()[nu];
7409            
7410            Double_t calcul       = ((((Double_t) ((AliTRDPInfo *) fVectorPRF->At(((AliTRDPlace *) fPlaPRF->At(k))->GetPlace()))->GetSum()[nu])
7411                                    * ((Double_t) ((AliTRDPInfo *) fVectorPRF->At(((AliTRDPlace *) fPlaPRF->At(k))->GetPlace()))->GetEntries()[nu]))
7412                                   + (((Double_t) ((AliTRDPInfo *)  vVectorP2->At(((AliTRDPlace *) fPlaPRF->At(k))->GetPlace()))->GetSum()[nu])
7413                                    * ((Double_t) ((AliTRDPInfo *)  vVectorP2->At(((AliTRDPlace *) fPlaPRF->At(k))->GetPlace()))->GetEntries()[nu])))
7414                                  / ((Double_t) fPInfo->GetEntries()[nu]);
7415
7416            sum[nu]               = (Float_t) calcul;
7417            
7418            Double_t calculsquare = ((((Double_t) ((AliTRDPInfo *) fVectorPRF->At(((AliTRDPlace *) fPlaPRF->At(k))->GetPlace()))->GetSumSquare()[nu])
7419                                    * ((Double_t) ((AliTRDPInfo *) fVectorPRF->At(((AliTRDPlace *) fPlaPRF->At(k))->GetPlace()))->GetEntries()[nu]))
7420                                   + (((Double_t) ((AliTRDPInfo *)  vVectorP2->At(((AliTRDPlace *) fPlaPRF->At(k))->GetPlace()))->GetSumSquare()[nu])
7421                                    * ((Double_t) ((AliTRDPInfo *)  vVectorP2->At(((AliTRDPlace *) fPlaPRF->At(k))->GetPlace()))->GetEntries()[nu])))
7422                                  / ((Double_t) fPInfo->GetEntries()[nu]);
7423
7424            sumsquare[nu]         = calculsquare;
7425
7426          }
7427
7428          // Set
7429          fPInfo->SetSum(sum);
7430          fPInfo->SetSumSquare(sumsquare);
7431          fPInfo->SetEntries(entries);
7432
7433          // Nothing to do on PlaCT1
7434          
7435          // Update the vector VectorCT1
7436          fVectorPRF->AddAt((TObject *) fPInfo,((AliTRDPlace *) fPlaPRF->At(k))->GetPlace());
7437          
7438        }
7439
7440      }
7441
7442      // And at the end the vector in P2 but not in CH1
7443      for (Int_t k = 0; k < (Int_t) pPlaP2->GetEntriesFast(); k++) {
7444        
7445        // Look if PlaCT2[k] it is also in the second vector
7446        Int_t place = -1;
7447        for (Int_t j = 0; j < (Int_t) fPlaPRF->GetEntriesFast(); j++) {
7448          if (((AliTRDPlace *) fPlaPRF->At(j))->GetPlace() == ((AliTRDPlace *) pPlaP2->At(k))->GetPlace()) {
7449            place = j;
7450            break;
7451          }
7452        }
7453
7454        // If not in the first vector
7455        if (place == -1) {
7456
7457          AliTRDPInfo *fPInfo = new AliTRDPInfo();
7458          fPInfo = (AliTRDPInfo *) vVectorP2->At(((AliTRDPlace *) pPlaP2->At(k))->GetPlace());
7459
7460          // Add at the end of CH1
7461          fPlaPRF->Add(((TObject *) pPlaP2->At(k)));
7462          fVectorPRF->Add((TObject *) fPInfo);
7463
7464        }
7465        
7466      }
7467
7468    } 
7469
7470    return kTRUE;
7471
7472 }
7473
7474 //____________Fit Methods______________________________________________________
7475
7476 //_____________________________________________________________________________
7477 void AliTRDCalibra::FitPente(TH1* projPH, Int_t idect)
7478 {
7479   //
7480   // Slope methode for the drift velocity
7481   //
7482   
7483   // Constants
7484   const Float_t kDrWidth = AliTRDgeometry::DrThick();
7485   Int_t binmax   = 0;
7486   Int_t binmin   = 0;
7487   fPhd[0]        = 0.0;
7488   fPhd[1]        = 0.0;
7489   fPhd[2]        = 0.0;
7490   Int_t ju       = 0;
7491   Double_t vdriftCoefE = 0.0;
7492   Double_t t0CoefE = 0.0;
7493   fVdriftCoef[1] = 0.0;
7494   fT0Coef[1]     = 0.0;
7495   TLine *line = new TLine();
7496
7497   // Some variables
7498   TAxis   *xpph    = projPH->GetXaxis();
7499   Int_t    nbins   = xpph->GetNbins();
7500   Double_t lowedge = xpph->GetBinLowEdge(1);
7501   Double_t upedge  = xpph->GetBinUpEdge(xpph->GetNbins());
7502   Double_t widbins = (upedge - lowedge) / nbins;
7503   Double_t limit   = upedge + 0.5 * widbins; 
7504
7505   // Beginning of the signal
7506   TH1D *pentea = new TH1D("pentea","pentea",projPH->GetNbinsX(),0,(Float_t) limit);
7507   for (Int_t k = 1; k <  projPH->GetNbinsX(); k++) {
7508     pentea->SetBinContent(k,(Double_t) (projPH->GetBinContent(k+1) - projPH->GetBinContent(k)));
7509   }
7510
7511   binmax = (Int_t) pentea->GetMaximumBin();
7512   if (binmax == 1) {
7513     binmax = 2;
7514     AliInfo("Put the binmax from 1 to 2 to enable the fit");
7515   }
7516   pentea->Fit("pol2","0MR","",TMath::Max(pentea->GetBinCenter(binmax-1),0.0),pentea->GetBinCenter(binmax+1));
7517   Float_t l3P1am = pentea->GetFunction("pol2")->GetParameter(1);
7518   Float_t l3P2am = pentea->GetFunction("pol2")->GetParameter(2);
7519   Float_t l3P1amE = pentea->GetFunction("pol2")->GetParError(1);
7520   Float_t l3P2amE = pentea->GetFunction("pol2")->GetParError(2);
7521   if (l3P2am != 0) {
7522     fPhd[0] = -(l3P1am / (2 * l3P2am));
7523   }
7524   if((l3P1am != 0.0) && (l3P2am != 0.0)){
7525     t0CoefE = (l3P1amE/l3P1am + l3P2amE/l3P2am)*fPhd[0];
7526   }
7527   
7528   // Amplification region
7529   binmax = 0;
7530   ju     = 0;
7531   for (Int_t kbin = 1; kbin < projPH->GetNbinsX(); kbin ++) {
7532     if (((projPH->GetBinContent(kbin+1) - projPH->GetBinContent(kbin)) <= 0.0) && (ju == 0) && (kbin > (fPhd[0]/widbins))) {
7533       binmax = kbin;
7534       ju     = 1;
7535     }
7536   }
7537   if (binmax == 1) {
7538     binmax = 2;
7539     AliInfo("Put the binmax from 1 to 2 to enable the fit");
7540   }
7541   projPH->Fit("pol2","0MR","",TMath::Max(projPH->GetBinCenter(binmax-1),0.0),projPH->GetBinCenter(binmax+1));
7542   Float_t l3P1amf = projPH->GetFunction("pol2")->GetParameter(1);
7543   Float_t l3P2amf = projPH->GetFunction("pol2")->GetParameter(2);
7544   Float_t l3P1amfE = projPH->GetFunction("pol2")->GetParError(1);
7545   Float_t l3P2amfE = projPH->GetFunction("pol2")->GetParError(2);
7546   
7547   if (l3P2amf != 0) {
7548     fPhd[1] = -(l3P1amf / (2 * l3P2amf));
7549   }
7550   if((l3P1amf != 0.0) && (l3P2amf != 0.0)){
7551     vdriftCoefE = (l3P1amfE/l3P1amf + l3P2amfE/l3P2amf)*fPhd[1];
7552   }
7553
7554   // Drift region
7555   TH1D *pente = new TH1D("pente","pente",projPH->GetNbinsX(),0,(Float_t) limit);
7556   for (Int_t k = binmax+4; k <  projPH->GetNbinsX(); k++) {
7557     pente->SetBinContent(k,(Double_t) (projPH->GetBinContent(k+1) - projPH->GetBinContent(k)));
7558   }
7559   binmin = (Int_t) pente->GetMinimumBin();
7560   if (binmin == 1) {
7561     binmin = 2;
7562     AliInfo("Put the binmax from 1 to 2 to enable the fit");
7563   }
7564   pente->Fit("pol2"
7565             ,"0MR"
7566             ,""
7567             ,TMath::Max(pente->GetBinCenter(binmin-1),             0.0)
7568             ,TMath::Min(pente->GetBinCenter(binmin+2),(Double_t) limit));
7569   Float_t l3P1dr = pente->GetFunction("pol2")->GetParameter(1);
7570   Float_t l3P2dr = pente->GetFunction("pol2")->GetParameter(2);
7571   Float_t l3P1drE = pente->GetFunction("pol2")->GetParError(1);
7572   Float_t l3P2drE = pente->GetFunction("pol2")->GetParError(2);
7573   if (l3P2dr != 0) {
7574     fPhd[2] = -(l3P1dr / (2 * l3P2dr));
7575   }
7576   if((l3P1dr != 0.0) && (l3P2dr != 0.0)){
7577     vdriftCoefE += (l3P1drE/l3P1dr + l3P2drE/l3P2dr)*fPhd[2]; 
7578   }
7579
7580   if ((fPhd[2] > fPhd[0]) && 
7581       (fPhd[2] > fPhd[1]) && 
7582       (fPhd[1] > fPhd[0])) {
7583     fVdriftCoef[1] = (kDrWidth) / (fPhd[2]-fPhd[1]);
7584     if (fPhd[0] >= 0.0) {
7585       fT0Coef[1] = (fPhd[0] - fT0Shift) / widbins;
7586       if (fT0Coef[1] < -1.0) {
7587         fT0Coef[1] = fT0Coef[2];
7588       }
7589     }
7590     else {
7591       fT0Coef[1] = fT0Coef[2];
7592     }
7593   }
7594   else {
7595     fVdriftCoef[1] = -TMath::Abs(fVdriftCoef[2]);
7596     fT0Coef[1]     = fT0Coef[2];
7597   }
7598
7599   if ((fDebug == 1) || 
7600       (fDebug == 4)) {
7601     fCoefVdrift[1][idect] = fVdriftCoef[1];
7602     fCoefVdriftE[1] [idect] = vdriftCoefE;
7603     fCoefT0[1][idect] = fT0Coef[1];
7604     fCoefT0E[1][idect] = t0CoefE;
7605   }
7606   
7607   if (fDebug == 2) {
7608     TCanvas *cpentei = new TCanvas("cpentei","cpentei",50,50,600,800);
7609     cpentei->cd();
7610     projPH->Draw();
7611     line->SetLineColor(2);
7612     line->DrawLine(fPhd[0],0,fPhd[0],projPH->GetMaximum());
7613     line->DrawLine(fPhd[1],0,fPhd[1],projPH->GetMaximum());
7614     line->DrawLine(fPhd[2],0,fPhd[2],projPH->GetMaximum());
7615     AliInfo(Form("fPhd[0] (beginning of the signal): %f"                  ,(Float_t) fPhd[0]));
7616     AliInfo(Form("fPhd[1] (end of the amplification region): %f"          ,(Float_t) fPhd[1]));
7617     AliInfo(Form("fPhd[2] (end of the drift region): %f"                  ,(Float_t) fPhd[2]));
7618     AliInfo(Form("fVriftCoef[1] (with only the drift region(default)): %f",(Float_t) fVdriftCoef[1]));
7619   }
7620
7621   if (fDebug != 2) {
7622     delete pentea;
7623   }
7624   if (fDebug != 2) {
7625     delete pente;
7626   }
7627
7628 }
7629
7630 //_____________________________________________________________________________
7631 void AliTRDCalibra::FitPH(TH1* projPH, Int_t idect)
7632 {
7633   //
7634   // Fit methode for the drift velocity
7635   //
7636   
7637   // Constants
7638   const Float_t kDrWidth = AliTRDgeometry::DrThick();  
7639
7640   // Some variables
7641   TAxis   *xpph   = projPH->GetXaxis();
7642   Double_t upedge = xpph->GetBinUpEdge(xpph->GetNbins());
7643
7644   TF1 *fPH = new TF1("fPH",AliTRDCalibra::PH,-0.05,3.2,6);
7645   fPH->SetParameter(0,0.469);     // Scaling
7646   fPH->SetParameter(1,0.18);      // Start 
7647   fPH->SetParameter(2,0.0857325); // AR
7648   fPH->SetParameter(3,1.89);      // DR
7649   fPH->SetParameter(4,0.08);      // QA/QD
7650   fPH->SetParameter(5,0.0);       // Baseline
7651
7652   TLine *line = new TLine();
7653
7654   fVdriftCoef[0] = 0.0;
7655   fT0Coef[0]     = 0.0;
7656   Double_t vdriftCoefE = 0.0;
7657   Double_t t0CoefE = 0.0;
7658  
7659   if (idect%fFitPHPeriode == 0) {
7660
7661     AliInfo(Form("<AliTRDCalibra::FitPH> The detector %d will be fitted",idect));
7662     fPH->SetParameter(0,(projPH->Integral()-(projPH->GetBinContent(1)*projPH->GetNbinsX())) * 0.00028); // Scaling
7663     fPH->SetParameter(1,fPhd[0] - 0.1);                                                                 // Start 
7664     fPH->SetParameter(2,fPhd[1] - fPhd[0]);                                                             // AR
7665     fPH->SetParameter(3,fPhd[2] - fPhd[1]);                                                             // DR
7666     fPH->SetParameter(4,0.225);                                                                         // QA/QD
7667     fPH->SetParameter(5,(Float_t) projPH->GetBinContent(1));
7668     
7669     if (fDebug != 2) {
7670       projPH->Fit(fPH,"0M","",0.0,upedge);
7671     }
7672
7673     if (fDebug == 2) {
7674       TCanvas *cpente = new TCanvas("cpente","cpente",50,50,600,800);
7675       cpente->cd();
7676       projPH->Fit(fPH,"M+","",0.0,upedge);
7677       projPH->Draw("E0");
7678       line->SetLineColor(4);
7679       line->DrawLine(fPH->GetParameter(1)
7680                     ,0
7681                     ,fPH->GetParameter(1)
7682                     ,projPH->GetMaximum());
7683       line->DrawLine(fPH->GetParameter(1)+fPH->GetParameter(2)
7684                     ,0
7685                     ,fPH->GetParameter(1)+fPH->GetParameter(2)
7686                     ,projPH->GetMaximum());
7687       line->DrawLine(fPH->GetParameter(1)+fPH->GetParameter(2)+fPH->GetParameter(3)
7688                     ,0
7689                     ,fPH->GetParameter(1)+fPH->GetParameter(2)+fPH->GetParameter(3)
7690                     ,projPH->GetMaximum());
7691     }
7692
7693     if (fPH->GetParameter(3) != 0) {
7694       fVdriftCoef[0] = kDrWidth / (fPH->GetParameter(3));
7695       vdriftCoefE = (fPH->GetParError(3)/fPH->GetParameter(3))*fVdriftCoef[0];
7696       fT0Coef[0]     = fPH->GetParameter(1);
7697       t0CoefE = fPH->GetParError(1);
7698     } 
7699     else {
7700       fVdriftCoef[0] = -TMath::Abs(fVdriftCoef[2]);
7701       fT0Coef[0]     = fT0Coef[2];
7702     }
7703
7704     if ((fDebug == 1) || 
7705         (fDebug == 4)) {
7706       fCoefVdrift[0][idect] = fVdriftCoef[0];
7707       fCoefVdriftE[0][idect] = vdriftCoefE;
7708       fCoefT0[0][idect] = fT0Coef[0];
7709       fCoefT0E[0][idect] = t0CoefE;
7710     }
7711     if (fDebug == 2) {
7712       AliInfo(Form("fVdriftCoef[0]: %f",(Float_t) fVdriftCoef[0]));
7713     }
7714
7715   }
7716
7717   else {
7718
7719     // Put the default value 
7720     if ((fDebug <= 1) || 
7721         (fDebug == 4)) {
7722       fCoefVdrift[0][idect] = -TMath::Abs(fVdriftCoef[2]);
7723       fCoefT0[0][idect] = -TMath::Abs(fT0Coef[2]);
7724     }
7725
7726   }
7727
7728   if (fDebug != 2) {
7729     delete fPH;
7730   }
7731   
7732 }
7733
7734 //_____________________________________________________________________________
7735 void AliTRDCalibra::FitPRF(TH1 *projPRF, Int_t idect)
7736 {
7737   //
7738   // Fit methode for the sigma of the pad response function
7739   //
7740   
7741   fPRFCoef[0] = 0.0;
7742   Double_t prfCoefE = 0.0;
7743
7744   if (fDebug != 2) {
7745     projPRF->Fit("gaus","0M","",-fRangeFitPRF,fRangeFitPRF);
7746   }
7747   
7748   if (fDebug == 2) {
7749     TCanvas *cfit = new TCanvas("cfit","cfit",50,50,600,800);
7750     cfit->cd();
7751     projPRF->Fit("gaus","M+","",-fRangeFitPRF,fRangeFitPRF);
7752     projPRF->Draw();
7753   }
7754
7755   fPRFCoef[0] = projPRF->GetFunction("gaus")->GetParameter(2);
7756   prfCoefE = projPRF->GetFunction("gaus")->GetParError(2);
7757   if(fPRFCoef[0] <= 0.0) fPRFCoef[0] = -fPRFCoef[1];
7758
7759   if ((fDebug == 1) || 
7760       (fDebug == 4)) {
7761     fCoefPRF[0][idect] = fPRFCoef[0];
7762     fCoefPRFE[idect] = prfCoefE;
7763   }
7764   if (fDebug == 2) {
7765     AliInfo(Form("fPRFCoef[0]: %f",(Float_t) fPRFCoef[0]));
7766   }
7767   
7768 }
7769
7770 //_____________________________________________________________________________
7771 void AliTRDCalibra::FitCH(TH1 *projch, Int_t idect)
7772 {
7773   //
7774   // Fit methode for the gain factor
7775   //
7776  
7777   fChargeCoef[0] = 0.0;
7778   fChargeCoef[1] = 0.0;
7779   Double_t chargeCoefE0 = 0.0;
7780   Double_t chargeCoefE1 = 0.0;
7781   TF1 *fLandauGaus = new TF1("fLandauGaus",FuncLandauGaus,0,300,5);
7782
7783   fChargeCoef[1] = projch->GetMean();
7784   chargeCoefE1 = projch->GetMeanError();
7785   projch->Fit("landau","0",""
7786              ,(Float_t) fChargeCoef[1]/fBeginFitCharge
7787              ,projch->GetBinCenter(projch->GetNbinsX()));
7788   fL3P0         = projch->GetFunction("landau")->GetParameter(0);
7789   Double_t l3P1 = projch->GetFunction("landau")->GetParameter(1);
7790   fL3P2         = projch->GetFunction("landau")->GetParameter(2);
7791     
7792   projch->Fit("gaus","0",""
7793              ,(Float_t) fChargeCoef[1]/fBeginFitCharge
7794              ,projch->GetBinCenter(projch->GetNbinsX()));
7795   Double_t g3P0 = projch->GetFunction("gaus")->GetParameter(0);
7796   fG3P2         = projch->GetFunction("gaus")->GetParameter(2);
7797         
7798   fLandauGaus->SetParameters(fL3P0,l3P1,fL3P2,g3P0,fG3P2);
7799   if ((fDebug <= 1) || 
7800       (fDebug >= 3)) {
7801     projch->Fit("fLandauGaus","0",""
7802                ,(Float_t) fChargeCoef[1]/fBeginFitCharge
7803                ,projch->GetBinCenter(projch->GetNbinsX()));
7804   }
7805
7806   if (fDebug == 2) {
7807     TCanvas *cp = new TCanvas("cp","cp",50,50,600,800);
7808     cp->cd();
7809     projch->Fit("fLandauGaus","+",""
7810                ,(Float_t) fChargeCoef[1]/fBeginFitCharge
7811                ,projch->GetBinCenter(projch->GetNbinsX()));
7812     projch->Draw();
7813     fLandauGaus->Draw("same");
7814   }
7815   
7816   if (projch->GetFunction("fLandauGaus")->GetParameter(1) > 0) {
7817     // Calcul of "real" coef
7818     CalculChargeCoefMean(fCountDet[0],(Int_t) idect,kTRUE);
7819     fChargeCoef[0] = projch->GetFunction("fLandauGaus")->GetParameter(1);
7820     chargeCoefE0 = projch->GetFunction("fLandauGaus")->GetParError(1);
7821   }
7822   else {
7823     // Calcul of "real" coef
7824     CalculChargeCoefMean(fCountDet[0],(Int_t) idect,kFALSE);
7825     fChargeCoef[0] = -TMath::Abs(fChargeCoef[3]);
7826   }
7827
7828   if (fDebug == 2) {
7829     AliInfo(Form("fChargeCoef[0]: %f",(Float_t) fChargeCoef[0]));
7830     AliInfo(Form("fChargeCoef[1]: %f",(Float_t) fChargeCoef[1]));
7831   }
7832   
7833   if ((fDebug == 1) || 
7834       (fDebug == 4)) {
7835     if (fChargeCoef[0] > 0.0) {
7836       fCoefCharge[0][idect]= fChargeCoef[0];
7837       fCoefChargeE[0][idect]= chargeCoefE0;
7838       fCoefCharge[1][idect]= fChargeCoef[1];
7839       fCoefChargeE[1][idect]= chargeCoefE1;
7840     }
7841   }
7842   fL3P0 = fLandauGaus->Integral(0.3*projch->GetMean(),3*projch->GetMean());
7843   fG3P2 = fLandauGaus->GetParameter(2);
7844   fL3P2 = fLandauGaus->GetParameter(4);
7845    
7846   if (fDebug != 2) {
7847     delete fLandauGaus;
7848   }
7849
7850 }
7851
7852 //_____________________________________________________________________________
7853 void AliTRDCalibra::FitBisCH(TH1* projch, Int_t idect)
7854 {
7855   //
7856   // Fit methode for the gain factor more time consuming
7857   //
7858
7859   // Setting fit range and start values
7860   Double_t fr[2];
7861   //Double_t sv[4] = { l3P2, fChargeCoef[1], projch->Integral("width"), fG3P2 };
7862   Double_t sv[4]   = { fL3P2, fChargeCoef[1], fL3P0, fG3P2 };
7863   Double_t pllo[4] = { 0.001, 0.001, 0.001, 0.001 };
7864   Double_t plhi[4] = { 300.0, 300.0, 100000000.0, 300.0 };
7865   Double_t fp[4]   = { 1.0, 1.0, 1.0, 1.0 };
7866   Double_t fpe[4]  = { 1.0, 1.0, 1.0, 1.0 };
7867   fr[0]            = 0.3 * projch->GetMean();
7868   fr[1]            = 3.0 * projch->GetMean();
7869   fChargeCoef[2]   = 0.0;
7870   Double_t chargeCoefE2 = 0.0;
7871
7872   Double_t chisqr;
7873   Int_t    ndf;
7874   TF1 *fitsnr = LanGauFit(projch,&fr[0],&sv[0]
7875                                 ,&pllo[0],&plhi[0]
7876                                 ,&fp[0],&fpe[0]
7877                                 ,&chisqr,&ndf);
7878     
7879   Double_t projchPeak;
7880   Double_t projchFWHM;
7881   LanGauPro(fp,projchPeak,projchFWHM);
7882
7883   if (fp[1] > 0) {
7884     fChargeCoef[2] = fp[1];
7885     chargeCoefE2 = fpe[1];
7886     //chargeCoefE2 = chisqr;
7887   } 
7888   else {
7889     fChargeCoef[2] = -TMath::Abs(fChargeCoef[3]);
7890   }
7891   
7892   if (fDebug == 2) {
7893     AliInfo(Form("fChargeCoef[2]: %f",(Float_t) fChargeCoef[2]));
7894     TCanvas *cpy = new TCanvas("cpy","cpy",50,50,600,800);
7895     cpy->cd();
7896     projch->Draw();
7897     fitsnr->Draw("same");
7898   }
7899
7900   if ((fDebug == 1) || 
7901       (fDebug == 4)) {
7902     if (fChargeCoef[2] > 0.0) {
7903       fCoefCharge[2][idect]= fChargeCoef[2];
7904       fCoefChargeE[2][idect]= chargeCoefE2;
7905     }
7906   }
7907
7908   if (fDebug != 2) {
7909     delete fitsnr;
7910   }
7911
7912
7913
7914 //_____________________________________________________________________________
7915 void AliTRDCalibra::NormierungCharge()
7916 {
7917   //
7918   // Normalisation of the gain factor resulting for the fits
7919   //
7920   
7921   // Calcul of the mean of the fit
7922   Double_t sum         = 0.0;
7923   for (Int_t k = 0; k < (Int_t) fVectorFitCH->GetEntriesFast(); k++) {
7924     Int_t    total    = 0;
7925     Int_t    detector = ((AliTRDFitCHInfo *) fVectorFitCH->At(k))->GetDetector();
7926     Float_t *coef     = ((AliTRDFitCHInfo *) fVectorFitCH->At(k))->GetCoef();
7927     if (GetChamber(detector) == 2) {
7928       total = 1728;
7929     }
7930     if (GetChamber(detector) != 2) {
7931       total = 2304;
7932     }
7933     for (Int_t j = 0; j < total; j++) {
7934       if (coef[j] >= 0) {
7935         sum += coef[j];
7936       }
7937     }
7938   }
7939
7940   if (sum > 0) {
7941     fScaleFitFactor = fScaleFitFactor / sum;
7942   }
7943   else {
7944     fScaleFitFactor = 1.0;
7945   }
7946
7947   if ((fDebug == 3) || 
7948       (fDebug == 4)) {
7949     if ((fCoefChargeDB[0]->GetEntries()      > 0.0) && 
7950         (fCoefChargeDB[0]->GetSumOfWeights() > 0.0)) {
7951       fCoefChargeDB[0]->Scale(fCoefChargeDB[0]->GetEntries() / fCoefChargeDB[0]->GetSumOfWeights());
7952     }
7953     if ((fMeanChargeOn)  && 
7954         (fCoefChargeDB[1]->GetEntries()      > 0.0) && 
7955         (fCoefChargeDB[1]->GetSumOfWeights() > 0.0)) {
7956       fCoefChargeDB[1]->Scale(fCoefChargeDB[1]->GetEntries() / fCoefChargeDB[1]->GetSumOfWeights());
7957     }
7958     if ((fFitChargeBisOn) && 
7959         (fCoefChargeDB[2]->GetEntries()      > 0.0) && 
7960         (fCoefChargeDB[2]->GetSumOfWeights() > 0.0)) {
7961       fCoefChargeDB[2]->Scale(fCoefChargeDB[2]->GetEntries() / fCoefChargeDB[2]->GetSumOfWeights());
7962     }
7963   }
7964   
7965 }
7966
7967 //_____________________________________________________________________________
7968 TH1I *AliTRDCalibra::ReBin(TH1I *hist) const
7969 {
7970   //
7971   // Rebin of the 1D histo for the gain calibration if needed.
7972   // you have to choose fRebin, divider of fNumberBinCharge
7973   //
7974
7975  TAxis *xhist  = hist->GetXaxis();
7976  TH1I  *rehist = new TH1I("projrebin","",(Int_t) xhist->GetNbins()/fRebin
7977                                         ,xhist->GetBinLowEdge(1)
7978                                         ,xhist->GetBinUpEdge(xhist->GetNbins()));
7979
7980  AliInfo(Form("fRebin: %d",fRebin));
7981  Int_t i = 1;
7982  for (Int_t k = 1; k <= (Int_t) xhist->GetNbins()/fRebin; k++) {
7983    Double_t sum = 0.0;
7984    for (Int_t ji = i; ji < i+fRebin; ji++) {
7985      sum += hist->GetBinContent(ji);
7986    }
7987    sum = sum / fRebin;
7988    rehist->SetBinContent(k,sum);
7989    i += fRebin;
7990  }
7991
7992  if (fDebug == 2) {
7993    TCanvas *crebin = new TCanvas("crebin","",50,50,600,800);
7994    crebin->cd();
7995    rehist->Draw();
7996  }
7997
7998  return rehist;
7999
8000 }
8001
8002 //_____________________________________________________________________________
8003 TH1F *AliTRDCalibra::ReBin(TH1F *hist) const
8004 {
8005   //
8006   // Rebin of the 1D histo for the gain calibration if needed
8007   // you have to choose fRebin divider of fNumberBinCharge
8008   //
8009
8010   TAxis *xhist  = hist->GetXaxis();
8011   TH1F  *rehist = new TH1F("projrebin","",(Int_t) xhist->GetNbins()/fRebin
8012                                          ,xhist->GetBinLowEdge(1)
8013                                          ,xhist->GetBinUpEdge(xhist->GetNbins()));
8014
8015   AliInfo(Form("fRebin: %d",fRebin));
8016   Int_t i = 1;
8017   for (Int_t k = 1; k <= (Int_t) xhist->GetNbins()/fRebin; k++) {
8018     Double_t sum = 0.0;
8019     for (Int_t ji = i; ji < i+fRebin; ji++) {
8020       sum += hist->GetBinContent(ji);
8021     }
8022     sum = sum/fRebin;
8023     rehist->SetBinContent(k,sum);
8024     i += fRebin;
8025   }
8026
8027   if (fDebug == 2) {
8028     TCanvas *crebin = new TCanvas("crebin","",50,50,600,800);
8029     crebin->cd();
8030     rehist->Draw();
8031   }
8032   
8033   return rehist;
8034   
8035 }
8036
8037 //_____________________________________________________________________________
8038 TH1F *AliTRDCalibra::CorrectTheError(TGraphErrors *hist)
8039 {
8040   //
8041   // In the case of the vectors method the trees contains TGraphErrors for PH and PRF
8042   // to be able to add them after
8043   // We convert it to a TH1F to be able to applied the same fit function method
8044   // After having called this function you can not add the statistics anymore
8045   //
8046
8047   TH1F *rehist = 0x0;
8048
8049   Int_t     nbins   = hist->GetN();
8050   Double_t *x       = hist->GetX();
8051   Double_t *entries = hist->GetEX();
8052   Double_t *mean    = hist->GetY();
8053   Double_t *square  = hist->GetEY();
8054   fEntriesCurrent   = 0;
8055
8056   if (nbins < 2) {
8057     return rehist; 
8058   }
8059
8060   Double_t step     = x[1] - x[0]; 
8061   Double_t minvalue = x[0] - step/2;
8062   Double_t maxvalue = x[(nbins-1)] + step/2;
8063
8064   rehist = new TH1F("projcorrecterror","",nbins,minvalue,maxvalue);
8065
8066   for (Int_t k = 0; k < nbins; k++) {
8067     rehist->SetBinContent(k+1,mean[k]);
8068     if (entries[k] > 0.0) {
8069       fEntriesCurrent += (Int_t) entries[k];
8070       Double_t d = TMath::Abs(square[k] - (mean[k]*mean[k]));
8071       rehist->SetBinError(k+1,TMath::Sqrt(d/entries[k]));
8072     }
8073     else {
8074       rehist->SetBinError(k+1,0.0);
8075     }
8076   }
8077
8078   return rehist;
8079  
8080 }
8081
8082 //_____________________________________________________________________________
8083 TGraphErrors *AliTRDCalibra::AddProfiles(TGraphErrors *hist1
8084                                        , TGraphErrors *hist2) const
8085 {
8086   //
8087   // In the case of the vectors method we use TGraphErrors for PH and PRF
8088   // to be able to add the them after
8089   // Here we add the TGraphErrors  
8090   //
8091
8092   // First TGraphErrors
8093   Int_t     nbins1 = hist1->GetN();
8094   Double_t *x1     = hist1->GetX();
8095   Double_t *ex1    = hist1->GetEX();
8096   Double_t *y1     = hist1->GetY();
8097   Double_t *ey1    = hist1->GetEY();
8098
8099   TGraphErrors *rehist = new TGraphErrors(nbins1);
8100
8101   // Second TGraphErrors
8102   Double_t *ex2    = hist2->GetEX();
8103   Double_t *y2     = hist2->GetY();
8104   Double_t *ey2    = hist2->GetEY();
8105
8106   // Define the Variables for the new TGraphErrors
8107   Double_t x;
8108   Double_t ex;
8109   Double_t y;
8110   Double_t ey;
8111   
8112   for (Int_t k = 0; k < nbins1; k++) {
8113     Double_t nentries = 0.0;
8114     x  = x1[k];
8115     y  = 0.0;
8116     ey = 0.0;
8117     ex = 0.0;
8118     if ((ex2[k] == 0.0) && 
8119         (ex1[k] == 0.0)) {
8120       nentries = 0.0;
8121     }
8122     if ((ex2[k] == 0.0) && 
8123         (ex1[k]  > 0.0)) {
8124       nentries = ex1[k];
8125       y  = y1[k];
8126       ey = ey1[k];
8127       ex = ex1[k];
8128     }
8129     if ((ex2[k]  > 0.0) && 
8130         (ex1[k] == 0.0)) {
8131       nentries = ex2[k];
8132       y  = y2[k];
8133       ey = ey2[k];
8134       ex = ex2[k];
8135     }
8136     if ((ex2[k] > 0.0) && 
8137         (ex1[k] > 0.0)) { 
8138      nentries = ex1[k] + ex2[k];
8139      y  = ( y1[k]*ex1[k]+ y2[k]*ex2[k]) / nentries;
8140      ey = (ey1[k]*ex1[k]+ey2[k]*ex2[k]) / nentries;
8141      ex = nentries;
8142    }
8143    rehist->SetPoint(k,x,y);
8144    rehist->SetPointError(k,ex,ey);
8145  }
8146
8147  return rehist;
8148
8149 }
8150
8151 //
8152 //____________Some basic geometry function_____________________________________
8153 //
8154
8155 //_____________________________________________________________________________
8156 Int_t AliTRDCalibra::GetPlane(Int_t d) const
8157 {
8158   //
8159   // Reconstruct the plane number from the detector number
8160   //
8161
8162   return ((Int_t) (d % 6));
8163
8164 }
8165
8166 //_____________________________________________________________________________
8167 Int_t AliTRDCalibra::GetChamber(Int_t d) const
8168 {
8169   //
8170   // Reconstruct the chamber number from the detector number
8171   //
8172   Int_t fgkNplan = 6;
8173
8174   return ((Int_t) (d % 30) / fgkNplan);
8175
8176 }
8177
8178 //_____________________________________________________________________________
8179 Int_t AliTRDCalibra::GetSector(Int_t d) const
8180 {
8181   //
8182   // Reconstruct the sector number from the detector number
8183   //
8184   Int_t fg = 30;
8185
8186   return ((Int_t) (d / fg));
8187
8188 }
8189
8190 //
8191 //____________Fill and Init tree Gain, PRF, Vdrift and T0______________________
8192 //
8193
8194 //_____________________________________________________________________________
8195 void AliTRDCalibra::InitTreePRF()
8196 {
8197   //
8198   // Init the tree where the coefficients from the fit methods can be stored
8199   //
8200
8201   gDirectory = gROOT; 
8202   fPRFPad    = new Float_t[2304];
8203   fPRF       = new TTree("PRF","PRF");
8204   fPRF->Branch("detector",&fPRFDetector,"detector/I");
8205   fPRF->Branch("width"   ,fPRFPad      ,"width[2304]/F");
8206
8207   // Set to default value for the plane 0 supposed to be the first one
8208   for (Int_t k = 0; k < 2304; k++) {
8209     fPRFPad[k] = 0.515;
8210   }
8211   fPRFDetector = -1;
8212
8213 }
8214
8215 //_____________________________________________________________________________
8216 void AliTRDCalibra::FillTreePRF(Int_t countdet)
8217 {
8218   //
8219   // Fill the tree with the sigma of the pad response function for the detector countdet
8220   //
8221   
8222   Int_t numberofgroup = 0; 
8223   fPRFDetector = countdet;
8224   fPRF->Fill();
8225
8226   if (GetChamber((Int_t)(countdet+1)) == 2) {
8227     numberofgroup = 1728;
8228   }
8229   else {
8230     numberofgroup = 2304;
8231   }
8232
8233   // Reset to default value for the next
8234   for (Int_t k = 0; k < numberofgroup; k++) {
8235     if (GetPlane((Int_t) (countdet+1)) == 0) {
8236       fPRFPad[k] = 0.515;
8237     }
8238     if (GetPlane((Int_t) (countdet+1)) == 1) {
8239       fPRFPad[k] = 0.502;
8240     }
8241     if (GetPlane((Int_t) (countdet+1)) == 2) {
8242       fPRFPad[k] = 0.491;
8243     }
8244     if (GetPlane((Int_t) (countdet+1)) == 3) {
8245       fPRFPad[k] = 0.481;
8246     }
8247     if (GetPlane((Int_t) (countdet+1)) == 4) {
8248       fPRFPad[k] = 0.471;
8249     }
8250     if (GetPlane((Int_t) (countdet+1)) == 5) {
8251       fPRFPad[k] = 0.463;
8252     }
8253   }
8254
8255   fPRFDetector = -1;
8256
8257 }
8258
8259 //_____________________________________________________________________________
8260 void AliTRDCalibra::ConvertVectorFitCHTree()
8261 {
8262   //
8263   // Convert the vector stuff to a tree of 1D histos if the user
8264   // want to write it after the fill functions
8265   //
8266
8267   Int_t detector      = -1;
8268   Int_t numberofgroup =  1;
8269   Float_t gainPad[2304];
8270
8271   fGain = new TTree("Gain","Gain");
8272   fGain->Branch("detector",&detector,"detector/I");
8273   fGain->Branch("gainPad" ,gainPad  ,"gainPad[2304]/F");
8274
8275   Int_t loop = (Int_t) fVectorFitCH->GetEntriesFast();
8276   for (Int_t k = 0; k < loop; k++) {
8277     detector = ((AliTRDFitCHInfo *) fVectorFitCH->At(k))->GetDetector();
8278     if (GetChamber((Int_t) ((AliTRDFitCHInfo *) fVectorFitCH->At(k))->GetDetector()) == 2) {
8279       numberofgroup = 1728;
8280     }
8281     else {
8282       numberofgroup = 2304;
8283     }
8284     for (Int_t i = 0; i < numberofgroup; i++) {
8285       if (((AliTRDFitCHInfo *) fVectorFitCH->At(k))->GetCoef()[i] >= 0) {
8286         gainPad[i] = ((AliTRDFitCHInfo *) fVectorFitCH->At(k))->GetCoef()[i] * fScaleFitFactor;
8287       }
8288       else {
8289         gainPad[i] = (Float_t) ((AliTRDFitCHInfo *) fVectorFitCH->At(k))->GetCoef()[i];
8290       }
8291     }
8292     fGain->Fill();
8293   }
8294
8295 }
8296
8297 //_____________________________________________________________________________
8298 void AliTRDCalibra::FillTreeVdrift(Int_t countdet)
8299 {
8300   //
8301   // Fill the tree with the drift velocities for the detector countdet
8302   //
8303
8304   Int_t numberofgroup = 0;
8305   fVdriftDetector = countdet;
8306  
8307   fVdrift->Fill();
8308   if (GetChamber((Int_t)(countdet+1)) == 2) {
8309     numberofgroup = 1728;
8310   }
8311   else {
8312     numberofgroup = 2304;
8313   }
8314   // Reset to default value the gain coef
8315   for (Int_t k = 0; k < numberofgroup; k++) {
8316     fVdriftPad[k] = -1.5;
8317   }
8318   fVdriftDetector = -1;
8319
8320 }
8321
8322 //_____________________________________________________________________________
8323 void AliTRDCalibra::InitTreePH()
8324 {
8325   //
8326   // Init the tree where the coefficients from the fit methods can be stored
8327   //
8328   
8329   gDirectory = gROOT;
8330   fVdriftPad = new Float_t[2304];
8331   fVdrift    = new TTree("Vdrift","Vdrift");
8332   fVdrift->Branch("detector",&fVdriftDetector,"detector/I");
8333   fVdrift->Branch("vdrift"  ,fVdriftPad      ,"vdrift[2304]/F");
8334   // Set to default value for the plane 0 supposed to be the first one
8335   for (Int_t k = 0; k < 2304; k++) {
8336     fVdriftPad[k] = -1.5;
8337   }
8338   fVdriftDetector = -1;
8339
8340 }
8341
8342 //_____________________________________________________________________________
8343 void AliTRDCalibra::FillTreeT0(Int_t countdet)
8344 {
8345   //
8346   // Fill the tree with the t0 value for the detector countdet
8347   //
8348
8349   Int_t numberofgroup = 0;
8350
8351   fT0Detector = countdet;
8352  
8353   fT0->Fill();
8354   if (GetChamber((Int_t) (countdet+1)) == 2) {
8355     numberofgroup = 1728;
8356   }
8357   else {
8358     numberofgroup = 2304;
8359   }
8360   // Reset to default value 
8361   for (Int_t k = 0; k < numberofgroup; k++) {
8362     fT0Pad[k] = 0.0;
8363   }
8364   fT0Detector = -1;
8365
8366 }
8367
8368 //_____________________________________________________________________________
8369 void AliTRDCalibra::InitTreeT0()
8370 {
8371   //
8372   // Init the tree where the coefficients from the fit methods can be stored
8373   //
8374   
8375   gDirectory = gROOT;
8376   fT0Pad = new Float_t[2304];
8377   fT0 = new TTree("T0","T0");
8378   fT0->Branch("detector",&fT0Detector,"detector/I");
8379   fT0->Branch("t0",fT0Pad,"t0[2304]/F");
8380   //Set to default value for the plane 0 supposed to be the first one
8381   for(Int_t k = 0; k < 2304; k++){
8382     fT0Pad[k] = 0.0;
8383   }
8384   fT0Detector = -1;
8385
8386 }
8387
8388 //
8389 //____________Private Functions________________________________________________
8390 //
8391
8392 //_____________________________________________________________________________
8393 Double_t AliTRDCalibra::PH(Double_t *x, Double_t *par) 
8394 {
8395   //
8396   // Function for the fit
8397   //
8398
8399   //TF1 *fAsymmGauss = new TF1("fAsymmGauss",AsymmGauss,0,4,6);
8400
8401   //PARAMETERS FOR FIT PH
8402   // PASAv.4
8403   //fAsymmGauss->SetParameter(0,0.113755);
8404   //fAsymmGauss->SetParameter(1,0.350706);
8405   //fAsymmGauss->SetParameter(2,0.0604244);
8406   //fAsymmGauss->SetParameter(3,7.65596);
8407   //fAsymmGauss->SetParameter(4,1.00124);
8408   //fAsymmGauss->SetParameter(5,0.870597);  // No tail cancelation
8409
8410   Double_t xx = x[0];
8411   
8412   if (xx < par[1]) {
8413     return par[5];
8414   }
8415
8416   Double_t dx       = 0.005;
8417   Double_t xs       = par[1];
8418   Double_t ss       = 0.0;
8419   Double_t paras[2] = { 0.0, 0.0 };
8420
8421   while (xs < xx) {
8422     if ((xs >= par[1]) &&
8423         (xs < (par[1]+par[2]))) {
8424       //fAsymmGauss->SetParameter(0,par[0]);
8425       //fAsymmGauss->SetParameter(1,xs);
8426       //ss += fAsymmGauss->Eval(xx);
8427       paras[0] = par[0];
8428       paras[1] = xs;
8429       ss += AsymmGauss(&xx,paras);
8430     }
8431     if ((xs >= (par[1]+par[2])) && 
8432         (xs <  (par[1]+par[2]+par[3]))) {
8433       //fAsymmGauss->SetParameter(0,par[0]*par[4]);
8434       //fAsymmGauss->SetParameter(1,xs);
8435       //ss += fAsymmGauss->Eval(xx);
8436       paras[0] = par[0]*par[4];
8437       paras[1] = xs;
8438       ss += AsymmGauss(&xx,paras);
8439     }
8440     xs += dx;
8441   }
8442   
8443   return ss + par[5];
8444
8445 }
8446
8447 //_____________________________________________________________________________
8448 Double_t AliTRDCalibra::AsymmGauss(Double_t *x, Double_t *par) 
8449 {
8450   //
8451   // Function for the fit
8452   //
8453
8454   //par[0] = normalization
8455   //par[1] = mean
8456   //par[2] = sigma
8457   //norm0  = 1
8458   //par[3] = lambda0
8459   //par[4] = norm1
8460   //par[5] = lambda1
8461   
8462   Double_t par1save = par[1];    
8463   //Double_t par2save = par[2];
8464   Double_t par2save = 0.0604244;
8465   //Double_t par3save = par[3];
8466   Double_t par3save = 7.65596;
8467   //Double_t par5save = par[5];
8468   Double_t par5save = 0.870597;
8469   Double_t dx       = x[0] - par1save;
8470
8471   Double_t  sigma2  = par2save*par2save;
8472   Double_t  sqrt2   = TMath::Sqrt(2.0);
8473   Double_t  exp1    = par3save * TMath::Exp(-par3save * (dx - 0.5 * par3save * sigma2))
8474                                * (1.0 - TMath::Erf((par3save * sigma2 - dx) / (sqrt2 * par2save)));
8475   Double_t  exp2    = par5save * TMath::Exp(-par5save * (dx - 0.5 * par5save * sigma2))
8476                                * (1.0 - TMath::Erf((par5save * sigma2 - dx) / (sqrt2 * par2save)));
8477
8478   //return par[0]*(exp1+par[4]*exp2);
8479   return par[0] * (exp1 + 1.00124 * exp2);
8480
8481 }
8482
8483 //_____________________________________________________________________________
8484 Double_t AliTRDCalibra::FuncLandauGaus(Double_t *x, Double_t *par)
8485 {
8486   //
8487   // Sum Landau + Gaus with identical mean
8488   //
8489
8490   Double_t valLandau = par[0] * TMath::Landau(x[0],par[1],par[2]);
8491   //Double_t valGaus   = par[3] * TMath::Gaus(x[0],par[4],par[5]);
8492   Double_t valGaus   = par[3] * TMath::Gaus(x[0],par[1],par[4]);
8493   Double_t val       = valLandau + valGaus;
8494
8495   return val;
8496
8497 }
8498
8499 //_____________________________________________________________________________
8500 Double_t AliTRDCalibra::LanGauFun(Double_t *x, Double_t *par) 
8501 {
8502   //
8503   // Function for the fit
8504   //
8505   // Fit parameters:
8506   // par[0]=Width (scale) parameter of Landau density
8507   // par[1]=Most Probable (MP, location) parameter of Landau density
8508   // par[2]=Total area (integral -inf to inf, normalization constant)
8509   // par[3]=Width (sigma) of convoluted Gaussian function
8510   //
8511   // In the Landau distribution (represented by the CERNLIB approximation), 
8512   // the maximum is located at x=-0.22278298 with the location parameter=0.
8513   // This shift is corrected within this function, so that the actual
8514   // maximum is identical to the MP parameter.
8515   //  
8516
8517   // Numeric constants
8518   Double_t invsq2pi = 0.3989422804014;   // (2 pi)^(-1/2)
8519   Double_t mpshift  = -0.22278298;       // Landau maximum location
8520   
8521   // Control constants
8522   Double_t np       = 100.0;             // Number of convolution steps
8523   Double_t sc       =   5.0;             // Convolution extends to +-sc Gaussian sigmas
8524   
8525   // Variables
8526   Double_t xx;
8527   Double_t mpc;
8528   Double_t fland;
8529   Double_t sum = 0.0;
8530   Double_t xlow;
8531   Double_t xupp;
8532   Double_t step;
8533   Double_t i;
8534   
8535   // MP shift correction
8536   mpc = par[1] - mpshift * par[0]; 
8537
8538   // Range of convolution integral
8539   xlow = x[0] - sc * par[3];
8540   xupp = x[0] + sc * par[3];
8541   
8542   step = (xupp - xlow) / np;
8543
8544   // Convolution integral of Landau and Gaussian by sum
8545   for (i = 1.0; i <= np/2; i++) {
8546
8547     xx    = xlow + (i-.5) * step;
8548     fland = TMath::Landau(xx,mpc,par[0]) / par[0];
8549     sum  += fland * TMath::Gaus(x[0],xx,par[3]);
8550     
8551     xx    = xupp - (i-.5) * step;
8552     fland = TMath::Landau(xx,mpc,par[0]) / par[0];
8553     sum  += fland * TMath::Gaus(x[0],xx,par[3]);
8554
8555   }
8556
8557   return (par[2] * step * sum * invsq2pi / par[3]);
8558
8559 }
8560
8561 //_____________________________________________________________________________
8562 TF1 *AliTRDCalibra::LanGauFit(TH1 *his, Double_t *fitrange, Double_t *startvalues
8563                                       , Double_t *parlimitslo, Double_t *parlimitshi
8564                                       , Double_t *fitparams, Double_t *fiterrors
8565                                       , Double_t *chiSqr, Int_t *ndf)
8566 {
8567   //
8568   // Function for the fit
8569   //
8570   
8571   Int_t i;
8572   Char_t funname[100];
8573   
8574   AliInfo(Form(funname,"Fitfcn_%s",his->GetName()));
8575   
8576   TF1 *ffitold = (TF1 *) gROOT->GetListOfFunctions()->FindObject(funname);
8577   if (ffitold) {
8578     delete ffitold;
8579   }  
8580
8581   TF1 *ffit    = new TF1(funname,LanGauFun,fitrange[0],fitrange[1],4);
8582   ffit->SetParameters(startvalues);
8583   ffit->SetParNames("Width","MP","Area","GSigma");
8584   
8585   for (i = 0; i < 4; i++) {
8586     ffit->SetParLimits(i,parlimitslo[i],parlimitshi[i]);
8587   }
8588   
8589   his->Fit(funname,"RB0");                   // Fit within specified range, use ParLimits, do not plot
8590   
8591   ffit->GetParameters(fitparams);            // Obtain fit parameters
8592   for (i = 0; i < 4; i++) {
8593     fiterrors[i] = ffit->GetParError(i);     // Obtain fit parameter errors
8594   }
8595   chiSqr[0] = ffit->GetChisquare();          // Obtain chi^2
8596   ndf[0]    = ffit->GetNDF();                // Obtain ndf
8597
8598   return (ffit);                             // Return fit function
8599    
8600 }
8601
8602 //_____________________________________________________________________________
8603 Int_t AliTRDCalibra::LanGauPro(Double_t *params, Double_t &maxx, Double_t &fwhm) 
8604 {
8605   //
8606   // Function for the fit
8607   //
8608
8609   Double_t p;
8610   Double_t x;
8611   Double_t fy;
8612   Double_t fxr;
8613   Double_t fxl;
8614   Double_t step;
8615   Double_t l;
8616   Double_t lold;
8617
8618   Int_t    i        = 0;
8619   Int_t    maxcalls = 10000;
8620   
8621   // Search for maximum
8622   p    = params[1] - 0.1 * params[0];
8623   step = 0.05 * params[0];
8624   lold = -2.0;
8625   l    = -1.0;
8626   
8627   while ((l != lold) && (i < maxcalls)) {
8628     i++;
8629     lold = l;
8630     x    = p + step;
8631     l    = LanGauFun(&x,params);
8632     if (l < lold) {
8633       step = -step / 10.0;
8634     }
8635     p += step;
8636   }
8637   
8638   if (i == maxcalls) {
8639     return (-1);
8640   }
8641   maxx = x;
8642   fy = l / 2.0;
8643
8644   // Search for right x location of fy  
8645   p    = maxx + params[0];
8646   step = params[0];
8647   lold = -2.0;
8648   l    = -1e300;
8649   i    = 0;
8650   
8651   while ( (l != lold) && (i < maxcalls) ) {
8652     i++;
8653     
8654     lold = l;
8655     x = p + step;
8656     l = TMath::Abs(LanGauFun(&x,params) - fy);
8657     
8658     if (l > lold)
8659       step = -step/10;
8660  
8661     p += step;
8662   }
8663   
8664   if (i == maxcalls)
8665     return (-2);
8666   
8667   fxr = x;
8668   
8669   
8670   // Search for left x location of fy
8671   
8672   p = maxx - 0.5 * params[0];
8673   step = -params[0];
8674   lold = -2.0;
8675   l    = -1.0e300;
8676   i    = 0;
8677   
8678   while ((l != lold) && (i < maxcalls)) {
8679     i++;
8680     lold = l;
8681     x    = p + step;
8682     l    = TMath::Abs(LanGauFun(&x,params) - fy);
8683     if (l > lold) {
8684       step = -step / 10.0;
8685     }
8686     p += step;
8687   }
8688   
8689   if (i == maxcalls) {
8690     return (-3);
8691   }
8692
8693   fxl  = x;
8694   fwhm = fxr - fxl;
8695
8696   return (0);
8697
8698 }