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