]> git.uio.no Git - u/mrichter/AliRoot.git/blob - TPC/AliTPCcalibDB.cxx
Reverting back changes for the Cavern Pressure sensor 2
[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   if (run>=fVdriftArray.GetEntriesFast())  UpdateRunInformations(run);
1183   AliTPCCalibVdrift  * vdrift = (AliTPCCalibVdrift*)fVdriftArray.At(run);
1184   if (!vdrift) {
1185     UpdateRunInformations(run);
1186     vdrift= (AliTPCCalibVdrift*)fVdriftArray.At(run);
1187   }
1188   return vdrift;
1189 }
1190
1191 Float_t AliTPCcalibDB::GetCEdriftTime(Int_t run, Int_t sector, Double_t timeStamp, Int_t *entries)
1192 {
1193   //
1194   // GetCE drift time information for 'sector'
1195   // sector 72 is the mean drift time of the A-Side
1196   // sector 73 is the mean drift time of the C-Side
1197   // it timestamp==-1 return mean value
1198   //
1199   AliTPCcalibDB::Instance()->SetRun(run);
1200   TGraph *gr=AliTPCcalibDB::Instance()->GetCErocTgraph(sector);
1201   if (!gr||sector<0||sector>73) {
1202     if (entries) *entries=0;
1203     return 0.;
1204   }
1205   Float_t val=0.;
1206   if (timeStamp==-1.){
1207     val=gr->GetMean(2);
1208   }else{
1209     for (Int_t ipoint=0;ipoint<gr->GetN();++ipoint){
1210       Double_t x,y;
1211       gr->GetPoint(ipoint,x,y);
1212       if (x<timeStamp) continue;
1213       val=y;
1214       break;
1215     }
1216   }
1217   return val;
1218 }
1219   
1220 Float_t AliTPCcalibDB::GetCEchargeTime(Int_t run, Int_t sector, Double_t timeStamp, Int_t *entries)
1221 {
1222   //
1223   // GetCE mean charge for 'sector'
1224   // it timestamp==-1 return mean value
1225   //
1226   AliTPCcalibDB::Instance()->SetRun(run);
1227   TGraph *gr=AliTPCcalibDB::Instance()->GetCErocQgraph(sector);
1228   if (!gr||sector<0||sector>71) {
1229     if (entries) *entries=0;
1230     return 0.;
1231   }
1232   Float_t val=0.;
1233   if (timeStamp==-1.){
1234     val=gr->GetMean(2);
1235   }else{
1236     for (Int_t ipoint=0;ipoint<gr->GetN();++ipoint){
1237       Double_t x,y;
1238       gr->GetPoint(ipoint,x,y);
1239       if (x<timeStamp) continue;
1240       val=y;
1241       break;
1242     }
1243   }
1244   return val;
1245 }
1246
1247 Float_t AliTPCcalibDB::GetDCSSensorValue(AliDCSSensorArray *arr, Int_t timeStamp, const char * sensorName, Int_t sigDigits)
1248 {
1249   //
1250   // Get Value for a DCS sensor 'sensorName', run 'run' at time 'timeStamp'
1251   //
1252   Float_t val=0;
1253   const TString sensorNameString(sensorName);
1254   AliDCSSensor *sensor = arr->GetSensor(sensorNameString);
1255   if (!sensor) return val;
1256   //use the dcs graph if possible
1257   TGraph *gr=sensor->GetGraph();
1258   if (gr){
1259     for (Int_t ipoint=0;ipoint<gr->GetN();++ipoint){
1260       Double_t x,y;
1261       gr->GetPoint(ipoint,x,y);
1262       Int_t time=TMath::Nint(sensor->GetStartTime()+x*3600); //time in graph is hours
1263       if (time<timeStamp) continue;
1264       val=y;
1265       break;
1266     }
1267     //if val is still 0, test if if the requested time if within 5min of the first/last
1268     //data point. If this is the case return the firs/last entry
1269     //the timestamps might not be syncronised for all calibration types, sometimes a 'pre'
1270     //and 'pos' period is requested. Especially to the HV this is not the case!
1271     //first point
1272     if (val==0 ){
1273       Double_t x,y;
1274       gr->GetPoint(0,x,y);
1275       Int_t time=TMath::Nint(sensor->GetStartTime()+x*3600); //time in graph is hours
1276       if ((time-timeStamp)<5*60) val=y;
1277     }
1278     //last point
1279     if (val==0 ){
1280       Double_t x,y;
1281       gr->GetPoint(gr->GetN()-1,x,y);
1282       Int_t time=TMath::Nint(sensor->GetStartTime()+x*3600); //time in graph is hours
1283       if ((timeStamp-time)<5*60) val=y;
1284     }
1285   } else {
1286     val=sensor->GetValue(timeStamp);
1287   }
1288   if (sigDigits>=0){
1289     val=(Float_t)TMath::Floor(val * TMath::Power(10., sigDigits) + .5) / TMath::Power(10., sigDigits);
1290   }
1291   return val;
1292 }
1293
1294 Float_t AliTPCcalibDB::GetDCSSensorMeanValue(AliDCSSensorArray *arr, const char * sensorName, Int_t sigDigits)
1295 {
1296   //
1297   // Get mean Value for a DCS sensor 'sensorName' during run 'run'
1298   //
1299   Float_t val=0;
1300   const TString sensorNameString(sensorName);
1301   AliDCSSensor *sensor = arr->GetSensor(sensorNameString);
1302   if (!sensor) return val;
1303
1304   //use dcs graph if it exists
1305   TGraph *gr=sensor->GetGraph();
1306   if (gr){
1307     val=gr->GetMean(2);
1308   } else {
1309     //if we don't have the dcs graph, try to get some meaningful information
1310     if (!sensor->GetFit()) return val;
1311     Int_t nKnots=sensor->GetFit()->GetKnots();
1312     Double_t tMid=(sensor->GetEndTime()-sensor->GetStartTime())/2.;
1313     for (Int_t iKnot=0;iKnot<nKnots;++iKnot){
1314       if (sensor->GetFit()->GetX()[iKnot]>tMid/3600.) break;
1315       val=(Float_t)sensor->GetFit()->GetY0()[iKnot];
1316     }
1317   }
1318   if (sigDigits>=0){
1319     // val/=10;
1320     val=(Float_t)TMath::Floor(val * TMath::Power(10., sigDigits) + .5) / TMath::Power(10., sigDigits);
1321     //    val*=10;
1322   }
1323   return val;
1324 }
1325
1326 Float_t AliTPCcalibDB::GetChamberHighVoltage(Int_t run, Int_t sector, Int_t timeStamp, Int_t sigDigits, Bool_t current) {
1327   //
1328   // return the chamber HV for given run and time: 0-35 IROC, 36-72 OROC
1329   // if timeStamp==-1 return mean value
1330   //
1331   Float_t val=0;
1332   TString sensorName="";
1333   TTimeStamp stamp(timeStamp);
1334   AliDCSSensorArray* voltageArray = AliTPCcalibDB::Instance()->GetVoltageSensors(run);
1335   if (!voltageArray || (sector<0) || (sector>71)) return val;
1336   Char_t sideName='A';
1337   if ((sector/18)%2==1) sideName='C';
1338   if (sector<36){
1339     //IROC
1340     sensorName=Form("TPC_ANODE_I_%c%02d_VMEAS",sideName,sector%18);
1341   }else{
1342     //OROC
1343     sensorName=Form("TPC_ANODE_O_%c%02d_0_VMEAS",sideName,sector%18);
1344   }
1345   if (current){
1346     if (sector<36){
1347       //IROC
1348       sensorName=Form("TPC_ANODE_I_%c%02d_IMEAS",sideName,sector%18);
1349   }else{
1350       //OROC
1351       sensorName=Form("TPC_ANODE_O_%c%02d_0_IMEAS",sideName,sector%18);
1352     }
1353
1354   }
1355   if (timeStamp==-1){
1356     val=AliTPCcalibDB::GetDCSSensorMeanValue(voltageArray, sensorName.Data(),sigDigits);
1357   } else {
1358     val=AliTPCcalibDB::GetDCSSensorValue(voltageArray, timeStamp, sensorName.Data(),sigDigits);
1359   }
1360   return val;
1361 }
1362 Float_t AliTPCcalibDB::GetSkirtVoltage(Int_t run, Int_t sector, Int_t timeStamp, Int_t sigDigits)
1363 {
1364   //
1365   // Get the skirt voltage for 'run' at 'timeStamp' and 'sector': 0-35 IROC, 36-72 OROC
1366   // type corresponds to the following: 0 - IROC A-Side; 1 - IROC C-Side; 2 - OROC A-Side; 3 - OROC C-Side
1367   // if timeStamp==-1 return the mean value for the run
1368   //
1369   Float_t val=0;
1370   TString sensorName="";
1371   TTimeStamp stamp(timeStamp);
1372   AliDCSSensorArray* voltageArray = AliTPCcalibDB::Instance()->GetVoltageSensors(run);
1373   if (!voltageArray || (sector<0) || (sector>71)) return val;
1374   Char_t sideName='A';
1375   if ((sector/18)%2==1) sideName='C';
1376   sensorName=Form("TPC_SKIRT_%c_VMEAS",sideName);
1377   if (timeStamp==-1){
1378     val=AliTPCcalibDB::GetDCSSensorMeanValue(voltageArray, sensorName.Data(),sigDigits);
1379   } else {
1380     val=AliTPCcalibDB::GetDCSSensorValue(voltageArray, timeStamp, sensorName.Data(),sigDigits);
1381   }
1382   return val;
1383 }
1384
1385 Float_t AliTPCcalibDB::GetCoverVoltage(Int_t run, Int_t sector, Int_t timeStamp, Int_t sigDigits)
1386 {
1387   //
1388   // Get the cover voltage for run 'run' at time 'timeStamp'
1389   // type corresponds to the following: 0 - IROC A-Side; 1 - IROC C-Side; 2 - OROC A-Side; 3 - OROC C-Side
1390   // if timeStamp==-1 return the mean value for the run
1391   //
1392   Float_t val=0;
1393   TString sensorName="";
1394   TTimeStamp stamp(timeStamp);
1395   AliDCSSensorArray* voltageArray = AliTPCcalibDB::Instance()->GetVoltageSensors(run);
1396   if (!voltageArray || (sector<0) || (sector>71)) return val;
1397   Char_t sideName='A';
1398   if ((sector/18)%2==1) sideName='C';
1399   if (sector<36){
1400     //IROC
1401     sensorName=Form("TPC_COVER_I_%c_VMEAS",sideName);
1402   }else{
1403     //OROC
1404     sensorName=Form("TPC_COVER_O_%c_VMEAS",sideName);
1405   }
1406   if (timeStamp==-1){
1407     val=AliTPCcalibDB::GetDCSSensorMeanValue(voltageArray, sensorName.Data(),sigDigits);
1408   } else {
1409     val=AliTPCcalibDB::GetDCSSensorValue(voltageArray, timeStamp, sensorName.Data(),sigDigits);
1410   }
1411   return val;
1412 }
1413
1414 Float_t AliTPCcalibDB::GetGGoffsetVoltage(Int_t run, Int_t sector, Int_t timeStamp, Int_t sigDigits)
1415 {
1416   //
1417   // Get the GG offset voltage for run 'run' at time 'timeStamp'
1418   // type corresponds to the following: 0 - IROC A-Side; 1 - IROC C-Side; 2 - OROC A-Side; 3 - OROC C-Side
1419   // if timeStamp==-1 return the mean value for the run
1420   //
1421   Float_t val=0;
1422   TString sensorName="";
1423   TTimeStamp stamp(timeStamp);
1424   AliDCSSensorArray* voltageArray = AliTPCcalibDB::Instance()->GetVoltageSensors(run);
1425   if (!voltageArray || (sector<0) || (sector>71)) return val;
1426   Char_t sideName='A';
1427   if ((sector/18)%2==1) sideName='C';
1428   if (sector<36){
1429     //IROC
1430     sensorName=Form("TPC_GATE_I_%c_OFF_VMEAS",sideName);
1431   }else{
1432     //OROC
1433     sensorName=Form("TPC_GATE_O_%c_OFF_VMEAS",sideName);
1434   }
1435   if (timeStamp==-1){
1436     val=AliTPCcalibDB::GetDCSSensorMeanValue(voltageArray, sensorName.Data(),sigDigits);
1437   } else {
1438     val=AliTPCcalibDB::GetDCSSensorValue(voltageArray, timeStamp, sensorName.Data(),sigDigits);
1439   }
1440   return val;
1441 }
1442
1443 Float_t AliTPCcalibDB::GetGGnegVoltage(Int_t run, Int_t sector, Int_t timeStamp, Int_t sigDigits)
1444 {
1445   //
1446   // Get the GG offset voltage for run 'run' at time 'timeStamp'
1447   // type corresponds to the following: 0 - IROC A-Side; 1 - IROC C-Side; 2 - OROC A-Side; 3 - OROC C-Side
1448   // if timeStamp==-1 return the mean value for the run
1449   //
1450   Float_t val=0;
1451   TString sensorName="";
1452   TTimeStamp stamp(timeStamp);
1453   AliDCSSensorArray* voltageArray = AliTPCcalibDB::Instance()->GetVoltageSensors(run);
1454   if (!voltageArray || (sector<0) || (sector>71)) return val;
1455   Char_t sideName='A';
1456   if ((sector/18)%2==1) sideName='C';
1457   if (sector<36){
1458     //IROC
1459     sensorName=Form("TPC_GATE_I_%c_NEG_VMEAS",sideName);
1460   }else{
1461     //OROC
1462     sensorName=Form("TPC_GATE_O_%c_NEG_VMEAS",sideName);
1463   }
1464   if (timeStamp==-1){
1465     val=AliTPCcalibDB::GetDCSSensorMeanValue(voltageArray, sensorName.Data(),sigDigits);
1466   } else {
1467     val=AliTPCcalibDB::GetDCSSensorValue(voltageArray, timeStamp, sensorName.Data(),sigDigits);
1468   }
1469   return val;
1470 }
1471
1472 Float_t AliTPCcalibDB::GetGGposVoltage(Int_t run, Int_t sector, Int_t timeStamp, Int_t sigDigits)
1473 {
1474   //
1475   // Get the GG offset voltage for run 'run' at time 'timeStamp'
1476   // type corresponds to the following: 0 - IROC A-Side; 1 - IROC C-Side; 2 - OROC A-Side; 3 - OROC C-Side
1477   // if timeStamp==-1 return the mean value for the run
1478   //
1479   Float_t val=0;
1480   TString sensorName="";
1481   TTimeStamp stamp(timeStamp);
1482   AliDCSSensorArray* voltageArray = AliTPCcalibDB::Instance()->GetVoltageSensors(run);
1483   if (!voltageArray || (sector<0) || (sector>71)) return val;
1484   Char_t sideName='A';
1485   if ((sector/18)%2==1) sideName='C';
1486   if (sector<36){
1487     //IROC
1488     sensorName=Form("TPC_GATE_I_%c_POS_VMEAS",sideName);
1489   }else{
1490     //OROC
1491     sensorName=Form("TPC_GATE_O_%c_POS_VMEAS",sideName);
1492   }
1493   if (timeStamp==-1){
1494     val=AliTPCcalibDB::GetDCSSensorMeanValue(voltageArray, sensorName.Data(),sigDigits);
1495   } else {
1496     val=AliTPCcalibDB::GetDCSSensorValue(voltageArray, timeStamp, sensorName.Data(),sigDigits);
1497   }
1498   return val;
1499 }
1500
1501 Float_t AliTPCcalibDB::GetPressure(Int_t timeStamp, Int_t run, Int_t type){
1502   //
1503   // GetPressure for given time stamp and runt
1504   //
1505   TTimeStamp stamp(timeStamp);
1506   AliDCSSensor * sensor = Instance()->GetPressureSensor(run,type);
1507   if (!sensor) return 0;
1508   return sensor->GetValue(stamp);
1509 }
1510
1511 Float_t AliTPCcalibDB::GetL3Current(Int_t run, Int_t statType){
1512   //
1513   // return L3 current
1514   // stat type is: AliGRPObject::Stats: kMean = 0, kTruncMean = 1, kMedian = 2, kSDMean = 3, kSDMedian = 4
1515   //
1516   Float_t current=-1;
1517   AliGRPObject *grp=AliTPCcalibDB::GetGRP(run);
1518   if (grp) current=grp->GetL3Current((AliGRPObject::Stats)statType);
1519   return current;
1520 }
1521
1522 Float_t AliTPCcalibDB::GetBz(Int_t run){
1523   //
1524   // calculate BZ in T from L3 current
1525   //
1526   Float_t bz=-1;
1527   Float_t current=AliTPCcalibDB::GetL3Current(run);
1528   if (current>-1) bz=5*current/30000.*.1;
1529   return bz;
1530 }
1531
1532 Char_t  AliTPCcalibDB::GetL3Polarity(Int_t run) {
1533   //
1534   // get l3 polarity from GRP
1535   //
1536   Char_t pol=-100;
1537   AliGRPObject *grp=AliTPCcalibDB::GetGRP(run);
1538   if (grp) pol=grp->GetL3Polarity();
1539   return pol;
1540 }
1541
1542 TString AliTPCcalibDB::GetRunType(Int_t run){
1543   //
1544   // return run type from grp
1545   //
1546
1547 //   TString type("UNKNOWN");
1548   AliGRPObject *grp=AliTPCcalibDB::GetGRP(run);
1549   if (grp) return grp->GetRunType();
1550   return "UNKNOWN";
1551 }
1552
1553 Float_t AliTPCcalibDB::GetValueGoofie(Int_t timeStamp, Int_t run, Int_t type){
1554   //
1555   // GetPressure for given time stamp and runt
1556   //
1557   TTimeStamp stamp(timeStamp);
1558   AliDCSSensorArray* goofieArray = AliTPCcalibDB::Instance()->GetGoofieSensors(run);
1559   if (!goofieArray) return 0;
1560   AliDCSSensor *sensor = goofieArray->GetSensor(type);
1561   return sensor->GetValue(stamp);
1562 }
1563
1564
1565
1566
1567
1568
1569 Bool_t  AliTPCcalibDB::GetTemperatureFit(Int_t timeStamp, Int_t run, Int_t side,TVectorD& fit){
1570   //
1571   // GetTmeparature fit at parameter for given time stamp
1572   //
1573   TTimeStamp tstamp(timeStamp);
1574   AliTPCSensorTempArray* tempArray  = Instance()->GetTemperatureSensor(run);
1575   if (! tempArray) return kFALSE;
1576   AliTPCTempMap * tempMap = new AliTPCTempMap(tempArray);
1577   TLinearFitter * fitter = tempMap->GetLinearFitter(3,side,tstamp);
1578   if (fitter){
1579     fitter->Eval(); 
1580     fitter->GetParameters(fit);
1581   }
1582   delete fitter;
1583   delete tempMap;
1584   if (!fitter) return kFALSE;
1585   return kTRUE;
1586 }
1587
1588 Float_t AliTPCcalibDB::GetTemperature(Int_t timeStamp, Int_t run, Int_t side){
1589   //
1590   // Get mean temperature
1591   // 
1592   TVectorD vec(5);
1593   if (side==0) {
1594     GetTemperatureFit(timeStamp,run,0,vec);
1595     return vec[0];
1596   }
1597   if (side==1){
1598     GetTemperatureFit(timeStamp,run,0,vec);
1599     return vec[0];
1600   }
1601   return 0;
1602 }
1603
1604
1605 Double_t AliTPCcalibDB::GetPTRelative(UInt_t timeSec, Int_t run, Int_t side){
1606   //
1607   // Get relative P/T 
1608   // time - absolute time
1609   // run  - run number
1610   // side - 0 - A side   1-C side
1611   AliTPCCalibVdrift * vdrift =  Instance()->GetVdrift(run);
1612   if (!vdrift) return 0;
1613   return vdrift->GetPTRelative(timeSec,side);
1614 }
1615
1616 AliGRPObject * AliTPCcalibDB::MakeGRPObjectFromMap(TMap *map){
1617   //
1618   // Function to covert old GRP run information from TMap to GRPObject
1619   //
1620   //  TMap * map = AliTPCcalibDB::GetGRPMap(52406);
1621   if (!map) return 0;
1622   AliDCSSensor * sensor = 0;
1623   TObject *osensor=0;
1624   osensor = ((*map)("fP2Pressure"));
1625   sensor  =dynamic_cast<AliDCSSensor *>(osensor); 
1626   //
1627   if (!sensor) return 0;
1628   //
1629   AliDCSSensor * sensor2 = new AliDCSSensor(*sensor);
1630   osensor = ((*map)("fCavernPressure"));
1631   TGraph * gr = new TGraph(2);
1632   gr->GetX()[0]= -100000.;
1633   gr->GetX()[1]= 1000000.;
1634   gr->GetY()[0]= atof(osensor->GetName());
1635   gr->GetY()[1]= atof(osensor->GetName());
1636   sensor2->SetGraph(gr);
1637   sensor2->SetFit(0);
1638   
1639
1640   AliGRPObject *grpRun = new AliGRPObject; 
1641   grpRun->ReadValuesFromMap(map);
1642   grpRun->SetCavernAtmosPressure(sensor2);
1643   grpRun->SetCavernAtmosPressure(sensor2);
1644   grpRun->SetSurfaceAtmosPressure(sensor);
1645   return grpRun;
1646 }
1647
1648 Bool_t AliTPCcalibDB::CreateGUITree(Int_t run, const char* filename)
1649 {
1650   //
1651   // Create a gui tree for run number 'run'
1652   //
1653
1654   if (!AliCDBManager::Instance()->GetDefaultStorage()){
1655     AliLog::Message(AliLog::kError, "Default Storage not set. Cannot create Calibration Tree!",
1656                     MODULENAME(), "AliTPCcalibDB", FUNCTIONNAME(), __FILE__, __LINE__);
1657     return kFALSE;
1658   }
1659   //db instance
1660   AliTPCcalibDB *db=AliTPCcalibDB::Instance();
1661   // retrieve cal pad objects
1662   db->SetRun(run);
1663   db->CreateGUITree(filename);
1664   return kTRUE;
1665 }
1666
1667 Bool_t AliTPCcalibDB::CreateGUITree(const char* filename){
1668   //
1669   //
1670   //
1671   if (!AliCDBManager::Instance()->GetDefaultStorage()){
1672     AliError("Default Storage not set. Cannot create calibration Tree!");
1673     return kFALSE;
1674   }
1675   UpdateNonRec();  // load all infromation now
1676
1677   AliTPCPreprocessorOnline prep;
1678   //noise and pedestals
1679   if (GetPedestals()) prep.AddComponent(new AliTPCCalPad(*(GetPedestals())));
1680   if (GetPadNoise() ) prep.AddComponent(new AliTPCCalPad(*(GetPadNoise())));
1681   //pulser data
1682   if (GetPulserTmean()) prep.AddComponent(new AliTPCCalPad(*(GetPulserTmean())));
1683   if (GetPulserTrms() ) prep.AddComponent(new AliTPCCalPad(*(GetPulserTrms())));
1684   if (GetPulserQmean()) prep.AddComponent(new AliTPCCalPad(*(GetPulserQmean())));
1685   //CE data
1686   if (GetCETmean()) prep.AddComponent(new AliTPCCalPad(*(GetCETmean())));
1687   if (GetCETrms() ) prep.AddComponent(new AliTPCCalPad(*(GetCETrms())));
1688   if (GetCEQmean()) prep.AddComponent(new AliTPCCalPad(*(GetCEQmean())));
1689   //Altro data
1690   if (GetALTROAcqStart() ) prep.AddComponent(new AliTPCCalPad(*(GetALTROAcqStart() )));
1691   if (GetALTROZsThr()    ) prep.AddComponent(new AliTPCCalPad(*(GetALTROZsThr()    )));
1692   if (GetALTROFPED()     ) prep.AddComponent(new AliTPCCalPad(*(GetALTROFPED()     )));
1693   if (GetALTROAcqStop()  ) prep.AddComponent(new AliTPCCalPad(*(GetALTROAcqStop()  )));
1694   if (GetALTROMasked()   ) prep.AddComponent(new AliTPCCalPad(*(GetALTROMasked()   )));
1695   //QA
1696   AliTPCdataQA *dataQA=GetDataQA();
1697   if (dataQA) {
1698     if (dataQA->GetNLocalMaxima())
1699       prep.AddComponent(new AliTPCCalPad(*(dataQA->GetNLocalMaxima())));
1700     if (dataQA->GetMaxCharge())
1701       prep.AddComponent(new AliTPCCalPad(*(dataQA->GetMaxCharge())));
1702     if (dataQA->GetMeanCharge())
1703       prep.AddComponent(new AliTPCCalPad(*(dataQA->GetMeanCharge())));
1704     if (dataQA->GetNoThreshold())
1705       prep.AddComponent(new AliTPCCalPad(*(dataQA->GetNoThreshold())));
1706     if (dataQA->GetNTimeBins())
1707       prep.AddComponent(new AliTPCCalPad(*(dataQA->GetNTimeBins())));
1708     if (dataQA->GetNPads())
1709       prep.AddComponent(new AliTPCCalPad(*(dataQA->GetNPads())));
1710     if (dataQA->GetTimePosition())
1711       prep.AddComponent(new AliTPCCalPad(*(dataQA->GetTimePosition())));
1712   }
1713   
1714   //
1715   TString file(filename);
1716   if (file.IsNull()) file=Form("guiTreeRun_%lld.root",fRun);
1717   prep.DumpToFile(file.Data());
1718   return kTRUE;
1719 }
1720
1721 Bool_t AliTPCcalibDB::CreateRefFile(Int_t run, const char* filename)
1722 {
1723   //
1724   // Create a gui tree for run number 'run'
1725   //
1726   
1727   if (!AliCDBManager::Instance()->GetDefaultStorage()){
1728     AliLog::Message(AliLog::kError, "Default Storage not set. Cannot create Calibration Tree!",
1729                     MODULENAME(), "AliTPCcalibDB", FUNCTIONNAME(), __FILE__, __LINE__);
1730     return kFALSE;
1731   }
1732   TString file(filename);
1733   if (file.IsNull()) file=Form("RefCalPads_%d.root",run);
1734   TDirectory *currDir=gDirectory;
1735   //db instance
1736   AliTPCcalibDB *db=AliTPCcalibDB::Instance();
1737   // retrieve cal pad objects
1738   db->SetRun(run);
1739   //open file
1740   TFile f(file.Data(),"recreate");
1741   //noise and pedestals
1742   db->GetPedestals()->Write("Pedestals");
1743   db->GetPadNoise()->Write("PadNoise");
1744   //pulser data
1745   db->GetPulserTmean()->Write("PulserTmean");
1746   db->GetPulserTrms()->Write("PulserTrms");
1747   db->GetPulserQmean()->Write("PulserQmean");
1748   //CE data
1749   db->GetCETmean()->Write("CETmean");
1750   db->GetCETrms()->Write("CETrms");
1751   db->GetCEQmean()->Write("CEQmean");
1752   //Altro data
1753   db->GetALTROAcqStart() ->Write("ALTROAcqStart");
1754   db->GetALTROZsThr()    ->Write("ALTROZsThr");
1755   db->GetALTROFPED()     ->Write("ALTROFPED");
1756   db->GetALTROAcqStop()  ->Write("ALTROAcqStop");
1757   db->GetALTROMasked()   ->Write("ALTROMasked");
1758   //
1759   f.Close();
1760   currDir->cd();
1761   return kTRUE;
1762 }
1763
1764
1765
1766 Double_t AliTPCcalibDB::GetVDriftCorrectionTime(Int_t timeStamp, Int_t run, Int_t /*side*/, Int_t mode){
1767   //
1768   // Get time dependent drift velocity correction
1769   // multiplication factor        vd = vdnom *(1+vdriftcorr)
1770   // Arguments:
1771   // mode determines the algorith how to combine the Laser Track, LaserCE and physics tracks
1772   // timestamp - timestamp
1773   // run       - run number
1774   // side      - the drift velocity per side (possible for laser and CE)
1775   //
1776   // Notice - Extrapolation outside of calibration range  - using constant function
1777   //
1778   Double_t result=0;
1779   // mode 1  automatic mode - according to the distance to the valid calibration
1780   //                        -  
1781   Double_t deltaP=0,  driftP=0,      wP  = 0.;
1782   Double_t deltaITS=0,driftITS=0,    wITS= 0.;
1783   Double_t deltaLT=0, driftLT=0,     wLT = 0.;
1784   Double_t deltaCE=0, driftCE=0,     wCE = 0.;
1785   driftP  = fDButil->GetVDriftTPC(deltaP,run,timeStamp); 
1786   driftITS= fDButil->GetVDriftTPCITS(deltaITS,run,timeStamp);
1787   driftCE = fDButil->GetVDriftTPCCE(deltaCE, run,timeStamp,36000,2);
1788   driftLT = fDButil->GetVDriftTPCLaserTracks(deltaLT,run,timeStamp,36000,2);
1789   deltaITS = TMath::Abs(deltaITS);
1790   deltaP   = TMath::Abs(deltaP);
1791   deltaLT  = TMath::Abs(deltaLT);
1792   deltaCE  = TMath::Abs(deltaCE);
1793   if (mode==1) {
1794     const Double_t kEpsilon=0.00000000001;
1795     const Double_t kdeltaT=360.; // 10 minutes
1796     if(TMath::Abs(deltaITS) < 12*kdeltaT) {
1797       result = driftITS;
1798     } else {
1799     wITS  = 64.*kdeltaT/(deltaITS +kdeltaT);
1800     wLT   = 16.*kdeltaT/(deltaLT  +kdeltaT);
1801     wP    = 0. *kdeltaT/(deltaP   +kdeltaT);
1802     wCE   = 1. *kdeltaT/(deltaCE  +kdeltaT);
1803     //
1804     //
1805     if (TMath::Abs(driftP)<kEpsilon)  wP=0;  // invalid calibration
1806     if (TMath::Abs(driftITS)<kEpsilon)wITS=0;  // invalid calibration
1807     if (TMath::Abs(driftLT)<kEpsilon) wLT=0;  // invalid calibration
1808     if (TMath::Abs(driftCE)<kEpsilon) wCE=0;  // invalid calibration
1809     if (wP+wITS+wLT+wCE<kEpsilon) return 0;
1810     result = (driftP*wP+driftITS*wITS+driftLT*wLT+driftCE*wCE)/(wP+wITS+wLT+wCE);
1811    }
1812    
1813
1814   }
1815
1816   return result;
1817 }
1818
1819 Double_t AliTPCcalibDB::GetTime0CorrectionTime(Int_t timeStamp, Int_t run, Int_t /*side*/, Int_t mode){
1820   //
1821   // Get time dependent time 0 (trigger delay in cm) correction
1822   // additive correction        time0 = time0+ GetTime0CorrectionTime
1823   // Value etracted combining the vdrift correction using laser tracks and CE and the physics track matchin
1824   // Arguments:
1825   // mode determines the algorith how to combine the Laser Track and physics tracks
1826   // timestamp - timestamp
1827   // run       - run number
1828   // side      - the drift velocity per side (possible for laser and CE)
1829   //
1830   // Notice - Extrapolation outside of calibration range  - using constant function
1831   //
1832   Double_t result=0;
1833   if (mode==2) {
1834     // TPC-TPC mode
1835     result=fDButil->GetTriggerOffsetTPC(run,timeStamp);    
1836     result  *=fParam->GetZLength();
1837   }
1838   if (mode==1){
1839     // TPC-ITS mode
1840     Double_t dist=0;
1841     result= -fDButil->GetTime0TPCITS(dist, run, timeStamp)*fParam->GetDriftV()/1000000.;
1842   }
1843   return result;
1844
1845 }
1846
1847
1848
1849
1850 Double_t AliTPCcalibDB::GetVDriftCorrectionGy(Int_t timeStamp, Int_t run, Int_t side, Int_t /*mode*/){
1851   //
1852   // Get global y correction drift velocity correction factor
1853   // additive factor        vd = vdnom*(1+GetVDriftCorrectionGy *gy)
1854   // Value etracted combining the vdrift correction using laser tracks and CE or TPC-ITS
1855   // Arguments:
1856   // mode determines the algorith how to combine the Laser Track, LaserCE or TPC-ITS
1857   // timestamp - timestamp
1858   // run       - run number
1859   // side      - the drift velocity gy correction per side (CE and Laser tracks)
1860   //
1861   // Notice - Extrapolation outside of calibration range  - using constant function
1862   // 
1863   if (run<=0 && fTransform) run = fTransform->GetCurrentRunNumber();
1864   UpdateRunInformations(run,kFALSE);
1865   TObjArray *array =AliTPCcalibDB::Instance()->GetTimeVdriftSplineRun(run);
1866   if (!array) return 0;
1867   Double_t result=0;
1868
1869   // use TPC-ITS if present
1870   TGraphErrors *gr= (TGraphErrors*)array->FindObject("ALIGN_ITSB_TPC_VDGY");
1871   if(gr) { 
1872     result = AliTPCcalibDButil::EvalGraphConst(gr,timeStamp);
1873
1874     // transform from [(cm/mus)/ m] to [1/cm]
1875     result /= (fParam->GetDriftV()/1000000.);
1876     result /= 100.;
1877
1878     //printf("result %e \n", result);
1879     return result; 
1880   }
1881
1882   // use laser if ITS-TPC not present
1883   TGraphErrors *laserA= (TGraphErrors*)array->FindObject("GRAPH_MEAN_GLOBALYGRADIENT_LASER_ALL_A");
1884   TGraphErrors *laserC= (TGraphErrors*)array->FindObject("GRAPH_MEAN_GLOBALYGRADIENT_LASER_ALL_C");
1885   
1886   if (laserA && laserC){
1887    result= (laserA->Eval(timeStamp)+laserC->Eval(timeStamp))*0.5;
1888   }
1889   if (laserA && side==0){
1890     result = (laserA->Eval(timeStamp));
1891   }
1892   if (laserC &&side==1){
1893     result = (laserC->Eval(timeStamp));
1894   }
1895   //printf("laser result %e \n", -result/250.);
1896
1897   return -result/250.; //normalized before
1898 }
1899
1900 AliTPCCalPad* AliTPCcalibDB::MakeDeadMap(Double_t notInMap, const char* nameMappingFile) {
1901 //
1902 //   Read list of active DDLs from OCDB entry
1903 //   Generate and return AliTPCCalPad containing 1 for all pads in active DDLs,
1904 //   0 for all pads in non-active DDLs. 
1905 //   For DDLs with missing status information (no DCS input point to Shuttle),
1906 //     the value of the AliTPCCalPad entry is determined by the parameter
1907 //     notInMap (default value 1)
1908 //
1909   char chinfo[1000];
1910    
1911   TFile *fileMapping = new TFile(nameMappingFile, "read");
1912   AliTPCmapper *mapping = (AliTPCmapper*) fileMapping->Get("tpcMapping");
1913   if (!mapping) {
1914     sprintf(chinfo,"Failed to get mapping object from %s.  ...\n", nameMappingFile);
1915     AliError (chinfo);
1916     return 0;
1917   }
1918   
1919   AliTPCCalPad *deadMap = new AliTPCCalPad("deadMap","deadMap");
1920   if (!deadMap) {
1921      AliError("Failed to allocate dead map AliTPCCalPad");
1922      return 0;
1923   }  
1924   
1925   /// get list of active DDLs from OCDB entry
1926   Int_t idDDL=0;
1927   if (!fALTROConfigData ) {
1928      AliError("No ALTRO config OCDB entry available");
1929      return 0; 
1930   }
1931   TMap *activeDDL = (TMap*)fALTROConfigData->FindObject("DDLArray");
1932   TObjString *ddlArray=0;
1933   if (activeDDL) {
1934     ddlArray = (TObjString*)activeDDL->GetValue("DDLArray");
1935     if (!ddlArray) {
1936       AliError("Empty list of active DDLs in OCDB entry");
1937       return 0;
1938     }
1939   } else { 
1940     AliError("List of active DDLs not available in OCDB entry");
1941     return 0;
1942   }
1943   TString arrDDL=ddlArray->GetString();
1944   Int_t offset = mapping->GetTpcDdlOffset();
1945   Double_t active;
1946   for (Int_t i=0; i<mapping->GetNumDdl(); i++) {
1947     idDDL= i+offset;
1948     Int_t patch = mapping->GetPatchFromEquipmentID(idDDL);   
1949     Int_t roc=mapping->GetRocFromEquipmentID(idDDL);
1950     AliTPCCalROC *calRoc=deadMap->GetCalROC(roc);
1951     if (calRoc) {
1952      for ( Int_t branch = 0; branch < 2; branch++ ) {
1953       for ( Int_t fec = 0; fec < mapping->GetNfec(patch, branch); fec++ ) {
1954         for ( Int_t altro = 0; altro < 8; altro++ ) {
1955          for ( Int_t channel = 0; channel < 16; channel++ ) {
1956            Int_t hwadd     = mapping->CodeHWAddress(branch, fec, altro, channel);
1957            Int_t row       = mapping->GetPadRow(patch, hwadd);        // row in a ROC (IROC or OROC)
1958 //              Int_t globalrow = mapping.GetGlobalPadRow(patch, hwadd);  // row in full sector (IROC plus OROC)
1959            Int_t pad       = mapping->GetPad(patch, hwadd);
1960            if (!TString(arrDDL[i]).IsDigit()) {
1961               active = notInMap;
1962            } else { 
1963               active=TString(arrDDL[i]).Atof();
1964            }
1965            calRoc->SetValue(row,pad,active);
1966          } // end channel for loop
1967         } // end altro for loop
1968       } // end fec for loop
1969      } // end branch for loop
1970     } // valid calROC 
1971    } // end loop on active DDLs
1972    return deadMap;
1973 }
1974
1975
1976
1977 AliTPCCorrection * AliTPCcalibDB::GetTPCComposedCorrection(Float_t field) const{
1978   //
1979   // GetComposed correction for given field setting
1980   //
1981   if (!fComposedCorrectionArray) return 0;
1982   if (field>0.1) return (AliTPCCorrection *)fComposedCorrectionArray->At(1);
1983   if (field<-0.1) return (AliTPCCorrection *)fComposedCorrectionArray->At(2);
1984   return (AliTPCCorrection *)fComposedCorrectionArray->At(0);
1985   
1986 }
1987