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