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