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