]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - TPC/AliTPCPreprocessorOffline.cxx
Add three particle correlation loop for correction of auto-correlaton bias
[u/mrichter/AliRoot.git] / TPC / AliTPCPreprocessorOffline.cxx
index ec859cdfa073632fc6bd5903a44a54ea458fe595..54a595c20f02e679ab7a8d4844ee62c3e32de64a 100644 (file)
   // default storage ""- data stored at current working directory 
  
   e.g.
-  AliTPCPreprocessorOffline process;
-  process.CalibTimeGain("CalibObjects.root",114000,121040,0);
+  gSystem->Load("libANALYSIS");
+  gSystem->Load("libTPCcalib");
+  AliTPCPreprocessorOffline proces;
+  proces.CalibTimeGain("TPCMultObjects.root",114000,140040,0);
   TFile oo("OCDB/TPC/Calib/TimeGain/Run114000_121040_v0_s0.root")
   TObjArray * arr = AliCDBEntry->GetObject()
   arr->At(4)->Draw("alp")
 #include "AliRelAlignerKalman.h"
 #include "AliTPCParamSR.h"
 #include "AliTPCcalibTimeGain.h"
+#include "AliTPCcalibGainMult.h"
+#include "AliTPCcalibAlign.h"
 #include "AliSplineFit.h"
+#include "AliTPCComposedCorrection.h"
+#include "AliTPCExBTwist.h"
+#include "AliTPCCalibGlobalMisalignment.h"
+#include "TStatToolkit.h"
+#include "TChain.h"
+#include "TCut.h"
+#include "AliTrackerBase.h"
+#include "AliTracker.h"
 #include "AliTPCPreprocessorOffline.h"
+#include "AliTPCCorrectionFit.h"
 
-
+using std::endl;
+using std::cout;
 ClassImp(AliTPCPreprocessorOffline)
 
 AliTPCPreprocessorOffline::AliTPCPreprocessorOffline():
   TNamed("TPCPreprocessorOffline","TPCPreprocessorOffline"),
   fMinEntries(500),                      // minimal number of entries for fit
-  startRun(0),                         // start Run - used to make fast selection in THnSparse
-  endRun(0),                           // end   Run - used to make fast selection in THnSparse
-  startTime(0),                        // startTime - used to make fast selection in THnSparse
-  endTime(0),                          // endTime   - used to make fast selection in THnSparse
-  ocdbStorage(""),                   // path to the OCDB storage
+  fStartRun(0),                         // start Run - used to make fast selection in THnSparse
+  fEndRun(0),                           // end   Run - used to make fast selection in THnSparse
+  fStartTime(0),                        // fStartTime - used to make fast selection in THnSparse
+  fEndTime(0),                          // fEndTime   - used to make fast selection in THnSparse
+  fOCDBstorage(0),                       // OCDB storage
   fVdriftArray(new TObjArray),
   fTimeDrift(0),
   fGraphMIP(0),                // graph time dependence of MIP
@@ -96,7 +110,17 @@ AliTPCPreprocessorOffline::AliTPCPreprocessorOffline():
   fGainArray(new TObjArray),               // array to be stored in the OCDB
   fGainMIP(0),          // calibration component for MIP
   fGainCosmic(0),       // calibration component for cosmic
-  fSwitchOnValidation(kFALSE) // flag to switch on validation of OCDB parameters
+  fGainMult(0),
+  fAlignTree(0),        // alignment tree
+  fSwitchOnValidation(kFALSE), // flag to switch on validation of OCDB parameters
+  fMinGain(2.0),
+  fMaxGain(3.0),
+  fMaxVdriftCorr(0.03),
+  fNtracksVdrift(0),
+  fMinTracksVdrift(0),
+  fNeventsVdrift(0),
+  fMinEventsVdrift(0),
+  fCalibrationStatus(0)
 {
   //
   // default constructor
@@ -119,39 +143,39 @@ void AliTPCPreprocessorOffline::GetRunRange(AliTPCcalibTime * const  timeDrift){
   TObjArray *hisArray =timeDrift->GetHistoDrift();
   {for (Int_t i=0; i<hisArray->GetEntriesFast(); i++){
     THnSparse* addHist=(THnSparse*)hisArray->UncheckedAt(i);
-    if (addHist->GetEntries()<fMinEntries) continue;
     if (!addHist) continue;
+    if (addHist->GetEntries()<fMinEntries) continue;
     TH1D* histo    =addHist->Projection(3);
     TH1D* histoTime=addHist->Projection(0);
     printf("%s\t%f\t%d\t%d\n",histo->GetName(), histo->GetEntries(),histo->FindFirstBinAbove(0),histo->FindLastBinAbove(0));
 
-    if (startRun<=0){ 
-      startRun=histo->FindFirstBinAbove(0);
-      endRun  =histo->FindLastBinAbove(0);
+    if (fStartRun<=0){ 
+      fStartRun=histo->FindFirstBinAbove(0);
+      fEndRun  =histo->FindLastBinAbove(0);
     }else{
-      startRun=TMath::Min(histo->FindFirstBinAbove(0),startRun);
-      endRun  =TMath::Max(histo->FindLastBinAbove(0),endRun);
+      fStartRun=TMath::Min(histo->FindFirstBinAbove(0),fStartRun);
+      fEndRun  =TMath::Max(histo->FindLastBinAbove(0),fEndRun);
     }
-    if (startTime==0){ 
-      startTime=histoTime->FindFirstBinAbove(0);
-      endTime  =histoTime->FindLastBinAbove(0);
+    if (fStartTime==0){ 
+      fStartTime=histoTime->FindFirstBinAbove(0);
+      fEndTime  =histoTime->FindLastBinAbove(0);
     }else{
-      startTime=TMath::Min(histoTime->FindFirstBinAbove(0),startTime);
-      endTime  =TMath::Max(histoTime->FindLastBinAbove(0),endTime);
+      fStartTime=TMath::Min(histoTime->FindFirstBinAbove(0),fStartTime);
+      fEndTime  =TMath::Max(histoTime->FindLastBinAbove(0),fEndTime);
     }
     delete histo;
     delete histoTime;
   }}
-  if (startRun<0) startRun=0;
-  if (endRun<0) endRun=100000000;
-  printf("Run range  :\t%d-%d\n", startRun, endRun);
-  printf("Time range :\t%d-%d\n", startTime, endTime);
+  if (fStartRun<0) fStartRun=0;
+  if (fEndRun<0) fEndRun=100000000;
+  printf("Run range  :\t%d-%d\n", fStartRun, fEndRun);
+  printf("Time range :\t%d-%d\n", fStartTime, fEndTime);
 
 }
 
 
 
-void AliTPCPreprocessorOffline::CalibTimeVdrift(const Char_t* file, Int_t ustartRun, Int_t uendRun, TString pocdbStorage){
+void AliTPCPreprocessorOffline::CalibTimeVdrift(const Char_t* file, Int_t ustartRun, Int_t uendRun, AliCDBStorage* pocdbStorage){
   //
   // make calibration of the drift velocity
   // Input parameters:
@@ -159,9 +183,12 @@ void AliTPCPreprocessorOffline::CalibTimeVdrift(const Char_t* file, Int_t ustart
   //      ustartRun, uendrun     - run validity period 
   //      pocdbStorage           - path to hte OCDB storage
   //                             - if empty - local storage 'pwd' uesed
-  if (pocdbStorage.Length()>0) ocdbStorage=pocdbStorage;
-  else
-  ocdbStorage="local://"+gSystem->GetFromPipe("pwd")+"/OCDB";
+  if (pocdbStorage) fOCDBstorage=pocdbStorage;
+  else {
+    TString localStorage = "local://"+gSystem->GetFromPipe("pwd")+"/OCDB"; 
+    fOCDBstorage=AliCDBManager::Instance()->GetStorage(localStorage.Data());
+  }
+
   //
   // 1. Initialization and run range setting
   TFile fcalib(file);
@@ -173,15 +200,21 @@ void AliTPCPreprocessorOffline::CalibTimeVdrift(const Char_t* file, Int_t ustart
   }
   if(!fTimeDrift) return;
 
-  startRun=ustartRun;
-  endRun=ustartRun; 
+  //extract statistics
+  fNtracksVdrift = TMath::Nint(fTimeDrift->GetResHistoTPCITS(0)->GetEntries());
+  //if we have 0 ITS TPC matches it means we have no ITS tracks and we try to use TPC-TOF matching for calibration
+  if (fNtracksVdrift==0) fNtracksVdrift=TMath::Nint(fTimeDrift->GetResHistoTPCTOF(0)->GetEntries());
+  fNeventsVdrift = TMath::Nint(fTimeDrift->GetTPCVertexHisto(0)->GetEntries());
+
+  fStartRun=ustartRun;
+  fEndRun=ustartRun; 
   TObjArray *hisArray =fTimeDrift->GetHistoDrift();  
   GetRunRange(fTimeDrift);
   for (Int_t i=0; i<hisArray->GetEntriesFast(); i++){
     THnSparse* addHist=(THnSparse*)hisArray->At(i);
     if (!addHist) continue;
-    if (startTime<endTime) addHist->GetAxis(0)->SetRange(startTime-1,endTime+1);
-    if (startRun<endRun) addHist->GetAxis(3)->SetRange(startRun-1,endRun+1);
+    if (fStartTime<fEndTime) addHist->GetAxis(0)->SetRange(fStartTime-1,fEndTime+1);
+    if (fStartRun<fEndRun) addHist->GetAxis(3)->SetRange(fStartRun-1,fEndRun+1);
   }
   //
   //
@@ -191,6 +224,7 @@ void AliTPCPreprocessorOffline::CalibTimeVdrift(const Char_t* file, Int_t ustart
   AddAlignmentGraphs(fVdriftArray,fTimeDrift);
   AddHistoGraphs(fVdriftArray,fTimeDrift,fMinEntries);
   AddLaserGraphs(fVdriftArray,fTimeDrift);
+  
   //
   // 3. Append QA plots
   //
@@ -203,16 +237,24 @@ void AliTPCPreprocessorOffline::CalibTimeVdrift(const Char_t* file, Int_t ustart
     Printf("TPC time drift OCDB parameters out of range!");
     return;
   }
-
+  //
+  //4.b make alignment
+  //
+  MakeFitTime();
+  TFile * ftime= TFile::Open("fitITSVertex.root");
+  if (ftime){
+    TObject * alignmentTime=ftime->Get("FitCorrectionTime");
+    if (alignmentTime) fVdriftArray->AddLast(alignmentTime);
+  }
   //
   //
   // 5. update of OCDB
   //
   //
-  UpdateOCDBDrift(ustartRun,uendRun,ocdbStorage);
+  UpdateOCDBDrift(ustartRun,uendRun,fOCDBstorage);
 }
 
-void AliTPCPreprocessorOffline::UpdateOCDBDrift( Int_t ustartRun, Int_t uendRun,  const char* storagePath ){
+void AliTPCPreprocessorOffline::UpdateOCDBDrift( Int_t ustartRun, Int_t uendRun,  AliCDBStorage* storage ){
   //
   // Update OCDB 
   //
@@ -224,48 +266,96 @@ void AliTPCPreprocessorOffline::UpdateOCDBDrift( Int_t ustartRun, Int_t uendRun,
   metaData->SetComment("Calibration of the time dependence of the drift velocity");
   AliCDBId* id1=NULL;
   id1=new AliCDBId("TPC/Calib/TimeDrift", ustartRun, uendRun);
-  AliCDBStorage* gStorage = AliCDBManager::Instance()->GetStorage(storagePath);
-  gStorage->Put(fVdriftArray, (*id1), metaData);
+  storage->Put(fVdriftArray, (*id1), metaData);
 }
 
-Bool_t AliTPCPreprocessorOffline::ValidateTimeGain(Double_t minGain, Double_t maxGain)
+Bool_t AliTPCPreprocessorOffline::ValidateTimeGain()
 {
   //
   // Validate time gain corrections 
   //
   Printf("ValidateTimeGain..." );
+  Float_t minGain = fMinGain;
+  Float_t maxGain = fMaxGain;
 
   TGraphErrors *gr = (TGraphErrors*)fGainArray->FindObject("TGRAPHERRORS_MEAN_GAIN_BEAM_ALL");
-  if(!gr) return kFALSE;
-  if(gr->GetN()<1) return kFALSE;
+  if (!gr) {
+    gr = (TGraphErrors*)fGainArray->FindObject("TGRAPHERRORS_MEAN_GAIN_COSMIC_ALL");
+    if (!gr) 
+    { 
+      fCalibrationStatus |= kCalibFailedTimeGain;
+      return kFALSE;
+    }
+    Printf("Assuming given run is a cosmic run. Using gain calibration from Fermi-plateau muons.");
+  }
+  if(gr->GetN()<1) 
+  { 
+    fCalibrationStatus |= kCalibFailedTimeGain;
+    return kFALSE;
+  }
 
   // check whether gain in the range
   for(Int_t iPoint=0; iPoint<gr->GetN(); iPoint++) 
   {
     if(gr->GetY()[iPoint] < minGain || gr->GetY()[iPoint] > maxGain)  
+    { 
+      fCalibrationStatus |= kCalibFailedTimeGain;
       return kFALSE;
+    }
   }
 
 return kTRUE;
 }
 
 
-Bool_t AliTPCPreprocessorOffline::ValidateTimeDrift(Double_t maxVDriftCorr)
+Bool_t AliTPCPreprocessorOffline::ValidateTimeDrift()
 {
   //
   // Validate time drift velocity corrections 
   //
   Printf("ValidateTimeDrift..." );
 
+  Float_t maxVDriftCorr = fMaxVdriftCorr;
+
   TGraphErrors* gr = (TGraphErrors*)fVdriftArray->FindObject("ALIGN_ITSB_TPC_DRIFTVD");
-  if(!gr) return kFALSE;
-  if(gr->GetN()<1) return kFALSE;
+  Printf("ALIGN_ITSB_TPC_DRIFTVD graph = %p",gr);
+  if (!gr)
+  {
+    gr = (TGraphErrors*)fVdriftArray->FindObject("ALIGN_TOFB_TPC_DRIFTVD");
+    Printf("ALIGN_TOFB_TPC_DRIFTVD graph = %p",gr);
+  }
+
+  if(!gr) 
+  {
+    fCalibrationStatus|=kCalibFailedTimeDrift;
+    return kFALSE;
+  }
+  
+  // for now we validate even with low statistics
+  ////check if we have enough statistics
+  //if (fNtracksVdrift<fMinTracksVdrift) 
+  //{
+  //  fCalibrationStatus|=kCalibFailedTimeDrift;
+  //  return kFALSE;
+  //}
+
+  if(gr->GetN()<1)  { 
+    Printf("ALIGN_ITSB_TPC_DRIFTVD number of points = %d",gr->GetN());
+    {
+      fCalibrationStatus|=kCalibFailedTimeDrift;
+      return kFALSE;
+    }
+  }
 
   // check whether drift velocity corrections in the range
   for(Int_t iPoint = 0; iPoint<gr->GetN(); iPoint++) 
   {
+    //Printf("Y value from the graph: %f",TMath::Abs(gr->GetY()[iPoint]));
     if(TMath::Abs(gr->GetY()[iPoint]) > maxVDriftCorr)  
+    {
+      fCalibrationStatus|=kCalibFailedTimeDrift;
       return kFALSE;
+    }
   }
 
 return kTRUE;
@@ -292,8 +382,7 @@ void AliTPCPreprocessorOffline::UpdateDriftParam(AliTPCParam *param, TObjArray *
   metaData->SetComment("Updated calibration of nominal time 0");
   AliCDBId* id1=NULL;
   id1=new AliCDBId("TPC/Calib/Parameters", lstartRun, AliCDBRunRange::Infinity());
-  AliCDBStorage* gStorage = AliCDBManager::Instance()->GetStorage(ocdbStorage);
-  gStorage->Put(param, (*id1), metaData);
+  fOCDBstorage->Put(param, (*id1), metaData);
 
 }
 
@@ -359,7 +448,13 @@ TGraphErrors* AliTPCPreprocessorOffline::FilterGraphMedianAbs(TGraphErrors * gra
   Double_t *erry=new Double_t[npoints0];
   //
   //
-  if (npoints0<kMinPoints) return 0;
+  if (npoints0<kMinPoints) {
+    delete []outx;
+    delete []outy;
+    delete []errx;
+    delete []erry;
+    return 0;
+  }
   for (Int_t iter=0; iter<3; iter++){
     npoints=0;
     for (Int_t ipoint=0; ipoint<npoints0; ipoint++){
@@ -377,6 +472,10 @@ TGraphErrors* AliTPCPreprocessorOffline::FilterGraphMedianAbs(TGraphErrors * gra
   }
   TGraphErrors *graphOut=0;
   if (npoints>1) graphOut= new TGraphErrors(npoints,outx,outy,errx,erry); 
+  delete []outx;
+  delete []outy;
+  delete []errx;
+  delete []erry;
   return graphOut;
 }
 
@@ -402,6 +501,10 @@ void AliTPCPreprocessorOffline::AddHistoGraphs(  TObjArray * vdriftArray, AliTPC
       THnSparse* newHist=hist->Projection(4,dim);
       newHist->SetName(name);
       TGraphErrors* graph=AliTPCcalibBase::FitSlices(newHist,2,0,400,100,0.05,0.95, kTRUE);
+      if (!graph) {
+       printf("Graph =%s filtered out\n", name.Data());
+       continue;
+      }
       printf("name=%s graph=%i, N=%i\n", name.Data(), graph==0, graph->GetN());
       Int_t pos=name.Index("_");
       name=name(pos,name.Capacity()-pos);
@@ -410,19 +513,17 @@ void AliTPCPreprocessorOffline::AddHistoGraphs(  TObjArray * vdriftArray, AliTPC
       graphName.ToUpper();
       //
       graph = FilterGraphDrift(graph, kErrSigmaCut, kMedianCutAbs);
-      if (!graph) {
-       printf("Graph =%s filtered out\n", name.Data());
-       continue;
-      }
       //
-      graph->SetMarkerStyle(i%8+20);
-      graph->SetMarkerColor(i%7);
-      graph->GetXaxis()->SetTitle("Time");
-      graph->GetYaxis()->SetTitle("v_{dcor}");
-      graph->SetName(graphName);
-      graph->SetTitle(graphName);
-      printf("Graph %d\t=\t%s\n", i, graphName.Data());
-      vdriftArray->Add(graph);
+      if (graph){
+        graph->SetMarkerStyle(i%8+20);
+        graph->SetMarkerColor(i%7);
+        graph->GetXaxis()->SetTitle("Time");
+        graph->GetYaxis()->SetTitle("v_{dcor}");
+        graph->SetName(graphName);
+        graph->SetTitle(graphName);
+        printf("Graph %d\t=\t%s\n", i, graphName.Data());
+        vdriftArray->Add(graph);
+      }
     }
   }
 }
@@ -445,9 +546,9 @@ void AliTPCPreprocessorOffline::AddAlignmentGraphs(  TObjArray * vdriftArray, Al
   arrayTRD=timeDrift->GetAlignTRDTPC();
   arrayTOF=timeDrift->GetAlignTOFTPC();
 
-  if (arrayITS->GetEntries()>0) mstatITS= AliTPCcalibDButil::MakeStatRelKalman(arrayITS,0.9,50,0.025);
-  if (arrayTOF->GetEntries()>0) mstatTOF= AliTPCcalibDButil::MakeStatRelKalman(arrayTOF,0.9,1000,0.025);
-  if (arrayTRD->GetEntries()>0) mstatTRD= AliTPCcalibDButil::MakeStatRelKalman(arrayTRD,0.9,50,0.025);
+  if (arrayITS->GetEntries()>0) mstatITS= AliTPCcalibDButil::MakeStatRelKalman(arrayITS,0.7,50,fMaxVdriftCorr);
+  if (arrayTOF->GetEntries()>0) mstatTOF= AliTPCcalibDButil::MakeStatRelKalman(arrayTOF,0.7,1000,fMaxVdriftCorr);
+  if (arrayTRD->GetEntries()>0) mstatTRD= AliTPCcalibDButil::MakeStatRelKalman(arrayTRD,0.7,50,fMaxVdriftCorr);
   //
   TObjArray * arrayITSP= AliTPCcalibDButil::SmoothRelKalman(arrayITS,*mstatITS, 0, 5.);
   TObjArray * arrayITSM= AliTPCcalibDButil::SmoothRelKalman(arrayITS,*mstatITS, 1, 5.);
@@ -518,9 +619,9 @@ void AliTPCPreprocessorOffline::AddLaserGraphs(  TObjArray * vdriftArray, AliTPC
   // add graphs for laser
   //
   const Double_t delayL0L1 = 0.071;  //this is hack for 1/2 weeks
-  THnSparse *hisN=0;
+  //THnSparse *hisN=0;
   TGraphErrors *grLaser[6]={0,0,0,0,0,0};
-  hisN = timeDrift->GetHistVdriftLaserA(0);
+  //hisN = timeDrift->GetHistVdriftLaserA(0);
   if (timeDrift->GetHistVdriftLaserA(0)){
     grLaser[0]=MakeGraphFilter0(timeDrift->GetHistVdriftLaserA(0),0,2,5,delayL0L1);
     grLaser[0]->SetName("GRAPH_MEAN_DELAY_LASER_ALL_A");
@@ -703,7 +804,7 @@ void AliTPCPreprocessorOffline::MakeDefaultPlots(TObjArray * const arr, TObjArra
     //picArray->AddLast(pad);
   }
 
-  if (itstpcP&&itstpcM){
+  if (itstpcP&&itstpcM&&itstpcB){
     pad = new TCanvas("ITSTPC","ITSTPC");
     itstpcP->Draw("alp");
     SetPadStyle(pad,mx0,mx1,my0,my1);    
@@ -720,7 +821,7 @@ void AliTPCPreprocessorOffline::MakeDefaultPlots(TObjArray * const arr, TObjArra
     //picArray->AddLast(pad);
   }
 
-  if (itstpcB&&laserA){
+  if (itstpcB&&laserA&&itstpcP&&itstpcM){
     pad = new TCanvas("ITSTPC_LASER","ITSTPC_LASER");
     SetPadStyle(pad,mx0,mx1,my0,my1);    
     laserA->Draw("alp");
@@ -771,11 +872,14 @@ void AliTPCPreprocessorOffline::MakeDefaultPlots(TObjArray * const arr, TObjArra
 
 
 
-void AliTPCPreprocessorOffline::CalibTimeGain(const Char_t* fileName, Int_t startRunNumber, Int_t endRunNumber,  TString  pocdbStorage){
+void AliTPCPreprocessorOffline::CalibTimeGain(const Char_t* fileName, Int_t startRunNumber, Int_t endRunNumber,  AliCDBStorage* pocdbStorage){
   //
   // Update OCDB gain
   //
-  if (pocdbStorage.Length()==0) pocdbStorage+="local://"+gSystem->GetFromPipe("pwd")+"/OCDB";
+  if (pocdbStorage==0) {
+    TString localStorage = "local://"+gSystem->GetFromPipe("pwd")+"/OCDB";
+    pocdbStorage = AliCDBManager::Instance()->GetStorage(localStorage.Data());
+  }
 
   //
   // 1. Read gain values
@@ -787,7 +891,9 @@ void AliTPCPreprocessorOffline::CalibTimeGain(const Char_t* fileName, Int_t star
   //
   AnalyzeGain(startRunNumber,endRunNumber, 1000,1.43);
   AnalyzeAttachment(startRunNumber,endRunNumber);
-
+  AnalyzePadRegionGain();
+  AnalyzeGainMultiplicity();
+  AnalyzeGainChamberByChamber();
   //
   // 3. Make control plots
   //
@@ -804,7 +910,7 @@ void AliTPCPreprocessorOffline::CalibTimeGain(const Char_t* fileName, Int_t star
   //
   // 5. Update OCDB
   //
-  UpdateOCDBGain( startRunNumber, endRunNumber, pocdbStorage.Data());
+  UpdateOCDBGain( startRunNumber, endRunNumber, pocdbStorage);
 }
 
 void AliTPCPreprocessorOffline::ReadGainGlobal(const Char_t* fileName){
@@ -816,9 +922,15 @@ void AliTPCPreprocessorOffline::ReadGainGlobal(const Char_t* fileName){
   if (array){
     fGainMIP    = ( AliTPCcalibTimeGain *)array->FindObject("calibTimeGain");
     fGainCosmic = ( AliTPCcalibTimeGain *)array->FindObject("calibTimeGainCosmic");
+    fGainMult   = ( AliTPCcalibGainMult *)array->FindObject("calibGainMult");
   }else{
     fGainMIP    = ( AliTPCcalibTimeGain *)fcalib.Get("calibTimeGain");
     fGainCosmic = ( AliTPCcalibTimeGain *)fcalib.Get("calibTimeGainCosmic");
+    fGainMult   = ( AliTPCcalibGainMult *)fcalib.Get("calibGainMult");
+  }
+  if (!fGainMult){
+    TFile calibMultFile("TPCMultObjects.root");
+    fGainMult   = ( AliTPCcalibGainMult *)calibMultFile.Get("calibGainMult");
   }
   TH1 * hisT=0;
   Int_t firstBinA =0, lastBinA=0;
@@ -841,8 +953,6 @@ void AliTPCPreprocessorOffline::ReadGainGlobal(const Char_t* fileName){
 
 }
 
-
-
 Bool_t AliTPCPreprocessorOffline::AnalyzeGain(Int_t startRunNumber, Int_t endRunNumber, Int_t minEntriesGaussFit,  Float_t FPtoMIPratio){
   //
   // Analyze gain - produce the calibration graphs
@@ -968,7 +1078,148 @@ Bool_t AliTPCPreprocessorOffline::AnalyzeAttachment(Int_t startRunNumber, Int_t
 }
 
 
-void AliTPCPreprocessorOffline::UpdateOCDBGain(Int_t startRunNumber, Int_t endRunNumber, const Char_t *storagePath){
+Bool_t AliTPCPreprocessorOffline::AnalyzePadRegionGain(){
+  //
+  // Analyze gain for different pad regions - produce the calibration graphs 0,1,2
+  //
+  if (fGainMult) 
+  {
+    TH2D * histQmax = (TH2D*) fGainMult->GetHistPadEqual()->Projection(0,2);
+    TH2D * histQtot = (TH2D*) fGainMult->GetHistPadEqual()->Projection(1,2);
+    //
+    TObjArray arr;
+    histQmax->FitSlicesY(0,0,-1,0,"QNR",&arr);
+    Double_t xMax[3] = {0,1,2};
+    Double_t yMax[3]    = {((TH1D*)arr.At(1))->GetBinContent(1),
+                          ((TH1D*)arr.At(1))->GetBinContent(2),
+                          ((TH1D*)arr.At(1))->GetBinContent(3)};
+    Double_t yMaxErr[3] = {((TH1D*)arr.At(1))->GetBinError(1),
+                          ((TH1D*)arr.At(1))->GetBinError(2),
+                          ((TH1D*)arr.At(1))->GetBinError(3)};
+    TGraphErrors * fitPadRegionQmax = new TGraphErrors(3, xMax, yMax, 0, yMaxErr);
+    //
+    histQtot->FitSlicesY(0,0,-1,0,"QNR",&arr);
+    Double_t xTot[3] = {0,1,2};
+    Double_t yTot[3]    = {((TH1D*)arr.At(1))->GetBinContent(1),
+                          ((TH1D*)arr.At(1))->GetBinContent(2),
+                          ((TH1D*)arr.At(1))->GetBinContent(3)};
+    Double_t yTotErr[3] = {((TH1D*)arr.At(1))->GetBinError(1),
+                          ((TH1D*)arr.At(1))->GetBinError(2),
+                          ((TH1D*)arr.At(1))->GetBinError(3)};
+    TGraphErrors * fitPadRegionQtot = new TGraphErrors(3, xTot, yTot, 0, yTotErr);
+    //
+    fitPadRegionQtot->SetName("TGRAPHERRORS_MEANQTOT_PADREGIONGAIN_BEAM_ALL");// set proper names according to naming convention
+    fitPadRegionQmax->SetName("TGRAPHERRORS_MEANQMAX_PADREGIONGAIN_BEAM_ALL");// set proper names according to naming convention
+    //
+    fGainArray->AddLast(fitPadRegionQtot);
+    fGainArray->AddLast(fitPadRegionQmax);
+    return kTRUE;
+  } 
+  return kFALSE;
+
+}
+
+
+Bool_t AliTPCPreprocessorOffline::AnalyzeGainMultiplicity() {
+  //
+  // Analyze gain as a function of multiplicity and produce calibration graphs
+  //
+  if (!fGainMult) return kFALSE;
+  fGainMult->GetHistGainMult()->GetAxis(3)->SetRangeUser(3,3);
+  TH2D * histMultMax = fGainMult->GetHistGainMult()->Projection(0,4);
+  TH2D * histMultTot = fGainMult->GetHistGainMult()->Projection(1,4);
+  histMultMax->RebinX(4);
+  histMultTot->RebinX(4);
+  //
+  TObjArray arrMax;
+  TObjArray arrTot;
+  histMultMax->FitSlicesY(0,0,-1,0,"QNR",&arrMax);
+  histMultTot->FitSlicesY(0,0,-1,0,"QNR",&arrTot);
+  //
+  TH1D * meanMax = (TH1D*)arrMax.At(1);
+  TH1D * meanTot = (TH1D*)arrTot.At(1);
+  Float_t meanMult = histMultMax->GetMean();
+  if(meanMax->GetBinContent(meanMax->FindBin(meanMult))) {
+    meanMax->Scale(1./meanMax->GetBinContent(meanMax->FindBin(meanMult)));
+  }
+  else {
+   return kFALSE;
+  }
+  if(meanTot->GetBinContent(meanTot->FindBin(meanMult))) {
+    meanTot->Scale(1./meanTot->GetBinContent(meanTot->FindBin(meanMult)));
+  }
+  else {
+   return kFALSE;
+  }
+  Float_t xMultMax[50];
+  Float_t yMultMax[50];
+  Float_t yMultErrMax[50];
+  Float_t xMultTot[50];
+  Float_t yMultTot[50];
+  Float_t yMultErrTot[50];
+  //
+  Int_t nCountMax = 0;
+  for(Int_t iBin = 1; iBin < meanMax->GetXaxis()->GetNbins(); iBin++) {
+    Float_t yValMax = meanMax->GetBinContent(iBin);
+    if (yValMax < 0.7) continue;
+    if (yValMax > 1.3) continue;
+    if (meanMax->GetBinError(iBin)/yValMax > 0.01) continue;
+    xMultMax[nCountMax] = meanMax->GetXaxis()->GetBinCenter(iBin);
+    yMultMax[nCountMax] = yValMax;
+    yMultErrMax[nCountMax] = meanMax->GetBinError(iBin);
+    nCountMax++;
+  }
+  //
+  if (nCountMax < 10) return kFALSE;
+  TGraphErrors * fitMultMax = new TGraphErrors(nCountMax, xMultMax, yMultMax, 0, yMultErrMax);
+  fitMultMax->SetName("TGRAPHERRORS_MEANQMAX_MULTIPLICITYDEPENDENCE_BEAM_ALL");
+  //
+  Int_t nCountTot = 0;
+  for(Int_t iBin = 1; iBin < meanTot->GetXaxis()->GetNbins(); iBin++) {
+    Float_t yValTot = meanTot->GetBinContent(iBin);
+    if (yValTot < 0.7) continue;
+    if (yValTot > 1.3) continue;
+    if (meanTot->GetBinError(iBin)/yValTot > 0.1) continue;
+    xMultTot[nCountTot] = meanTot->GetXaxis()->GetBinCenter(iBin);
+    yMultTot[nCountTot] = yValTot;
+    yMultErrTot[nCountTot] = meanTot->GetBinError(iBin);
+    nCountTot++;
+  }
+  //
+  if (nCountTot < 10) return kFALSE;
+  TGraphErrors *  fitMultTot = new TGraphErrors(nCountTot, xMultTot, yMultTot, 0, yMultErrTot);
+  fitMultTot->SetName("TGRAPHERRORS_MEANQTOT_MULTIPLICITYDEPENDENCE_BEAM_ALL");
+  //
+  fGainArray->AddLast(fitMultMax);
+  fGainArray->AddLast(fitMultTot);
+  //
+  return kTRUE;
+
+}
+
+Bool_t AliTPCPreprocessorOffline::AnalyzeGainChamberByChamber(){
+  //
+  // get chamber by chamber gain
+  //
+  if (!fGainMult) return kFALSE;
+  TGraphErrors *grShort  = fGainMult->GetGainPerChamber(0);
+  TGraphErrors *grMedium = fGainMult->GetGainPerChamber(1);
+  TGraphErrors *grLong   = fGainMult->GetGainPerChamber(2);
+  if (grShort==0x0 || grMedium==0x0 || grLong==0x0) {
+    delete grShort;
+    delete grMedium;
+    delete grLong;
+    return kFALSE;
+  }
+
+  fGainArray->AddLast(grShort);
+  fGainArray->AddLast(grMedium);
+  fGainArray->AddLast(grLong);
+
+  return kTRUE;
+}
+
+void AliTPCPreprocessorOffline::UpdateOCDBGain(Int_t startRunNumber, Int_t endRunNumber, AliCDBStorage *storage){
   //
   // Update OCDB entry
   //
@@ -979,8 +1230,7 @@ void AliTPCPreprocessorOffline::UpdateOCDBGain(Int_t startRunNumber, Int_t endRu
   metaData->SetAliRootVersion("05-24-00"); //root version
   metaData->SetComment("Calibration of the time dependence of the gain due to pressure and temperature changes.");
   AliCDBId id1("TPC/Calib/TimeGain", startRunNumber, endRunNumber);
-  AliCDBStorage * gStorage = AliCDBManager::Instance()->GetStorage(storagePath);
-  gStorage->Put(fGainArray, id1, metaData);    
+  storage->Put(fGainArray, id1, metaData);    
 }
 
 void AliTPCPreprocessorOffline::MakeQAPlot(Float_t  FPtoMIPratio) {
@@ -1010,9 +1260,11 @@ void AliTPCPreprocessorOffline::MakeQAPlot(Float_t  FPtoMIPratio) {
        fGraphCosmic->GetY()[i] *= FPtoMIPratio;        
       }
     }
-    fGraphCosmic->Draw("lp");
-    grfFitCosmic->SetLineColor(2);
-    grfFitCosmic->Draw("lu");
+    fGraphCosmic->Draw("lp"); 
+    if (grfFitCosmic) {
+      grfFitCosmic->SetLineColor(2);
+      grfFitCosmic->Draw("lu");
+    }
     fGainArray->AddLast(gainHistoCosmic);
     //fGainArray->AddLast(canvasCosmic->Clone());
     delete canvasCosmic;    
@@ -1037,5 +1289,422 @@ void AliTPCPreprocessorOffline::MakeQAPlot(Float_t  FPtoMIPratio) {
   }  
 }
 
+void AliTPCPreprocessorOffline::MakeFitTime(){
+  //
+  // make aligment fit - store results in the file
+  //
+  const Int_t kMinEntries=1000;
+  MakeChainTime();
+  MakePrimitivesTime();
+  if (!fAlignTree) return;
+  if (fAlignTree->GetEntries()<kMinEntries) return;
+  fAlignTree->SetAlias("ptype","type");
+  fAlignTree->SetAlias("hasITS","(1+0)");
+  fAlignTree->SetAlias("dITS","1-2*(refX<40)");
+  fAlignTree->SetAlias("isITS","refX>10");
+  fAlignTree->SetAlias("isVertex","refX<10");
+  // 
+  Int_t  npointsMax=30000000;
+  TStatToolkit toolkit;
+  Double_t chi2=0;
+  Int_t    npoints=0;
+  TVectorD param;
+  TMatrixD covar;
+
+  TString fstringFast="";
+  fstringFast+="FExBTwistX++";
+  fstringFast+="FExBTwistY++";
+  fstringFast+="FAlignRot0D++";
+  fstringFast+="FAlignTrans0D++";
+  fstringFast+="FAlignTrans1D++";
+  //
+  fstringFast+="hasITS*FAlignTrans0++";
+  fstringFast+="hasITS*FAlignTrans1++";
+  fstringFast+="hasITS*FAlignRot0++";
+  fstringFast+="hasITS*FAlignRot1++";
+  fstringFast+="hasITS*FAlignRot2++";
+  //
+  fstringFast+="dITS*FAlignTrans0++";
+  fstringFast+="dITS*FAlignTrans1++";
+  fstringFast+="dITS*FAlignRot0++";
+  fstringFast+="dITS*FAlignRot1++";
+  fstringFast+="dITS*FAlignRot2++";
+  
+  TCut cutFit="entries>10&&abs(mean)>0.00001&&rms>0";
+  fAlignTree->SetAlias("err","rms");
+
+  TString *strDeltaITS = TStatToolkit::FitPlaneConstrain(fAlignTree,"mean:err", fstringFast.Data(),cutFit, chi2,npoints,param,covar,-1,0, npointsMax, 1);
+  strDeltaITS->Tokenize("++")->Print();
+  fAlignTree->SetAlias("fitYFast",strDeltaITS->Data());
+  // 
+  TVectorD paramC= param;
+  TMatrixD covarC= covar;
+  TStatToolkit::Constrain1D(fstringFast,"Trans0D",paramC,covarC,0, 0.1);
+  TStatToolkit::Constrain1D(fstringFast,"Trans1D",paramC,covarC,0, 0.1);
+  TStatToolkit::Constrain1D(fstringFast,"TwistX",paramC,covarC,0, 0.1);
+  TStatToolkit::Constrain1D(fstringFast,"TwistY",paramC,covarC,0, 0.1);
+  TString strFitConst=TStatToolkit::MakeFitString(fstringFast, paramC,covar);
+  fAlignTree->SetAlias("fitYFastC",strFitConst.Data());
+  CreateAlignTime(fstringFast,paramC);
+
+
+}
 
 
+void AliTPCPreprocessorOffline::MakeChainTime(){
+  //
+  //
+  //
+  TFile f("CalibObjects.root");
+  
+  //  const char *cdtype[7]={"ITS","TRD","Vertex","TOF","TPC","TPC0","TPC1"};
+  //const char *cptype[5]={"dy","dz","dsnp","dtheta","d1pt"}; 
+  const char * hname[5]={"dy","dz","dsnp","dtheta","d1pt"};
+  Int_t run=0;
+  AliTPCcalibTime  *calibTime = 0;
+  TObjArray * array = (TObjArray*)f.Get("TPCCalib");
+  if (array){
+    calibTime = (AliTPCcalibTime *)array->FindObject("calibTime");
+  } else {
+    calibTime = (AliTPCcalibTime*)f.Get("calibTime");
+  }
+  if (!calibTime) return;
+  AliTPCCorrectionFit::CreateAlignMaps(AliTracker::GetBz(), run);
+  TTreeSRedirector *pcstream = new TTreeSRedirector("meanITSVertex.root");
+  //
+  Int_t ihis=0;
+  THnSparse *his = calibTime->GetResHistoTPCITS(ihis);
+  if (his){
+    his->GetAxis(1)->SetRangeUser(-1.1,1.1);
+    his->GetAxis(2)->SetRange(0,1000000);
+    his->GetAxis(3)->SetRangeUser(-0.35,0.35);
+    AliTPCCorrection::MakeDistortionMap(his,pcstream, Form("ITS%s",hname[ihis]),run,85.,ihis,3);
+  }
+  ihis=1;
+  his = calibTime->GetResHistoTPCITS(ihis);
+  if (his){
+    his->GetAxis(1)->SetRangeUser(-1.1,1.1);
+    his->GetAxis(2)->SetRange(0,1000000);
+    his->GetAxis(3)->SetRangeUser(-0.35,0.35);
+    AliTPCCorrection::MakeDistortionMap(his,pcstream, Form("ITS%s",hname[ihis]),run,85.,ihis,3);
+  }
+  ihis=2;
+  his = calibTime->GetResHistoTPCITS(ihis);
+  if (his){
+    his->GetAxis(1)->SetRangeUser(-1.1,1.1);
+    his->GetAxis(2)->SetRange(0,1000000);
+    his->GetAxis(3)->SetRangeUser(-0.35,0.35);
+    AliTPCCorrection::MakeDistortionMap(his,pcstream, Form("ITS%s",hname[ihis]),run,85.,ihis,3);
+  }
+  ihis=0;
+  his = calibTime->GetResHistoTPCvertex(ihis);
+  if (his){
+    his->GetAxis(1)->SetRangeUser(-1.1,1.1);
+    his->GetAxis(2)->SetRange(0,1000000);
+    his->GetAxis(3)->SetRangeUser(-0.35,0.35);
+    AliTPCCorrection::MakeDistortionMap(his,pcstream, Form("Vertex%s",hname[ihis]),run,0.,ihis,3);
+  }
+  ihis=2;
+  his = calibTime->GetResHistoTPCvertex(ihis);
+  if (his){
+    his->GetAxis(1)->SetRangeUser(-1.1,1.1);
+    his->GetAxis(2)->SetRange(0,1000000);
+    his->GetAxis(3)->SetRangeUser(-0.35,0.35);
+    AliTPCCorrection::MakeDistortionMap(his,pcstream, Form("Vertex%s",hname[ihis]),run,0.,ihis,3);
+
+  }
+  ihis=1;
+  his = calibTime->GetResHistoTPCvertex(ihis);
+  if (his){
+    his->GetAxis(1)->SetRangeUser(-1.1,1.1);
+    his->GetAxis(2)->SetRange(0,1000000);
+    his->GetAxis(3)->SetRangeUser(-0.35,0.35);
+    AliTPCCorrection::MakeDistortionMap(his,pcstream, Form("Vertex%s",hname[ihis]),run,0.,ihis,3);
+
+  }
+  ihis=0;
+  his = calibTime->GetResHistoTPCTOF(ihis);
+  if (his){
+    his->GetAxis(1)->SetRangeUser(-1.1,1.1);
+    his->GetAxis(2)->SetRange(0,1000000);
+    his->GetAxis(3)->SetRangeUser(-0.35,0.35);
+    AliTPCCorrection::MakeDistortionMap(his,pcstream, Form("TOF%s",hname[ihis]),run,0.,ihis,3);
+
+  }
+  ihis=0;
+  his = calibTime->GetResHistoTPCTRD(ihis);
+  if (his){
+    his->GetAxis(1)->SetRangeUser(-1.1,1.1);
+    his->GetAxis(2)->SetRange(0,1000000);
+    his->GetAxis(3)->SetRangeUser(-0.35,0.35);
+    AliTPCCorrection::MakeDistortionMap(his,pcstream, Form("TRD%s",hname[ihis]),run,0.,ihis,3);
+
+  }
+  delete pcstream;
+}
+
+
+Double_t AliTPCPreprocessorOffline::EvalAt(Double_t phi, Double_t refX, Double_t theta, Int_t corr, Int_t ptype){
+  //
+  //
+  //
+  Double_t sector = 9*phi/TMath::Pi();
+  if (sector<0) sector+=18;
+  Double_t y85=AliTPCCorrection::GetCorrSector(sector,85,theta,1,corr);
+  Double_t y245=AliTPCCorrection::GetCorrSector(sector,245,theta,1,corr);
+  if (ptype==0) return y85+(y245-y85)*(refX-85.)/(245.-85.);
+  if (ptype==2) return (y245-y85)/(245.-85.);
+  return 0;
+}
+
+
+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){
+  //
+  // Fit the distortion along the line with the parabolic model
+  // Parameters:
+  //  phi0 - phi at the entrance of the TPC
+  //  snp  - local inclination angle at the entrance of the TPC
+  //  refX - ref X where the distortion is evanluated
+  //  theta
+  //  
+  static TLinearFitter fitter(3,"pol2"); 
+  fitter.ClearPoints();
+  if (nsteps<3) nsteps=3;
+  Double_t deltaX=(245-85)/(nsteps);
+  for (Int_t istep=0; istep<(nsteps+1); istep++){
+    //
+    Double_t localX =85.+deltaX*istep;
+    Double_t localPhi=phi0+deltaX*snp*istep;
+    Double_t sector = 9*localPhi/TMath::Pi();
+    if (sector<0) sector+=18;
+    Double_t y=AliTPCCorrection::GetCorrSector(sector,localX,theta,1,corr);
+    Double_t dlocalX=AliTPCCorrection::GetCorrSector(sector,localX,theta,0,corr);
+    Double_t x[1]={localX-dlocalX};
+    fitter.AddPoint(x,y);
+  }
+  fitter.Eval();
+  Double_t par[3];
+  par[0]=fitter.GetParameter(0);
+  par[1]=fitter.GetParameter(1);
+  par[2]=fitter.GetParameter(2);
+
+  if (ptype==0) return par[0]+par[1]*refX+par[2]*refX*refX;
+  if (ptype==2) return par[1]+2*par[2]*refX;
+  if (ptype==4) return par[2];
+  return 0;
+}
+
+
+
+
+
+
+void AliTPCPreprocessorOffline::MakePrimitivesTime(){
+  //
+  // Create primitive transformation to fit
+  //
+  fAlignTree=new TChain("fit","fit");
+  fAlignTree->AddFile("meanITSVertex.root",10000000,"ITSdy");
+  fAlignTree->AddFile("meanITSVertex.root",10000000,"ITSdsnp");
+  fAlignTree->AddFile("meanITSVertex.root",10000000,"Vertexdy");
+  fAlignTree->AddFile("meanITSVertex.root",10000000,"Vertexdsnp");
+  // 
+  AliTPCParam *param= AliTPCcalibDB::Instance()->GetParameters();
+  Double_t bzField=AliTrackerBase::GetBz(); 
+  Double_t vdrift = param->GetDriftV()/1000000.; // [cm/us]   // From dataBase: to be updated: per second (ideally)
+  Double_t ezField = 400; // [V/cm]   // to be updated: never (hopefully)
+  Double_t wtP = -10.0 * (bzField) * vdrift /  ezField ; 
+  AliTPCExBTwist *fitExBTwistX= new  AliTPCExBTwist;
+  AliTPCExBTwist *fitExBTwistY= new  AliTPCExBTwist;
+  AliTPCCalibGlobalMisalignment *trans0   =new  AliTPCCalibGlobalMisalignment;
+  AliTPCCalibGlobalMisalignment *trans1   =new  AliTPCCalibGlobalMisalignment;
+  AliTPCCalibGlobalMisalignment *trans0D  =new  AliTPCCalibGlobalMisalignment;
+  AliTPCCalibGlobalMisalignment *trans1D  =new  AliTPCCalibGlobalMisalignment;
+  AliTPCCalibGlobalMisalignment *rot0     =new  AliTPCCalibGlobalMisalignment;
+  AliTPCCalibGlobalMisalignment *rot1     =new  AliTPCCalibGlobalMisalignment;
+  AliTPCCalibGlobalMisalignment *rot2     =new  AliTPCCalibGlobalMisalignment;
+  AliTPCCalibGlobalMisalignment *rot3     =new  AliTPCCalibGlobalMisalignment;
+  //
+  //
+  fitExBTwistX->SetXTwist(0.001);
+  fitExBTwistX->SetOmegaTauT1T2(wtP,1,1);  
+  //
+  fitExBTwistY->SetYTwist(0.001);
+  fitExBTwistY->SetOmegaTauT1T2(wtP,1,1);  
+  //
+  TGeoHMatrix *matrixRot = new TGeoHMatrix; 
+  TGeoHMatrix *matrixX = new TGeoHMatrix; 
+  TGeoHMatrix *matrixY = new TGeoHMatrix; 
+  matrixX->SetDx(0.1);
+  matrixY->SetDy(0.1);
+  Double_t rotAngles0[9]={0};
+  Double_t rotAngles1[9]={0};
+  Double_t rotAngles2[9]={0};
+  //
+  Double_t rotAngles3[9]={0};
+
+  rotAngles0[0]=1; rotAngles0[4]=1; rotAngles0[8]=1;
+  rotAngles1[0]=1; rotAngles1[4]=1; rotAngles1[8]=1;
+  rotAngles2[0]=1; rotAngles2[4]=1; rotAngles2[8]=1;
+  rotAngles3[0]=1; rotAngles3[4]=1; rotAngles3[8]=1;
+
+  rotAngles0[1]=-0.001;rotAngles0[3]=0.001;
+  rotAngles1[5]=-0.001;rotAngles1[7]=0.001;
+  rotAngles2[2]=0.001;rotAngles2[6]=-0.001;
+  rotAngles3[1]=0.001;rotAngles3[3]=-0.001;
+  matrixRot->SetRotation(rotAngles0);
+  rot0->SetAlignGlobal(matrixRot);
+  matrixRot->SetRotation(rotAngles1);
+  rot1->SetAlignGlobal(matrixRot);
+  matrixRot->SetRotation(rotAngles2);
+  rot2->SetAlignGlobal(matrixRot); 
+  matrixRot->SetRotation(rotAngles3);
+  rot3->SetAlignGlobalDelta(matrixRot); 
+  //
+  trans0->SetAlignGlobal(matrixX);
+  trans1->SetAlignGlobal(matrixY);
+  trans0D->SetAlignGlobalDelta(matrixX);
+  trans1D->SetAlignGlobalDelta(matrixY);
+  fitExBTwistX->Init();
+  fitExBTwistY->Init();
+  //
+  fitExBTwistX->AddVisualCorrection((AliTPCExBTwist*)(fitExBTwistX->Clone()),100);
+  fitExBTwistY->AddVisualCorrection((AliTPCExBTwist*)(fitExBTwistY->Clone()),101);
+  //
+  fitExBTwistX->AddVisualCorrection((AliTPCExBTwist*)(rot0->Clone()),102);
+  fitExBTwistY->AddVisualCorrection((AliTPCExBTwist*)(rot1->Clone()),103);
+  fitExBTwistX->AddVisualCorrection((AliTPCExBTwist*)(rot2->Clone()),104);
+  fitExBTwistX->AddVisualCorrection((AliTPCExBTwist*)(rot3->Clone()),105);
+
+  fitExBTwistX->AddVisualCorrection((AliTPCExBTwist*)(trans0->Clone()),106);
+  fitExBTwistX->AddVisualCorrection((AliTPCExBTwist*)(trans1->Clone()),107);
+  fitExBTwistX->AddVisualCorrection((AliTPCExBTwist*)(trans0D->Clone()),108);
+  fitExBTwistX->AddVisualCorrection((AliTPCExBTwist*)(trans1D->Clone()),109);
+  //
+  fAlignTree->SetAlias("FExBTwistX", "AliTPCPreprocessorOffline::EvalAt(phi,refX,theta,100,ptype)+0");
+  fAlignTree->SetAlias("FExBTwistY","AliTPCPreprocessorOffline::EvalAt(phi,refX,theta,101,ptype)+0");
+  fAlignTree->SetAlias("FAlignRot0","AliTPCPreprocessorOffline::EvalAt(phi,refX,theta,102,ptype)+0");
+  fAlignTree->SetAlias("FAlignRot0D","AliTPCPreprocessorOffline::EvalAt(phi,refX,theta,105,ptype)+0");
+  fAlignTree->SetAlias("FAlignRot1","AliTPCPreprocessorOffline::EvalAt(phi,refX,theta,103,ptype)+0");
+  fAlignTree->SetAlias("FAlignRot2","AliTPCPreprocessorOffline::EvalAt(phi,refX,theta,104,ptype)+0");
+  fAlignTree->SetAlias("FAlignTrans0","AliTPCPreprocessorOffline::EvalAt(phi,refX,theta,106,ptype)+0");
+  fAlignTree->SetAlias("FAlignTrans1","AliTPCPreprocessorOffline::EvalAt(phi,refX,theta,107,ptype)+0");
+  fAlignTree->SetAlias("FAlignTrans0D","AliTPCPreprocessorOffline::EvalAt(phi,refX,theta,108,ptype)+0");
+  fAlignTree->SetAlias("FAlignTrans1D","AliTPCPreprocessorOffline::EvalAt(phi,refX,theta,109,ptype)+0");
+  //
+  // test fast function
+  //
+//   fAlignTree->Draw("FExBTwistX:ExBTwistX","isITS&&ptype==0&&abs(snp)<0.05","");
+//   fAlignTree->Draw("FExBTwistY:ExBTwistY","isITS&&ptype==0&&abs(snp)<0.05","");
+//   fAlignTree->Draw("FAlignRot0:alignRot0","isITS&&ptype==0&&abs(snp)<0.05","");
+//   fAlignTree->Draw("FAlignRot1:alignRot1","isITS&&ptype==0&&abs(snp)<0.05","");
+//   fAlignTree->Draw("FAlignRot2:alignRot2","isITS&&ptype==0&&abs(snp)<0.05","");
+//   //
+//   fAlignTree->Draw("FAlignTrans0:alignTrans0","isITS&&ptype==0&&abs(snp)<0.05","");
+//   fAlignTree->Draw("FAlignTrans1:alignTrans1","isITS&&ptype==0&&abs(snp)<0.05","");
+
+} 
+
+
+void AliTPCPreprocessorOffline::CreateAlignTime(TString fstring, TVectorD paramC){
+  //
+  //
+  //
+  //
+  TGeoHMatrix *matrixDelta     = new TGeoHMatrix; 
+  TGeoHMatrix *matrixGlobal    = new TGeoHMatrix; 
+  Double_t rAngles[9];
+  Int_t index=0;
+  //
+  index=TStatToolkit::GetFitIndex(fstring,"FAlignTrans0D");
+  if (index>=0) matrixDelta->SetDx(paramC[index+1]*0.1);
+  index=TStatToolkit::GetFitIndex(fstring,"FAlignTrans1D");
+  if (index>=0) matrixDelta->SetDy(paramC[index+1]*0.1);
+  rAngles[0]=1; rAngles[4]=1; rAngles[8]=1;
+  index=TStatToolkit::GetFitIndex(fstring,"FAlignRot0D");
+  rAngles[1]=-paramC[index+1]*0.001; rAngles[3]=paramC[index+1]*0.001;
+  rAngles[5]=0; rAngles[7] =0;
+  rAngles[2]=0; rAngles[6] =0;
+  matrixDelta->SetRotation(rAngles);
+  //
+  //
+  //
+  index=TStatToolkit::GetFitIndex(fstring,"hasITS*FAlignTrans0");
+  if (index>=0) matrixGlobal->SetDx(paramC[index+1]*0.1);
+  index=TStatToolkit::GetFitIndex(fstring,"hasITS*FAlignTrans1");
+  if (index>=0) matrixGlobal->SetDy(paramC[index+1]*0.1);
+  rAngles[0]=1; rAngles[4]=1; rAngles[8]=1;
+  index=TStatToolkit::GetFitIndex(fstring,"hasITS*FAlignRot0");
+  rAngles[1]=-paramC[index+1]*0.001; rAngles[3]=paramC[index+1]*0.001;
+  index=TStatToolkit::GetFitIndex(fstring,"hasITS*FAlignRot1");  
+  rAngles[5]=-paramC[index+1]*0.001; rAngles[7]=paramC[index+1]*0.001;
+  index=TStatToolkit::GetFitIndex(fstring,"hasITS*FAlignRot2");  
+  rAngles[2]=paramC[index+1]*0.001; rAngles[6] =-paramC[index+1]*0.001;
+  matrixGlobal->SetRotation(rAngles);
+  //
+  AliTPCCalibGlobalMisalignment *fitAlignTime  =0;
+  fitAlignTime  =new  AliTPCCalibGlobalMisalignment;
+  fitAlignTime->SetName("FitAlignTime");
+  fitAlignTime->SetTitle("FitAlignTime");
+  fitAlignTime->SetAlignGlobalDelta(matrixDelta);
+  fitAlignTime->SetAlignGlobal(matrixGlobal);
+  //
+  AliTPCExBTwist * fitExBTwist= new  AliTPCExBTwist;
+  Int_t indexX=TStatToolkit::GetFitIndex(fstring,"ExBTwistX");
+  Int_t indexY=TStatToolkit::GetFitIndex(fstring,"ExBTwistY");  
+  fitExBTwist->SetXTwist(0.001*paramC[indexX+1]);  // 1 mrad twist in x
+  fitExBTwist->SetYTwist(0.001*paramC[indexY+1]);  // 1 mrad twist in x
+  fitExBTwist->SetName("FitExBTwistTime");
+  fitExBTwist->SetTitle("FitExBTwistTime"); 
+  AliTPCParam *param= AliTPCcalibDB::Instance()->GetParameters();
+  Double_t bzField=AliTrackerBase::GetBz();
+  Double_t vdrift = param->GetDriftV()/1000000.; // [cm/us]   // From dataBase: to be updated: per second (ideally)
+
+  Double_t ezField = 400; // [V/cm]   // to be updated: never (hopefully)
+  Double_t wt = -10.0 * (bzField) * vdrift /  ezField ; 
+  //
+  fitExBTwist->SetOmegaTauT1T2(wt,1,1);  
+  fitExBTwist->Init();  
+
+  AliTPCComposedCorrection *corrTime =  new AliTPCComposedCorrection;
+  TObjArray *arr = new TObjArray;
+  corrTime->SetCorrections(arr);
+  
+  corrTime->GetCorrections()->Add(fitExBTwist);
+  corrTime->GetCorrections()->Add(fitAlignTime);
+  corrTime->SetName("FitCorrectionTime");
+  corrTime->SetTitle("FitCorrectionTime");
+
+  fitExBTwist->AddVisualCorrection((AliTPCExBTwist*)(fitExBTwist->Clone()),1001);
+  fitAlignTime->AddVisualCorrection((AliTPCExBTwist*)(fitAlignTime->Clone()),1002);
+  fitAlignTime->AddVisualCorrection((AliTPCExBTwist*)(corrTime->Clone()),1003);
+  
+  
+  fAlignTree->SetAlias("ExBTwistTime","AliTPCPreprocessorOffline::EvalAt(phi,refX,theta,1001,ptype)+0");
+  fAlignTree->SetAlias("AlignTime","AliTPCPreprocessorOffline::EvalAt(phi,refX,theta,1002,ptype)+0");
+  fAlignTree->SetAlias("FitCorrectionTime","AliTPCPreprocessorOffline::EvalAt(phi,refX,theta,1003,ptype)+0");
+
+
+  TFile *f = new TFile("fitITSVertex.root","update");
+  corrTime->Write("FitCorrectionTime");
+  f->Close();
+}
+
+//_____________________________________________________________________________
+Int_t AliTPCPreprocessorOffline::GetStatus()
+{
+  //get the calibration status
+  // 0 means OK
+  // positive numbers invalidate for unknown reasons.
+  // negative numbers invalidate with a known reason (e.g. low statistics).
+  // the returned integer has one bit set for every component that failed.
+
+  Bool_t enoughStatistics = (fNtracksVdrift>fMinTracksVdrift && fNeventsVdrift>fMinEventsVdrift);
+  
+  if (!enoughStatistics) 
+  {
+    fCalibrationStatus=-TMath::Abs(fCalibrationStatus);
+  }
+
+  return fCalibrationStatus;
+}