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