]> git.uio.no Git - u/mrichter/AliRoot.git/blob - TPC/AliTPCcalibDB.cxx
one more tpcrefit added
[u/mrichter/AliRoot.git] / TPC / AliTPCcalibDB.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 // Class providing the calibration parameters by accessing the CDB           //
20 //                                                                           //
21 // Request an instance with AliTPCcalibDB::Instance()                        //
22 // If a new event is processed set the event number with SetRun              //
23 // Then request the calibration data                                         ////
24 //
25 //
26 // Calibration data:
27 // 0.)  Altro mapping
28 //          Simulation      - not yet 
29 //          Reconstruction  - AliTPCclustererMI::Digits2Clusters(AliRawReader* rawReader)
30 //
31 // 1.)  pad by pad calibration -  AliTPCCalPad
32 //      
33 //      a.) fPadGainFactor
34 //          Simulation: AliTPCDigitizer::ExecFast - Multiply by gain
35 //          Reconstruction : AliTPCclustererMI::Digits2Clusters - Divide by gain  
36 //
37 //      b.) fPadNoise -
38 //          Simulation:        AliTPCDigitizer::ExecFast
39 //          Reconstruction:    AliTPCclustererMI::FindClusters(AliTPCCalROC * noiseROC)
40 //                             Noise depending cut on clusters charge (n sigma)
41 //      c.) fPedestal:
42 //          Simulation:     Not used yet - To be impleneted - Rounding to the nearest integer
43 //          Reconstruction: Used in AliTPCclustererMI::Digits2Clusters(AliRawReader* rawReader) 
44 //                          if data taken without zero suppression  
45 //                          Currently switch in  fRecoParam->GetCalcPedestal();
46 //      
47 //      d.) fPadTime0
48 //          Simulation:      applied in the AliTPC::MakeSector - adding offset
49 //          Reconstruction:  AliTPCTransform::Transform() - remove offset
50 //                           AliTPCTransform::Transform() - to be called
51 //                           in AliTPCtracker::Transform()      
52 //
53 // 
54 // 2.)  Space points transformation:
55 //
56 //      a.) General coordinate tranformation - AliTPCtransform (see $ALICE_ROOT/TPC/AliTPCtransform.cxx)
57 //          Created on fly - use the other calibration components
58 //                 Unisochronity  - (substract time0 - pad by pad)
59 //                 Drift velocity - Currently common drift velocity - functionality of AliTPCParam
60 //                 ExB effect    
61 //          Simulation     - Not used directly (the effects are applied one by one (see AliTPC::MakeSector)
62 //          Reconstruction - 
63 //                           AliTPCclustererMI::AddCluster
64 //                           AliTPCtrackerMI::Transform
65 //      b.) ExB effect calibration - 
66 //             classes (base class AliTPCExB, implementation- AliTPCExBExact.h  AliTPCExBFirst.h)
67 //             a.a) Simulation:   applied in the AliTPC::MakeSector - 
68 //                                calib->GetExB()->CorrectInverse(dxyz0,dxyz1);
69 //             a.b) Reconstruction -  
70 //                  
71 //                  in AliTPCtransform::Correct() - called calib->GetExB()->Correct(dxyz0,dxyz1)
72 //
73 //  3.)   cluster error, shape and Q parameterization
74 //
75 //
76 //
77 ///////////////////////////////////////////////////////////////////////////////
78
79 #include <iostream>
80 #include <fstream>
81
82
83 #include <AliCDBManager.h>
84 #include <AliCDBEntry.h>
85 #include <AliCDBId.h>
86 #include <AliLog.h>
87 #include <AliMagF.h>
88 #include <AliSplineFit.h>
89 #include <AliCTPTimeParams.h>
90
91 #include "AliTPCcalibDB.h"
92 #include "AliTPCdataQA.h"
93 #include "AliTPCcalibDButil.h"
94 #include "AliTPCAltroMapping.h"
95 #include "AliTPCExB.h"
96
97 #include "AliTPCCalROC.h"
98 #include "AliTPCCalPad.h"
99 #include "AliTPCSensorTempArray.h"
100 #include "AliGRPObject.h"
101 #include "AliTPCTransform.h"
102 #include "AliTPCmapper.h"
103
104 class AliCDBStorage;
105 class AliTPCCalDet;
106 //
107 //
108
109 #include "TFile.h"
110 #include "TKey.h"
111 #include "TGraphErrors.h"
112
113 #include "TObjArray.h"
114 #include "TObjString.h"
115 #include "TString.h"
116 #include "TDirectory.h"
117 #include "TArrayI.h"
118 #include "AliTPCCalPad.h"
119 #include "AliTPCCalibPulser.h"
120 #include "AliTPCCalibPedestal.h"
121 #include "AliTPCCalibCE.h"
122 #include "AliTPCExBFirst.h"
123 #include "AliTPCTempMap.h"
124 #include "AliTPCCalibVdrift.h"
125 #include "AliTPCCalibRaw.h"
126 #include "AliTPCParam.h"
127 #include "AliTPCCorrection.h"
128 #include "AliTPCComposedCorrection.h"
129 #include "AliTPCPreprocessorOnline.h"
130
131
132 ClassImp(AliTPCcalibDB)
133
134 AliTPCcalibDB* AliTPCcalibDB::fgInstance = 0;
135 Bool_t AliTPCcalibDB::fgTerminated = kFALSE;
136 TObjArray    AliTPCcalibDB::fgExBArray;    // array of ExB corrections
137
138
139 //_ singleton implementation __________________________________________________
140 AliTPCcalibDB* AliTPCcalibDB::Instance()
141 {
142   //
143   // Singleton implementation
144   // Returns an instance of this class, it is created if neccessary
145   //
146   
147   if (fgTerminated != kFALSE)
148     return 0;
149
150   if (fgInstance == 0)
151     fgInstance = new AliTPCcalibDB();
152   
153   return fgInstance;
154 }
155
156 void AliTPCcalibDB::Terminate()
157 {
158   //
159   // Singleton implementation
160   // Deletes the instance of this class and sets the terminated flag, instances cannot be requested anymore
161   // This function can be called several times.
162   //
163   
164   fgTerminated = kTRUE;
165   
166   if (fgInstance != 0)
167   {
168     delete fgInstance;
169     fgInstance = 0;
170   }
171 }
172
173 //_____________________________________________________________________________
174 AliTPCcalibDB::AliTPCcalibDB():
175   TObject(),
176   fRun(-1),
177   fTransform(0),
178   fExB(0),
179   fPadGainFactor(0),
180   fDedxGainFactor(0),
181   fPadTime0(0),
182   fDistortionMap(0),
183   fComposedCorrection(0),
184   fComposedCorrectionArray(0),
185   fPadNoise(0),
186   fPedestals(0),
187   fCalibRaw(0),
188   fDataQA(0),
189   fALTROConfigData(0),
190   fPulserData(0),
191   fCEData(0),
192   fTemperature(0),
193   fMapping(0),
194   fParam(0),
195   fClusterParam(0),
196   fTimeGainSplines(0),
197   fTimeGainSplinesArray(100000),
198   fGRPArray(100000),            //! array of GRPs  -  per run  - JUST for calibration studies
199   fGRPMaps(100000),            //! array of GRPs  -  per run  - JUST for calibration studies
200   fGoofieArray(100000),         //! array of GOOFIE values -per run - Just for calibration studies
201   fVoltageArray(100000),
202   fTemperatureArray(100000),    //! array of temperature sensors - per run - Just for calibration studies
203   fVdriftArray(100000),                 //! array of v drift interfaces
204   fDriftCorrectionArray(100000),  //! array of drift correction
205   fRunList(100000),              //! run list - indicates try to get the run param 
206   fBHasAlignmentOCDB(kFALSE),    // Flag  - has the alignment on the composed correction ?
207   fDButil(0),
208   fCTPTimeParams(0),
209   fMode(-1)
210 {
211   //
212   // constructor
213   //  
214   //
215   fgInstance=this;
216   Update();    // temporary
217 }
218
219 AliTPCcalibDB::AliTPCcalibDB(const AliTPCcalibDB& ):
220   TObject(),
221   fRun(-1),
222   fTransform(0),
223   fExB(0),
224   fPadGainFactor(0),
225   fDedxGainFactor(0),
226   fPadTime0(0),
227   fDistortionMap(0),
228   fComposedCorrection(0),
229   fComposedCorrectionArray(0),
230   fPadNoise(0),
231   fPedestals(0),
232   fCalibRaw(0),
233   fDataQA(0),
234   fALTROConfigData(0),
235   fPulserData(0),
236   fCEData(0),
237   fTemperature(0),
238   fMapping(0),
239   fParam(0),
240   fClusterParam(0),
241   fTimeGainSplines(0),
242   fTimeGainSplinesArray(100000),
243   fGRPArray(0),          //! array of GRPs  -  per run  - JUST for calibration studies
244   fGRPMaps(0),          //! array of GRPs  -  per run  - JUST for calibration studies
245   fGoofieArray(0),        //! array of GOOFIE values -per run - Just for calibration studies
246   fVoltageArray(0),
247   fTemperatureArray(0),   //! array of temperature sensors - per run - Just for calibration studies
248   fVdriftArray(0),         //! array of v drift interfaces
249   fDriftCorrectionArray(0), //! array of v drift corrections
250   fRunList(0),              //! run list - indicates try to get the run param 
251   fBHasAlignmentOCDB(kFALSE),    // Flag  - has the alignment on the composed correction ?
252   fDButil(0),
253   fCTPTimeParams(0),
254   fMode(-1)
255 {
256   //
257   // Copy constructor invalid -- singleton implementation
258   //
259    Error("copy constructor","invalid -- singleton implementation");
260 }
261
262 AliTPCcalibDB& AliTPCcalibDB::operator= (const AliTPCcalibDB& )
263 {
264 //
265 // Singleton implementation - no assignment operator
266 //
267   Error("operator =", "assignment operator not implemented");
268   return *this;
269 }
270
271
272
273 //_____________________________________________________________________________
274 AliTPCcalibDB::~AliTPCcalibDB() 
275 {
276   //
277   // destructor
278   //
279   
280 }
281 AliTPCCalPad* AliTPCcalibDB::GetDistortionMap(Int_t i) const {
282   //
283   // get distortion map - due E field distortions
284   //
285   return (fDistortionMap) ? (AliTPCCalPad*)fDistortionMap->At(i):0;
286 }
287
288 //_____________________________________________________________________________
289 AliCDBEntry* AliTPCcalibDB::GetCDBEntry(const char* cdbPath)
290 {
291   // 
292   // Retrieves an entry with path <cdbPath> from the CDB.
293   //
294   char chinfo[1000];
295     
296   AliCDBEntry* entry = AliCDBManager::Instance()->Get(cdbPath, fRun); 
297   if (!entry) 
298   { 
299     snprintf(chinfo,1000,"AliTPCcalibDB: Failed to get entry:\t%s ", cdbPath);
300     AliError(chinfo); 
301     return 0; 
302   }
303   return entry;
304 }
305
306
307 //_____________________________________________________________________________
308 void AliTPCcalibDB::SetRun(Long64_t run)
309 {
310   //
311   // Sets current run number. Calibration data is read from the corresponding file. 
312   //  
313   if (fRun == run)
314     return;  
315         fRun = run;
316   Update();
317 }
318   
319
320
321 void AliTPCcalibDB::Update(){
322   //
323   // cache the OCDB entries for simulation, reconstruction, calibration
324   //  
325   //
326   AliCDBEntry * entry=0;
327   Bool_t cdbCache = AliCDBManager::Instance()->GetCacheFlag(); // save cache status
328   AliCDBManager::Instance()->SetCacheFlag(kTRUE); // activate CDB cache
329   fDButil = new AliTPCcalibDButil;   
330   //
331
332   entry          = GetCDBEntry("TPC/Calib/PadGainFactor");
333   if (entry){
334     //if (fPadGainFactor) delete fPadGainFactor;
335     entry->SetOwner(kTRUE);
336     fPadGainFactor = (AliTPCCalPad*)entry->GetObject();
337   }else{
338     AliFatal("TPC - Missing calibration entry TPC/Calib/PadGainFactor");
339   }
340   //
341   entry          = GetCDBEntry("TPC/Calib/TimeGain");
342   if (entry){
343     //if (fTimeGainSplines) delete fTimeGainSplines;
344     entry->SetOwner(kTRUE);
345     fTimeGainSplines = (TObjArray*)entry->GetObject();
346   }else{
347     AliFatal("TPC - Missing calibration entry TPC/Calib/Timegain");
348   }
349   //
350   entry          = GetCDBEntry("TPC/Calib/GainFactorDedx");
351   if (entry){
352     entry->SetOwner(kTRUE);
353     fDedxGainFactor = (AliTPCCalPad*)entry->GetObject();
354   }else{
355     AliFatal("TPC - Missing calibration entry TPC/Calib/gainFactordEdx");
356   }
357   //
358   entry          = GetCDBEntry("TPC/Calib/PadTime0");
359   if (entry){
360     //if (fPadTime0) delete fPadTime0;
361     entry->SetOwner(kTRUE);
362     fPadTime0 = (AliTPCCalPad*)entry->GetObject();
363   }else{
364     AliFatal("TPC - Missing calibration entry");
365   }
366
367   entry          = GetCDBEntry("TPC/Calib/Distortion");
368   if (entry){
369     //if (fPadTime0) delete fPadTime0;
370     entry->SetOwner(kTRUE);
371     fDistortionMap =dynamic_cast<TObjArray*>(entry->GetObject());
372   }else{
373     //AliFatal("TPC - Missing calibration entry")
374   }
375
376
377   //
378   //
379   entry          = GetCDBEntry("TPC/Calib/PadNoise");
380   if (entry){
381     //if (fPadNoise) delete fPadNoise;
382     entry->SetOwner(kTRUE);
383     fPadNoise = (AliTPCCalPad*)entry->GetObject();
384   }else{
385     AliFatal("TPC - Missing calibration entry");
386   }
387
388   entry          = GetCDBEntry("TPC/Calib/Pedestals");
389   if (entry){
390     //if (fPedestals) delete fPedestals;
391     entry->SetOwner(kTRUE);
392     fPedestals = (AliTPCCalPad*)entry->GetObject();
393   }
394
395   entry          = GetCDBEntry("TPC/Calib/Temperature");
396   if (entry){
397     //if (fTemperature) delete fTemperature;
398     entry->SetOwner(kTRUE);
399     fTemperature = (AliTPCSensorTempArray*)entry->GetObject();
400   }
401
402   entry          = GetCDBEntry("TPC/Calib/Parameters");
403   if (entry){
404     //if (fPadNoise) delete fPadNoise;
405     entry->SetOwner(kTRUE);
406     fParam = (AliTPCParam*)(entry->GetObject()->Clone());
407   }else{
408     AliFatal("TPC - Missing calibration entry TPC/Calib/Parameters");
409   }
410
411   entry          = GetCDBEntry("TPC/Calib/ClusterParam");
412   if (entry){
413     entry->SetOwner(kTRUE);
414     fClusterParam = (AliTPCClusterParam*)(entry->GetObject()->Clone());
415   }else{
416     AliFatal("TPC - Missing calibration entry");
417   }
418
419   //ALTRO configuration data
420   entry          = GetCDBEntry("TPC/Calib/AltroConfig");
421   if (entry){
422     entry->SetOwner(kTRUE);
423     fALTROConfigData=(TObjArray*)(entry->GetObject());
424   }else{
425     AliFatal("TPC - Missing calibration entry");
426   }
427   
428   //Calibration Pulser data
429   entry          = GetCDBEntry("TPC/Calib/Pulser");
430   if (entry){
431     entry->SetOwner(kTRUE);
432     fPulserData=(TObjArray*)(entry->GetObject());
433   }
434   
435   //CE data
436   entry          = GetCDBEntry("TPC/Calib/CE");
437   if (entry){
438     entry->SetOwner(kTRUE);
439     fCEData=(TObjArray*)(entry->GetObject());
440   }
441   //RAW calibration data
442  //  entry          = GetCDBEntry("TPC/Calib/Raw");
443   
444   entry          = GetCDBEntry("TPC/Calib/Mapping");
445   if (entry){
446     //if (fPadNoise) delete fPadNoise;
447     entry->SetOwner(kTRUE);
448     TObjArray * array = dynamic_cast<TObjArray*>(entry->GetObject());
449     if (array && array->GetEntriesFast()==6){
450       fMapping = new AliTPCAltroMapping*[6];
451       for (Int_t i=0; i<6; i++){
452         fMapping[i] =  dynamic_cast<AliTPCAltroMapping*>(array->At(i));
453       }
454     }
455   }
456
457   //CTP calibration data
458   entry          = GetCDBEntry("GRP/CTP/CTPtiming");
459   if (entry){
460     //entry->SetOwner(kTRUE);
461     fCTPTimeParams=dynamic_cast<AliCTPTimeParams*>(entry->GetObject());
462   }else{
463     AliError("TPC - Missing calibration entry");
464   }  
465   //TPC space point correction data
466   entry          = GetCDBEntry("TPC/Calib/Correction");
467   if (entry){
468     //entry->SetOwner(kTRUE);
469     fComposedCorrection=dynamic_cast<AliTPCCorrection*>(entry->GetObject());
470     if (fComposedCorrection) fComposedCorrection->Init();
471     fComposedCorrectionArray=dynamic_cast<TObjArray*>(entry->GetObject());
472     if (fComposedCorrectionArray){
473       for (Int_t i=0; i<fComposedCorrectionArray->GetEntries(); i++){
474         AliTPCComposedCorrection* composedCorrection= dynamic_cast<AliTPCComposedCorrection*>(fComposedCorrectionArray->At(i));
475         if (composedCorrection) {
476           composedCorrection->Init();
477           if (composedCorrection->GetCorrections()){
478             if (composedCorrection->GetCorrections()->FindObject("FitAlignTPC")){
479               fBHasAlignmentOCDB=kTRUE;
480             }
481           }
482         }
483       }
484     }  
485   }else{
486     AliError("TPC - Missing calibration entry-  TPC/Calib/Correction");
487   } 
488   //RCU trigger config mode
489   fMode=GetRCUTriggerConfig();
490   //
491   if (!fTransform) {
492     fTransform=new AliTPCTransform(); 
493     fTransform->SetCurrentRun(AliCDBManager::Instance()->GetRun());
494   }
495
496   //
497   AliCDBManager::Instance()->SetCacheFlag(cdbCache); // reset original CDB cache
498 }
499
500 void AliTPCcalibDB::UpdateNonRec(){
501   //
502   // Update/Load the parameters which are important for QA studies
503   // and not used yet for the reconstruction
504   //
505    //RAW calibration data
506   AliCDBEntry * entry=0;
507   entry          = GetCDBEntry("TPC/Calib/Raw");
508   if (entry){
509     entry->SetOwner(kTRUE);
510     TObjArray *arr=(TObjArray*)(entry->GetObject());
511     if (arr) fCalibRaw=(AliTPCCalibRaw*)arr->At(0);
512   }
513   //QA calibration data
514   entry          = GetCDBEntry("TPC/Calib/QA");
515   if (entry){
516     entry->SetOwner(kTRUE);
517     fDataQA=dynamic_cast<AliTPCdataQA*>(entry->GetObject());
518   }
519   // High voltage
520   if (fRun>=0){
521     entry = AliCDBManager::Instance()->Get("TPC/Calib/HighVoltage",fRun);
522     if (entry)  {
523       fVoltageArray.AddAt(entry->GetObject(),fRun);
524     }
525   }
526
527 }
528
529
530
531 void AliTPCcalibDB::CreateObjectList(const Char_t *filename, TObjArray *calibObjects)
532 {
533 //
534 // Create calibration objects and read contents from OCDB
535 //
536    if ( calibObjects == 0x0 ) return;
537    ifstream in;
538    in.open(filename);
539    if ( !in.is_open() ){
540       fprintf(stderr,"Error: cannot open list file '%s'", filename);
541       return;
542    }
543    
544    AliTPCCalPad *calPad=0x0;
545    
546    TString sFile;
547    sFile.ReadFile(in);
548    in.close();
549    
550    TObjArray *arrFileLine = sFile.Tokenize("\n");
551    
552    TIter nextLine(arrFileLine);
553    
554    TObjString *sObjLine=0x0;
555    while ( (sObjLine = (TObjString*)nextLine()) ){
556       TString sLine(sObjLine->GetString());
557       
558       TObjArray *arrNextCol = sLine.Tokenize("\t");
559       
560       TObjString *sObjType     = (TObjString*)(arrNextCol->At(0));
561       TObjString *sObjFileName = (TObjString*)(arrNextCol->At(1));
562       
563       if ( !sObjType || ! sObjFileName ) continue;
564       TString sType(sObjType->GetString());
565       TString sFileName(sObjFileName->GetString());
566       printf("%s\t%s\n",sType.Data(),sFileName.Data());
567       
568       TFile *fIn = TFile::Open(sFileName);
569       if ( !fIn ){
570          fprintf(stderr,"File not found: '%s'", sFileName.Data());
571          continue;
572       }
573       
574       if ( sType == "CE" ){
575          AliTPCCalibCE *ce = (AliTPCCalibCE*)fIn->Get("AliTPCCalibCE");
576          
577          calPad = new AliTPCCalPad((TObjArray*)ce->GetCalPadT0());         
578          calPad->SetNameTitle("CETmean","CETmean");
579          calibObjects->Add(calPad);
580          
581          calPad = new AliTPCCalPad((TObjArray*)ce->GetCalPadQ());         
582          calPad->SetNameTitle("CEQmean","CEQmean");
583          calibObjects->Add(calPad);        
584          
585          calPad = new AliTPCCalPad((TObjArray*)ce->GetCalPadRMS());
586          calPad->SetNameTitle("CETrms","CETrms");
587          calibObjects->Add(calPad);         
588                   
589       } else if ( sType == "Pulser") {
590          AliTPCCalibPulser *sig = (AliTPCCalibPulser*)fIn->Get("AliTPCCalibPulser");
591          
592          calPad = new AliTPCCalPad((TObjArray*)sig->GetCalPadT0());         
593          calPad->SetNameTitle("PulserTmean","PulserTmean");
594          calibObjects->Add(calPad);
595          
596          calPad = new AliTPCCalPad((TObjArray*)sig->GetCalPadQ());         
597          calPad->SetNameTitle("PulserQmean","PulserQmean");
598          calibObjects->Add(calPad);        
599          
600          calPad = new AliTPCCalPad((TObjArray*)sig->GetCalPadRMS());
601          calPad->SetNameTitle("PulserTrms","PulserTrms");
602          calibObjects->Add(calPad);         
603       
604       } else if ( sType == "Pedestals") {
605          AliTPCCalibPedestal *ped = (AliTPCCalibPedestal*)fIn->Get("AliTPCCalibPedestal");
606          
607          calPad = new AliTPCCalPad((TObjArray*)ped->GetCalPadPedestal());         
608          calPad->SetNameTitle("Pedestals","Pedestals");
609          calibObjects->Add(calPad);
610          
611          calPad = new AliTPCCalPad((TObjArray*)ped->GetCalPadRMS());         
612          calPad->SetNameTitle("Noise","Noise");
613          calibObjects->Add(calPad);        
614      
615       } else {
616          fprintf(stderr,"Undefined Type: '%s'",sType.Data());
617          
618       }
619       delete fIn;
620    }
621 }
622
623
624
625 void AliTPCcalibDB::MakeTree(const char * fileName, TObjArray * array, const char * mapFileName, AliTPCCalPad* outlierPad, Float_t ltmFraction) {
626   //
627   // Write a tree with all available information
628   // if mapFileName is specified, the Map information are also written to the tree
629   // pads specified in outlierPad are not used for calculating statistics
630   //  - the same function as AliTPCCalPad::MakeTree - 
631   //
632    AliTPCROC* tpcROCinstance = AliTPCROC::Instance();
633
634    TObjArray* mapIROCs = 0;
635    TObjArray* mapOROCs = 0;
636    TVectorF *mapIROCArray = 0;
637    TVectorF *mapOROCArray = 0;
638    Int_t mapEntries = 0;
639    TString* mapNames = 0;
640    
641    if (mapFileName) {
642       TFile mapFile(mapFileName, "read");
643       
644       TList* listOfROCs = mapFile.GetListOfKeys();
645       mapEntries = listOfROCs->GetEntries()/2;
646       mapIROCs = new TObjArray(mapEntries*2);
647       mapOROCs = new TObjArray(mapEntries*2);
648       mapIROCArray = new TVectorF[mapEntries];
649       mapOROCArray = new TVectorF[mapEntries];
650       
651       mapNames = new TString[mapEntries];
652       for (Int_t ivalue = 0; ivalue < mapEntries; ivalue++) {
653         TString nameROC(((TKey*)(listOfROCs->At(ivalue*2)))->GetName());
654          nameROC.Remove(nameROC.Length()-4, 4);
655          mapIROCs->AddAt((AliTPCCalROC*)mapFile.Get((nameROC + "IROC").Data()), ivalue);
656          mapOROCs->AddAt((AliTPCCalROC*)mapFile.Get((nameROC + "OROC").Data()), ivalue);
657          mapNames[ivalue].Append(nameROC);
658       }
659       
660       for (Int_t ivalue = 0; ivalue < mapEntries; ivalue++) {
661          mapIROCArray[ivalue].ResizeTo(tpcROCinstance->GetNChannels(0));
662          mapOROCArray[ivalue].ResizeTo(tpcROCinstance->GetNChannels(36));
663       
664          for (UInt_t ichannel = 0; ichannel < tpcROCinstance->GetNChannels(0); ichannel++)
665             (mapIROCArray[ivalue])[ichannel] = ((AliTPCCalROC*)(mapIROCs->At(ivalue)))->GetValue(ichannel);
666          for (UInt_t ichannel = 0; ichannel < tpcROCinstance->GetNChannels(36); ichannel++)
667             (mapOROCArray[ivalue])[ichannel] = ((AliTPCCalROC*)(mapOROCs->At(ivalue)))->GetValue(ichannel);
668       }
669
670    } //  if (mapFileName)
671   
672    TTreeSRedirector cstream(fileName);
673    Int_t arrayEntries = array->GetEntries();
674    
675    TString* names = new TString[arrayEntries];
676    for (Int_t ivalue = 0; ivalue < arrayEntries; ivalue++)
677       names[ivalue].Append(((AliTPCCalPad*)array->At(ivalue))->GetName());
678
679    for (UInt_t isector = 0; isector < tpcROCinstance->GetNSectors(); isector++) {
680       //
681       // get statistic for given sector
682       //
683       TVectorF median(arrayEntries);
684       TVectorF mean(arrayEntries);
685       TVectorF rms(arrayEntries);
686       TVectorF ltm(arrayEntries);
687       TVectorF ltmrms(arrayEntries);
688       TVectorF medianWithOut(arrayEntries);
689       TVectorF meanWithOut(arrayEntries);
690       TVectorF rmsWithOut(arrayEntries);
691       TVectorF ltmWithOut(arrayEntries);
692       TVectorF ltmrmsWithOut(arrayEntries);
693       
694       TVectorF *vectorArray = new TVectorF[arrayEntries];
695       for (Int_t ivalue = 0; ivalue < arrayEntries; ivalue++)
696          vectorArray[ivalue].ResizeTo(tpcROCinstance->GetNChannels(isector));
697       
698       for (Int_t ivalue = 0; ivalue < arrayEntries; ivalue++) {
699          AliTPCCalPad* calPad = (AliTPCCalPad*) array->At(ivalue);
700          AliTPCCalROC* calROC = calPad->GetCalROC(isector);
701          AliTPCCalROC* outlierROC = 0;
702          if (outlierPad) outlierROC = outlierPad->GetCalROC(isector);
703          if (calROC) {
704             median[ivalue] = calROC->GetMedian();
705             mean[ivalue] = calROC->GetMean();
706             rms[ivalue] = calROC->GetRMS();
707             Double_t ltmrmsValue = 0;
708             ltm[ivalue] = calROC->GetLTM(&ltmrmsValue, ltmFraction);
709             ltmrms[ivalue] = ltmrmsValue;
710             if (outlierROC) {
711                medianWithOut[ivalue] = calROC->GetMedian(outlierROC);
712                meanWithOut[ivalue] = calROC->GetMean(outlierROC);
713                rmsWithOut[ivalue] = calROC->GetRMS(outlierROC);
714                ltmrmsValue = 0;
715                ltmWithOut[ivalue] = calROC->GetLTM(&ltmrmsValue, ltmFraction, outlierROC);
716                ltmrmsWithOut[ivalue] = ltmrmsValue;
717             }
718          }
719          else {
720             median[ivalue] = 0.;
721             mean[ivalue] = 0.;
722             rms[ivalue] = 0.;
723             ltm[ivalue] = 0.;
724             ltmrms[ivalue] = 0.;
725             medianWithOut[ivalue] = 0.;
726             meanWithOut[ivalue] = 0.;
727             rmsWithOut[ivalue] = 0.;
728             ltmWithOut[ivalue] = 0.;
729             ltmrmsWithOut[ivalue] = 0.;
730          }
731       }
732       
733       //
734       // fill vectors of variable per pad
735       //
736       TVectorF *posArray = new TVectorF[8];
737       for (Int_t ivalue = 0; ivalue < 8; ivalue++)
738          posArray[ivalue].ResizeTo(tpcROCinstance->GetNChannels(isector));
739
740       Float_t posG[3] = {0};
741       Float_t posL[3] = {0};
742       Int_t ichannel = 0;
743       for (UInt_t irow = 0; irow < tpcROCinstance->GetNRows(isector); irow++) {
744          for (UInt_t ipad = 0; ipad < tpcROCinstance->GetNPads(isector, irow); ipad++) {
745             tpcROCinstance->GetPositionLocal(isector, irow, ipad, posL);
746             tpcROCinstance->GetPositionGlobal(isector, irow, ipad, posG);
747             posArray[0][ichannel] = irow;
748             posArray[1][ichannel] = ipad;
749             posArray[2][ichannel] = posL[0];
750             posArray[3][ichannel] = posL[1];
751             posArray[4][ichannel] = posG[0];
752             posArray[5][ichannel] = posG[1];
753             posArray[6][ichannel] = (Int_t)(ipad - (Double_t)(tpcROCinstance->GetNPads(isector, irow))/2);
754             posArray[7][ichannel] = ichannel;
755             
756             // loop over array containing AliTPCCalPads
757             for (Int_t ivalue = 0; ivalue < arrayEntries; ivalue++) {
758                AliTPCCalPad* calPad = (AliTPCCalPad*) array->At(ivalue);
759                AliTPCCalROC* calROC = calPad->GetCalROC(isector);
760                if (calROC)
761                   (vectorArray[ivalue])[ichannel] = calROC->GetValue(irow, ipad);
762                else
763                   (vectorArray[ivalue])[ichannel] = 0;
764             }
765             ichannel++;
766          }
767       }
768       
769       cstream << "calPads" <<
770          "sector=" << isector;
771       
772       for  (Int_t ivalue = 0; ivalue < arrayEntries; ivalue++) {
773          cstream << "calPads" <<
774             (Char_t*)((names[ivalue] + "_Median=").Data()) << median[ivalue] <<
775             (Char_t*)((names[ivalue] + "_Mean=").Data()) << mean[ivalue] <<
776             (Char_t*)((names[ivalue] + "_RMS=").Data()) << rms[ivalue] <<
777             (Char_t*)((names[ivalue] + "_LTM=").Data()) << ltm[ivalue] <<
778             (Char_t*)((names[ivalue] + "_RMS_LTM=").Data()) << ltmrms[ivalue];
779          if (outlierPad) {
780             cstream << "calPads" <<
781                (Char_t*)((names[ivalue] + "_Median_OutlierCutted=").Data()) << medianWithOut[ivalue] <<
782                (Char_t*)((names[ivalue] + "_Mean_OutlierCutted=").Data()) << meanWithOut[ivalue] <<
783                (Char_t*)((names[ivalue] + "_RMS_OutlierCutted=").Data()) << rmsWithOut[ivalue] <<
784                (Char_t*)((names[ivalue] + "_LTM_OutlierCutted=").Data()) << ltmWithOut[ivalue] <<
785                (Char_t*)((names[ivalue] + "_RMS_LTM_OutlierCutted=").Data()) << ltmrmsWithOut[ivalue];
786          }
787       }
788
789       for  (Int_t ivalue = 0; ivalue < arrayEntries; ivalue++) {
790          cstream << "calPads" <<
791             (Char_t*)((names[ivalue] + ".=").Data()) << &vectorArray[ivalue];
792       }
793
794       if (mapFileName) {
795          for  (Int_t ivalue = 0; ivalue < mapEntries; ivalue++) {
796             if (isector < 36)
797                cstream << "calPads" <<
798                   (Char_t*)((mapNames[ivalue] + ".=").Data()) << &mapIROCArray[ivalue];
799             else
800                cstream << "calPads" <<
801                   (Char_t*)((mapNames[ivalue] + ".=").Data()) << &mapOROCArray[ivalue];
802          }
803       }
804
805       cstream << "calPads" <<
806          "row.=" << &posArray[0] <<
807          "pad.=" << &posArray[1] <<
808          "lx.=" << &posArray[2] <<
809          "ly.=" << &posArray[3] <<
810          "gx.=" << &posArray[4] <<
811          "gy.=" << &posArray[5] <<
812          "rpad.=" << &posArray[6] <<
813          "channel.=" << &posArray[7];
814          
815       cstream << "calPads" <<
816          "\n";
817
818       delete[] posArray;
819       delete[] vectorArray;
820    }
821    
822
823    delete[] names;
824    if (mapFileName) {
825       delete mapIROCs;
826       delete mapOROCs;
827       delete[] mapIROCArray;
828       delete[] mapOROCArray;
829       delete[] mapNames;
830    }
831 }
832
833 Int_t AliTPCcalibDB::GetRCUTriggerConfig() const
834 {
835   //
836   // return the RCU trigger configuration register
837   //
838   TMap *map=GetRCUconfig();
839   if (!map) return -1;
840   TVectorF *v=(TVectorF*)map->GetValue("TRGCONF_TRG_MODE");
841   Float_t mode=-1;
842   for (Int_t i=0; i<v->GetNrows(); ++i){
843     Float_t newmode=v->GetMatrixArray()[i];
844     if (newmode>-1){
845       if (mode>-1&&newmode!=mode) AliWarning("Found different RCU trigger configurations!!!");
846       mode=newmode;
847     }
848   }
849   return (Int_t)mode;
850 }
851
852 Bool_t AliTPCcalibDB::IsTrgL0() 
853 {
854   //
855   // return if the FEE readout was triggered on L0
856   //
857   if (fMode<0) return kFALSE;
858   return (fMode==1);
859 }
860
861 Bool_t AliTPCcalibDB::IsTrgL1()
862 {
863   //
864   // return if the FEE readout was triggered on L1
865   //
866   if (fMode<0) return kFALSE;
867   return (fMode==0);
868 }
869
870 void AliTPCcalibDB::RegisterExB(Int_t index, Float_t bz, Bool_t bdelete){
871   //
872   // Register static ExB correction map
873   // index - registration index - used for visualization
874   // bz    - bz field in kGaus
875
876   //  Float_t factor =  bz/(-5.);  // default b filed in Cheb with minus sign
877   Float_t factor =  bz/(5.);  // default b filed in Cheb with minus sign
878                               // was chenged in the Revision ???? (Ruben can you add here number)
879   
880   AliMagF*   bmap = new AliMagF("MapsExB","MapsExB", factor,TMath::Sign(1.f,factor),AliMagF::k5kG);
881   
882   AliTPCExBFirst *exb  = new  AliTPCExBFirst(bmap,0.88*2.6400e+04,50,50,50);
883   AliTPCExB::SetInstance(exb);
884   
885   if (bdelete){
886     delete bmap;
887   }else{
888     AliTPCExB::RegisterField(index,bmap);
889   }
890   if (index>=fgExBArray.GetEntries()) fgExBArray.Expand((index+1)*2+11);
891   fgExBArray.AddAt(exb,index);
892 }
893
894
895 AliTPCExB*    AliTPCcalibDB::GetExB(Float_t bz, Bool_t deleteB) {
896   //
897   // bz filed in KGaus not in tesla
898   // Get ExB correction map
899   // if doesn't exist - create it
900   //
901   Int_t index = TMath::Nint(5+bz);
902   if (index>fgExBArray.GetEntries()) fgExBArray.Expand((index+1)*2+11);
903   if (!fgExBArray.At(index)) AliTPCcalibDB::RegisterExB(index,bz,deleteB);
904   return (AliTPCExB*)fgExBArray.At(index);
905 }
906
907
908 void  AliTPCcalibDB::SetExBField(Float_t bz){
909   //
910   // Set magnetic filed for ExB correction
911   //
912   fExB = GetExB(bz,kFALSE);
913 }
914
915 void  AliTPCcalibDB::SetExBField(const AliMagF*   bmap){
916   //
917   // Set magnetic field for ExB correction
918   //
919   AliTPCExBFirst *exb  = new  AliTPCExBFirst(bmap,0.88*2.6400e+04,50,50,50);
920   AliTPCExB::SetInstance(exb);
921   fExB=exb;
922 }
923
924
925
926
927
928 void AliTPCcalibDB::UpdateRunInformations( Int_t run, Bool_t force){
929   //
930   // - > Don't use it for reconstruction - Only for Calibration studies
931   //
932   if (run<=0) return;
933   fRun=run;
934   AliCDBEntry * entry = 0;
935   if (run>= fRunList.fN){
936     fRunList.Set(run*2+1);
937     fGRPArray.Expand(run*2+1);
938     fGRPMaps.Expand(run*2+1);
939     fGoofieArray.Expand(run*2+1);
940     fVoltageArray.Expand(run*2+1); 
941     fTemperatureArray.Expand(run*2+1);
942     fVdriftArray.Expand(run*2+1);
943     fDriftCorrectionArray.Expand(run*2+1);
944     fTimeGainSplinesArray.Expand(run*2+1);
945     //
946     //
947     fALTROConfigData->Expand(run*2+1);    // ALTRO configuration data
948     fPulserData->Expand(run*2+1);         // Calibration Pulser data
949     fCEData->Expand(run*2+1);             // CE data
950     if (!fTimeGainSplines) fTimeGainSplines = new TObjArray(run*2+1);
951     fTimeGainSplines->Expand(run*2+1); // Array of AliSplineFits: at 0 MIP position in
952   }
953   if (fRunList[run]>0 &&force==kFALSE) return;
954
955   fRunList[run]=1;  // sign as used
956
957   //
958   entry = AliCDBManager::Instance()->Get("GRP/GRP/Data",run);
959   if (entry)  {
960     AliGRPObject * grpRun = dynamic_cast<AliGRPObject*>(entry->GetObject());
961     if (!grpRun){
962       TMap* map = dynamic_cast<TMap*>(entry->GetObject());
963       if (map){
964         //grpRun = new AliGRPObject; 
965         //grpRun->ReadValuesFromMap(map);
966         grpRun =  MakeGRPObjectFromMap(map);
967
968         fGRPMaps.AddAt(map,run);
969       }
970     }
971     fGRPArray.AddAt(grpRun,run);
972   }
973   entry = AliCDBManager::Instance()->Get("TPC/Calib/Goofie",run);
974   if (entry){
975     fGoofieArray.AddAt(entry->GetObject(),run);
976   }
977   //
978   
979   //
980   entry = AliCDBManager::Instance()->Get("TPC/Calib/TimeGain",run);
981   if (entry)  {
982     fTimeGainSplinesArray.AddAt(entry->GetObject(),run);
983   }else{
984     AliFatal("TPC - Missing calibration entry TimeGain");
985   }
986   //
987   entry = AliCDBManager::Instance()->Get("TPC/Calib/TimeDrift",run);
988   if (entry)  {
989     TObjArray * timeArray = (TObjArray*)entry->GetObject();    
990     fDriftCorrectionArray.AddAt(entry->GetObject(),run);  
991     AliTPCCorrection * correctionTime = (AliTPCCorrection *)timeArray->FindObject("FitCorrectionTime");
992     if (correctionTime && fComposedCorrectionArray){
993       correctionTime->Init();
994       if (fComposedCorrectionArray->GetEntriesFast()<4) fComposedCorrectionArray->Expand(40);
995       fComposedCorrectionArray->AddAt(correctionTime,4); //add time dependent correction to the list of available corrections
996     }
997   }else{
998     AliFatal("TPC - Missing calibration entry TimeDrift");
999   }
1000   //
1001   entry = AliCDBManager::Instance()->Get("TPC/Calib/Temperature",run);
1002   if (entry)  {
1003     fTemperatureArray.AddAt(entry->GetObject(),run);
1004   }
1005   //apply fDButil filters
1006
1007   fDButil->UpdateFromCalibDB();
1008   if (fTemperature) fDButil->FilterTemperature(fTemperature);
1009
1010   AliDCSSensor * press = GetPressureSensor(run,0);
1011   AliTPCSensorTempArray * temp = GetTemperatureSensor(run);
1012   Bool_t accept=kTRUE;
1013   if (temp) {
1014     accept = fDButil->FilterTemperature(temp)>0.1;
1015   }
1016   if (press) {
1017     const Double_t kMinP=900.;
1018     const Double_t kMaxP=1050.;
1019     const Double_t kMaxdP=10.;
1020     const Double_t kSigmaCut=4.;
1021     fDButil->FilterSensor(press,kMinP,kMaxP,kMaxdP,kSigmaCut);
1022     if (press->GetFit()==0) accept=kFALSE;
1023   }
1024
1025   if (press && temp &&accept){
1026     AliTPCCalibVdrift * vdrift = new AliTPCCalibVdrift(temp, press,0);
1027     fVdriftArray.AddAt(vdrift,run);
1028   }
1029
1030   fDButil->FilterCE(120., 3., 4.,0);
1031   fDButil->FilterTracks(run, 10.,0);
1032
1033 }
1034
1035
1036 Float_t AliTPCcalibDB::GetGain(Int_t sector, Int_t row, Int_t pad){
1037   //
1038   // Get Gain factor for given pad
1039   //
1040   AliTPCCalPad *calPad = Instance()->fDedxGainFactor;;
1041   if (!calPad) return 0;
1042   return calPad->GetCalROC(sector)->GetValue(row,pad);
1043 }
1044
1045 AliSplineFit* AliTPCcalibDB::GetVdriftSplineFit(const char* name, Int_t run){
1046   //
1047   // GetDrift velocity spline fit
1048   //
1049   TObjArray *arr=GetTimeVdriftSplineRun(run);
1050   if (!arr) return 0;
1051   return dynamic_cast<AliSplineFit*>(arr->FindObject(name));
1052 }
1053
1054 AliSplineFit* AliTPCcalibDB::CreateVdriftSplineFit(const char* graphName, Int_t run){
1055   //
1056   // create spline fit from the drift time graph in TimeDrift
1057   //
1058   TObjArray *arr=GetTimeVdriftSplineRun(run);
1059   if (!arr) return 0;
1060   TGraph *graph=dynamic_cast<TGraph*>(arr->FindObject(graphName));
1061   if (!graph) return 0;
1062   AliSplineFit *fit = new AliSplineFit();
1063   fit->SetGraph(graph);
1064   fit->SetMinPoints(graph->GetN()+1);
1065   fit->InitKnots(graph,2,0,0.001);
1066   fit->SplineFit(0);
1067   return fit;
1068 }
1069
1070 AliGRPObject *AliTPCcalibDB::GetGRP(Int_t run){
1071   //
1072   // Get GRP object for given run 
1073   //
1074   if (run>= ((Instance()->fGRPArray)).GetEntriesFast()){
1075     Instance()->UpdateRunInformations(run);    
1076   }
1077   AliGRPObject * grpRun = dynamic_cast<AliGRPObject *>((Instance()->fGRPArray).At(run));
1078   if (!grpRun) {
1079     Instance()->UpdateRunInformations(run);
1080     grpRun = dynamic_cast<AliGRPObject *>(Instance()->fGRPArray.At(run));
1081     if (!grpRun) return 0; 
1082   }
1083   return grpRun;
1084 }
1085
1086 TMap *  AliTPCcalibDB::GetGRPMap(Int_t run){
1087   //
1088   // Get GRP map for given run
1089   //
1090   TMap * grpRun = dynamic_cast<TMap *>((Instance()->fGRPMaps).At(run));
1091   if (!grpRun) {
1092     Instance()->UpdateRunInformations(run);
1093     grpRun = dynamic_cast<TMap *>(Instance()->fGRPMaps.At(run));
1094     if (!grpRun) return 0; 
1095   }
1096   return grpRun;
1097 }
1098
1099
1100 AliDCSSensor * AliTPCcalibDB::GetPressureSensor(Int_t run, Int_t type){
1101   //
1102   // Get Pressure sensor
1103   // run  = run number
1104   // type = 0 - Cavern pressure
1105   //        1 - Suface pressure
1106   // First try to get if trom map - if existing  (Old format of data storing)
1107   //
1108
1109
1110   TMap *map = GetGRPMap(run);  
1111   if (map){
1112     AliDCSSensor * sensor = 0;
1113     TObject *osensor=0;
1114     if (type==0) osensor = ((*map)("fCavernPressure"));
1115     if (type==1) osensor = ((*map)("fP2Pressure"));
1116     sensor =dynamic_cast<AliDCSSensor *>(osensor); 
1117     if (sensor) return sensor;
1118   }
1119   //
1120   // If not map try to get it from the GRPObject
1121   //
1122   AliGRPObject * grpRun = dynamic_cast<AliGRPObject *>(fGRPArray.At(run)); 
1123   if (!grpRun) {
1124     UpdateRunInformations(run);
1125     grpRun = dynamic_cast<AliGRPObject *>(fGRPArray.At(run));
1126     if (!grpRun) return 0; 
1127   }
1128   AliDCSSensor * sensor = grpRun->GetCavernAtmosPressure();
1129   if (type==1) sensor = grpRun->GetSurfaceAtmosPressure();
1130   return sensor; 
1131 }
1132
1133 AliTPCSensorTempArray * AliTPCcalibDB::GetTemperatureSensor(Int_t run){
1134   //
1135   // Get temperature sensor array
1136   //
1137   AliTPCSensorTempArray * tempArray = (AliTPCSensorTempArray *)fTemperatureArray.At(run);
1138   if (!tempArray) {
1139     UpdateRunInformations(run);
1140     tempArray = (AliTPCSensorTempArray *)fTemperatureArray.At(run);
1141   }
1142   return tempArray;
1143 }
1144
1145
1146 TObjArray * AliTPCcalibDB::GetTimeGainSplinesRun(Int_t run){
1147   //
1148   // Get temperature sensor array
1149   //
1150   TObjArray * gainSplines = (TObjArray *)fTimeGainSplinesArray.At(run);
1151   if (!gainSplines) {
1152     UpdateRunInformations(run);
1153     gainSplines = (TObjArray *)fTimeGainSplinesArray.At(run);
1154   }
1155   return gainSplines;
1156 }
1157
1158 TObjArray * AliTPCcalibDB::GetTimeVdriftSplineRun(Int_t run){
1159   //
1160   // Get drift spline array
1161   //
1162   TObjArray * driftSplines = (TObjArray *)fDriftCorrectionArray.At(run);
1163   if (!driftSplines) {
1164     UpdateRunInformations(run);
1165     driftSplines = (TObjArray *)fDriftCorrectionArray.At(run);
1166   }
1167   return driftSplines;
1168 }
1169
1170 AliDCSSensorArray * AliTPCcalibDB::GetVoltageSensors(Int_t run){
1171   //
1172   // Get temperature sensor array
1173   //
1174   AliDCSSensorArray * voltageArray = (AliDCSSensorArray *)fVoltageArray.At(run);
1175   if (!voltageArray) {
1176     UpdateRunInformations(run);
1177     voltageArray = (AliDCSSensorArray *)fVoltageArray.At(run);
1178   }
1179   return voltageArray;
1180 }
1181
1182 AliDCSSensorArray * AliTPCcalibDB::GetGoofieSensors(Int_t run){
1183   //
1184   // Get temperature sensor array
1185   //
1186   AliDCSSensorArray * goofieArray = (AliDCSSensorArray *)fGoofieArray.At(run);
1187   if (!goofieArray) {
1188     UpdateRunInformations(run);
1189     goofieArray = (AliDCSSensorArray *)fGoofieArray.At(run);
1190   }
1191   return goofieArray;
1192 }
1193
1194
1195
1196 AliTPCCalibVdrift *     AliTPCcalibDB::GetVdrift(Int_t run){
1197   //
1198   // Get the interface to the the vdrift 
1199   //
1200   if (run>=fVdriftArray.GetEntriesFast())  UpdateRunInformations(run);
1201   AliTPCCalibVdrift  * vdrift = (AliTPCCalibVdrift*)fVdriftArray.At(run);
1202   if (!vdrift) {
1203     UpdateRunInformations(run);
1204     vdrift= (AliTPCCalibVdrift*)fVdriftArray.At(run);
1205   }
1206   return vdrift;
1207 }
1208
1209 Float_t AliTPCcalibDB::GetCEdriftTime(Int_t run, Int_t sector, Double_t timeStamp, Int_t *entries)
1210 {
1211   //
1212   // GetCE drift time information for 'sector'
1213   // sector 72 is the mean drift time of the A-Side
1214   // sector 73 is the mean drift time of the C-Side
1215   // it timestamp==-1 return mean value
1216   //
1217   AliTPCcalibDB::Instance()->SetRun(run);
1218   TGraph *gr=AliTPCcalibDB::Instance()->GetCErocTgraph(sector);
1219   if (!gr||sector<0||sector>73) {
1220     if (entries) *entries=0;
1221     return 0.;
1222   }
1223   Float_t val=0.;
1224   if (timeStamp==-1.){
1225     val=gr->GetMean(2);
1226   }else{
1227     for (Int_t ipoint=0;ipoint<gr->GetN();++ipoint){
1228       Double_t x,y;
1229       gr->GetPoint(ipoint,x,y);
1230       if (x<timeStamp) continue;
1231       val=y;
1232       break;
1233     }
1234   }
1235   return val;
1236 }
1237   
1238 Float_t AliTPCcalibDB::GetCEchargeTime(Int_t run, Int_t sector, Double_t timeStamp, Int_t *entries)
1239 {
1240   //
1241   // GetCE mean charge for 'sector'
1242   // it timestamp==-1 return mean value
1243   //
1244   AliTPCcalibDB::Instance()->SetRun(run);
1245   TGraph *gr=AliTPCcalibDB::Instance()->GetCErocQgraph(sector);
1246   if (!gr||sector<0||sector>71) {
1247     if (entries) *entries=0;
1248     return 0.;
1249   }
1250   Float_t val=0.;
1251   if (timeStamp==-1.){
1252     val=gr->GetMean(2);
1253   }else{
1254     for (Int_t ipoint=0;ipoint<gr->GetN();++ipoint){
1255       Double_t x,y;
1256       gr->GetPoint(ipoint,x,y);
1257       if (x<timeStamp) continue;
1258       val=y;
1259       break;
1260     }
1261   }
1262   return val;
1263 }
1264
1265 Float_t AliTPCcalibDB::GetDCSSensorValue(AliDCSSensorArray *arr, Int_t timeStamp, const char * sensorName, Int_t sigDigits)
1266 {
1267   //
1268   // Get Value for a DCS sensor 'sensorName', run 'run' at time 'timeStamp'
1269   //
1270   Float_t val=0;
1271   const TString sensorNameString(sensorName);
1272   AliDCSSensor *sensor = arr->GetSensor(sensorNameString);
1273   if (!sensor) return val;
1274   //use the dcs graph if possible
1275   TGraph *gr=sensor->GetGraph();
1276   if (gr){
1277     for (Int_t ipoint=0;ipoint<gr->GetN();++ipoint){
1278       Double_t x,y;
1279       gr->GetPoint(ipoint,x,y);
1280       Int_t time=TMath::Nint(sensor->GetStartTime()+x*3600); //time in graph is hours
1281       if (time<timeStamp) continue;
1282       val=y;
1283       break;
1284     }
1285     //if val is still 0, test if if the requested time if within 5min of the first/last
1286     //data point. If this is the case return the firs/last entry
1287     //the timestamps might not be syncronised for all calibration types, sometimes a 'pre'
1288     //and 'pos' period is requested. Especially to the HV this is not the case!
1289     //first point
1290     if (val==0 ){
1291       Double_t x,y;
1292       gr->GetPoint(0,x,y);
1293       Int_t time=TMath::Nint(sensor->GetStartTime()+x*3600); //time in graph is hours
1294       if ((time-timeStamp)<5*60) val=y;
1295     }
1296     //last point
1297     if (val==0 ){
1298       Double_t x,y;
1299       gr->GetPoint(gr->GetN()-1,x,y);
1300       Int_t time=TMath::Nint(sensor->GetStartTime()+x*3600); //time in graph is hours
1301       if ((timeStamp-time)<5*60) val=y;
1302     }
1303   } else {
1304     val=sensor->GetValue(timeStamp);
1305   }
1306   if (sigDigits>=0){
1307     val=(Float_t)TMath::Floor(val * TMath::Power(10., sigDigits) + .5) / TMath::Power(10., sigDigits);
1308   }
1309   return val;
1310 }
1311
1312 Float_t AliTPCcalibDB::GetDCSSensorMeanValue(AliDCSSensorArray *arr, const char * sensorName, Int_t sigDigits)
1313 {
1314   //
1315   // Get mean Value for a DCS sensor 'sensorName' during run 'run'
1316   //
1317   Float_t val=0;
1318   const TString sensorNameString(sensorName);
1319   AliDCSSensor *sensor = arr->GetSensor(sensorNameString);
1320   if (!sensor) return val;
1321
1322   //use dcs graph if it exists
1323   TGraph *gr=sensor->GetGraph();
1324   if (gr){
1325     val=gr->GetMean(2);
1326   } else {
1327     //if we don't have the dcs graph, try to get some meaningful information
1328     if (!sensor->GetFit()) return val;
1329     Int_t nKnots=sensor->GetFit()->GetKnots();
1330     Double_t tMid=(sensor->GetEndTime()-sensor->GetStartTime())/2.;
1331     for (Int_t iKnot=0;iKnot<nKnots;++iKnot){
1332       if (sensor->GetFit()->GetX()[iKnot]>tMid/3600.) break;
1333       val=(Float_t)sensor->GetFit()->GetY0()[iKnot];
1334     }
1335   }
1336   if (sigDigits>=0){
1337     // val/=10;
1338     val=(Float_t)TMath::Floor(val * TMath::Power(10., sigDigits) + .5) / TMath::Power(10., sigDigits);
1339     //    val*=10;
1340   }
1341   return val;
1342 }
1343
1344 Float_t AliTPCcalibDB::GetChamberHighVoltage(Int_t run, Int_t sector, Int_t timeStamp, Int_t sigDigits, Bool_t current) {
1345   //
1346   // return the chamber HV for given run and time: 0-35 IROC, 36-72 OROC
1347   // if timeStamp==-1 return mean value
1348   //
1349   Float_t val=0;
1350   TString sensorName="";
1351   TTimeStamp stamp(timeStamp);
1352   AliDCSSensorArray* voltageArray = AliTPCcalibDB::Instance()->GetVoltageSensors(run);
1353   if (!voltageArray || (sector<0) || (sector>71)) return val;
1354   Char_t sideName='A';
1355   if ((sector/18)%2==1) sideName='C';
1356   if (sector<36){
1357     //IROC
1358     sensorName=Form("TPC_ANODE_I_%c%02d_VMEAS",sideName,sector%18);
1359   }else{
1360     //OROC
1361     sensorName=Form("TPC_ANODE_O_%c%02d_0_VMEAS",sideName,sector%18);
1362   }
1363   if (current){
1364     if (sector<36){
1365       //IROC
1366       sensorName=Form("TPC_ANODE_I_%c%02d_IMEAS",sideName,sector%18);
1367   }else{
1368       //OROC
1369       sensorName=Form("TPC_ANODE_O_%c%02d_0_IMEAS",sideName,sector%18);
1370     }
1371
1372   }
1373   if (timeStamp==-1){
1374     val=AliTPCcalibDB::GetDCSSensorMeanValue(voltageArray, sensorName.Data(),sigDigits);
1375   } else {
1376     val=AliTPCcalibDB::GetDCSSensorValue(voltageArray, timeStamp, sensorName.Data(),sigDigits);
1377   }
1378   return val;
1379 }
1380 Float_t AliTPCcalibDB::GetSkirtVoltage(Int_t run, Int_t sector, Int_t timeStamp, Int_t sigDigits)
1381 {
1382   //
1383   // Get the skirt voltage for 'run' at 'timeStamp' and 'sector': 0-35 IROC, 36-72 OROC
1384   // type corresponds to the following: 0 - IROC A-Side; 1 - IROC C-Side; 2 - OROC A-Side; 3 - OROC C-Side
1385   // if timeStamp==-1 return the mean value for the run
1386   //
1387   Float_t val=0;
1388   TString sensorName="";
1389   TTimeStamp stamp(timeStamp);
1390   AliDCSSensorArray* voltageArray = AliTPCcalibDB::Instance()->GetVoltageSensors(run);
1391   if (!voltageArray || (sector<0) || (sector>71)) return val;
1392   Char_t sideName='A';
1393   if ((sector/18)%2==1) sideName='C';
1394   sensorName=Form("TPC_SKIRT_%c_VMEAS",sideName);
1395   if (timeStamp==-1){
1396     val=AliTPCcalibDB::GetDCSSensorMeanValue(voltageArray, sensorName.Data(),sigDigits);
1397   } else {
1398     val=AliTPCcalibDB::GetDCSSensorValue(voltageArray, timeStamp, sensorName.Data(),sigDigits);
1399   }
1400   return val;
1401 }
1402
1403 Float_t AliTPCcalibDB::GetCoverVoltage(Int_t run, Int_t sector, Int_t timeStamp, Int_t sigDigits)
1404 {
1405   //
1406   // Get the cover voltage for run 'run' at time 'timeStamp'
1407   // type corresponds to the following: 0 - IROC A-Side; 1 - IROC C-Side; 2 - OROC A-Side; 3 - OROC C-Side
1408   // if timeStamp==-1 return the mean value for the run
1409   //
1410   Float_t val=0;
1411   TString sensorName="";
1412   TTimeStamp stamp(timeStamp);
1413   AliDCSSensorArray* voltageArray = AliTPCcalibDB::Instance()->GetVoltageSensors(run);
1414   if (!voltageArray || (sector<0) || (sector>71)) return val;
1415   Char_t sideName='A';
1416   if ((sector/18)%2==1) sideName='C';
1417   if (sector<36){
1418     //IROC
1419     sensorName=Form("TPC_COVER_I_%c_VMEAS",sideName);
1420   }else{
1421     //OROC
1422     sensorName=Form("TPC_COVER_O_%c_VMEAS",sideName);
1423   }
1424   if (timeStamp==-1){
1425     val=AliTPCcalibDB::GetDCSSensorMeanValue(voltageArray, sensorName.Data(),sigDigits);
1426   } else {
1427     val=AliTPCcalibDB::GetDCSSensorValue(voltageArray, timeStamp, sensorName.Data(),sigDigits);
1428   }
1429   return val;
1430 }
1431
1432 Float_t AliTPCcalibDB::GetGGoffsetVoltage(Int_t run, Int_t sector, Int_t timeStamp, Int_t sigDigits)
1433 {
1434   //
1435   // Get the GG offset voltage for run 'run' at time 'timeStamp'
1436   // type corresponds to the following: 0 - IROC A-Side; 1 - IROC C-Side; 2 - OROC A-Side; 3 - OROC C-Side
1437   // if timeStamp==-1 return the mean value for the run
1438   //
1439   Float_t val=0;
1440   TString sensorName="";
1441   TTimeStamp stamp(timeStamp);
1442   AliDCSSensorArray* voltageArray = AliTPCcalibDB::Instance()->GetVoltageSensors(run);
1443   if (!voltageArray || (sector<0) || (sector>71)) return val;
1444   Char_t sideName='A';
1445   if ((sector/18)%2==1) sideName='C';
1446   if (sector<36){
1447     //IROC
1448     sensorName=Form("TPC_GATE_I_%c_OFF_VMEAS",sideName);
1449   }else{
1450     //OROC
1451     sensorName=Form("TPC_GATE_O_%c_OFF_VMEAS",sideName);
1452   }
1453   if (timeStamp==-1){
1454     val=AliTPCcalibDB::GetDCSSensorMeanValue(voltageArray, sensorName.Data(),sigDigits);
1455   } else {
1456     val=AliTPCcalibDB::GetDCSSensorValue(voltageArray, timeStamp, sensorName.Data(),sigDigits);
1457   }
1458   return val;
1459 }
1460
1461 Float_t AliTPCcalibDB::GetGGnegVoltage(Int_t run, Int_t sector, Int_t timeStamp, Int_t sigDigits)
1462 {
1463   //
1464   // Get the GG offset voltage for run 'run' at time 'timeStamp'
1465   // type corresponds to the following: 0 - IROC A-Side; 1 - IROC C-Side; 2 - OROC A-Side; 3 - OROC C-Side
1466   // if timeStamp==-1 return the mean value for the run
1467   //
1468   Float_t val=0;
1469   TString sensorName="";
1470   TTimeStamp stamp(timeStamp);
1471   AliDCSSensorArray* voltageArray = AliTPCcalibDB::Instance()->GetVoltageSensors(run);
1472   if (!voltageArray || (sector<0) || (sector>71)) return val;
1473   Char_t sideName='A';
1474   if ((sector/18)%2==1) sideName='C';
1475   if (sector<36){
1476     //IROC
1477     sensorName=Form("TPC_GATE_I_%c_NEG_VMEAS",sideName);
1478   }else{
1479     //OROC
1480     sensorName=Form("TPC_GATE_O_%c_NEG_VMEAS",sideName);
1481   }
1482   if (timeStamp==-1){
1483     val=AliTPCcalibDB::GetDCSSensorMeanValue(voltageArray, sensorName.Data(),sigDigits);
1484   } else {
1485     val=AliTPCcalibDB::GetDCSSensorValue(voltageArray, timeStamp, sensorName.Data(),sigDigits);
1486   }
1487   return val;
1488 }
1489
1490 Float_t AliTPCcalibDB::GetGGposVoltage(Int_t run, Int_t sector, Int_t timeStamp, Int_t sigDigits)
1491 {
1492   //
1493   // Get the GG offset voltage for run 'run' at time 'timeStamp'
1494   // type corresponds to the following: 0 - IROC A-Side; 1 - IROC C-Side; 2 - OROC A-Side; 3 - OROC C-Side
1495   // if timeStamp==-1 return the mean value for the run
1496   //
1497   Float_t val=0;
1498   TString sensorName="";
1499   TTimeStamp stamp(timeStamp);
1500   AliDCSSensorArray* voltageArray = AliTPCcalibDB::Instance()->GetVoltageSensors(run);
1501   if (!voltageArray || (sector<0) || (sector>71)) return val;
1502   Char_t sideName='A';
1503   if ((sector/18)%2==1) sideName='C';
1504   if (sector<36){
1505     //IROC
1506     sensorName=Form("TPC_GATE_I_%c_POS_VMEAS",sideName);
1507   }else{
1508     //OROC
1509     sensorName=Form("TPC_GATE_O_%c_POS_VMEAS",sideName);
1510   }
1511   if (timeStamp==-1){
1512     val=AliTPCcalibDB::GetDCSSensorMeanValue(voltageArray, sensorName.Data(),sigDigits);
1513   } else {
1514     val=AliTPCcalibDB::GetDCSSensorValue(voltageArray, timeStamp, sensorName.Data(),sigDigits);
1515   }
1516   return val;
1517 }
1518
1519 Float_t AliTPCcalibDB::GetPressure(Int_t timeStamp, Int_t run, Int_t type){
1520   //
1521   // GetPressure for given time stamp and runt
1522   //
1523   TTimeStamp stamp(timeStamp);
1524   AliDCSSensor * sensor = Instance()->GetPressureSensor(run,type);
1525   if (!sensor) return 0;
1526   return sensor->GetValue(stamp);
1527 }
1528
1529 Float_t AliTPCcalibDB::GetL3Current(Int_t run, Int_t statType){
1530   //
1531   // return L3 current
1532   // stat type is: AliGRPObject::Stats: kMean = 0, kTruncMean = 1, kMedian = 2, kSDMean = 3, kSDMedian = 4
1533   //
1534   Float_t current=-1;
1535   AliGRPObject *grp=AliTPCcalibDB::GetGRP(run);
1536   if (grp) current=grp->GetL3Current((AliGRPObject::Stats)statType);
1537   return current;
1538 }
1539
1540 Float_t AliTPCcalibDB::GetBz(Int_t run){
1541   //
1542   // calculate BZ in T from L3 current
1543   //
1544   Float_t bz=-1;
1545   Float_t current=AliTPCcalibDB::GetL3Current(run);
1546   if (current>-1) bz=5*current/30000.*.1;
1547   return bz;
1548 }
1549
1550 Char_t  AliTPCcalibDB::GetL3Polarity(Int_t run) {
1551   //
1552   // get l3 polarity from GRP
1553   //
1554   Char_t pol=-100;
1555   AliGRPObject *grp=AliTPCcalibDB::GetGRP(run);
1556   if (grp) pol=grp->GetL3Polarity();
1557   return pol;
1558 }
1559
1560 TString AliTPCcalibDB::GetRunType(Int_t run){
1561   //
1562   // return run type from grp
1563   //
1564
1565 //   TString type("UNKNOWN");
1566   AliGRPObject *grp=AliTPCcalibDB::GetGRP(run);
1567   if (grp) return grp->GetRunType();
1568   return "UNKNOWN";
1569 }
1570
1571 Float_t AliTPCcalibDB::GetValueGoofie(Int_t timeStamp, Int_t run, Int_t type){
1572   //
1573   // GetPressure for given time stamp and runt
1574   //
1575   TTimeStamp stamp(timeStamp);
1576   AliDCSSensorArray* goofieArray = AliTPCcalibDB::Instance()->GetGoofieSensors(run);
1577   if (!goofieArray) return 0;
1578   AliDCSSensor *sensor = goofieArray->GetSensor(type);
1579   return sensor->GetValue(stamp);
1580 }
1581
1582
1583
1584
1585
1586
1587 Bool_t  AliTPCcalibDB::GetTemperatureFit(Int_t timeStamp, Int_t run, Int_t side,TVectorD& fit){
1588   //
1589   // GetTmeparature fit at parameter for given time stamp
1590   //
1591   TTimeStamp tstamp(timeStamp);
1592   AliTPCSensorTempArray* tempArray  = Instance()->GetTemperatureSensor(run);
1593   if (! tempArray) return kFALSE;
1594   AliTPCTempMap * tempMap = new AliTPCTempMap(tempArray);
1595   TLinearFitter * fitter = tempMap->GetLinearFitter(3,side,tstamp);
1596   if (fitter){
1597     fitter->Eval(); 
1598     fitter->GetParameters(fit);
1599   }
1600   delete fitter;
1601   delete tempMap;
1602   if (!fitter) return kFALSE;
1603   return kTRUE;
1604 }
1605
1606 Float_t AliTPCcalibDB::GetTemperature(Int_t timeStamp, Int_t run, Int_t side){
1607   //
1608   // Get mean temperature
1609   // 
1610   TVectorD vec(5);
1611   if (side==0) {
1612     GetTemperatureFit(timeStamp,run,0,vec);
1613     return vec[0];
1614   }
1615   if (side==1){
1616     GetTemperatureFit(timeStamp,run,0,vec);
1617     return vec[0];
1618   }
1619   return 0;
1620 }
1621
1622
1623 Double_t AliTPCcalibDB::GetPTRelative(UInt_t timeSec, Int_t run, Int_t side){
1624   //
1625   // Get relative P/T 
1626   // time - absolute time
1627   // run  - run number
1628   // side - 0 - A side   1-C side
1629   AliTPCCalibVdrift * vdrift =  Instance()->GetVdrift(run);
1630   if (!vdrift) return 0;
1631   return vdrift->GetPTRelative(timeSec,side);
1632 }
1633
1634 AliGRPObject * AliTPCcalibDB::MakeGRPObjectFromMap(TMap *map){
1635   //
1636   // Function to covert old GRP run information from TMap to GRPObject
1637   //
1638   //  TMap * map = AliTPCcalibDB::GetGRPMap(52406);
1639   if (!map) return 0;
1640   AliDCSSensor * sensor = 0;
1641   TObject *osensor=0;
1642   osensor = ((*map)("fP2Pressure"));
1643   sensor  =dynamic_cast<AliDCSSensor *>(osensor); 
1644   //
1645   if (!sensor) return 0;
1646   //
1647   AliDCSSensor * sensor2 = new AliDCSSensor(*sensor);
1648   osensor = ((*map)("fCavernPressure"));
1649   TGraph * gr = new TGraph(2);
1650   gr->GetX()[0]= -100000.;
1651   gr->GetX()[1]= 1000000.;
1652   gr->GetY()[0]= atof(osensor->GetName());
1653   gr->GetY()[1]= atof(osensor->GetName());
1654   sensor2->SetGraph(gr);
1655   sensor2->SetFit(0);
1656   
1657
1658   AliGRPObject *grpRun = new AliGRPObject; 
1659   grpRun->ReadValuesFromMap(map);
1660   grpRun->SetCavernAtmosPressure(sensor2);
1661   grpRun->SetCavernAtmosPressure(sensor2);
1662   grpRun->SetSurfaceAtmosPressure(sensor);
1663   return grpRun;
1664 }
1665
1666 Bool_t AliTPCcalibDB::CreateGUITree(Int_t run, const char* filename)
1667 {
1668   //
1669   // Create a gui tree for run number 'run'
1670   //
1671
1672   if (!AliCDBManager::Instance()->GetDefaultStorage()){
1673     AliLog::Message(AliLog::kError, "Default Storage not set. Cannot create Calibration Tree!",
1674                     MODULENAME(), "AliTPCcalibDB", FUNCTIONNAME(), __FILE__, __LINE__);
1675     return kFALSE;
1676   }
1677   //db instance
1678   AliTPCcalibDB *db=AliTPCcalibDB::Instance();
1679   // retrieve cal pad objects
1680   db->SetRun(run);
1681   db->CreateGUITree(filename);
1682   return kTRUE;
1683 }
1684
1685 Bool_t AliTPCcalibDB::CreateGUITree(const char* filename){
1686   //
1687   //
1688   //
1689   if (!AliCDBManager::Instance()->GetDefaultStorage()){
1690     AliError("Default Storage not set. Cannot create calibration Tree!");
1691     return kFALSE;
1692   }
1693   UpdateNonRec();  // load all infromation now
1694
1695   AliTPCPreprocessorOnline prep;
1696   //noise and pedestals
1697   if (GetPedestals()) prep.AddComponent(new AliTPCCalPad(*(GetPedestals())));
1698   if (GetPadNoise() ) prep.AddComponent(new AliTPCCalPad(*(GetPadNoise())));
1699   //pulser data
1700   if (GetPulserTmean()) prep.AddComponent(new AliTPCCalPad(*(GetPulserTmean())));
1701   if (GetPulserTrms() ) prep.AddComponent(new AliTPCCalPad(*(GetPulserTrms())));
1702   if (GetPulserQmean()) prep.AddComponent(new AliTPCCalPad(*(GetPulserQmean())));
1703   //CE data
1704   if (GetCETmean()) prep.AddComponent(new AliTPCCalPad(*(GetCETmean())));
1705   if (GetCETrms() ) prep.AddComponent(new AliTPCCalPad(*(GetCETrms())));
1706   if (GetCEQmean()) prep.AddComponent(new AliTPCCalPad(*(GetCEQmean())));
1707   //Altro data
1708   if (GetALTROAcqStart() ) prep.AddComponent(new AliTPCCalPad(*(GetALTROAcqStart() )));
1709   if (GetALTROZsThr()    ) prep.AddComponent(new AliTPCCalPad(*(GetALTROZsThr()    )));
1710   if (GetALTROFPED()     ) prep.AddComponent(new AliTPCCalPad(*(GetALTROFPED()     )));
1711   if (GetALTROAcqStop()  ) prep.AddComponent(new AliTPCCalPad(*(GetALTROAcqStop()  )));
1712   if (GetALTROMasked()   ) prep.AddComponent(new AliTPCCalPad(*(GetALTROMasked()   )));
1713   //QA
1714   AliTPCdataQA *dataQA=GetDataQA();
1715   if (dataQA) {
1716     if (dataQA->GetNLocalMaxima())
1717       prep.AddComponent(new AliTPCCalPad(*(dataQA->GetNLocalMaxima())));
1718     if (dataQA->GetMaxCharge())
1719       prep.AddComponent(new AliTPCCalPad(*(dataQA->GetMaxCharge())));
1720     if (dataQA->GetMeanCharge())
1721       prep.AddComponent(new AliTPCCalPad(*(dataQA->GetMeanCharge())));
1722     if (dataQA->GetNoThreshold())
1723       prep.AddComponent(new AliTPCCalPad(*(dataQA->GetNoThreshold())));
1724     if (dataQA->GetNTimeBins())
1725       prep.AddComponent(new AliTPCCalPad(*(dataQA->GetNTimeBins())));
1726     if (dataQA->GetNPads())
1727       prep.AddComponent(new AliTPCCalPad(*(dataQA->GetNPads())));
1728     if (dataQA->GetTimePosition())
1729       prep.AddComponent(new AliTPCCalPad(*(dataQA->GetTimePosition())));
1730   }
1731   
1732   //
1733   TString file(filename);
1734   if (file.IsNull()) file=Form("guiTreeRun_%lld.root",fRun);
1735   prep.DumpToFile(file.Data());
1736   return kTRUE;
1737 }
1738
1739 Bool_t AliTPCcalibDB::CreateRefFile(Int_t run, const char* filename)
1740 {
1741   //
1742   // Create a gui tree for run number 'run'
1743   //
1744   
1745   if (!AliCDBManager::Instance()->GetDefaultStorage()){
1746     AliLog::Message(AliLog::kError, "Default Storage not set. Cannot create Calibration Tree!",
1747                     MODULENAME(), "AliTPCcalibDB", FUNCTIONNAME(), __FILE__, __LINE__);
1748     return kFALSE;
1749   }
1750   TString file(filename);
1751   if (file.IsNull()) file=Form("RefCalPads_%d.root",run);
1752   TDirectory *currDir=gDirectory;
1753   //db instance
1754   AliTPCcalibDB *db=AliTPCcalibDB::Instance();
1755   // retrieve cal pad objects
1756   db->SetRun(run);
1757   //open file
1758   TFile f(file.Data(),"recreate");
1759   //noise and pedestals
1760   db->GetPedestals()->Write("Pedestals");
1761   db->GetPadNoise()->Write("PadNoise");
1762   //pulser data
1763   db->GetPulserTmean()->Write("PulserTmean");
1764   db->GetPulserTrms()->Write("PulserTrms");
1765   db->GetPulserQmean()->Write("PulserQmean");
1766   //CE data
1767   db->GetCETmean()->Write("CETmean");
1768   db->GetCETrms()->Write("CETrms");
1769   db->GetCEQmean()->Write("CEQmean");
1770   //Altro data
1771   db->GetALTROAcqStart() ->Write("ALTROAcqStart");
1772   db->GetALTROZsThr()    ->Write("ALTROZsThr");
1773   db->GetALTROFPED()     ->Write("ALTROFPED");
1774   db->GetALTROAcqStop()  ->Write("ALTROAcqStop");
1775   db->GetALTROMasked()   ->Write("ALTROMasked");
1776   //
1777   f.Close();
1778   currDir->cd();
1779   return kTRUE;
1780 }
1781
1782
1783
1784 Double_t AliTPCcalibDB::GetVDriftCorrectionTime(Int_t timeStamp, Int_t run, Int_t /*side*/, Int_t mode){
1785   //
1786   // Get time dependent drift velocity correction
1787   // multiplication factor        vd = vdnom *(1+vdriftcorr)
1788   // Arguments:
1789   // mode determines the algorith how to combine the Laser Track, LaserCE and physics tracks
1790   // timestamp - timestamp
1791   // run       - run number
1792   // side      - the drift velocity per side (possible for laser and CE)
1793   //
1794   // Notice - Extrapolation outside of calibration range  - using constant function
1795   //
1796   Double_t result=0;
1797   // mode 1  automatic mode - according to the distance to the valid calibration
1798   //                        -  
1799   Double_t deltaP=0,  driftP=0,      wP  = 0.;
1800   Double_t deltaITS=0,driftITS=0,    wITS= 0.;
1801   Double_t deltaLT=0, driftLT=0,     wLT = 0.;
1802   Double_t deltaCE=0, driftCE=0,     wCE = 0.;
1803   driftP  = fDButil->GetVDriftTPC(deltaP,run,timeStamp); 
1804   driftITS= fDButil->GetVDriftTPCITS(deltaITS,run,timeStamp);
1805   driftCE = fDButil->GetVDriftTPCCE(deltaCE, run,timeStamp,36000,2);
1806   driftLT = fDButil->GetVDriftTPCLaserTracks(deltaLT,run,timeStamp,36000,2);
1807   deltaITS = TMath::Abs(deltaITS);
1808   deltaP   = TMath::Abs(deltaP);
1809   deltaLT  = TMath::Abs(deltaLT);
1810   deltaCE  = TMath::Abs(deltaCE);
1811   if (mode==1) {
1812     const Double_t kEpsilon=0.00000000001;
1813     const Double_t kdeltaT=360.; // 10 minutes
1814     if(TMath::Abs(deltaITS) < 12*kdeltaT) {
1815       result = driftITS;
1816     } else {
1817     wITS  = 64.*kdeltaT/(deltaITS +kdeltaT);
1818     wLT   = 16.*kdeltaT/(deltaLT  +kdeltaT);
1819     wP    = 0. *kdeltaT/(deltaP   +kdeltaT);
1820     wCE   = 1. *kdeltaT/(deltaCE  +kdeltaT);
1821     //
1822     //
1823     if (TMath::Abs(driftP)<kEpsilon)  wP=0;  // invalid calibration
1824     if (TMath::Abs(driftITS)<kEpsilon)wITS=0;  // invalid calibration
1825     if (TMath::Abs(driftLT)<kEpsilon) wLT=0;  // invalid calibration
1826     if (TMath::Abs(driftCE)<kEpsilon) wCE=0;  // invalid calibration
1827     if (wP+wITS+wLT+wCE<kEpsilon) return 0;
1828     result = (driftP*wP+driftITS*wITS+driftLT*wLT+driftCE*wCE)/(wP+wITS+wLT+wCE);
1829    }
1830    
1831
1832   }
1833
1834   return result;
1835 }
1836
1837 Double_t AliTPCcalibDB::GetTime0CorrectionTime(Int_t timeStamp, Int_t run, Int_t /*side*/, Int_t mode){
1838   //
1839   // Get time dependent time 0 (trigger delay in cm) correction
1840   // additive correction        time0 = time0+ GetTime0CorrectionTime
1841   // Value etracted combining the vdrift correction using laser tracks and CE and the physics track matchin
1842   // Arguments:
1843   // mode determines the algorith how to combine the Laser Track and physics tracks
1844   // timestamp - timestamp
1845   // run       - run number
1846   // side      - the drift velocity per side (possible for laser and CE)
1847   //
1848   // Notice - Extrapolation outside of calibration range  - using constant function
1849   //
1850   Double_t result=0;
1851   if (mode==2) {
1852     // TPC-TPC mode
1853     result=fDButil->GetTriggerOffsetTPC(run,timeStamp);    
1854     result  *=fParam->GetZLength();
1855   }
1856   if (mode==1){
1857     // TPC-ITS mode
1858     Double_t dist=0;
1859     result= -fDButil->GetTime0TPCITS(dist, run, timeStamp)*fParam->GetDriftV()/1000000.;
1860   }
1861   return result;
1862
1863 }
1864
1865
1866
1867
1868 Double_t AliTPCcalibDB::GetVDriftCorrectionGy(Int_t timeStamp, Int_t run, Int_t side, Int_t /*mode*/){
1869   //
1870   // Get global y correction drift velocity correction factor
1871   // additive factor        vd = vdnom*(1+GetVDriftCorrectionGy *gy)
1872   // Value etracted combining the vdrift correction using laser tracks and CE or TPC-ITS
1873   // Arguments:
1874   // mode determines the algorith how to combine the Laser Track, LaserCE or TPC-ITS
1875   // timestamp - timestamp
1876   // run       - run number
1877   // side      - the drift velocity gy correction per side (CE and Laser tracks)
1878   //
1879   // Notice - Extrapolation outside of calibration range  - using constant function
1880   // 
1881   if (run<=0 && fTransform) run = fTransform->GetCurrentRunNumber();
1882   UpdateRunInformations(run,kFALSE);
1883   TObjArray *array =AliTPCcalibDB::Instance()->GetTimeVdriftSplineRun(run);
1884   if (!array) return 0;
1885   Double_t result=0;
1886
1887   // use TPC-ITS if present
1888   TGraphErrors *gr= (TGraphErrors*)array->FindObject("ALIGN_ITSB_TPC_VDGY");
1889   if(gr) { 
1890     result = AliTPCcalibDButil::EvalGraphConst(gr,timeStamp);
1891
1892     // transform from [(cm/mus)/ m] to [1/cm]
1893     result /= (fParam->GetDriftV()/1000000.);
1894     result /= 100.;
1895
1896     //printf("result %e \n", result);
1897     return result; 
1898   }
1899
1900   // use laser if ITS-TPC not present
1901   TGraphErrors *laserA= (TGraphErrors*)array->FindObject("GRAPH_MEAN_GLOBALYGRADIENT_LASER_ALL_A");
1902   TGraphErrors *laserC= (TGraphErrors*)array->FindObject("GRAPH_MEAN_GLOBALYGRADIENT_LASER_ALL_C");
1903   
1904   if (laserA && laserC){
1905    result= (laserA->Eval(timeStamp)+laserC->Eval(timeStamp))*0.5;
1906   }
1907   if (laserA && side==0){
1908     result = (laserA->Eval(timeStamp));
1909   }
1910   if (laserC &&side==1){
1911     result = (laserC->Eval(timeStamp));
1912   }
1913   //printf("laser result %e \n", -result/250.);
1914
1915   return -result/250.; //normalized before
1916 }
1917
1918 AliTPCCalPad* AliTPCcalibDB::MakeDeadMap(Double_t notInMap, const char* nameMappingFile) {
1919 //
1920 //   Read list of active DDLs from OCDB entry
1921 //   Generate and return AliTPCCalPad containing 1 for all pads in active DDLs,
1922 //   0 for all pads in non-active DDLs. 
1923 //   For DDLs with missing status information (no DCS input point to Shuttle),
1924 //     the value of the AliTPCCalPad entry is determined by the parameter
1925 //     notInMap (default value 1)
1926 //
1927   char chinfo[1000];
1928    
1929   TFile *fileMapping = new TFile(nameMappingFile, "read");
1930   AliTPCmapper *mapping = (AliTPCmapper*) fileMapping->Get("tpcMapping");
1931   if (!mapping) {
1932     snprintf(chinfo,1000,"Failed to get mapping object from %s.  ...\n", nameMappingFile);
1933     AliError (chinfo);
1934     return 0;
1935   }
1936   
1937   AliTPCCalPad *deadMap = new AliTPCCalPad("deadMap","deadMap");
1938   if (!deadMap) {
1939      AliError("Failed to allocate dead map AliTPCCalPad");
1940      return 0;
1941   }  
1942   
1943   /// get list of active DDLs from OCDB entry
1944   Int_t idDDL=0;
1945   if (!fALTROConfigData ) {
1946      AliError("No ALTRO config OCDB entry available");
1947      return 0; 
1948   }
1949   TMap *activeDDL = (TMap*)fALTROConfigData->FindObject("DDLArray");
1950   TObjString *ddlArray=0;
1951   if (activeDDL) {
1952     ddlArray = (TObjString*)activeDDL->GetValue("DDLArray");
1953     if (!ddlArray) {
1954       AliError("Empty list of active DDLs in OCDB entry");
1955       return 0;
1956     }
1957   } else { 
1958     AliError("List of active DDLs not available in OCDB entry");
1959     return 0;
1960   }
1961   TString arrDDL=ddlArray->GetString();
1962   Int_t offset = mapping->GetTpcDdlOffset();
1963   Double_t active;
1964   for (Int_t i=0; i<mapping->GetNumDdl(); i++) {
1965     idDDL= i+offset;
1966     if (idDDL<0) continue;
1967     Int_t patch = mapping->GetPatchFromEquipmentID(idDDL);   
1968     if (patch<0) continue;
1969     Int_t roc=mapping->GetRocFromEquipmentID(idDDL);
1970     if (roc<0) continue;
1971     AliTPCCalROC *calRoc=deadMap->GetCalROC(roc);
1972     if (calRoc) {
1973      for ( Int_t branch = 0; branch < 2; branch++ ) {
1974       for ( Int_t fec = 0; fec < mapping->GetNfec(patch, branch); fec++ ) {
1975         for ( Int_t altro = 0; altro < 8; altro++ ) {
1976          for ( Int_t channel = 0; channel < 16; channel++ ) {
1977            Int_t hwadd     = mapping->CodeHWAddress(branch, fec, altro, channel);
1978            Int_t row       = mapping->GetPadRow(patch, hwadd);        // row in a ROC (IROC or OROC)
1979 //              Int_t globalrow = mapping.GetGlobalPadRow(patch, hwadd);  // row in full sector (IROC plus OROC)
1980            Int_t pad       = mapping->GetPad(patch, hwadd);
1981            if (!TString(arrDDL[i]).IsDigit()) {
1982               active = notInMap;
1983            } else { 
1984               active=TString(arrDDL[i]).Atof();
1985            }
1986            calRoc->SetValue(row,pad,active);
1987          } // end channel for loop
1988         } // end altro for loop
1989       } // end fec for loop
1990      } // end branch for loop
1991     } // valid calROC 
1992    } // end loop on active DDLs
1993    return deadMap;
1994 }
1995
1996
1997
1998 AliTPCCorrection * AliTPCcalibDB::GetTPCComposedCorrection(Float_t field) const{
1999   //
2000   // GetComposed correction for given field setting
2001   // If not specific correction for field used return correction for all field
2002   //        - Complication needed to gaurantee OCDB back compatibility 
2003   //        - Not neeeded for the new space point correction 
2004   if (!fComposedCorrectionArray) return 0;
2005   if (field>0.1 && fComposedCorrectionArray->At(1)) {   
2006     return (AliTPCCorrection *)fComposedCorrectionArray->At(1);
2007   }
2008   if (field<-0.1 &&fComposedCorrectionArray->At(2)) {
2009     return (AliTPCCorrection *)fComposedCorrectionArray->At(2);
2010   }
2011   return (AliTPCCorrection *)fComposedCorrectionArray->At(0);
2012   
2013 }
2014
2015
2016 AliTPCCorrection * AliTPCcalibDB::GetTPCComposedCorrectionDelta() const{
2017   //
2018   // GetComposedCorrection delta
2019   // Delta is time dependent - taken form the CalibTime OCDB entry
2020   //
2021   if (!fComposedCorrectionArray) return 0;
2022   if (fRun<0) return 0;
2023   if (fDriftCorrectionArray.GetEntriesFast()<=fRun) return 0;
2024   if (fDriftCorrectionArray.At(fRun)==0) return 0;
2025   if (fComposedCorrectionArray->GetEntriesFast()<=4) {
2026     fComposedCorrectionArray->Expand(5);
2027     TObjArray * timeArray =(TObjArray*)(fDriftCorrectionArray.At(fRun));
2028      AliTPCCorrection * correctionTime = (AliTPCCorrection *)timeArray->FindObject("FitCorrectionTime");
2029      if (correctionTime){
2030        correctionTime->Init();
2031        fComposedCorrectionArray->AddAt(correctionTime,4); //add time dependent c
2032      }
2033   }
2034   return (AliTPCCorrection *)fComposedCorrectionArray->At(4);  //
2035 }
2036