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