]> git.uio.no Git - u/mrichter/AliRoot.git/blob - TPC/AliTPCcalibDB.cxx
Fixed warning (shadowed local variable "source" )
[u/mrichter/AliRoot.git] / TPC / AliTPCcalibDB.cxx
1 /**************************************************************************
2  * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
3  *                                                                        *
4  * Author: The ALICE Off-line Project.                                    *
5  * Contributors are mentioned in the code where appropriate.              *
6  *                                                                        *
7  * Permission to use, copy, modify and distribute this software and its   *
8  * documentation strictly for non-commercial purposes is hereby granted   *
9  * without fee, provided that the above copyright notice appears in all   *
10  * copies and that both the copyright notice and this permission notice   *
11  * appear in the supporting documentation. The authors make no claims     *
12  * about the suitability of this software for any purpose. It is          *
13  * provided "as is" without express or implied warranty.                  *
14  **************************************************************************/
15
16
17 ///////////////////////////////////////////////////////////////////////////////
18 //                                                                           //
19 // Class providing the calibration parameters by accessing the CDB           //
20 //                                                                           //
21 // Request an instance with AliTPCcalibDB::Instance()                        //
22 // If a new event is processed set the event number with SetRun              //
23 // Then request the calibration data                                         ////
24 //
25 //
26 // Calibration data:
27 // 0.)  Altro mapping
28 //          Simulation      - not yet 
29 //          Reconstruction  - AliTPCclustererMI::Digits2Clusters(AliRawReader* rawReader)
30 //
31 // 1.)  pad by pad calibration -  AliTPCCalPad
32 //      
33 //      a.) fPadGainFactor
34 //          Simulation: AliTPCDigitizer::ExecFast - Multiply by gain
35 //          Reconstruction : AliTPCclustererMI::Digits2Clusters - Divide by gain  
36 //
37 //      b.) fPadNoise -
38 //          Simulation:        AliTPCDigitizer::ExecFast
39 //          Reconstruction:    AliTPCclustererMI::FindClusters(AliTPCCalROC * noiseROC)
40 //                             Noise depending cut on clusters charge (n sigma)
41 //      c.) fPedestal:
42 //          Simulation:     Not used yet - To be impleneted - Rounding to the nearest integer
43 //          Reconstruction: Used in AliTPCclustererMI::Digits2Clusters(AliRawReader* rawReader) 
44 //                          if data taken without zero suppression  
45 //                          Currently switch in  fRecoParam->GetCalcPedestal();
46 //      
47 //      d.) fPadTime0
48 //          Simulation:      applied in the AliTPC::MakeSector - adding offset
49 //          Reconstruction:  AliTPCTransform::Transform() - remove offset
50 //                           AliTPCTransform::Transform() - to be called
51 //                           in AliTPCtracker::Transform()      
52 //
53 // 
54 // 2.)  Space points transformation:
55 //
56 //      a.) General coordinate tranformation - AliTPCtransform (see $ALICE_ROOT/TPC/AliTPCtransform.cxx)
57 //          Created on fly - use the other calibration components
58 //                 Unisochronity  - (substract time0 - pad by pad)
59 //                 Drift velocity - Currently common drift velocity - functionality of AliTPCParam
60 //                 ExB effect    
61 //          Simulation     - Not used directly (the effects are applied one by one (see AliTPC::MakeSector)
62 //          Reconstruction - 
63 //                           AliTPCclustererMI::AddCluster
64 //                           AliTPCtrackerMI::Transform
65 //      b.) ExB effect calibration - 
66 //             classes (base class AliTPCExB, implementation- AliTPCExBExact.h  AliTPCExBFirst.h)
67 //             a.a) Simulation:   applied in the AliTPC::MakeSector - 
68 //                                calib->GetExB()->CorrectInverse(dxyz0,dxyz1);
69 //             a.b) Reconstruction -  
70 //                  
71 //                  in AliTPCtransform::Correct() - called calib->GetExB()->Correct(dxyz0,dxyz1)
72 //
73 //  3.)   cluster error, shape and Q parameterization
74 //
75 //
76 //
77 ///////////////////////////////////////////////////////////////////////////////
78
79 #include <iostream>
80 #include <fstream>
81
82
83 #include <AliCDBManager.h>
84 #include <AliCDBEntry.h>
85 #include <AliLog.h>
86 #include <AliMagF.h>
87 #include <AliMagWrapCheb.h>
88
89 #include "AliTPCcalibDB.h"
90 #include "AliTPCAltroMapping.h"
91 #include "AliTPCExB.h"
92
93 #include "AliTPCCalROC.h"
94 #include "AliTPCCalPad.h"
95 #include "AliTPCSensorTempArray.h"
96 #include "AliGRPObject.h"
97 #include "AliTPCTransform.h"
98
99 class AliCDBStorage;
100 class AliTPCCalDet;
101 //
102 //
103
104 #include "TFile.h"
105 #include "TKey.h"
106
107 #include "TObjArray.h"
108 #include "TObjString.h"
109 #include "TString.h"
110 #include "AliTPCCalPad.h"
111 #include "AliTPCCalibPulser.h"
112 #include "AliTPCCalibPedestal.h"
113 #include "AliTPCCalibCE.h"
114 #include "AliTPCExBFirst.h"
115 #include "AliTPCTempMap.h"
116 #include "AliTPCCalibVdrift.h"
117
118
119
120
121 ClassImp(AliTPCcalibDB)
122
123 AliTPCcalibDB* AliTPCcalibDB::fgInstance = 0;
124 Bool_t AliTPCcalibDB::fgTerminated = kFALSE;
125 TObjArray    AliTPCcalibDB::fgExBArray;    // array of ExB corrections
126
127
128 //_ singleton implementation __________________________________________________
129 AliTPCcalibDB* AliTPCcalibDB::Instance()
130 {
131   //
132   // Singleton implementation
133   // Returns an instance of this class, it is created if neccessary
134   //
135   
136   if (fgTerminated != kFALSE)
137     return 0;
138
139   if (fgInstance == 0)
140     fgInstance = new AliTPCcalibDB();
141   
142   return fgInstance;
143 }
144
145 void AliTPCcalibDB::Terminate()
146 {
147   //
148   // Singleton implementation
149   // Deletes the instance of this class and sets the terminated flag, instances cannot be requested anymore
150   // This function can be called several times.
151   //
152   
153   fgTerminated = kTRUE;
154   
155   if (fgInstance != 0)
156   {
157     delete fgInstance;
158     fgInstance = 0;
159   }
160 }
161
162 //_____________________________________________________________________________
163 AliTPCcalibDB::AliTPCcalibDB():
164   TObject(),
165   fRun(-1),
166   fTransform(0),
167   fExB(0),
168   fPadGainFactor(0),
169   fDedxGainFactor(0),
170   fPadTime0(0),
171   fPadNoise(0),
172   fPedestals(0),
173   fTemperature(0),
174   fMapping(0),
175   fParam(0),
176   fClusterParam(0),  
177   fGRPArray(100000),            //! array of GRPs  -  per run  - JUST for calibration studies
178   fGoofieArray(100000),         //! array of GOOFIE values -per run - Just for calibration studies
179   fTemperatureArray(100000),    //! array of temperature sensors - per run - Just for calibration studies
180   fVdriftArray(100000),                 //! array of v drift interfaces
181   fRunList(100000)              //! run list - indicates try to get the run param 
182
183 {
184   //
185   // constructor
186   //  
187   //
188   Update();    // temporary
189 }
190
191 AliTPCcalibDB::AliTPCcalibDB(const AliTPCcalibDB& ):
192   TObject(),
193   fRun(-1),
194   fTransform(0),
195   fExB(0),
196   fPadGainFactor(0),
197   fDedxGainFactor(0),
198   fPadTime0(0),
199   fPadNoise(0),
200   fPedestals(0),
201   fTemperature(0),
202   fMapping(0),
203   fParam(0),
204   fClusterParam(0),
205   fGRPArray(0),          //! array of GRPs  -  per run  - JUST for calibration studies
206   fGoofieArray(0),        //! array of GOOFIE values -per run - Just for calibration studies
207   fTemperatureArray(0),   //! array of temperature sensors - per run - Just for calibration studies
208   fVdriftArray(0),         //! array of v drift interfaces
209   fRunList(0)              //! run list - indicates try to get the run param 
210 {
211   //
212   // Copy constructor invalid -- singleton implementation
213   //
214    Error("copy constructor","invalid -- singleton implementation");
215 }
216
217 AliTPCcalibDB& AliTPCcalibDB::operator= (const AliTPCcalibDB& )
218 {
219 //
220 // Singleton implementation - no assignment operator
221 //
222   Error("operator =", "assignment operator not implemented");
223   return *this;
224 }
225
226
227
228 //_____________________________________________________________________________
229 AliTPCcalibDB::~AliTPCcalibDB() 
230 {
231   //
232   // destructor
233   //
234   
235   // don't delete anything, CDB cache is active!
236   //if (fPadGainFactor) delete fPadGainFactor;
237   //if (fPadTime0) delete fPadTime0;
238   //if (fPadNoise) delete fPadNoise;
239 }
240
241
242 //_____________________________________________________________________________
243 AliCDBEntry* AliTPCcalibDB::GetCDBEntry(const char* cdbPath)
244 {
245   // 
246   // Retrieves an entry with path <cdbPath> from the CDB.
247   //
248   char chinfo[1000];
249     
250   AliCDBEntry* entry = AliCDBManager::Instance()->Get(cdbPath, fRun); 
251   if (!entry) 
252   { 
253     sprintf(chinfo,"AliTPCcalibDB: Failed to get entry:\t%s ", cdbPath);
254     AliError(chinfo); 
255     return 0; 
256   }
257   return entry;
258 }
259
260
261 //_____________________________________________________________________________
262 void AliTPCcalibDB::SetRun(Long64_t run)
263 {
264   //
265   // Sets current run number. Calibration data is read from the corresponding file. 
266   //  
267   if (fRun == run)
268     return;  
269   fRun = run;
270   Update();
271 }
272   
273
274
275 void AliTPCcalibDB::Update(){
276   //
277   AliCDBEntry * entry=0;
278   
279   Bool_t cdbCache = AliCDBManager::Instance()->GetCacheFlag(); // save cache status
280   AliCDBManager::Instance()->SetCacheFlag(kTRUE); // activate CDB cache
281   
282   //
283   entry          = GetCDBEntry("TPC/Calib/PadGainFactor");
284   if (entry){
285     //if (fPadGainFactor) delete fPadGainFactor;
286     entry->SetOwner(kTRUE);
287     fPadGainFactor = (AliTPCCalPad*)entry->GetObject();
288   }
289   //
290   entry          = GetCDBEntry("TPC/Calib/GainFactorDedx");
291   if (entry){
292     entry->SetOwner(kTRUE);
293     fDedxGainFactor = (AliTPCCalPad*)entry->GetObject();
294   }
295   //
296   entry          = GetCDBEntry("TPC/Calib/PadTime0");
297   if (entry){
298     //if (fPadTime0) delete fPadTime0;
299     entry->SetOwner(kTRUE);
300     fPadTime0 = (AliTPCCalPad*)entry->GetObject();
301   }
302   //
303   //
304   entry          = GetCDBEntry("TPC/Calib/PadNoise");
305   if (entry){
306     //if (fPadNoise) delete fPadNoise;
307     entry->SetOwner(kTRUE);
308     fPadNoise = (AliTPCCalPad*)entry->GetObject();
309   }
310
311   entry          = GetCDBEntry("TPC/Calib/Pedestals");
312   if (entry){
313     //if (fPedestals) delete fPedestals;
314     entry->SetOwner(kTRUE);
315     fPedestals = (AliTPCCalPad*)entry->GetObject();
316   }
317
318   entry          = GetCDBEntry("TPC/Calib/Temperature");
319   if (entry){
320     //if (fTemperature) delete fTemperature;
321     entry->SetOwner(kTRUE);
322     fTemperature = (AliTPCSensorTempArray*)entry->GetObject();
323   }
324
325   entry          = GetCDBEntry("TPC/Calib/Parameters");
326   if (entry){
327     //if (fPadNoise) delete fPadNoise;
328     entry->SetOwner(kTRUE);
329     fParam = (AliTPCParam*)(entry->GetObject()->Clone());
330   }
331
332   entry          = GetCDBEntry("TPC/Calib/ClusterParam");
333   if (entry){
334     //if (fPadNoise) delete fPadNoise;
335     entry->SetOwner(kTRUE);
336     fClusterParam = (AliTPCClusterParam*)(entry->GetObject()->Clone());
337   }
338
339   entry          = GetCDBEntry("TPC/Calib/Mapping");
340   if (entry){
341     //if (fPadNoise) delete fPadNoise;
342     entry->SetOwner(kTRUE);
343     TObjArray * array = dynamic_cast<TObjArray*>(entry->GetObject());
344     if (array && array->GetEntriesFast()==6){
345       fMapping = new AliTPCAltroMapping*[6];
346       for (Int_t i=0; i<6; i++){
347         fMapping[i] =  dynamic_cast<AliTPCAltroMapping*>(array->At(i));
348       }
349     }
350   }
351
352
353
354   //entry          = GetCDBEntry("TPC/Calib/ExB");
355   //if (entry) {
356   //  entry->SetOwner(kTRUE);
357   //  fExB=dynamic_cast<AliTPCExB*>(entry->GetObject()->Clone());
358   //}
359   //
360   // ExB  - calculate during initialization 
361   //      - 
362   fExB =  GetExB(-5,kTRUE);
363      //
364   if (!fTransform) {
365     fTransform=new AliTPCTransform(); 
366   }
367
368   //
369   AliCDBManager::Instance()->SetCacheFlag(cdbCache); // reset original CDB cache
370   
371 }
372
373
374
375 void AliTPCcalibDB::CreateObjectList(const Char_t *filename, TObjArray *calibObjects)
376 {
377 //
378 // Create calibration objects and read contents from OCDB
379 //
380    if ( calibObjects == 0x0 ) return;
381    ifstream in;
382    in.open(filename);
383    if ( !in.is_open() ){
384       fprintf(stderr,"Error: cannot open list file '%s'", filename);
385       return;
386    }
387    
388    AliTPCCalPad *calPad=0x0;
389    
390    TString sFile;
391    sFile.ReadFile(in);
392    in.close();
393    
394    TObjArray *arrFileLine = sFile.Tokenize("\n");
395    
396    TIter nextLine(arrFileLine);
397    
398    TObjString *sObjLine=0x0;
399    while ( (sObjLine = (TObjString*)nextLine()) ){
400       TString sLine(sObjLine->GetString());
401       
402       TObjArray *arrNextCol = sLine.Tokenize("\t");
403       
404       TObjString *sObjType     = (TObjString*)(arrNextCol->At(0));
405       TObjString *sObjFileName = (TObjString*)(arrNextCol->At(1));
406       
407       if ( !sObjType || ! sObjFileName ) continue;
408       TString sType(sObjType->GetString());
409       TString sFileName(sObjFileName->GetString());
410       printf("%s\t%s\n",sType.Data(),sFileName.Data());
411       
412       TFile *fIn = TFile::Open(sFileName);
413       if ( !fIn ){
414          fprintf(stderr,"File not found: '%s'", sFileName.Data());
415          continue;
416       }
417       
418       if ( sType == "CE" ){
419          AliTPCCalibCE *ce = (AliTPCCalibCE*)fIn->Get("AliTPCCalibCE");
420          
421          calPad = new AliTPCCalPad((TObjArray*)ce->GetCalPadT0());         
422          calPad->SetNameTitle("CETmean","CETmean");
423          calibObjects->Add(calPad);
424          
425          calPad = new AliTPCCalPad((TObjArray*)ce->GetCalPadQ());         
426          calPad->SetNameTitle("CEQmean","CEQmean");
427          calibObjects->Add(calPad);        
428          
429          calPad = new AliTPCCalPad((TObjArray*)ce->GetCalPadRMS());
430          calPad->SetNameTitle("CETrms","CETrms");
431          calibObjects->Add(calPad);         
432                   
433       } else if ( sType == "Pulser") {
434          AliTPCCalibPulser *sig = (AliTPCCalibPulser*)fIn->Get("AliTPCCalibPulser");
435          
436          calPad = new AliTPCCalPad((TObjArray*)sig->GetCalPadT0());         
437          calPad->SetNameTitle("PulserTmean","PulserTmean");
438          calibObjects->Add(calPad);
439          
440          calPad = new AliTPCCalPad((TObjArray*)sig->GetCalPadQ());         
441          calPad->SetNameTitle("PulserQmean","PulserQmean");
442          calibObjects->Add(calPad);        
443          
444          calPad = new AliTPCCalPad((TObjArray*)sig->GetCalPadRMS());
445          calPad->SetNameTitle("PulserTrms","PulserTrms");
446          calibObjects->Add(calPad);         
447       
448       } else if ( sType == "Pedestals") {
449          AliTPCCalibPedestal *ped = (AliTPCCalibPedestal*)fIn->Get("AliTPCCalibPedestal");
450          
451          calPad = new AliTPCCalPad((TObjArray*)ped->GetCalPadPedestal());         
452          calPad->SetNameTitle("Pedestals","Pedestals");
453          calibObjects->Add(calPad);
454          
455          calPad = new AliTPCCalPad((TObjArray*)ped->GetCalPadRMS());         
456          calPad->SetNameTitle("Noise","Noise");
457          calibObjects->Add(calPad);        
458      
459       } else {
460          fprintf(stderr,"Undefined Type: '%s'",sType.Data());
461          
462       }
463       delete fIn;
464    }
465 }
466
467
468
469 void AliTPCcalibDB::MakeTree(const char * fileName, TObjArray * array, const char * mapFileName, AliTPCCalPad* outlierPad, Float_t ltmFraction) {
470   //
471   // Write a tree with all available information
472   // if mapFileName is specified, the Map information are also written to the tree
473   // pads specified in outlierPad are not used for calculating statistics
474   //  - the same function as AliTPCCalPad::MakeTree - 
475   //
476    AliTPCROC* tpcROCinstance = AliTPCROC::Instance();
477
478    TObjArray* mapIROCs = 0;
479    TObjArray* mapOROCs = 0;
480    TVectorF *mapIROCArray = 0;
481    TVectorF *mapOROCArray = 0;
482    Int_t mapEntries = 0;
483    TString* mapNames = 0;
484    
485    if (mapFileName) {
486       TFile mapFile(mapFileName, "read");
487       
488       TList* listOfROCs = mapFile.GetListOfKeys();
489       mapEntries = listOfROCs->GetEntries()/2;
490       mapIROCs = new TObjArray(mapEntries*2);
491       mapOROCs = new TObjArray(mapEntries*2);
492       mapIROCArray = new TVectorF[mapEntries];
493       mapOROCArray = new TVectorF[mapEntries];
494       
495       mapNames = new TString[mapEntries];
496       for (Int_t ivalue = 0; ivalue < mapEntries; ivalue++) {
497         TString nameROC(((TKey*)(listOfROCs->At(ivalue*2)))->GetName());
498          nameROC.Remove(nameROC.Length()-4, 4);
499          mapIROCs->AddAt((AliTPCCalROC*)mapFile.Get((nameROC + "IROC").Data()), ivalue);
500          mapOROCs->AddAt((AliTPCCalROC*)mapFile.Get((nameROC + "OROC").Data()), ivalue);
501          mapNames[ivalue].Append(nameROC);
502       }
503       
504       for (Int_t ivalue = 0; ivalue < mapEntries; ivalue++) {
505          mapIROCArray[ivalue].ResizeTo(tpcROCinstance->GetNChannels(0));
506          mapOROCArray[ivalue].ResizeTo(tpcROCinstance->GetNChannels(36));
507       
508          for (UInt_t ichannel = 0; ichannel < tpcROCinstance->GetNChannels(0); ichannel++)
509             (mapIROCArray[ivalue])[ichannel] = ((AliTPCCalROC*)(mapIROCs->At(ivalue)))->GetValue(ichannel);
510          for (UInt_t ichannel = 0; ichannel < tpcROCinstance->GetNChannels(36); ichannel++)
511             (mapOROCArray[ivalue])[ichannel] = ((AliTPCCalROC*)(mapOROCs->At(ivalue)))->GetValue(ichannel);
512       }
513
514    } //  if (mapFileName)
515   
516    TTreeSRedirector cstream(fileName);
517    Int_t arrayEntries = array->GetEntries();
518    
519    TString* names = new TString[arrayEntries];
520    for (Int_t ivalue = 0; ivalue < arrayEntries; ivalue++)
521       names[ivalue].Append(((AliTPCCalPad*)array->At(ivalue))->GetName());
522
523    for (UInt_t isector = 0; isector < tpcROCinstance->GetNSectors(); isector++) {
524       //
525       // get statistic for given sector
526       //
527       TVectorF median(arrayEntries);
528       TVectorF mean(arrayEntries);
529       TVectorF rms(arrayEntries);
530       TVectorF ltm(arrayEntries);
531       TVectorF ltmrms(arrayEntries);
532       TVectorF medianWithOut(arrayEntries);
533       TVectorF meanWithOut(arrayEntries);
534       TVectorF rmsWithOut(arrayEntries);
535       TVectorF ltmWithOut(arrayEntries);
536       TVectorF ltmrmsWithOut(arrayEntries);
537       
538       TVectorF *vectorArray = new TVectorF[arrayEntries];
539       for (Int_t ivalue = 0; ivalue < arrayEntries; ivalue++)
540          vectorArray[ivalue].ResizeTo(tpcROCinstance->GetNChannels(isector));
541       
542       for (Int_t ivalue = 0; ivalue < arrayEntries; ivalue++) {
543          AliTPCCalPad* calPad = (AliTPCCalPad*) array->At(ivalue);
544          AliTPCCalROC* calROC = calPad->GetCalROC(isector);
545          AliTPCCalROC* outlierROC = 0;
546          if (outlierPad) outlierROC = outlierPad->GetCalROC(isector);
547          if (calROC) {
548             median[ivalue] = calROC->GetMedian();
549             mean[ivalue] = calROC->GetMean();
550             rms[ivalue] = calROC->GetRMS();
551             Double_t ltmrmsValue = 0;
552             ltm[ivalue] = calROC->GetLTM(&ltmrmsValue, ltmFraction);
553             ltmrms[ivalue] = ltmrmsValue;
554             if (outlierROC) {
555                medianWithOut[ivalue] = calROC->GetMedian(outlierROC);
556                meanWithOut[ivalue] = calROC->GetMean(outlierROC);
557                rmsWithOut[ivalue] = calROC->GetRMS(outlierROC);
558                ltmrmsValue = 0;
559                ltmWithOut[ivalue] = calROC->GetLTM(&ltmrmsValue, ltmFraction, outlierROC);
560                ltmrmsWithOut[ivalue] = ltmrmsValue;
561             }
562          }
563          else {
564             median[ivalue] = 0.;
565             mean[ivalue] = 0.;
566             rms[ivalue] = 0.;
567             ltm[ivalue] = 0.;
568             ltmrms[ivalue] = 0.;
569             medianWithOut[ivalue] = 0.;
570             meanWithOut[ivalue] = 0.;
571             rmsWithOut[ivalue] = 0.;
572             ltmWithOut[ivalue] = 0.;
573             ltmrmsWithOut[ivalue] = 0.;
574          }
575       }
576       
577       //
578       // fill vectors of variable per pad
579       //
580       TVectorF *posArray = new TVectorF[8];
581       for (Int_t ivalue = 0; ivalue < 8; ivalue++)
582          posArray[ivalue].ResizeTo(tpcROCinstance->GetNChannels(isector));
583
584       Float_t posG[3] = {0};
585       Float_t posL[3] = {0};
586       Int_t ichannel = 0;
587       for (UInt_t irow = 0; irow < tpcROCinstance->GetNRows(isector); irow++) {
588          for (UInt_t ipad = 0; ipad < tpcROCinstance->GetNPads(isector, irow); ipad++) {
589             tpcROCinstance->GetPositionLocal(isector, irow, ipad, posL);
590             tpcROCinstance->GetPositionGlobal(isector, irow, ipad, posG);
591             posArray[0][ichannel] = irow;
592             posArray[1][ichannel] = ipad;
593             posArray[2][ichannel] = posL[0];
594             posArray[3][ichannel] = posL[1];
595             posArray[4][ichannel] = posG[0];
596             posArray[5][ichannel] = posG[1];
597             posArray[6][ichannel] = (Int_t)(ipad - (Double_t)(tpcROCinstance->GetNPads(isector, irow))/2);
598             posArray[7][ichannel] = ichannel;
599             
600             // loop over array containing AliTPCCalPads
601             for (Int_t ivalue = 0; ivalue < arrayEntries; ivalue++) {
602                AliTPCCalPad* calPad = (AliTPCCalPad*) array->At(ivalue);
603                AliTPCCalROC* calROC = calPad->GetCalROC(isector);
604                if (calROC)
605                   (vectorArray[ivalue])[ichannel] = calROC->GetValue(irow, ipad);
606                else
607                   (vectorArray[ivalue])[ichannel] = 0;
608             }
609             ichannel++;
610          }
611       }
612       
613       cstream << "calPads" <<
614          "sector=" << isector;
615       
616       for  (Int_t ivalue = 0; ivalue < arrayEntries; ivalue++) {
617          cstream << "calPads" <<
618             (Char_t*)((names[ivalue] + "_Median=").Data()) << median[ivalue] <<
619             (Char_t*)((names[ivalue] + "_Mean=").Data()) << mean[ivalue] <<
620             (Char_t*)((names[ivalue] + "_RMS=").Data()) << rms[ivalue] <<
621             (Char_t*)((names[ivalue] + "_LTM=").Data()) << ltm[ivalue] <<
622             (Char_t*)((names[ivalue] + "_RMS_LTM=").Data()) << ltmrms[ivalue];
623          if (outlierPad) {
624             cstream << "calPads" <<
625                (Char_t*)((names[ivalue] + "_Median_OutlierCutted=").Data()) << medianWithOut[ivalue] <<
626                (Char_t*)((names[ivalue] + "_Mean_OutlierCutted=").Data()) << meanWithOut[ivalue] <<
627                (Char_t*)((names[ivalue] + "_RMS_OutlierCutted=").Data()) << rmsWithOut[ivalue] <<
628                (Char_t*)((names[ivalue] + "_LTM_OutlierCutted=").Data()) << ltmWithOut[ivalue] <<
629                (Char_t*)((names[ivalue] + "_RMS_LTM_OutlierCutted=").Data()) << ltmrmsWithOut[ivalue];
630          }
631       }
632
633       for  (Int_t ivalue = 0; ivalue < arrayEntries; ivalue++) {
634          cstream << "calPads" <<
635             (Char_t*)((names[ivalue] + ".=").Data()) << &vectorArray[ivalue];
636       }
637
638       if (mapFileName) {
639          for  (Int_t ivalue = 0; ivalue < mapEntries; ivalue++) {
640             if (isector < 36)
641                cstream << "calPads" <<
642                   (Char_t*)((mapNames[ivalue] + ".=").Data()) << &mapIROCArray[ivalue];
643             else
644                cstream << "calPads" <<
645                   (Char_t*)((mapNames[ivalue] + ".=").Data()) << &mapOROCArray[ivalue];
646          }
647       }
648
649       cstream << "calPads" <<
650          "row.=" << &posArray[0] <<
651          "pad.=" << &posArray[1] <<
652          "lx.=" << &posArray[2] <<
653          "ly.=" << &posArray[3] <<
654          "gx.=" << &posArray[4] <<
655          "gy.=" << &posArray[5] <<
656          "rpad.=" << &posArray[6] <<
657          "channel.=" << &posArray[7];
658          
659       cstream << "calPads" <<
660          "\n";
661
662       delete[] posArray;
663       delete[] vectorArray;
664    }
665    
666
667    delete[] names;
668    if (mapFileName) {
669       delete mapIROCs;
670       delete mapOROCs;
671       delete[] mapIROCArray;
672       delete[] mapOROCArray;
673       delete[] mapNames;
674    }
675 }
676
677
678
679 void AliTPCcalibDB::RegisterExB(Int_t index, Float_t bz, Bool_t bdelete){
680   //
681   // Register static ExB correction map
682   // index - registration index - used for visualization
683   // bz    - bz field in kGaus
684
685   Float_t factor =  bz/(-5.);  // default b filed in Cheb with minus sign
686   
687   AliMagF*   bmap = new AliMagWrapCheb("Maps","Maps", 2, factor, 10., AliMagWrapCheb::k5kG,kTRUE,"$(ALICE_ROOT)/data/maps/mfchebKGI_sym.root");
688   
689   AliTPCExBFirst *exb  = new  AliTPCExBFirst(bmap,0.88*2.6400e+04,50,50,50);
690   AliTPCExB::SetInstance(exb);
691   
692   if (bdelete){
693     delete bmap;
694   }else{
695     AliTPCExB::RegisterField(index,bmap);
696   }
697   if (index>=fgExBArray.GetEntries()) fgExBArray.Expand((index+1)*2+11);
698   fgExBArray.AddAt(exb,index);
699 }
700
701
702 AliTPCExB*    AliTPCcalibDB::GetExB(Float_t bz, Bool_t deleteB) {
703   //
704   // bz filed in KGaus not in tesla
705   // Get ExB correction map
706   // if doesn't exist - create it
707   //
708   Int_t index = TMath::Nint(5+bz);
709   if (index>fgExBArray.GetEntries()) fgExBArray.Expand((index+1)*2+11);
710   if (!fgExBArray.At(index)) AliTPCcalibDB::RegisterExB(index,bz,deleteB);
711   return (AliTPCExB*)fgExBArray.At(index);
712 }
713
714
715 void  AliTPCcalibDB::SetExBField(Float_t bz){
716   //
717   // Set magnetic filed for ExB correction
718   //
719   printf("Set magnetic field for ExB correction = %f\n",bz); 
720   fExB = GetExB(bz,kFALSE);
721 }
722
723
724
725 void AliTPCcalibDB::GetRunInformations( Int_t run){
726   //
727   // - > Don't use it for reconstruction - Only for Calibration studies
728   //
729   AliCDBEntry * entry = 0;
730   if (run>= fRunList.GetSize()){
731     fRunList.Set(run*2+1);
732     fGRPArray.Expand(run*2+1);
733     fGoofieArray.Expand(run*2+1); 
734     fTemperatureArray.Expand(run*2+1);
735     fVdriftArray.Expand(run*2+1);
736   }
737   if (fRunList[run]>0) return;
738   entry = AliCDBManager::Instance()->Get("GRP/GRP/Data",run);
739   if (entry)  fGRPArray.AddAt(entry->GetObject(),run);
740   entry = AliCDBManager::Instance()->Get("TPC/Calib/Goofie",run);
741   if (entry)  fGoofieArray.AddAt(entry->GetObject(),run);
742   entry = AliCDBManager::Instance()->Get("TPC/Calib/Temperature",run);
743   if (entry)  fTemperatureArray.AddAt(entry->GetObject(),run);
744   fRunList[run]=1;  // sign as used
745
746   AliDCSSensor * press = GetPressureSensor(run);
747   AliTPCSensorTempArray * temp = GetTemperatureSensor(run);
748   if (press && temp){
749     AliTPCCalibVdrift * vdrift = new AliTPCCalibVdrift(temp, press,0);
750     fVdriftArray.AddAt(vdrift,run);
751   }
752 }
753
754
755 Float_t AliTPCcalibDB::GetGain(Int_t sector, Int_t row, Int_t pad){
756   //
757   //
758   AliTPCCalPad *calPad = Instance()->fDedxGainFactor;;
759   if (!calPad) return 0;
760   return calPad->GetCalROC(sector)->GetValue(row,pad);
761 }
762
763 AliDCSSensor * AliTPCcalibDB::GetPressureSensor(Int_t run, Int_t type){
764   //
765   //
766   AliGRPObject * grpRun = dynamic_cast<AliGRPObject *>(fGRPArray.At(run));
767   if (!grpRun) {
768     GetRunInformations(run);
769     grpRun = dynamic_cast<AliGRPObject *>(fGRPArray.At(run));
770     if (!grpRun) return 0; 
771   }
772   AliDCSSensor * sensor = grpRun->GetCavernAtmosPressure();
773   if (type==1) sensor = grpRun->GetSurfaceAtmosPressure();
774   return sensor; 
775 }
776
777 AliTPCSensorTempArray * AliTPCcalibDB::GetTemperatureSensor(Int_t run){
778   //
779   // Get temperature sensor array
780   //
781   AliTPCSensorTempArray * tempArray = (AliTPCSensorTempArray *)fTemperatureArray.At(run);
782   if (!tempArray) {
783     GetRunInformations(run);
784     tempArray = (AliTPCSensorTempArray *)fTemperatureArray.At(run);
785   }
786   return tempArray;
787 }
788
789 AliDCSSensorArray * AliTPCcalibDB::GetGoofieSensors(Int_t run){
790   //
791   // Get temperature sensor array
792   //
793   AliDCSSensorArray * goofieArray = (AliDCSSensorArray *)fGoofieArray.At(run);
794   if (!goofieArray) {
795     GetRunInformations(run);
796     goofieArray = (AliDCSSensorArray *)fGoofieArray.At(run);
797   }
798   return goofieArray;
799 }
800
801 AliTPCCalibVdrift *     AliTPCcalibDB::GetVdrift(Int_t run){
802   //
803   // Get the interface to the the vdrift 
804   //
805   AliTPCCalibVdrift  * vdrift = (AliTPCCalibVdrift*)fVdriftArray.At(run);
806   if (!vdrift) {
807     GetRunInformations(run);
808     vdrift= (AliTPCCalibVdrift*)fVdriftArray.At(run);
809   }
810   return vdrift;
811 }
812
813
814
815
816 Float_t AliTPCcalibDB::GetPressure(Int_t timeStamp, Int_t run, Int_t type){
817   //
818   // GetPressure for given time stamp and runt
819   //
820   TTimeStamp stamp(timeStamp);
821   AliDCSSensor * sensor = Instance()->GetPressureSensor(run,type);
822   if (!sensor) return 0;
823   if (!sensor->GetFit()) return 0;
824   return sensor->GetValue(stamp);
825 }
826
827 Bool_t  AliTPCcalibDB::GetTemperatureFit(Int_t timeStamp, Int_t run, Int_t side,TVectorD& fit){
828   //
829   //
830   //
831   TTimeStamp tstamp(timeStamp);
832   AliTPCSensorTempArray* tempArray  = Instance()->GetTemperatureSensor(run);
833   if (! tempArray) return kFALSE;
834   AliTPCTempMap * tempMap = new AliTPCTempMap(tempArray);
835   TLinearFitter * fitter = tempMap->GetLinearFitter(3,side,tstamp);
836   if (fitter){
837     fitter->Eval(); 
838     fitter->GetParameters(fit);
839   }
840   delete fitter;
841   delete tempMap;
842   if (!fitter) return kFALSE;
843   return kTRUE;
844 }
845
846 Float_t AliTPCcalibDB::GetTemperature(Int_t timeStamp, Int_t run, Int_t side){
847   //
848   //
849   //
850   TVectorD vec;
851   if (side==0) {
852     GetTemperatureFit(timeStamp,run,0,vec);
853     return vec[0];
854   }
855   if (side==1){
856     GetTemperatureFit(timeStamp,run,0,vec);
857     return vec[0];
858   }
859   return 0;
860 }
861
862
863 Double_t AliTPCcalibDB::GetPTRelative(UInt_t timeSec, Int_t run, Int_t side){
864   //
865   // Get relative P/T 
866   // time - absolute time
867   // run  - run number
868   // side - 0 - A side   1-C side
869   AliTPCCalibVdrift * vdrift =  Instance()->GetVdrift(run);
870   if (!vdrift) return 0;
871   return vdrift->GetPTRelative(timeSec,side);
872 }
873
874
875 void AliTPCcalibDB::ProcessEnv(const char * runList){
876   //
877   // Example test function  - how to use the environment variables
878   // runList  -  ascii file with run numbers
879   // output   -  dcsTime.root file with tree 
880
881   ifstream in;
882   in.open(runList);
883   Int_t irun=0;
884   TTreeSRedirector *pcstream = new TTreeSRedirector("dcsTime.root");
885   while(in.good()) {
886     in >> irun;
887     if (irun==0) continue;
888     printf("Processing run %d\n",irun);
889     AliDCSSensor * sensorPressure = AliTPCcalibDB::Instance()->GetPressureSensor(irun);
890     if (!sensorPressure) continue;
891     AliTPCSensorTempArray * tempArray = AliTPCcalibDB::Instance()->GetTemperatureSensor(irun);
892     AliTPCTempMap * tempMap = new AliTPCTempMap(tempArray);
893     AliDCSSensorArray* goofieArray = AliTPCcalibDB::Instance()->GetGoofieSensors(irun);
894     //
895     Int_t startTime = sensorPressure->GetStartTime();
896     Int_t endTime = sensorPressure->GetEndTime();
897     Int_t dtime = TMath::Max((endTime-startTime)/20,10*60);
898     for (Int_t itime=startTime; itime<endTime; itime+=dtime){
899       //
900       TTimeStamp tstamp(itime);
901       Float_t valuePressure = sensorPressure->GetValue(tstamp);
902
903       TLinearFitter * fitter = 0;
904       TVectorD vecTemp[10];
905       if (itime<tempArray->GetStartTime().GetSec() || itime>tempArray->GetEndTime().GetSec()){  
906       }else{
907         for (Int_t itype=0; itype<5; itype++)
908           for (Int_t iside=0; iside<2; iside++){
909             fitter= tempMap->GetLinearFitter(itype,iside,tstamp);
910             if (!fitter) continue;
911             fitter->Eval(); fitter->GetParameters(vecTemp[itype+iside*5]);
912             delete fitter;
913           }
914       }
915       
916       TVectorD vecGoofie, vecEntries, vecMean, vecMedian,vecRMS;
917       if (goofieArray){ 
918         vecGoofie.ResizeTo(goofieArray->NumSensors());
919         ProcessGoofie(goofieArray, vecEntries ,vecMedian, vecMean, vecRMS);
920   //
921         for (Int_t isensor=0; isensor<goofieArray->NumSensors();isensor++){
922           AliDCSSensor *gsensor = goofieArray->GetSensor(isensor);
923           if (gsensor){
924             vecGoofie[isensor] = gsensor->GetValue(tstamp);
925           }
926         }
927       }
928
929
930       //tempMap->GetLinearFitter(0,0,itime);
931       (*pcstream)<<"dcs"<<
932         "run="<<irun<<
933         "time="<<itime<<
934         "goofie.="<<&vecGoofie<<
935         "goofieE.="<<&vecEntries<<
936         "goofieMean.="<<&vecMean<<
937         "goofieMedian.="<<&vecMedian<<
938         "goofieRMS.="<<&vecRMS<<
939         "press="<<valuePressure<<
940         "temp00.="<<&vecTemp[0]<<
941         "temp10.="<<&vecTemp[1]<<
942         "temp20.="<<&vecTemp[2]<<
943         "temp30.="<<&vecTemp[3]<<
944         "temp40.="<<&vecTemp[4]<<
945         "temp01.="<<&vecTemp[5]<<
946         "temp11.="<<&vecTemp[6]<<
947         "temp21.="<<&vecTemp[7]<<
948         "temp31.="<<&vecTemp[8]<<
949         "temp41.="<<&vecTemp[9]<<
950         "\n";
951     }
952   }
953   delete pcstream;
954 }
955
956
957 void AliTPCcalibDB::ProcessGoofie( AliDCSSensorArray* goofieArray, TVectorD & vecEntries, TVectorD & vecMedian, TVectorD &vecMean, TVectorD &vecRMS){
958   /*
959     
960   1       TPC_ANODE_I_A00_STAT
961   2       TPC_DVM_CO2
962   3       TPC_DVM_DriftVelocity
963   4       TPC_DVM_FCageHV
964   5       TPC_DVM_GainFar
965   6       TPC_DVM_GainNear
966   7       TPC_DVM_N2
967   8       TPC_DVM_NumberOfSparks
968   9       TPC_DVM_PeakAreaFar
969   10      TPC_DVM_PeakAreaNear
970   11      TPC_DVM_PeakPosFar
971   12      TPC_DVM_PeakPosNear
972   13      TPC_DVM_PickupHV
973   14      TPC_DVM_Pressure
974   15      TPC_DVM_T1_Over_P
975   16      TPC_DVM_T2_Over_P
976   17      TPC_DVM_T_Over_P
977   18      TPC_DVM_TemperatureS1
978    */
979   //
980   //
981   //  TVectorD  vecMedian; TVectorD  vecEntries; TVectorD  vecMean; TVectorD  vecRMS;
982   Double_t kEpsilon=0.0000000001;
983   Double_t kBig=100000000000.;
984   Int_t nsensors = goofieArray->NumSensors();
985   vecEntries.ResizeTo(nsensors);
986   vecMedian.ResizeTo(nsensors);
987   vecMean.ResizeTo(nsensors);
988   vecRMS.ResizeTo(nsensors);
989   TVectorF values;
990   for (Int_t isensor=0; isensor<goofieArray->NumSensors();isensor++){
991     AliDCSSensor *gsensor = goofieArray->GetSensor(isensor);
992     if (gsensor &&  gsensor->GetGraph()){
993       Int_t npoints = gsensor->GetGraph()->GetN();
994       // filter zeroes
995       values.ResizeTo(npoints);
996       Int_t nused =0;
997       for (Int_t ipoint=0; ipoint<npoints; ipoint++){
998         if (TMath::Abs(gsensor->GetGraph()->GetY()[ipoint])>kEpsilon && 
999            TMath::Abs(gsensor->GetGraph()->GetY()[ipoint])<kBig ){
1000           values[nused]=gsensor->GetGraph()->GetY()[ipoint];
1001           nused++;
1002         }
1003       }
1004       //
1005       vecEntries[isensor]= nused;      
1006       if (nused>1){
1007         vecMedian[isensor] = TMath::Median(nused,values.GetMatrixArray());
1008         vecMean[isensor]   = TMath::Mean(nused,values.GetMatrixArray());
1009         vecRMS[isensor]    = TMath::RMS(nused,values.GetMatrixArray());
1010       }
1011     }
1012   }
1013 }
1014