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