]> git.uio.no Git - u/mrichter/AliRoot.git/blob - TPC/Calib/AliTPCPreprocessorOffline.cxx
b0937d7520938ce76351165c9e590f9df439190d
[u/mrichter/AliRoot.git] / TPC / Calib / AliTPCPreprocessorOffline.cxx
1 /**************************************************************************
2  * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
3  *                                                                        *
4  * Author: The ALICE Off-line Project.                                    *
5  * Contributors are mentioned in the code where appropriate.              *
6  *                                                                        *
7  * Permission to use, copy, modify and distribute this software and its   *
8  * documentation strictly for non-commercial purposes is hereby granted   *
9  * without fee, provided that the above copyright notice appears in all   *
10  * copies and that both the copyright notice and this permission notice   *
11  * appear in the supporting documentation. The authors make no claims     *
12  * about the suitability of this software for any purpose. It is          *
13  * provided "as is" without express or implied warranty.                  *
14  **************************************************************************/
15
16
17
18 /*
19   Responsible: marian.ivanov@cern.ch 
20   Code to analyze the TPC calibration and to produce OCDB entries  
21
22
23    .x ~/rootlogon.C
24    gSystem->Load("libANALYSIS");
25    gSystem->Load("libTPCcalib");
26
27    AliTPCPreprocessorOffline proces;
28    TString ocdbPath="local:////"
29    ocdbPath+=gSystem->GetFromPipe("pwd");
30
31    proces.CalibTimeGain("CalibObjects.root",run0,run1,ocdbPath);
32    proces.CalibTimeVdrift("CalibObjects.root",run0,run1,ocdbPath);
33   // take the raw calibration data from the file CalibObjects.root 
34   // and make a OCDB entry with run  validity run0-run1
35   // results are stored at the ocdbPath - local or alien ...
36   // default storage ""- data stored at current working directory 
37  
38   e.g.
39   gSystem->Load("libANALYSIS");
40   gSystem->Load("libTPCcalib");
41   AliTPCPreprocessorOffline proces;
42   proces.CalibTimeGain("TPCMultObjects.root",114000,140040,0);
43   TFile oo("OCDB/TPC/Calib/TimeGain/Run114000_121040_v0_s0.root")
44  TObjArray * arr = AliCDBEntry->GetObject()
45   arr->At(4)->Draw("alp")
46
47 */
48 #include "Riostream.h"
49 #include <fstream>
50 #include "TMap.h"
51 #include "TGraphErrors.h"
52 #include "AliExternalTrackParam.h"
53 #include "TFile.h"
54 #include "TDirectory.h"
55 #include "TGraph.h"
56 #include "TMultiGraph.h"
57 #include "TCanvas.h"
58 #include "THnSparse.h"
59 #include "TLegend.h"
60 #include "TPad.h"
61 #include "TH2D.h"
62 #include "TH3D.h"
63 #include "AliTPCROC.h"
64 #include "AliTPCCalROC.h"
65 #include "AliESDfriend.h"
66 #include "AliTPCcalibTime.h"
67 #include "AliSplineFit.h"
68 #include "AliCDBMetaData.h"
69 #include "AliCDBId.h"
70 #include "AliCDBManager.h"
71 #include "AliCDBStorage.h"
72 #include "AliTPCcalibBase.h"
73 #include "AliTPCcalibDB.h"
74 #include "AliTPCcalibDButil.h"
75 #include "AliRelAlignerKalman.h"
76 #include "AliTPCParamSR.h"
77 #include "AliTPCcalibTimeGain.h"
78 #include "AliTPCcalibGainMult.h"
79 #include "AliTPCcalibAlign.h"
80 #include "AliSplineFit.h"
81 #include "AliTPCComposedCorrection.h"
82 #include "AliTPCExBTwist.h"
83 #include "AliTPCCalibGlobalMisalignment.h"
84 #include "TStatToolkit.h"
85 #include "TChain.h"
86 #include "TCut.h"
87 #include "AliTrackerBase.h"
88 #include "AliTracker.h"
89 #include "AliTPCPreprocessorOffline.h"
90 #include "AliTPCCorrectionFit.h"
91
92 #include "AliTPCClusterParam.h"
93 #include "AliTPCRecoParam.h"
94
95 using std::endl;
96 using std::cout;
97
98 ClassImp(AliTPCPreprocessorOffline)
99
100 AliTPCPreprocessorOffline::AliTPCPreprocessorOffline():
101   TNamed("TPCPreprocessorOffline","TPCPreprocessorOffline"),
102   fMinEntries(500),                      // minimal number of entries for fit
103   fStartRun(0),                         // start Run - used to make fast selection in THnSparse
104   fEndRun(0),                           // end   Run - used to make fast selection in THnSparse
105   fStartTime(0),                        // fStartTime - used to make fast selection in THnSparse
106   fEndTime(0),                          // fEndTime   - used to make fast selection in THnSparse
107   fOCDBstorage(0),                       // OCDB storage
108   fVdriftArray(new TObjArray),
109   fTimeDrift(0),
110   fGraphMIP(0),                // graph time dependence of MIP
111   fGraphCosmic(0),             // graph time dependence at Plateu
112   fGraphAttachmentMIP(0),
113   fFitMIP(0),                  // fit of dependence - MIP
114   fFitCosmic(0),               // fit of dependence - Plateu
115   fGainArray(new TObjArray),               // array to be stored in the OCDB
116   fGainMIP(0),          // calibration component for MIP
117   fGainCosmic(0),       // calibration component for cosmic
118   fGainMult(0),
119   fAlignTree(0),        // alignment tree
120   fSwitchOnValidation(kFALSE), // flag to switch on validation of OCDB parameters
121   fMinGain(2.0),
122   fMaxGain(3.0),
123   fMaxVdriftCorr(0.03),
124   fNtracksVdrift(0),
125   fMinTracksVdrift(0),
126   fNeventsVdrift(0),
127   fMinEventsVdrift(0),
128   fCalibrationStatus(0)
129 {
130   //
131   // default constructor
132   //
133 }
134
135 AliTPCPreprocessorOffline::~AliTPCPreprocessorOffline() {
136   //
137   // Destructor
138   //
139 }
140
141
142
143
144 void AliTPCPreprocessorOffline::GetRunRange(AliTPCcalibTime * const  timeDrift){
145   //
146   // find the fist and last run
147   //
148   TObjArray *hisArray =timeDrift->GetHistoDrift();
149   {for (Int_t i=0; i<hisArray->GetEntriesFast(); i++){
150     THnSparse* addHist=(THnSparse*)hisArray->UncheckedAt(i);
151     if (!addHist) continue;
152     if (addHist->GetEntries()<fMinEntries) continue;
153     TH1D* histo    =addHist->Projection(3);
154     TH1D* histoTime=addHist->Projection(0);
155     printf("%s\t%f\t%d\t%d\n",histo->GetName(), histo->GetEntries(),histo->FindFirstBinAbove(0),histo->FindLastBinAbove(0));
156
157     if (fStartRun<=0){ 
158       fStartRun=histo->FindFirstBinAbove(0);
159       fEndRun  =histo->FindLastBinAbove(0);
160     }else{
161       fStartRun=TMath::Min(histo->FindFirstBinAbove(0),fStartRun);
162       fEndRun  =TMath::Max(histo->FindLastBinAbove(0),fEndRun);
163     }
164     if (fStartTime==0){ 
165       fStartTime=histoTime->FindFirstBinAbove(0);
166       fEndTime  =histoTime->FindLastBinAbove(0);
167     }else{
168       fStartTime=TMath::Min(histoTime->FindFirstBinAbove(0),fStartTime);
169       fEndTime  =TMath::Max(histoTime->FindLastBinAbove(0),fEndTime);
170     }
171     delete histo;
172     delete histoTime;
173   }}
174   if (fStartRun<0) fStartRun=0;
175   if (fEndRun<0) fEndRun=100000000;
176   printf("Run range  :\t%d-%d\n", fStartRun, fEndRun);
177   printf("Time range :\t%d-%d\n", fStartTime, fEndTime);
178
179 }
180
181
182
183 void AliTPCPreprocessorOffline::CalibTimeVdrift(const Char_t* file, Int_t ustartRun, Int_t uendRun, AliCDBStorage* pocdbStorage){
184   //
185   // make calibration of the drift velocity
186   // Input parameters:
187   //      file                   - the location of input file
188   //      ustartRun, uendrun     - run validity period 
189   //      pocdbStorage           - path to hte OCDB storage
190   //                             - if empty - local storage 'pwd' uesed
191   if (pocdbStorage) fOCDBstorage=pocdbStorage;
192   else {
193     TString localStorage = "local://"+gSystem->GetFromPipe("pwd")+"/OCDB"; 
194     fOCDBstorage=AliCDBManager::Instance()->GetStorage(localStorage.Data());
195   }
196
197   //
198   // 1. Initialization and run range setting
199   TFile fcalib(file);
200   TObject* obj = dynamic_cast<TObject*>(fcalib.Get("TPCCalib"));
201   TObjArray* array = dynamic_cast<TObjArray*>(obj);
202   TDirectory* dir = dynamic_cast<TDirectory*>(obj);
203   if (dir) {
204     fTimeDrift = dynamic_cast<AliTPCcalibTime*>(dir->Get("calibTime"));
205   }
206   else if (array){
207     fTimeDrift = (AliTPCcalibTime *)array->FindObject("calibTime");
208   } else {
209     fTimeDrift = (AliTPCcalibTime*)fcalib.Get("calibTime");
210   }
211   if(!fTimeDrift) return;
212
213   //extract statistics
214   fNtracksVdrift = TMath::Nint(fTimeDrift->GetResHistoTPCITS(0)->GetEntries());
215   //if we have 0 ITS TPC matches it means we have no ITS tracks and we try to use TPC-TOF matching for calibration
216   if (fNtracksVdrift==0) fNtracksVdrift=TMath::Nint(fTimeDrift->GetResHistoTPCTOF(0)->GetEntries());
217   fNeventsVdrift = TMath::Nint(fTimeDrift->GetTPCVertexHisto(0)->GetEntries());
218
219   fStartRun=ustartRun;
220   fEndRun=ustartRun; 
221   TObjArray *hisArray =fTimeDrift->GetHistoDrift();  
222   GetRunRange(fTimeDrift);
223   for (Int_t i=0; i<hisArray->GetEntriesFast(); i++){
224     THnSparse* addHist=(THnSparse*)hisArray->At(i);
225     if (!addHist) continue;
226     if (fStartTime<fEndTime) addHist->GetAxis(0)->SetRange(fStartTime-1,fEndTime+1);
227     if (fStartRun<fEndRun) addHist->GetAxis(3)->SetRange(fStartRun-1,fEndRun+1);
228   }
229   //
230   //
231   // 2. extraction of the information
232   //
233   fVdriftArray = new TObjArray();
234   AddAlignmentGraphs(fVdriftArray,fTimeDrift);
235   AddHistoGraphs(fVdriftArray,fTimeDrift,fMinEntries);
236   AddLaserGraphs(fVdriftArray,fTimeDrift);
237   
238   //
239   // 3. Append QA plots
240   //
241   MakeDefaultPlots(fVdriftArray,fVdriftArray);
242
243   //
244   // 4. validate OCDB entries
245   //
246   if(fSwitchOnValidation==kTRUE && ValidateTimeDrift()==kFALSE) { 
247     Printf("TPC time drift OCDB parameters out of range!");
248     return;
249   }
250   //
251   //4.b make alignment
252   //
253   MakeFitTime();
254   TFile * ftime= TFile::Open("fitITSVertex.root");
255   if (ftime){
256     TObject * alignmentTime=ftime->Get("FitCorrectionTime");
257     if (alignmentTime) fVdriftArray->AddLast(alignmentTime);
258   }
259   //
260   // 5.) Add the RecoParam and ClusterParam - for compatibility checks -different sets of parameters can invalidate calibration 
261   //
262   AliTPCClusterParam *clParam =   AliTPCcalibDB::Instance()->GetClusterParam();
263   TObjArray *recoParams = new TObjArray(4) ;
264   for (Int_t i=0;i<4;i++) recoParams->AddAt(AliTPCcalibDB::Instance()->GetRecoParam(i),i);
265   fVdriftArray->AddLast(clParam);
266   fVdriftArray->AddLast(recoParams);
267   //
268   //
269   // 6. update of OCDB
270   //
271   //
272   UpdateOCDBDrift(ustartRun,uendRun,fOCDBstorage);
273 }
274
275 void AliTPCPreprocessorOffline::UpdateOCDBDrift( Int_t ustartRun, Int_t uendRun,  AliCDBStorage* storage ){
276   //
277   // Update OCDB 
278   //
279   AliCDBMetaData *metaData= new AliCDBMetaData();
280   metaData->SetObjectClassName("TObjArray");
281   metaData->SetResponsible("Marian Ivanov");
282   metaData->SetBeamPeriod(1);
283   metaData->SetAliRootVersion("05-25-01"); //root version
284   metaData->SetComment("Calibration of the time dependence of the drift velocity");
285   AliCDBId* id1=NULL;
286   id1=new AliCDBId("TPC/Calib/TimeDrift", ustartRun, uendRun);
287   storage->Put(fVdriftArray, (*id1), metaData);
288 }
289
290 Bool_t AliTPCPreprocessorOffline::ValidateTimeGain()
291 {
292   //
293   // Validate time gain corrections 
294   //
295   Printf("ValidateTimeGain..." );
296   Float_t minGain = fMinGain;
297   Float_t maxGain = fMaxGain;
298
299   TGraphErrors *gr = (TGraphErrors*)fGainArray->FindObject("TGRAPHERRORS_MEAN_GAIN_BEAM_ALL");
300   if (!gr) {
301     gr = (TGraphErrors*)fGainArray->FindObject("TGRAPHERRORS_MEAN_GAIN_COSMIC_ALL");
302     if (!gr) 
303     { 
304       fCalibrationStatus |= kCalibFailedTimeGain;
305       return kFALSE;
306     }
307     Printf("Assuming given run is a cosmic run. Using gain calibration from Fermi-plateau muons.");
308   }
309   if(gr->GetN()<1) 
310   { 
311     fCalibrationStatus |= kCalibFailedTimeGain;
312     return kFALSE;
313   }
314
315   // check whether gain in the range
316   for(Int_t iPoint=0; iPoint<gr->GetN(); iPoint++) 
317   {
318     if(gr->GetY()[iPoint] < minGain || gr->GetY()[iPoint] > maxGain)  
319     { 
320       fCalibrationStatus |= kCalibFailedTimeGain;
321       return kFALSE;
322     }
323   }
324
325 return kTRUE;
326 }
327
328
329 Bool_t AliTPCPreprocessorOffline::ValidateTimeDrift()
330 {
331   //
332   // Validate time drift velocity corrections 
333   //
334   Printf("ValidateTimeDrift..." );
335
336   Float_t maxVDriftCorr = fMaxVdriftCorr;
337
338   TGraphErrors* gr = (TGraphErrors*)fVdriftArray->FindObject("ALIGN_ITSB_TPC_DRIFTVD");
339   Printf("ALIGN_ITSB_TPC_DRIFTVD graph = %p",gr);
340   if (!gr)
341   {
342     gr = (TGraphErrors*)fVdriftArray->FindObject("ALIGN_TOFB_TPC_DRIFTVD");
343     Printf("ALIGN_TOFB_TPC_DRIFTVD graph = %p",gr);
344   }
345
346   if(!gr) 
347   {
348     fCalibrationStatus|=kCalibFailedTimeDrift;
349     return kFALSE;
350   }
351   
352   // for now we validate even with low statistics
353   ////check if we have enough statistics
354   //if (fNtracksVdrift<fMinTracksVdrift) 
355   //{
356   //  fCalibrationStatus|=kCalibFailedTimeDrift;
357   //  return kFALSE;
358   //}
359
360   if(gr->GetN()<1)  { 
361     Printf("ALIGN_ITSB_TPC_DRIFTVD number of points = %d",gr->GetN());
362     {
363       fCalibrationStatus|=kCalibFailedTimeDrift;
364       return kFALSE;
365     }
366   }
367
368   // check whether drift velocity corrections in the range
369   for(Int_t iPoint = 0; iPoint<gr->GetN(); iPoint++) 
370   {
371     //Printf("Y value from the graph: %f",TMath::Abs(gr->GetY()[iPoint]));
372     if(TMath::Abs(gr->GetY()[iPoint]) > maxVDriftCorr)  
373     {
374       fCalibrationStatus|=kCalibFailedTimeDrift;
375       return kFALSE;
376     }
377   }
378
379 return kTRUE;
380 }
381
382 void AliTPCPreprocessorOffline::UpdateDriftParam(AliTPCParam *param, TObjArray *const arr, Int_t lstartRun){
383   //
384   //  update the OCDB entry for the nominal time0
385   //
386   //
387   //  AliTPCParam * param = AliTPCcalibDB::Instance()->GetParameters();
388   AliTPCParam *paramNew = (AliTPCParam *)param->Clone();
389   TGraphErrors *grT =  (TGraphErrors *)arr->FindObject("ALIGN_ITSM_TPC_T0");
390   Double_t deltaTcm = TMath::Median(grT->GetN(),grT->GetY());
391   Double_t deltaT   = deltaTcm/param->GetDriftV();
392   paramNew->SetL1Delay(param->GetL1Delay()-deltaT);
393   paramNew->Update();
394
395   AliCDBMetaData *metaData= new AliCDBMetaData();
396   metaData->SetObjectClassName("TObjArray");
397   metaData->SetResponsible("Marian Ivanov");
398   metaData->SetBeamPeriod(1);
399   metaData->SetAliRootVersion("05-25-02"); //root version
400   metaData->SetComment("Updated calibration of nominal time 0");
401   AliCDBId* id1=NULL;
402   id1=new AliCDBId("TPC/Calib/Parameters", lstartRun, AliCDBRunRange::Infinity());
403   fOCDBstorage->Put(param, (*id1), metaData);
404
405 }
406
407
408 void AliTPCPreprocessorOffline::PrintArray(TObjArray *array){
409   //
410   // Print the names of the entries in array
411   //
412   Int_t entries = array->GetEntries();
413   for (Int_t i=0; i<entries; i++){
414     if (!array->At(i)) continue;
415     printf("%d\t %s\n", i,  array->At(i)->GetName());
416   }
417 }
418
419
420
421 TGraphErrors* AliTPCPreprocessorOffline::FilterGraphDrift(TGraphErrors * graph, Float_t errSigmaCut, Float_t medianCutAbs){
422   // 2 filters:
423   //    1. filter graph - error cut errSigmaCut
424   //    2. filter graph - medianCutAbs around median
425   //
426   // errSigmaCut   - cut on error
427   // medianCutAbs  - cut on value around median
428   Double_t dummy=0;               //   
429   //
430   // 1. filter graph - error cut errSigmaCut
431   //              
432   TGraphErrors *graphF; 
433   graphF = AliTPCcalibDButil::FilterGraphMedianErr(graph,errSigmaCut,dummy);
434   delete graph;
435   if (!graphF) return 0;
436   graph = AliTPCcalibDButil::FilterGraphMedianErr(graphF,errSigmaCut,dummy);
437   delete graphF;
438   if (!graph) return 0;
439   //
440   // filter graph - kMedianCutAbs around median
441   // 
442   graphF=FilterGraphMedianAbs(graph, medianCutAbs,dummy);
443   delete graph;
444   if (!graphF) return 0;
445   graph=FilterGraphMedianAbs(graphF, medianCutAbs,dummy);
446   delete graphF;
447   if (!graph) return 0;
448   return graph;
449 }
450
451
452
453 TGraphErrors* AliTPCPreprocessorOffline::FilterGraphMedianAbs(TGraphErrors * graph, Float_t cut,Double_t &medianY){
454   //
455   // filter outlyer measurement
456   // Only points around median +- cut filtered 
457   //
458   if (!graph) return  0;
459   Int_t kMinPoints=2;
460   Int_t npoints0 = graph->GetN();
461   Int_t npoints=0;
462   Float_t  rmsY=0;
463   Double_t *outx=new Double_t[npoints0];
464   Double_t *outy=new Double_t[npoints0];
465   Double_t *errx=new Double_t[npoints0];
466   Double_t *erry=new Double_t[npoints0];
467   //
468   //
469   if (npoints0<kMinPoints) {
470     delete []outx;
471     delete []outy;
472     delete []errx;
473     delete []erry;
474     return 0;
475   }
476   for (Int_t iter=0; iter<3; iter++){
477     npoints=0;
478     for (Int_t ipoint=0; ipoint<npoints0; ipoint++){
479       if (graph->GetY()[ipoint]==0) continue;
480       if (iter>0 &&TMath::Abs(graph->GetY()[ipoint]-medianY)>cut) continue;  
481       outx[npoints]  = graph->GetX()[ipoint];
482       outy[npoints]  = graph->GetY()[ipoint];
483       errx[npoints]  = graph->GetErrorX(ipoint);
484       erry[npoints]  = graph->GetErrorY(ipoint);
485       npoints++;
486     }
487     if (npoints<=1) break;
488     medianY  =TMath::Median(npoints,outy);
489     rmsY   =TMath::RMS(npoints,outy);
490   }
491   TGraphErrors *graphOut=0;
492   if (npoints>1) graphOut= new TGraphErrors(npoints,outx,outy,errx,erry); 
493   delete []outx;
494   delete []outy;
495   delete []errx;
496   delete []erry;
497   return graphOut;
498 }
499
500
501 void AliTPCPreprocessorOffline::AddHistoGraphs(  TObjArray * vdriftArray, AliTPCcalibTime * const timeDrift, Int_t minEntries){
502   //
503   // Add graphs corresponding to the alignment
504   //
505   const Double_t kErrSigmaCut=5;      // error sigma cut - for filtering
506   const Double_t kMedianCutAbs=0.03;  // error sigma cut - for filtering
507   //
508   TObjArray * array=timeDrift->GetHistoDrift();
509   if (array){
510     THnSparse* hist=NULL;
511     // 2.a) cosmics with different triggers
512     for (Int_t i=0; i<array->GetEntriesFast();i++){
513       hist=(THnSparseF*)array->UncheckedAt(i);
514       if(!hist) continue;
515       if (hist->GetEntries()<minEntries) continue;
516       //hist->Print();
517       TString name=hist->GetName();
518       Int_t dim[4]={0,1,2,3};
519       THnSparse* newHist=hist->Projection(4,dim);
520       newHist->SetName(name);
521       TGraphErrors* graph=AliTPCcalibBase::FitSlices(newHist,2,0,400,100,0.05,0.95, kTRUE);
522       if (!graph) {
523         printf("Graph =%s filtered out\n", name.Data());
524         continue;
525       }
526       printf("name=%s graph=%i, N=%i\n", name.Data(), graph==0, graph->GetN());
527       Int_t pos=name.Index("_");
528       name=name(pos,name.Capacity()-pos);
529       TString graphName=graph->ClassName();
530       graphName+=name;
531       graphName.ToUpper();
532       //
533       graph = FilterGraphDrift(graph, kErrSigmaCut, kMedianCutAbs);
534       //
535       if (graph){
536         graph->SetMarkerStyle(i%8+20);
537         graph->SetMarkerColor(i%7);
538         graph->GetXaxis()->SetTitle("Time");
539         graph->GetYaxis()->SetTitle("v_{dcor}");
540         graph->SetName(graphName);
541         graph->SetTitle(graphName);
542         printf("Graph %d\t=\t%s\n", i, graphName.Data());
543         vdriftArray->Add(graph);
544       }
545     }
546   }
547 }
548
549
550
551
552 void AliTPCPreprocessorOffline::AddAlignmentGraphs(  TObjArray * vdriftArray, AliTPCcalibTime *const timeDrift){
553   //
554   // Add graphs corresponding to alignment to the object array
555   //
556   TObjArray *arrayITS=0;
557   TObjArray *arrayTOF=0;
558   TObjArray *arrayTRD=0;
559   TMatrixD *mstatITS=0;
560   TMatrixD *mstatTOF=0;
561   TMatrixD *mstatTRD=0;
562   //
563   arrayITS=timeDrift->GetAlignITSTPC();
564   arrayTRD=timeDrift->GetAlignTRDTPC();
565   arrayTOF=timeDrift->GetAlignTOFTPC();
566
567   if (arrayITS->GetEntries()>0) mstatITS= AliTPCcalibDButil::MakeStatRelKalman(arrayITS,0.7,50,fMaxVdriftCorr);
568   if (arrayTOF->GetEntries()>0) mstatTOF= AliTPCcalibDButil::MakeStatRelKalman(arrayTOF,0.7,1000,fMaxVdriftCorr);
569   if (arrayTRD->GetEntries()>0) mstatTRD= AliTPCcalibDButil::MakeStatRelKalman(arrayTRD,0.7,50,fMaxVdriftCorr);
570   //
571   TObjArray * arrayITSP= AliTPCcalibDButil::SmoothRelKalman(arrayITS,*mstatITS, 0, 5.);
572   TObjArray * arrayITSM= AliTPCcalibDButil::SmoothRelKalman(arrayITS,*mstatITS, 1, 5.);
573   TObjArray * arrayITSB= AliTPCcalibDButil::SmoothRelKalman(arrayITSP,arrayITSM);
574   TObjArray * arrayTOFP= AliTPCcalibDButil::SmoothRelKalman(arrayTOF,*mstatTOF, 0, 5.);
575   TObjArray * arrayTOFM= AliTPCcalibDButil::SmoothRelKalman(arrayTOF,*mstatTOF, 1, 5.);
576   TObjArray * arrayTOFB= AliTPCcalibDButil::SmoothRelKalman(arrayTOFP,arrayTOFM);
577
578   TObjArray * arrayTRDP= 0x0;
579   TObjArray * arrayTRDM= 0x0;
580   TObjArray * arrayTRDB= 0x0;
581   arrayTRDP= AliTPCcalibDButil::SmoothRelKalman(arrayTRD,*mstatTRD, 0, 5.);
582   arrayTRDM= AliTPCcalibDButil::SmoothRelKalman(arrayTRD,*mstatTRD, 1, 5.);
583   arrayTRDB= AliTPCcalibDButil::SmoothRelKalman(arrayTRDP,arrayTRDM);
584   //
585   //
586   Int_t entries=TMath::Max(arrayITS->GetEntriesFast(),arrayTOF->GetEntriesFast());
587   TObjArray *arrays[12]={arrayITS, arrayITSP, arrayITSM, arrayITSB,
588                          arrayTRD, arrayTRDP, arrayTRDM, arrayTRDB,
589                          arrayTOF, arrayTOFP, arrayTOFM, arrayTOFB};
590   TString   grnames[12]={"ALIGN_ITS", "ALIGN_ITSP", "ALIGN_ITSM", "ALIGN_ITSB",
591                          "ALIGN_TRD", "ALIGN_TRDP", "ALIGN_TRDM","ALIGN_TRDB",
592                          "ALIGN_TOF", "ALIGN_TOFP", "ALIGN_TOFM","ALIGN_TOFB"};
593   TString   grpar[9]={"DELTAPSI", "DELTATHETA", "DELTAPHI",
594                       "DELTAX", "DELTAY", "DELTAZ",
595                       "DRIFTVD", "T0", "VDGY"};
596
597   
598   TVectorD vX(entries);
599   TVectorD vY(entries);
600   TVectorD vEx(entries);
601   TVectorD vEy(entries);
602   TObjArray *arr=0;
603   for (Int_t iarray=0; iarray<12; iarray++){
604     arr = arrays[iarray];
605     if (arr==0) continue;
606     for (Int_t ipar=0; ipar<9; ipar++){      
607       Int_t counter=0;
608       for (Int_t itime=0; itime<arr->GetEntriesFast(); itime++){
609         AliRelAlignerKalman * kalman = (AliRelAlignerKalman *) arr->UncheckedAt(itime);
610         if (!kalman) continue;
611         vX[counter]=kalman->GetTimeStamp();
612         vY[counter]=(*(kalman->GetState()))[ipar];
613         if (ipar==6) vY[counter]=1./(*(kalman->GetState()))[ipar]-1;
614         vEx[counter]=0;
615         vEy[counter]=TMath::Sqrt((*(kalman->GetStateCov()))(ipar,ipar));
616         counter++;
617       }
618     
619       TGraphErrors * graph=new TGraphErrors(counter, vX.GetMatrixArray(),
620                                           vY.GetMatrixArray(),
621                                           vEx.GetMatrixArray(),
622                                           vEy.GetMatrixArray());
623       TString grName=grnames[iarray];
624       grName+="_TPC_";
625       grName+=grpar[ipar];
626       graph->SetName(grName.Data());
627       vdriftArray->AddLast(graph);
628     }
629   }  
630 }
631
632
633
634
635 void AliTPCPreprocessorOffline::AddLaserGraphs(  TObjArray * vdriftArray, AliTPCcalibTime *timeDrift){
636   //
637   // add graphs for laser
638   //
639   const Double_t delayL0L1 = 0.071;  //this is hack for 1/2 weeks
640   //THnSparse *hisN=0;
641   TGraphErrors *grLaser[6]={0,0,0,0,0,0};
642   //hisN = timeDrift->GetHistVdriftLaserA(0);
643   if (timeDrift->GetHistVdriftLaserA(0)){
644     grLaser[0]=MakeGraphFilter0(timeDrift->GetHistVdriftLaserA(0),0,2,5,delayL0L1);
645     grLaser[0]->SetName("GRAPH_MEAN_DELAY_LASER_ALL_A");
646     vdriftArray->AddLast(grLaser[0]);
647   }    
648   if (timeDrift->GetHistVdriftLaserA(1)){
649     grLaser[1]=MakeGraphFilter0(timeDrift->GetHistVdriftLaserA(1),0,2,5);
650     grLaser[1]->SetName("GRAPH_MEAN_DRIFT_LASER_ALL_A");
651     vdriftArray->AddLast(grLaser[1]);
652   }    
653   if (timeDrift->GetHistVdriftLaserA(2)){
654     grLaser[2]=MakeGraphFilter0(timeDrift->GetHistVdriftLaserA(2),0,2,5);
655     grLaser[2]->SetName("GRAPH_MEAN_GLOBALYGRADIENT_LASER_ALL_A");
656     vdriftArray->AddLast(grLaser[2]);
657   }    
658   if (timeDrift->GetHistVdriftLaserC(0)){
659     grLaser[3]=MakeGraphFilter0(timeDrift->GetHistVdriftLaserC(0),0,2,5,delayL0L1);
660     grLaser[3]->SetName("GRAPH_MEAN_DELAY_LASER_ALL_C");
661     vdriftArray->AddLast(grLaser[3]);
662   }    
663   if (timeDrift->GetHistVdriftLaserC(1)){
664     grLaser[4]=MakeGraphFilter0(timeDrift->GetHistVdriftLaserC(1),0,2,5);
665     grLaser[4]->SetName("GRAPH_MEAN_DRIFT_LASER_ALL_C");
666     vdriftArray->AddLast(grLaser[4]);
667   }    
668   if (timeDrift->GetHistVdriftLaserC(2)){
669     grLaser[5]=MakeGraphFilter0(timeDrift->GetHistVdriftLaserC(2),0,2,5);
670     grLaser[5]->SetName("GRAPH_MEAN_GLOBALYGRADIENT_LASER_ALL_C");    
671     vdriftArray->AddLast(grLaser[5]);
672   }    
673   for (Int_t i=0; i<6;i++){
674     if (grLaser[i]) {
675       SetDefaultGraphDrift(grLaser[i], 1,(i+20));
676       grLaser[i]->GetYaxis()->SetTitle("Laser Correction");
677     }
678   }
679 }
680  
681  
682 TGraphErrors * AliTPCPreprocessorOffline::MakeGraphFilter0(THnSparse *hisN, Int_t itime, Int_t ival, Int_t minEntries, Double_t offset){
683   //
684   // Make graph with mean values and rms
685   //
686   hisN->GetAxis(itime)->SetRange(0,100000000);
687   hisN->GetAxis(ival)->SetRange(0,100000000);
688   TH1 * hisT      = hisN->Projection(itime);
689   TH1 * hisV      = hisN->Projection(ival);
690   //
691   Int_t firstBinA = hisT->FindFirstBinAbove(2);
692   Int_t lastBinA  = hisT->FindLastBinAbove(2);    
693   Int_t firstBinV = hisV->FindFirstBinAbove(0);
694   Int_t lastBinV  = hisV->FindLastBinAbove(0);    
695   hisN->GetAxis(itime)->SetRange(firstBinA,lastBinA);
696   hisN->GetAxis(ival)->SetRange(firstBinV,lastBinV);
697   Int_t entries=0;
698   for (Int_t ibin=firstBinA; ibin<=lastBinA; ibin++){
699     Double_t cont = hisT->GetBinContent(ibin);
700     if (cont<minEntries) continue;
701     entries++;
702   }
703   TVectorD vecTime(entries);
704   TVectorD vecMean0(entries);
705   TVectorD vecRMS0(entries);
706   TVectorD vecMean1(entries);
707   TVectorD vecRMS1(entries);
708   entries=0;
709   for (Int_t ibin=firstBinA; ibin<=lastBinA; ibin++){
710       Double_t cont = hisT->GetBinContent(ibin);
711       if (cont<minEntries) continue;
712       //hisN->GetAxis(itime)->SetRange(ibin-1,ibin+1);
713       Int_t minBin = ibin-1;
714       Int_t maxBin = ibin+1;
715       if(minBin <= 0) minBin = 1;
716       if(maxBin >= hisN->GetAxis(itime)->GetNbins()) maxBin = hisN->GetAxis(itime)->GetNbins()-1;
717       hisN->GetAxis(itime)->SetRange(minBin,maxBin);
718       
719       Double_t time = hisT->GetBinCenter(ibin);
720       TH1 * his = hisN->Projection(ival);
721       Double_t nentries0= his->GetBinContent(his->FindBin(0));
722       if (cont-nentries0<minEntries) continue;
723       //
724       his->SetBinContent(his->FindBin(0),0);
725       vecTime[entries]=time;
726       vecMean0[entries]=his->GetMean()+offset;
727       vecMean1[entries]=his->GetMeanError();
728       vecRMS0[entries] =his->GetRMS();
729       vecRMS1[entries] =his->GetRMSError();
730       delete his;  
731       entries++;
732   }
733   delete hisT;
734   delete hisV;
735   TGraphErrors * graph =  new TGraphErrors(entries,vecTime.GetMatrixArray(), vecMean0.GetMatrixArray(),                                    0, vecMean1.GetMatrixArray());
736   return graph;
737 }
738
739
740
741
742
743
744
745
746 void AliTPCPreprocessorOffline::SetDefaultGraphDrift(TGraph *graph, Int_t color, Int_t style){
747   //
748   // Set default style for QA views
749   //
750   graph->GetXaxis()->SetTimeDisplay(kTRUE);
751   graph->GetXaxis()->SetTimeFormat("#splitline{%d/%m}{%H:%M}");
752   graph->SetMaximum( 0.025);
753   graph->SetMinimum(-0.025);
754   graph->GetXaxis()->SetTitle("Time");
755   graph->GetYaxis()->SetTitle("v_{dcorr}");
756   //
757   graph->GetYaxis()->SetLabelSize(0.03);
758   graph->GetXaxis()->SetLabelSize(0.03);
759   //
760   graph->GetXaxis()->SetNdivisions(10,5,0);
761   graph->GetYaxis()->SetNdivisions(10,5,0);
762   //
763   graph->GetXaxis()->SetLabelOffset(0.02);
764   graph->GetYaxis()->SetLabelOffset(0.005);
765   //
766   graph->GetXaxis()->SetTitleOffset(1.3);
767   graph->GetYaxis()->SetTitleOffset(1.2);
768   //
769   graph->SetMarkerColor(color);
770   graph->SetLineColor(color);
771   graph->SetMarkerStyle(style);
772 }
773
774 void AliTPCPreprocessorOffline::SetPadStyle(TPad *pad, Float_t mx0, Float_t mx1, Float_t my0, Float_t my1){
775   // 
776   // Set default pad style for QA
777   // 
778   pad->SetTicks(1,1);
779   pad->SetMargin(mx0,mx1,my0,my1);
780 }
781
782
783 void AliTPCPreprocessorOffline::MakeDefaultPlots(TObjArray * const arr, TObjArray * /*picArray*/){
784   //
785   // 0. make a default QA plots
786   // 1. Store them in the array
787   //
788   //
789   Float_t mx0=0.12, mx1=0.1, my0=0.15, my1=0.1;
790   //
791   TGraphErrors* laserA       =(TGraphErrors*)arr->FindObject("GRAPH_MEAN_DRIFT_LASER_ALL_A");
792   TGraphErrors* laserC       =(TGraphErrors*)arr->FindObject("GRAPH_MEAN_DRIFT_LASER_ALL_C");
793   TGraphErrors* cosmic       =(TGraphErrors*)arr->FindObject("TGRAPHERRORS_MEAN_VDRIFT_COSMICS_ALL");
794   TGraphErrors* cross        =(TGraphErrors*)arr->FindObject("TGRAPHERRORS_VDRIFT_CROSS_ALL");
795   TGraphErrors* itstpcP       =(TGraphErrors*)arr->FindObject("ALIGN_ITSP_TPC_DRIFTVD");
796   TGraphErrors* itstpcM       =(TGraphErrors*)arr->FindObject("ALIGN_ITSM_TPC_DRIFTVD");
797   TGraphErrors* itstpcB       =(TGraphErrors*)arr->FindObject("ALIGN_ITSB_TPC_DRIFTVD");
798   //
799   if (laserA)  SetDefaultGraphDrift(laserA,2,25);
800   if (laserC)  SetDefaultGraphDrift(laserC,4,26);
801   if (cosmic)  SetDefaultGraphDrift(cosmic,3,27);
802   if (cross)   SetDefaultGraphDrift(cross,4,28);
803   if (itstpcP) SetDefaultGraphDrift(itstpcP,2,29);
804   if (itstpcM) SetDefaultGraphDrift(itstpcM,4,30);
805   if (itstpcB) SetDefaultGraphDrift(itstpcB,1,31);
806   //
807   //
808   TPad *pad=0;
809   //
810   // Laser-Laser
811   //
812   if (laserA&&laserC){
813     pad = new TCanvas("TPCLaserVDrift","TPCLaserVDrift");
814     laserA->Draw("alp");
815     SetPadStyle(pad,mx0,mx1,my0,my1);
816     laserA->Draw("apl");
817     laserC->Draw("p");
818     TLegend *legend = new TLegend(mx0+0.01,1-my1-0.2, 0.5, 1-my1-0.01, "Drift velocity correction");
819     legend->AddEntry(laserA,"Laser A side");
820     legend->AddEntry(laserC,"Laser C side");
821     legend->Draw();    
822     //picArray->AddLast(pad);
823   }
824
825   if (itstpcP&&itstpcM&&itstpcB){
826     pad = new TCanvas("ITSTPC","ITSTPC");
827     itstpcP->Draw("alp");
828     SetPadStyle(pad,mx0,mx1,my0,my1);    
829     itstpcP->Draw("alp");
830     gPad->Clear();
831     itstpcM->Draw("apl");
832     itstpcP->Draw("p");
833     itstpcB->Draw("p");
834     TLegend *legend = new TLegend(mx0+0.01,1-my1-0.2, 0.5, 1-my1-0.01, "Drift velocity correction");
835     legend->AddEntry(itstpcP,"ITS-TPC smooth plus");
836     legend->AddEntry(itstpcM,"ITS-TPC smooth minus");
837     legend->AddEntry(itstpcB,"ITS-TPC smooth ");
838     legend->Draw();    
839     //picArray->AddLast(pad);
840   }
841
842   if (itstpcB&&laserA&&itstpcP&&itstpcM){
843     pad = new TCanvas("ITSTPC_LASER","ITSTPC_LASER");
844     SetPadStyle(pad,mx0,mx1,my0,my1);    
845     laserA->Draw("alp");
846     itstpcP->Draw("p");
847     itstpcM->Draw("p");
848     itstpcB->Draw("p");
849     TLegend *legend = new TLegend(mx0+0.01,1-my1-0.2, 0.5, 1-my1-0.01, "Drift velocity correction");
850     legend->AddEntry(laserA,"TPC laser");
851     legend->AddEntry(itstpcP,"ITS-TPC smooth plus");   
852     legend->AddEntry(itstpcM,"ITS-TPC smooth minus");   
853     legend->AddEntry(itstpcB,"ITS-TPC smooth ");
854     legend->Draw();
855     //picArray->AddLast(pad);
856   }
857
858   if (itstpcP&&cross){ 
859     pad = new TCanvas("ITSTPC_CROSS","ITSTPC_CROSS");
860     SetPadStyle(pad,mx0,mx1,my0,my1);    
861     itstpcP->Draw("alp");
862     pad->Clear();
863     cross->Draw("ap");
864     itstpcP->Draw("p");
865     //
866     TLegend *legend = new TLegend(mx0+0.01,1-my1-0.2, 0.5, 1-my1-0.01, "Drift velocity correction");
867
868     legend->AddEntry(cross,"TPC cross tracks");
869     legend->AddEntry(itstpcB,"ITS-TPC smooth");
870     legend->Draw();        
871     //picArray->AddLast(pad);
872   }
873   if (itstpcP&&cosmic){ 
874     pad = new TCanvas("ITSTPC_COSMIC","ITSTPC_COSMIC");
875     SetPadStyle(pad,mx0,mx1,my0,my1);    
876     itstpcP->Draw("alp");
877     pad->Clear();
878     cosmic->Draw("ap");
879     itstpcP->Draw("p");
880     //
881     TLegend *legend = new TLegend(mx0+0.01,1-my1-0.2, 0.5, 1-my1-0.01, "Drift velocity correction");
882
883     legend->AddEntry(cosmic,"TPC cross tracks0 up-down");
884     legend->AddEntry(itstpcB,"ITS-TPC smooth");
885     legend->Draw();        
886     //picArray->AddLast(pad);
887   }
888 }
889
890
891
892
893 void AliTPCPreprocessorOffline::CalibTimeGain(const Char_t* fileName, Int_t startRunNumber, Int_t endRunNumber,  AliCDBStorage* pocdbStorage){
894   //
895   // Update OCDB gain
896   //
897   if (pocdbStorage==0) {
898     TString localStorage = "local://"+gSystem->GetFromPipe("pwd")+"/OCDB";
899     pocdbStorage = AliCDBManager::Instance()->GetStorage(localStorage.Data());
900   }
901
902   //
903   // 1. Read gain values
904   //
905   ReadGainGlobal(fileName);
906
907   //
908   // 2. Extract calibration values
909   //
910   AnalyzeGain(startRunNumber,endRunNumber, 1000,1.43);
911   AnalyzeAttachment(startRunNumber,endRunNumber);
912   AnalyzePadRegionGain();
913   AnalyzeGainMultiplicity();
914   AnalyzeGainChamberByChamber();
915   //
916   AnalyzeGainDipAngle(0); // short pads
917   AnalyzeGainDipAngle(1); // medium pads
918   AnalyzeGainDipAngle(2); // long pads
919   AnalyzeGainDipAngle(3); // absolute calibration on full track
920   //
921   // 3. Make control plots
922   //
923   MakeQAPlot(1.43);  
924
925   //
926   // 4. validate OCDB entries
927   //
928   if(fSwitchOnValidation==kTRUE && ValidateTimeGain()==kFALSE) { 
929     Printf("TPC time gain OCDB parameters out of range!");
930     return;
931   }
932
933   //
934   // 5. Update OCDB
935   //
936   UpdateOCDBGain( startRunNumber, endRunNumber, pocdbStorage);
937 }
938
939 void AliTPCPreprocessorOffline::ReadGainGlobal(const Char_t* fileName){
940   //
941   // read calibration entries from file
942   // 
943   TFile fcalib(fileName);
944   TObject* obj = dynamic_cast<TObject*>(fcalib.Get("TPCCalib"));
945   TObjArray * array = dynamic_cast<TObjArray*>(obj);
946   TDirectory * dir = dynamic_cast<TDirectory*>(obj);
947   if (dir) {
948     fGainMIP    = dynamic_cast<AliTPCcalibTimeGain *>(dir->Get("calibTimeGain"));
949     fGainCosmic = dynamic_cast<AliTPCcalibTimeGain *>(dir->Get("calibTimeGainCosmic"));
950     fGainMult   = dynamic_cast<AliTPCcalibGainMult *>(dir->Get("calibGainMult"));
951   }
952   else if (array){
953     fGainMIP    = ( AliTPCcalibTimeGain *)array->FindObject("calibTimeGain");
954     fGainCosmic = ( AliTPCcalibTimeGain *)array->FindObject("calibTimeGainCosmic");
955     fGainMult   = ( AliTPCcalibGainMult *)array->FindObject("calibGainMult");
956   }else{
957     fGainMIP    = ( AliTPCcalibTimeGain *)fcalib.Get("calibTimeGain");
958     fGainCosmic = ( AliTPCcalibTimeGain *)fcalib.Get("calibTimeGainCosmic");
959     fGainMult   = ( AliTPCcalibGainMult *)fcalib.Get("calibGainMult");
960   }
961   if (!fGainMult){
962     TFile calibMultFile("TPCMultObjects.root");
963     fGainMult   = ( AliTPCcalibGainMult *)calibMultFile.Get("calibGainMult");
964   }
965   TH1 * hisT=0;
966   Int_t firstBinA =0, lastBinA=0;
967
968   if (fGainCosmic){ 
969     hisT= fGainCosmic->GetHistGainTime()->Projection(1);
970     firstBinA = hisT->FindFirstBinAbove(2);
971     lastBinA  = hisT->FindLastBinAbove(2);    
972     fGainCosmic->GetHistGainTime()->GetAxis(1)->SetRange(firstBinA,lastBinA);
973     delete hisT;
974   }
975
976   if (fGainMIP){ 
977     hisT= fGainMIP->GetHistGainTime()->Projection(1);
978     firstBinA = hisT->FindFirstBinAbove(2);
979     lastBinA  = hisT->FindLastBinAbove(2);    
980     fGainMIP->GetHistGainTime()->GetAxis(1)->SetRange(firstBinA,lastBinA);
981     delete hisT;
982   }
983
984 }
985
986 Bool_t AliTPCPreprocessorOffline::AnalyzeGain(Int_t startRunNumber, Int_t endRunNumber, Int_t minEntriesGaussFit,  Float_t FPtoMIPratio){
987   //
988   // Analyze gain - produce the calibration graphs
989  //
990
991   // 1.) try to create MIP spline
992   if (fGainMIP) 
993   {
994     fGainMIP->GetHistGainTime()->GetAxis(5)->SetRangeUser(startRunNumber, endRunNumber);
995     fGainMIP->GetHistGainTime()->GetAxis(2)->SetRangeUser(1.51,2.49); // only beam data
996     fGainMIP->GetHistGainTime()->GetAxis(4)->SetRangeUser(0.39,0.51); // only MIP pions
997     //
998     fGraphMIP = AliTPCcalibBase::FitSlices(fGainMIP->GetHistGainTime(),0,1,minEntriesGaussFit,10,0.1,0.7);
999     if (fGraphMIP->GetN()==0) fGraphMIP = 0x0;
1000     if (fGraphMIP) fFitMIP = AliTPCcalibTimeGain::MakeSplineFit(fGraphMIP);
1001     if (fGraphMIP) fGraphMIP->SetName("TGRAPHERRORS_MEAN_GAIN_BEAM_ALL");// set proper names according to naming convention
1002     fGainArray->AddAt(fFitMIP,0);
1003   } 
1004
1005   // 2.) try to create Cosmic spline
1006   if (fGainCosmic)
1007   {
1008     fGainCosmic->GetHistGainTime()->GetAxis(2)->SetRangeUser(0.51,1.49); // only cosmics
1009     fGainCosmic->GetHistGainTime()->GetAxis(4)->SetRangeUser(20,100);    // only Fermi-Plateau muons
1010     //
1011     fGraphCosmic = AliTPCcalibBase::FitSlices(fGainCosmic->GetHistGainTime(),0,1,minEntriesGaussFit,10);
1012     if (fGraphCosmic->GetN()==0) fGraphCosmic = 0x0;
1013     //
1014     if (fGraphCosmic) {
1015       for(Int_t i=0; i < fGraphCosmic->GetN(); i++) {
1016         fGraphCosmic->GetY()[i] /= FPtoMIPratio;
1017         fGraphCosmic->GetEY()[i] /= FPtoMIPratio;
1018       }
1019     }
1020     //
1021     if (fGraphCosmic) fFitCosmic = AliTPCcalibTimeGain::MakeSplineFit(fGraphCosmic);
1022     if (fGraphCosmic) fGraphCosmic->SetName("TGRAPHERRORS_MEAN_GAIN_COSMIC_ALL"); // set proper names according to naming convention
1023     fGainArray->AddAt(fFitCosmic,1);
1024   }
1025   // with naming convention and backward compatibility
1026   fGainArray->AddAt(fGraphMIP,2);
1027   fGainArray->AddAt(fGraphCosmic,3);
1028   //
1029   // 3.) Add HV and PT correction parameterization which was used
1030   //
1031   AliTPCParam *param= AliTPCcalibDB::Instance()->GetParameters();
1032   if (param->GetGainSlopesHV())  fGainArray->AddLast(param->GetGainSlopesHV());
1033   if (param->GetGainSlopesPT())  fGainArray->AddLast(param->GetGainSlopesPT());
1034   //
1035   // 4.) Add the RecoParam and ClusterParam - for compatibility checks -deffrent sets of paramters can invalidate calibration 
1036   //
1037   AliTPCClusterParam *clParam =   AliTPCcalibDB::Instance()->GetClusterParam();
1038   TObjArray *recoParams = new TObjArray(4) ;
1039   for (Int_t i=0;i<4;i++) recoParams->AddAt(AliTPCcalibDB::Instance()->GetRecoParam(i),i);
1040   fGainArray->AddLast(clParam);
1041   fGainArray->AddLast(recoParams);
1042   //
1043   cout << "fGraphCosmic: " << fGraphCosmic << " fGraphMIP " << fGraphMIP << endl;
1044   return kTRUE;
1045
1046 }
1047
1048 Bool_t AliTPCPreprocessorOffline::AnalyzeAttachment(Int_t startRunNumber, Int_t endRunNumber, Int_t minEntriesFit) {
1049   //
1050   // determine slope as a function of mean driftlength
1051   //
1052   if(!fGainMIP) return kFALSE;
1053
1054   fGainMIP->GetHistGainTime()->GetAxis(5)->SetRangeUser(startRunNumber, endRunNumber);
1055   //
1056   fGainMIP->GetHistGainTime()->GetAxis(2)->SetRangeUser(1.51,2.49); // only beam data
1057   fGainMIP->GetHistGainTime()->GetAxis(4)->SetRangeUser(0.39,0.51); // only MIP pions
1058   //
1059   fGainMIP->GetHistGainTime()->GetAxis(3)->SetRangeUser(125,250);// only full tracking region (driftlength)
1060   fGainMIP->GetHistGainTime()->GetAxis(0)->SetRangeUser(1.5,3.5);// only full tracking region (driftlength)
1061   //
1062   TH3D * hist = fGainMIP->GetHistGainTime()->Projection(1, 0, 3);
1063   //
1064   Double_t *xvec = new Double_t[hist->GetNbinsX()];
1065   Double_t *yvec = new Double_t[hist->GetNbinsX()];
1066   Double_t *xerr = new Double_t[hist->GetNbinsX()];
1067   Double_t *yerr = new Double_t[hist->GetNbinsX()];
1068   Int_t counter  = 0;
1069   //
1070   for(Int_t i=1; i < hist->GetNbinsX(); i++) {
1071     Int_t nsum=0;
1072     Int_t imin   =  i;
1073     Int_t imax   =  i;    
1074     for (Int_t idelta=0; idelta<5; idelta++){
1075       //
1076       imin   =  TMath::Max(i-idelta,1);
1077       imax   =  TMath::Min(i+idelta,hist->GetNbinsX());
1078       nsum = TMath::Nint(hist->Integral(imin,imax,1,hist->GetNbinsY()-1,1,hist->GetNbinsZ()-1));
1079       //if (nsum==0) break;
1080       if (nsum>minEntriesFit) break;
1081     }
1082     if (nsum<minEntriesFit) continue;
1083     //
1084     fGainMIP->GetHistGainTime()->GetAxis(1)->SetRangeUser(hist->GetXaxis()->GetBinCenter(imin-1),hist->GetXaxis()->GetBinCenter(imax+1)); // define time range
1085     TH2D * histZdep = fGainMIP->GetHistGainTime()->Projection(0,3);
1086     TObjArray arr;
1087     histZdep->FitSlicesY(0,0,-1,0,"QNR",&arr);
1088     TH1D * driftDep = (TH1D*)arr.At(1);
1089     delete histZdep;
1090     //TGraphErrors * driftDep = AliTPCcalibBase::FitSlices(fGainMIP->GetHistGainTime(),0,3,100,1,0.,1);
1091     /*if (driftDep->GetN() < 4) {
1092       delete driftDep;
1093       continue;
1094       }*/
1095     //
1096     //TObjArray arr;
1097     //
1098     TF1 pol1("polynom1","pol1",125,240);
1099     //driftDep->Fit(&pol1,"QNRROB=0.8");
1100     driftDep->Fit(&pol1,"QNR");
1101     xvec[counter] = 0.5*(hist->GetXaxis()->GetBinCenter(imin-1)+hist->GetXaxis()->GetBinCenter(imax+1));
1102     yvec[counter] = pol1.GetParameter(1)/pol1.GetParameter(0);
1103     xerr[counter] = hist->GetXaxis()->GetBinCenter(imax+1)-hist->GetXaxis()->GetBinCenter(imin-1);
1104     yerr[counter] = pol1.GetParError(1)/pol1.GetParameter(0);
1105     counter++;
1106     //
1107     //delete driftDep;
1108   }
1109   //
1110   fGraphAttachmentMIP = new TGraphErrors(counter, xvec, yvec, xerr, yerr);
1111   if (fGraphAttachmentMIP) fGraphAttachmentMIP->SetName("TGRAPHERRORS_MEAN_ATTACHMENT_BEAM_ALL");// set proper names according to naming convention
1112   fGainArray->AddLast(fGraphAttachmentMIP);
1113   //
1114   delete [] xvec;
1115   delete [] yvec;
1116   delete [] xerr;
1117   delete [] yerr;
1118   delete hist;
1119   //
1120   if (counter < 1) return kFALSE;
1121   return kTRUE;
1122
1123 }
1124
1125
1126 Bool_t AliTPCPreprocessorOffline::AnalyzePadRegionGain(){
1127   //
1128   // Analyze gain for different pad regions - produce the calibration graphs 0,1,2
1129   //
1130   if (fGainMult) 
1131   {
1132     TH2D * histQmax = (TH2D*) fGainMult->GetHistPadEqual()->Projection(0,2);
1133     TH2D * histQtot = (TH2D*) fGainMult->GetHistPadEqual()->Projection(1,2);
1134     //
1135     TObjArray arr;
1136     histQmax->FitSlicesY(0,0,-1,0,"QNR",&arr);
1137     Double_t xMax[3] = {0,1,2};
1138     Double_t yMax[3]    = {((TH1D*)arr.At(1))->GetBinContent(1),
1139                            ((TH1D*)arr.At(1))->GetBinContent(2),
1140                            ((TH1D*)arr.At(1))->GetBinContent(3)};
1141     Double_t yMaxErr[3] = {((TH1D*)arr.At(1))->GetBinError(1),
1142                            ((TH1D*)arr.At(1))->GetBinError(2),
1143                            ((TH1D*)arr.At(1))->GetBinError(3)};
1144     TGraphErrors * fitPadRegionQmax = new TGraphErrors(3, xMax, yMax, 0, yMaxErr);
1145     //
1146     histQtot->FitSlicesY(0,0,-1,0,"QNR",&arr);
1147     Double_t xTot[3] = {0,1,2};
1148     Double_t yTot[3]    = {((TH1D*)arr.At(1))->GetBinContent(1),
1149                            ((TH1D*)arr.At(1))->GetBinContent(2),
1150                            ((TH1D*)arr.At(1))->GetBinContent(3)};
1151     Double_t yTotErr[3] = {((TH1D*)arr.At(1))->GetBinError(1),
1152                            ((TH1D*)arr.At(1))->GetBinError(2),
1153                            ((TH1D*)arr.At(1))->GetBinError(3)};
1154     TGraphErrors * fitPadRegionQtot = new TGraphErrors(3, xTot, yTot, 0, yTotErr);
1155     //
1156     fitPadRegionQtot->SetName("TGRAPHERRORS_MEANQTOT_PADREGIONGAIN_BEAM_ALL");// set proper names according to naming convention
1157     fitPadRegionQmax->SetName("TGRAPHERRORS_MEANQMAX_PADREGIONGAIN_BEAM_ALL");// set proper names according to naming convention
1158     //
1159     fGainArray->AddLast(fitPadRegionQtot);
1160     fGainArray->AddLast(fitPadRegionQmax);
1161     return kTRUE;
1162   } 
1163   return kFALSE;
1164
1165 }
1166
1167
1168 Bool_t AliTPCPreprocessorOffline::AnalyzeGainDipAngle(Int_t padRegion)  {
1169   //
1170   // Analyze gain as a function of multiplicity and produce calibration graphs
1171   // padRegion -- 0: short, 1: medium, 2: long, 3: absolute calibration of full track
1172   //
1173   if (!fGainMult) return kFALSE;
1174   if (!(fGainMult->GetHistTopology())) return kFALSE;
1175   //
1176   // "dEdxRatioMax","dEdxRatioTot","padType","mult","driftlength"
1177   TObjArray arrMax;
1178   TObjArray arrTot;
1179   //
1180   TH2D * histQmax = 0x0;
1181   TH2D * histQtot = 0x0;
1182   fGainMult->GetHistPadEqual()->GetAxis(4)->SetRangeUser(-0.85,0.85);
1183   fGainMult->GetHistTopology()->GetAxis(2)->SetRangeUser(-0.85,0.85);
1184   if (padRegion < 3) {
1185     fGainMult->GetHistPadEqual()->GetAxis(2)->SetRangeUser(padRegion,padRegion); // short,medium,long
1186     histQmax = (TH2D*) fGainMult->GetHistPadEqual()->Projection(0,4);
1187     histQtot = (TH2D*) fGainMult->GetHistPadEqual()->Projection(1,4);
1188   } else {
1189     fGainMult->GetHistTopology()->GetAxis(1)->SetRangeUser(1,1); //Qmax
1190     histQmax = (TH2D*) fGainMult->GetHistTopology()->Projection(0,2);
1191     histQmax->SetName("fGainMult_GetHistPadEqual_11");
1192     fGainMult->GetHistTopology()->GetAxis(1)->SetRangeUser(0,0); //Qtot
1193     histQtot = (TH2D*) fGainMult->GetHistTopology()->Projection(0,2);
1194     histQtot->SetName("fGainMult_GetHistPadEqual_00");
1195   }
1196   //  
1197   histQmax->FitSlicesY(0,0,-1,0,"QNR",&arrMax);
1198   TH1D * corrMax = (TH1D*)arrMax.At(1)->Clone();
1199   histQtot->FitSlicesY(0,0,-1,0,"QNR",&arrTot);
1200   TH1D * corrTot = (TH1D*)arrTot.At(1)->Clone();
1201   corrMax->Scale(1./histQmax->GetMean(2));
1202   corrTot->Scale(1./histQtot->GetMean(2));
1203   //
1204   const char* names[4]={"SHORT","MEDIUM","LONG","ABSOLUTE"};
1205   //
1206   TGraphErrors * graphMax = new TGraphErrors(corrMax);
1207   TGraphErrors * graphTot = new TGraphErrors(corrTot);
1208   Double_t meanMax = TMath::Mean(graphMax->GetN(), graphMax->GetY());
1209   Double_t meanTot = TMath::Mean(graphTot->GetN(), graphTot->GetY());
1210   //
1211   for (Int_t ipoint=0; ipoint<graphMax->GetN(); ipoint++) {graphMax->GetY()[ipoint]/=meanMax;}
1212   for (Int_t ipoint=0; ipoint<graphTot->GetN(); ipoint++) {graphTot->GetY()[ipoint]/=meanTot;}
1213
1214   //
1215   graphMax->SetNameTitle(Form("TGRAPHERRORS_QMAX_DIPANGLE_%s_BEAM_ALL",names[padRegion]),
1216                         Form("TGRAPHERRORS_QMAX_DIPANGLE_%s_BEAM_ALL",names[padRegion]));
1217   graphTot->SetNameTitle(Form("TGRAPHERRORS_QTOT_DIPANGLE_%s_BEAM_ALL",names[padRegion]),
1218                         Form("TGRAPHERRORS_QTOT_DIPANGLE_%s_BEAM_ALL",names[padRegion]));
1219   //
1220   fGainArray->AddLast(graphMax);
1221   fGainArray->AddLast(graphTot);
1222   //
1223   // Normalization to 1 (mean of the graph.fY --> 1)
1224   //
1225   TF1 * funMax= new TF1("","1++abs(x)++abs(x*x)");
1226   TF1 * funTot= new TF1("","1++abs(x)++abs(x*x)");
1227   graphMax->Fit(funMax,"w","rob=0.9",-0.8,0.8);
1228   graphTot->Fit(funTot,"w","rob=0.9",-0.8,0.8);
1229   funMax->SetNameTitle(Form("TF1_QMAX_DIPANGLE_%s_BEAM_ALL",names[padRegion]),
1230                         Form("TF1_QMAX_DIPANGLE_%s_BEAM_ALL",names[padRegion]));
1231   funTot->SetNameTitle(Form("TF1_QTOT_DIPANGLE_%s_BEAM_ALL",names[padRegion]),
1232                         Form("TF1_QTOT_DIPANGLE_%s_BEAM_ALL",names[padRegion]));
1233
1234   //
1235   fGainArray->AddLast(funMax);
1236   fGainArray->AddLast(funTot);
1237   //
1238   return kTRUE;
1239 }
1240
1241
1242 Bool_t AliTPCPreprocessorOffline::AnalyzeGainMultiplicity() {
1243   //
1244   // Analyze gain as a function of multiplicity and produce calibration graphs
1245   //
1246   if (!fGainMult) return kFALSE;
1247   fGainMult->GetHistGainMult()->GetAxis(3)->SetRangeUser(3,3);
1248   TH2D * histMultMax = fGainMult->GetHistGainMult()->Projection(0,4);
1249   TH2D * histMultTot = fGainMult->GetHistGainMult()->Projection(1,4);
1250   histMultMax->RebinX(4);
1251   histMultTot->RebinX(4);
1252   //
1253   TObjArray arrMax;
1254   TObjArray arrTot;
1255   TF1 fitGaus("fitGaus","gaus(0)",histMultMax->GetYaxis()->GetXmin(),histMultMax->GetYaxis()->GetXmax());
1256   fitGaus.SetParameters(histMultMax->GetEntries()/10., histMultMax->GetMean(2), TMath::Sqrt(TMath::Abs(histMultMax->GetMean(2))));
1257   histMultMax->FitSlicesY(&fitGaus,0,-1,1,"QNRB",&arrMax);
1258   fitGaus.SetParameters(histMultTot->GetEntries()/10., histMultTot->GetMean(2), TMath::Sqrt(TMath::Abs(histMultTot->GetMean(2))));
1259   histMultTot->FitSlicesY(&fitGaus,0,-1,1,"QNRB",&arrTot);
1260   //
1261   TH1D * meanMax = (TH1D*)arrMax.At(1);
1262   TH1D * meanTot = (TH1D*)arrTot.At(1);
1263   Float_t meanMult = histMultMax->GetMean();
1264   if(meanMax->GetBinContent(meanMax->FindBin(meanMult))) {
1265     meanMax->Scale(1./meanMax->GetBinContent(meanMax->FindBin(meanMult)));
1266   }
1267   else {
1268    return kFALSE;
1269   }
1270   if(meanTot->GetBinContent(meanTot->FindBin(meanMult))) {
1271     meanTot->Scale(1./meanTot->GetBinContent(meanTot->FindBin(meanMult)));
1272   }
1273   else {
1274    return kFALSE;
1275   }
1276   Float_t xMultMax[50];
1277   Float_t yMultMax[50];
1278   Float_t yMultErrMax[50];
1279   Float_t xMultTot[50];
1280   Float_t yMultTot[50];
1281   Float_t yMultErrTot[50];
1282   //
1283   Int_t nCountMax = 0;
1284   for(Int_t iBin = 1; iBin < meanMax->GetXaxis()->GetNbins(); iBin++) {
1285     Float_t yValMax = meanMax->GetBinContent(iBin);
1286     if (yValMax < 0.7) continue;
1287     if (yValMax > 1.3) continue;
1288     if (meanMax->GetBinError(iBin)/yValMax > 0.01) continue;
1289     xMultMax[nCountMax] = meanMax->GetXaxis()->GetBinCenter(iBin);
1290     yMultMax[nCountMax] = yValMax;
1291     yMultErrMax[nCountMax] = meanMax->GetBinError(iBin);
1292     nCountMax++;
1293   }
1294   //
1295   if (nCountMax < 10) return kFALSE;
1296   TGraphErrors * fitMultMax = new TGraphErrors(nCountMax, xMultMax, yMultMax, 0, yMultErrMax);
1297   fitMultMax->SetName("TGRAPHERRORS_MEANQMAX_MULTIPLICITYDEPENDENCE_BEAM_ALL");
1298   //
1299   Int_t nCountTot = 0;
1300   for(Int_t iBin = 1; iBin < meanTot->GetXaxis()->GetNbins(); iBin++) {
1301     Float_t yValTot = meanTot->GetBinContent(iBin);
1302     if (yValTot < 0.7) continue;
1303     if (yValTot > 1.3) continue;
1304     if (meanTot->GetBinError(iBin)/yValTot > 0.1) continue;
1305     xMultTot[nCountTot] = meanTot->GetXaxis()->GetBinCenter(iBin);
1306     yMultTot[nCountTot] = yValTot;
1307     yMultErrTot[nCountTot] = meanTot->GetBinError(iBin);
1308     nCountTot++;
1309   }
1310   //
1311   if (nCountTot < 10) return kFALSE;
1312   TGraphErrors *  fitMultTot = new TGraphErrors(nCountTot, xMultTot, yMultTot, 0, yMultErrTot);
1313   fitMultTot->SetName("TGRAPHERRORS_MEANQTOT_MULTIPLICITYDEPENDENCE_BEAM_ALL");
1314   //
1315   fGainArray->AddLast(fitMultMax);
1316   fGainArray->AddLast(fitMultTot);
1317   //
1318   return kTRUE;
1319
1320 }
1321
1322 Bool_t AliTPCPreprocessorOffline::AnalyzeGainChamberByChamber(){
1323   //
1324   // get chamber by chamber gain
1325   //
1326   if (!fGainMult) return kFALSE;
1327   TGraphErrors *grShort  = fGainMult->GetGainPerChamberRobust(0);
1328   TGraphErrors *grMedium = fGainMult->GetGainPerChamberRobust(1);
1329   TGraphErrors *grLong   = fGainMult->GetGainPerChamberRobust(2);
1330   if (grShort==0x0 || grMedium==0x0 || grLong==0x0) {
1331     delete grShort;
1332     delete grMedium;
1333     delete grLong;
1334     return kFALSE;
1335   }
1336
1337   fGainArray->AddLast(grShort);
1338   fGainArray->AddLast(grMedium);
1339   fGainArray->AddLast(grLong);
1340
1341   return kTRUE;
1342 }
1343
1344 void AliTPCPreprocessorOffline::UpdateOCDBGain(Int_t startRunNumber, Int_t endRunNumber, AliCDBStorage *storage){
1345   //
1346   // Update OCDB entry
1347   //
1348   AliCDBMetaData *metaData= new AliCDBMetaData();
1349   metaData->SetObjectClassName("TObjArray");
1350   metaData->SetResponsible("Alexander Kalweit");
1351   metaData->SetBeamPeriod(1);
1352   metaData->SetAliRootVersion("05-24-00"); //root version
1353   metaData->SetComment("Calibration of the time dependence of the gain due to pressure and temperature changes.");
1354   AliCDBId id1("TPC/Calib/TimeGain", startRunNumber, endRunNumber);
1355   storage->Put(fGainArray, id1, metaData);    
1356 }
1357
1358 void AliTPCPreprocessorOffline::MakeQAPlot(Float_t  FPtoMIPratio) {
1359   //
1360   // Make QA plot to visualize results
1361   //
1362   //
1363   //
1364   if (fGraphCosmic) {
1365     TCanvas * canvasCosmic = new TCanvas("gain Cosmic", "time dependent gain QA histogram cosmic");
1366     canvasCosmic->cd();
1367     TH2D * gainHistoCosmic = fGainCosmic->GetHistGainTime()->Projection(0,1);
1368     gainHistoCosmic->SetDirectory(0);
1369     gainHistoCosmic->SetName("GainHistoCosmic");
1370     gainHistoCosmic->GetXaxis()->SetTimeDisplay(kTRUE);
1371     gainHistoCosmic->GetXaxis()->SetTimeFormat("#splitline{%d/%m}{%H:%M}");
1372     gainHistoCosmic->Draw("colz");
1373     fGraphCosmic->SetMarkerStyle(25);
1374     fGraphCosmic->Draw("lp");
1375     fGraphCosmic->SetMarkerStyle(25);
1376     TGraph * grfFitCosmic = fFitCosmic->MakeGraph(fGraphCosmic->GetX()[0],fGraphCosmic->GetX()[fGraphCosmic->GetN()-1],50000,0);
1377     if (grfFitCosmic) {
1378       for(Int_t i=0; i < grfFitCosmic->GetN(); i++) {
1379         grfFitCosmic->GetY()[i] *= FPtoMIPratio;        
1380       }
1381       for(Int_t i=0; i < fGraphCosmic->GetN(); i++) {
1382         fGraphCosmic->GetY()[i] *= FPtoMIPratio;        
1383       }
1384     }
1385     fGraphCosmic->Draw("lp"); 
1386     if (grfFitCosmic) {
1387       grfFitCosmic->SetLineColor(2);
1388       grfFitCosmic->Draw("lu");
1389     }
1390     fGainArray->AddLast(gainHistoCosmic);
1391     //fGainArray->AddLast(canvasCosmic->Clone());
1392     delete canvasCosmic;    
1393   }
1394   if (fFitMIP) {
1395     TCanvas * canvasMIP = new TCanvas("gain MIP", "time dependent gain QA histogram MIP");
1396     canvasMIP->cd();
1397     TH2D * gainHistoMIP    = fGainMIP->GetHistGainTime()->Projection(0,1);
1398     gainHistoMIP->SetName("GainHistoCosmic");
1399     gainHistoMIP->SetDirectory(0);
1400     gainHistoMIP->GetXaxis()->SetTimeDisplay(kTRUE);
1401     gainHistoMIP->GetXaxis()->SetTimeFormat("#splitline{%d/%m}{%H:%M}");
1402     gainHistoMIP->Draw("colz");
1403     fGraphMIP->SetMarkerStyle(25);
1404     fGraphMIP->Draw("lp");
1405     TGraph * grfFitMIP = fFitMIP->MakeGraph(fGraphMIP->GetX()[0],fGraphMIP->GetX()[fGraphMIP->GetN()-1],50000,0);
1406     grfFitMIP->SetLineColor(2);
1407     grfFitMIP->Draw("lu");    
1408     fGainArray->AddLast(gainHistoMIP);
1409     //fGainArray->AddLast(canvasMIP->Clone());
1410     delete canvasMIP;    
1411   }  
1412 }
1413
1414 void AliTPCPreprocessorOffline::MakeFitTime(){
1415   //
1416   // make aligment fit - store results in the file
1417   //
1418   const Int_t kMinEntries=1000;
1419   MakeChainTime();
1420   MakePrimitivesTime();
1421   if (!fAlignTree) return;
1422   if (fAlignTree->GetEntries()<kMinEntries) return;
1423   fAlignTree->SetAlias("ptype","type");
1424   fAlignTree->SetAlias("hasITS","(1+0)");
1425   fAlignTree->SetAlias("dITS","1-2*(refX<40)");
1426   fAlignTree->SetAlias("isITS","refX>10");
1427   fAlignTree->SetAlias("isVertex","refX<10");
1428   // 
1429   Int_t  npointsMax=30000000;
1430   TStatToolkit toolkit;
1431   Double_t chi2=0;
1432   Int_t    npoints=0;
1433   TVectorD param;
1434   TMatrixD covar;
1435
1436   TString fstringFast="";
1437   fstringFast+="FExBTwistX++";
1438   fstringFast+="FExBTwistY++";
1439   fstringFast+="FAlignRot0D++";
1440   fstringFast+="FAlignTrans0D++";
1441   fstringFast+="FAlignTrans1D++";
1442   //
1443   fstringFast+="hasITS*FAlignTrans0++";
1444   fstringFast+="hasITS*FAlignTrans1++";
1445   fstringFast+="hasITS*FAlignRot0++";
1446   fstringFast+="hasITS*FAlignRot1++";
1447   fstringFast+="hasITS*FAlignRot2++";
1448   //
1449   fstringFast+="dITS*FAlignTrans0++";
1450   fstringFast+="dITS*FAlignTrans1++";
1451   fstringFast+="dITS*FAlignRot0++";
1452   fstringFast+="dITS*FAlignRot1++";
1453   fstringFast+="dITS*FAlignRot2++";
1454   
1455   TCut cutFit="entries>10&&abs(mean)>0.00001&&rms>0";
1456   fAlignTree->SetAlias("err","rms");
1457
1458   TString *strDeltaITS = TStatToolkit::FitPlaneConstrain(fAlignTree,"mean:err", fstringFast.Data(),cutFit, chi2,npoints,param,covar,-1,0, npointsMax, 1);
1459   TObjArray* tokArr = strDeltaITS->Tokenize("++");
1460   tokArr->Print();
1461   delete tokArr;
1462   fAlignTree->SetAlias("fitYFast",strDeltaITS->Data());
1463   // 
1464   TVectorD paramC= param;
1465   TMatrixD covarC= covar;
1466   TStatToolkit::Constrain1D(fstringFast,"Trans0D",paramC,covarC,0, 0.1);
1467   TStatToolkit::Constrain1D(fstringFast,"Trans1D",paramC,covarC,0, 0.1);
1468   TStatToolkit::Constrain1D(fstringFast,"TwistX",paramC,covarC,0, 0.1);
1469   TStatToolkit::Constrain1D(fstringFast,"TwistY",paramC,covarC,0, 0.1);
1470   TString strFitConst=TStatToolkit::MakeFitString(fstringFast, paramC,covar);
1471   fAlignTree->SetAlias("fitYFastC",strFitConst.Data());
1472   CreateAlignTime(fstringFast,paramC);
1473
1474
1475 }
1476
1477
1478 void AliTPCPreprocessorOffline::MakeChainTime(){
1479   //
1480   //
1481   //
1482   TFile f("CalibObjects.root");
1483   
1484   //  const char *cdtype[7]={"ITS","TRD","Vertex","TOF","TPC","TPC0","TPC1"};
1485   //const char *cptype[5]={"dy","dz","dsnp","dtheta","d1pt"}; 
1486   const char * hname[5]={"dy","dz","dsnp","dtheta","d1pt"};
1487   Int_t run=0;
1488   AliTPCcalibTime  *calibTime = 0;
1489   TObject* obj = dynamic_cast<TObject*>(f.Get("TPCCalib"));
1490   TObjArray * array = dynamic_cast<TObjArray*>(obj);
1491   TDirectory * dir = dynamic_cast<TDirectory*>(obj);
1492   if (dir) {
1493     calibTime = dynamic_cast<AliTPCcalibTime*>(dir->Get("calibTime"));
1494   }
1495   else if (array){
1496     calibTime = (AliTPCcalibTime *)array->FindObject("calibTime");
1497   } else {
1498     calibTime = (AliTPCcalibTime*)f.Get("calibTime");
1499   }
1500   if (!calibTime) return;
1501   AliTPCCorrectionFit::CreateAlignMaps(AliTracker::GetBz(), run);
1502   TTreeSRedirector *pcstream = new TTreeSRedirector("meanITSVertex.root");
1503   //
1504   Int_t ihis=0;
1505   THnSparse *his = calibTime->GetResHistoTPCITS(ihis);
1506   if (his){
1507     his->GetAxis(1)->SetRangeUser(-1.1,1.1);
1508     his->GetAxis(2)->SetRange(0,1000000);
1509     his->GetAxis(3)->SetRangeUser(-0.35,0.35);
1510     AliTPCCorrection::MakeDistortionMap(his,pcstream, Form("ITS%s",hname[ihis]),run,85.,ihis,3);
1511   }
1512   ihis=1;
1513   his = calibTime->GetResHistoTPCITS(ihis);
1514   if (his){
1515     his->GetAxis(1)->SetRangeUser(-1.1,1.1);
1516     his->GetAxis(2)->SetRange(0,1000000);
1517     his->GetAxis(3)->SetRangeUser(-0.35,0.35);
1518     AliTPCCorrection::MakeDistortionMap(his,pcstream, Form("ITS%s",hname[ihis]),run,85.,ihis,3);
1519   }
1520   ihis=2;
1521   his = calibTime->GetResHistoTPCITS(ihis);
1522   if (his){
1523     his->GetAxis(1)->SetRangeUser(-1.1,1.1);
1524     his->GetAxis(2)->SetRange(0,1000000);
1525     his->GetAxis(3)->SetRangeUser(-0.35,0.35);
1526     AliTPCCorrection::MakeDistortionMap(his,pcstream, Form("ITS%s",hname[ihis]),run,85.,ihis,3);
1527   }
1528   ihis=0;
1529   his = calibTime->GetResHistoTPCvertex(ihis);
1530   if (his){
1531     his->GetAxis(1)->SetRangeUser(-1.1,1.1);
1532     his->GetAxis(2)->SetRange(0,1000000);
1533     his->GetAxis(3)->SetRangeUser(-0.35,0.35);
1534     AliTPCCorrection::MakeDistortionMap(his,pcstream, Form("Vertex%s",hname[ihis]),run,0.,ihis,3);
1535   }
1536   ihis=2;
1537   his = calibTime->GetResHistoTPCvertex(ihis);
1538   if (his){
1539     his->GetAxis(1)->SetRangeUser(-1.1,1.1);
1540     his->GetAxis(2)->SetRange(0,1000000);
1541     his->GetAxis(3)->SetRangeUser(-0.35,0.35);
1542     AliTPCCorrection::MakeDistortionMap(his,pcstream, Form("Vertex%s",hname[ihis]),run,0.,ihis,3);
1543
1544   }
1545   ihis=1;
1546   his = calibTime->GetResHistoTPCvertex(ihis);
1547   if (his){
1548     his->GetAxis(1)->SetRangeUser(-1.1,1.1);
1549     his->GetAxis(2)->SetRange(0,1000000);
1550     his->GetAxis(3)->SetRangeUser(-0.35,0.35);
1551     AliTPCCorrection::MakeDistortionMap(his,pcstream, Form("Vertex%s",hname[ihis]),run,0.,ihis,3);
1552
1553   }
1554   ihis=0;
1555   his = calibTime->GetResHistoTPCTOF(ihis);
1556   if (his){
1557     his->GetAxis(1)->SetRangeUser(-1.1,1.1);
1558     his->GetAxis(2)->SetRange(0,1000000);
1559     his->GetAxis(3)->SetRangeUser(-0.35,0.35);
1560     AliTPCCorrection::MakeDistortionMap(his,pcstream, Form("TOF%s",hname[ihis]),run,0.,ihis,3);
1561
1562   }
1563   ihis=0;
1564   his = calibTime->GetResHistoTPCTRD(ihis);
1565   if (his){
1566     his->GetAxis(1)->SetRangeUser(-1.1,1.1);
1567     his->GetAxis(2)->SetRange(0,1000000);
1568     his->GetAxis(3)->SetRangeUser(-0.35,0.35);
1569     AliTPCCorrection::MakeDistortionMap(his,pcstream, Form("TRD%s",hname[ihis]),run,0.,ihis,3);
1570
1571   }
1572   delete pcstream;
1573 }
1574
1575
1576 Double_t AliTPCPreprocessorOffline::EvalAt(Double_t phi, Double_t refX, Double_t theta, Int_t corr, Int_t ptype){
1577   //
1578   //
1579   //
1580   Double_t sector = 9*phi/TMath::Pi();
1581   if (sector<0) sector+=18;
1582   Double_t y85=AliTPCCorrection::GetCorrSector(sector,85,theta,1,corr);
1583   Double_t y245=AliTPCCorrection::GetCorrSector(sector,245,theta,1,corr);
1584   if (ptype==0) return y85+(y245-y85)*(refX-85.)/(245.-85.);
1585   if (ptype==2) return (y245-y85)/(245.-85.);
1586   return 0;
1587 }
1588
1589
1590 Double_t AliTPCPreprocessorOffline::EvalAtPar(Double_t phi0, Double_t snp, Double_t refX, Double_t theta, Int_t corr, Int_t ptype, Int_t nsteps){
1591   //
1592   // Fit the distortion along the line with the parabolic model
1593   // Parameters:
1594   //  phi0 - phi at the entrance of the TPC
1595   //  snp  - local inclination angle at the entrance of the TPC
1596   //  refX - ref X where the distortion is evanluated
1597   //  theta
1598   //  
1599   static TLinearFitter fitter(3,"pol2"); 
1600   fitter.ClearPoints();
1601   if (nsteps<3) nsteps=3;
1602   Double_t deltaX=(245-85)/(nsteps);
1603   for (Int_t istep=0; istep<(nsteps+1); istep++){
1604     //
1605     Double_t localX =85.+deltaX*istep;
1606     Double_t localPhi=phi0+deltaX*snp*istep;
1607     Double_t sector = 9*localPhi/TMath::Pi();
1608     if (sector<0) sector+=18;
1609     Double_t y=AliTPCCorrection::GetCorrSector(sector,localX,theta,1,corr);
1610     Double_t dlocalX=AliTPCCorrection::GetCorrSector(sector,localX,theta,0,corr);
1611     Double_t x[1]={localX-dlocalX};
1612     fitter.AddPoint(x,y);
1613   }
1614   fitter.Eval();
1615   Double_t par[3];
1616   par[0]=fitter.GetParameter(0);
1617   par[1]=fitter.GetParameter(1);
1618   par[2]=fitter.GetParameter(2);
1619
1620   if (ptype==0) return par[0]+par[1]*refX+par[2]*refX*refX;
1621   if (ptype==2) return par[1]+2*par[2]*refX;
1622   if (ptype==4) return par[2];
1623   return 0;
1624 }
1625
1626
1627
1628
1629
1630
1631 void AliTPCPreprocessorOffline::MakePrimitivesTime(){
1632   //
1633   // Create primitive transformation to fit
1634   //
1635   fAlignTree=new TChain("fit","fit");
1636   fAlignTree->AddFile("meanITSVertex.root",10000000,"ITSdy");
1637   fAlignTree->AddFile("meanITSVertex.root",10000000,"ITSdsnp");
1638   fAlignTree->AddFile("meanITSVertex.root",10000000,"Vertexdy");
1639   fAlignTree->AddFile("meanITSVertex.root",10000000,"Vertexdsnp");
1640   // 
1641   AliTPCParam *param= AliTPCcalibDB::Instance()->GetParameters();
1642   Double_t bzField=AliTrackerBase::GetBz(); 
1643   Double_t vdrift = param->GetDriftV()/1000000.; // [cm/us]   // From dataBase: to be updated: per second (ideally)
1644   Double_t ezField = 400; // [V/cm]   // to be updated: never (hopefully)
1645   Double_t wtP = -10.0 * (bzField) * vdrift /  ezField ; 
1646   AliTPCExBTwist *fitExBTwistX= new  AliTPCExBTwist;
1647   AliTPCExBTwist *fitExBTwistY= new  AliTPCExBTwist;
1648   AliTPCCalibGlobalMisalignment *trans0   =new  AliTPCCalibGlobalMisalignment;
1649   AliTPCCalibGlobalMisalignment *trans1   =new  AliTPCCalibGlobalMisalignment;
1650   AliTPCCalibGlobalMisalignment *trans0D  =new  AliTPCCalibGlobalMisalignment;
1651   AliTPCCalibGlobalMisalignment *trans1D  =new  AliTPCCalibGlobalMisalignment;
1652   AliTPCCalibGlobalMisalignment *rot0     =new  AliTPCCalibGlobalMisalignment;
1653   AliTPCCalibGlobalMisalignment *rot1     =new  AliTPCCalibGlobalMisalignment;
1654   AliTPCCalibGlobalMisalignment *rot2     =new  AliTPCCalibGlobalMisalignment;
1655   AliTPCCalibGlobalMisalignment *rot3     =new  AliTPCCalibGlobalMisalignment;
1656   //
1657   //
1658   fitExBTwistX->SetXTwist(0.001);
1659   fitExBTwistX->SetOmegaTauT1T2(wtP,1,1);  
1660   //
1661   fitExBTwistY->SetYTwist(0.001);
1662   fitExBTwistY->SetOmegaTauT1T2(wtP,1,1);  
1663   //
1664   TGeoHMatrix *matrixRot = new TGeoHMatrix; 
1665   TGeoHMatrix *matrixX = new TGeoHMatrix; 
1666   TGeoHMatrix *matrixY = new TGeoHMatrix; 
1667   matrixX->SetDx(0.1);
1668   matrixY->SetDy(0.1);
1669   Double_t rotAngles0[9]={0};
1670   Double_t rotAngles1[9]={0};
1671   Double_t rotAngles2[9]={0};
1672   //
1673   Double_t rotAngles3[9]={0};
1674
1675   rotAngles0[0]=1; rotAngles0[4]=1; rotAngles0[8]=1;
1676   rotAngles1[0]=1; rotAngles1[4]=1; rotAngles1[8]=1;
1677   rotAngles2[0]=1; rotAngles2[4]=1; rotAngles2[8]=1;
1678   rotAngles3[0]=1; rotAngles3[4]=1; rotAngles3[8]=1;
1679
1680   rotAngles0[1]=-0.001;rotAngles0[3]=0.001;
1681   rotAngles1[5]=-0.001;rotAngles1[7]=0.001;
1682   rotAngles2[2]=0.001;rotAngles2[6]=-0.001;
1683   rotAngles3[1]=0.001;rotAngles3[3]=-0.001;
1684   matrixRot->SetRotation(rotAngles0);
1685   rot0->SetAlignGlobal(matrixRot);
1686   matrixRot->SetRotation(rotAngles1);
1687   rot1->SetAlignGlobal(matrixRot);
1688   matrixRot->SetRotation(rotAngles2);
1689   rot2->SetAlignGlobal(matrixRot); 
1690   matrixRot->SetRotation(rotAngles3);
1691   rot3->SetAlignGlobalDelta(matrixRot); 
1692   //
1693   trans0->SetAlignGlobal(matrixX);
1694   trans1->SetAlignGlobal(matrixY);
1695   trans0D->SetAlignGlobalDelta(matrixX);
1696   trans1D->SetAlignGlobalDelta(matrixY);
1697   fitExBTwistX->Init();
1698   fitExBTwistY->Init();
1699   //
1700   fitExBTwistX->AddVisualCorrection((AliTPCExBTwist*)(fitExBTwistX->Clone()),100);
1701   fitExBTwistY->AddVisualCorrection((AliTPCExBTwist*)(fitExBTwistY->Clone()),101);
1702   //
1703   fitExBTwistX->AddVisualCorrection((AliTPCExBTwist*)(rot0->Clone()),102);
1704   fitExBTwistY->AddVisualCorrection((AliTPCExBTwist*)(rot1->Clone()),103);
1705   fitExBTwistX->AddVisualCorrection((AliTPCExBTwist*)(rot2->Clone()),104);
1706   fitExBTwistX->AddVisualCorrection((AliTPCExBTwist*)(rot3->Clone()),105);
1707
1708   fitExBTwistX->AddVisualCorrection((AliTPCExBTwist*)(trans0->Clone()),106);
1709   fitExBTwistX->AddVisualCorrection((AliTPCExBTwist*)(trans1->Clone()),107);
1710   fitExBTwistX->AddVisualCorrection((AliTPCExBTwist*)(trans0D->Clone()),108);
1711   fitExBTwistX->AddVisualCorrection((AliTPCExBTwist*)(trans1D->Clone()),109);
1712   //
1713   fAlignTree->SetAlias("FExBTwistX", "AliTPCPreprocessorOffline::EvalAt(phi,refX,theta,100,ptype)+0");
1714   fAlignTree->SetAlias("FExBTwistY","AliTPCPreprocessorOffline::EvalAt(phi,refX,theta,101,ptype)+0");
1715   fAlignTree->SetAlias("FAlignRot0","AliTPCPreprocessorOffline::EvalAt(phi,refX,theta,102,ptype)+0");
1716   fAlignTree->SetAlias("FAlignRot0D","AliTPCPreprocessorOffline::EvalAt(phi,refX,theta,105,ptype)+0");
1717   fAlignTree->SetAlias("FAlignRot1","AliTPCPreprocessorOffline::EvalAt(phi,refX,theta,103,ptype)+0");
1718   fAlignTree->SetAlias("FAlignRot2","AliTPCPreprocessorOffline::EvalAt(phi,refX,theta,104,ptype)+0");
1719   fAlignTree->SetAlias("FAlignTrans0","AliTPCPreprocessorOffline::EvalAt(phi,refX,theta,106,ptype)+0");
1720   fAlignTree->SetAlias("FAlignTrans1","AliTPCPreprocessorOffline::EvalAt(phi,refX,theta,107,ptype)+0");
1721   fAlignTree->SetAlias("FAlignTrans0D","AliTPCPreprocessorOffline::EvalAt(phi,refX,theta,108,ptype)+0");
1722   fAlignTree->SetAlias("FAlignTrans1D","AliTPCPreprocessorOffline::EvalAt(phi,refX,theta,109,ptype)+0");
1723   //
1724   // test fast function
1725   //
1726 //   fAlignTree->Draw("FExBTwistX:ExBTwistX","isITS&&ptype==0&&abs(snp)<0.05","");
1727 //   fAlignTree->Draw("FExBTwistY:ExBTwistY","isITS&&ptype==0&&abs(snp)<0.05","");
1728 //   fAlignTree->Draw("FAlignRot0:alignRot0","isITS&&ptype==0&&abs(snp)<0.05","");
1729 //   fAlignTree->Draw("FAlignRot1:alignRot1","isITS&&ptype==0&&abs(snp)<0.05","");
1730 //   fAlignTree->Draw("FAlignRot2:alignRot2","isITS&&ptype==0&&abs(snp)<0.05","");
1731 //   //
1732 //   fAlignTree->Draw("FAlignTrans0:alignTrans0","isITS&&ptype==0&&abs(snp)<0.05","");
1733 //   fAlignTree->Draw("FAlignTrans1:alignTrans1","isITS&&ptype==0&&abs(snp)<0.05","");
1734
1735
1736
1737
1738 void AliTPCPreprocessorOffline::CreateAlignTime(TString fstring, TVectorD paramC){
1739   //
1740   //
1741   //
1742   //
1743   TGeoHMatrix *matrixDelta     = new TGeoHMatrix; 
1744   TGeoHMatrix *matrixGlobal    = new TGeoHMatrix; 
1745   Double_t rAngles[9];
1746   Int_t index=0;
1747   //
1748   index=TStatToolkit::GetFitIndex(fstring,"FAlignTrans0D");
1749   if (index>=0) matrixDelta->SetDx(paramC[index+1]*0.1);
1750   index=TStatToolkit::GetFitIndex(fstring,"FAlignTrans1D");
1751   if (index>=0) matrixDelta->SetDy(paramC[index+1]*0.1);
1752   rAngles[0]=1; rAngles[4]=1; rAngles[8]=1;
1753   index=TStatToolkit::GetFitIndex(fstring,"FAlignRot0D");
1754   rAngles[1]=-paramC[index+1]*0.001; rAngles[3]=paramC[index+1]*0.001;
1755   rAngles[5]=0; rAngles[7] =0;
1756   rAngles[2]=0; rAngles[6] =0;
1757   matrixDelta->SetRotation(rAngles);
1758   //
1759   //
1760   //
1761   index=TStatToolkit::GetFitIndex(fstring,"hasITS*FAlignTrans0");
1762   if (index>=0) matrixGlobal->SetDx(paramC[index+1]*0.1);
1763   index=TStatToolkit::GetFitIndex(fstring,"hasITS*FAlignTrans1");
1764   if (index>=0) matrixGlobal->SetDy(paramC[index+1]*0.1);
1765   rAngles[0]=1; rAngles[4]=1; rAngles[8]=1;
1766   index=TStatToolkit::GetFitIndex(fstring,"hasITS*FAlignRot0");
1767   rAngles[1]=-paramC[index+1]*0.001; rAngles[3]=paramC[index+1]*0.001;
1768   index=TStatToolkit::GetFitIndex(fstring,"hasITS*FAlignRot1");  
1769   rAngles[5]=-paramC[index+1]*0.001; rAngles[7]=paramC[index+1]*0.001;
1770   index=TStatToolkit::GetFitIndex(fstring,"hasITS*FAlignRot2");  
1771   rAngles[2]=paramC[index+1]*0.001; rAngles[6] =-paramC[index+1]*0.001;
1772   matrixGlobal->SetRotation(rAngles);
1773   //
1774   AliTPCCalibGlobalMisalignment *fitAlignTime  =0;
1775   fitAlignTime  =new  AliTPCCalibGlobalMisalignment;
1776   fitAlignTime->SetName("FitAlignTime");
1777   fitAlignTime->SetTitle("FitAlignTime");
1778   fitAlignTime->SetAlignGlobalDelta(matrixDelta);
1779   fitAlignTime->SetAlignGlobal(matrixGlobal);
1780   //
1781   AliTPCExBTwist * fitExBTwist= new  AliTPCExBTwist;
1782   Int_t indexX=TStatToolkit::GetFitIndex(fstring,"ExBTwistX");
1783   Int_t indexY=TStatToolkit::GetFitIndex(fstring,"ExBTwistY");  
1784   fitExBTwist->SetXTwist(0.001*paramC[indexX+1]);  // 1 mrad twist in x
1785   fitExBTwist->SetYTwist(0.001*paramC[indexY+1]);  // 1 mrad twist in x
1786   fitExBTwist->SetName("FitExBTwistTime");
1787   fitExBTwist->SetTitle("FitExBTwistTime"); 
1788   AliTPCParam *param= AliTPCcalibDB::Instance()->GetParameters();
1789   Double_t bzField=AliTrackerBase::GetBz();
1790   Double_t vdrift = param->GetDriftV()/1000000.; // [cm/us]   // From dataBase: to be updated: per second (ideally)
1791
1792   Double_t ezField = 400; // [V/cm]   // to be updated: never (hopefully)
1793   Double_t wt = -10.0 * (bzField) * vdrift /  ezField ; 
1794   //
1795   fitExBTwist->SetOmegaTauT1T2(wt,1,1);  
1796   fitExBTwist->Init();  
1797
1798   AliTPCComposedCorrection *corrTime =  new AliTPCComposedCorrection;
1799   TObjArray *arr = new TObjArray;
1800   corrTime->SetCorrections(arr);
1801   
1802   corrTime->GetCorrections()->Add(fitExBTwist);
1803   corrTime->GetCorrections()->Add(fitAlignTime);
1804   corrTime->SetName("FitCorrectionTime");
1805   corrTime->SetTitle("FitCorrectionTime");
1806
1807   fitExBTwist->AddVisualCorrection((AliTPCExBTwist*)(fitExBTwist->Clone()),1001);
1808   fitAlignTime->AddVisualCorrection((AliTPCExBTwist*)(fitAlignTime->Clone()),1002);
1809   fitAlignTime->AddVisualCorrection((AliTPCExBTwist*)(corrTime->Clone()),1003);
1810   
1811   
1812   fAlignTree->SetAlias("ExBTwistTime","AliTPCPreprocessorOffline::EvalAt(phi,refX,theta,1001,ptype)+0");
1813   fAlignTree->SetAlias("AlignTime","AliTPCPreprocessorOffline::EvalAt(phi,refX,theta,1002,ptype)+0");
1814   fAlignTree->SetAlias("FitCorrectionTime","AliTPCPreprocessorOffline::EvalAt(phi,refX,theta,1003,ptype)+0");
1815
1816
1817   TFile *f = new TFile("fitITSVertex.root","update");
1818   corrTime->Write("FitCorrectionTime");
1819   f->Close();
1820 }
1821
1822 //_____________________________________________________________________________
1823 Int_t AliTPCPreprocessorOffline::GetStatus()
1824 {
1825   //get the calibration status
1826   // 0 means OK
1827   // positive numbers invalidate for unknown reasons.
1828   // negative numbers invalidate with a known reason (e.g. low statistics).
1829   // the returned integer has one bit set for every component that failed.
1830
1831   Bool_t enoughStatistics = (fNtracksVdrift>fMinTracksVdrift && fNeventsVdrift>fMinEventsVdrift);
1832   
1833   if (!enoughStatistics) 
1834   {
1835     fCalibrationStatus=-TMath::Abs(fCalibrationStatus);
1836   }
1837
1838   return fCalibrationStatus;
1839 }
1840
1841 /*
1842   Short sequence to acces the calbration entry:
1843   TFile *f = TFile::Open("CalibObjects.root");
1844   AliTPCcalibGainMult      * fGainMult = (AliTPCcalibGainMult      *)f->Get("TPCCalib/calibGainMult");
1845   
1846  
1847 */