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