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