]> git.uio.no Git - u/mrichter/AliRoot.git/blob - MUON/AliMUONCDB.cxx
Script to create a random bad channel map.
[u/mrichter/AliRoot.git] / MUON / AliMUONCDB.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 /* $Id$ */
17
18 //-----------------------------------------------------------------------------
19 /// \class AliMUONCDB
20 ///
21 /// Helper class to experience the OCDB
22 /// It allows to generate dummy (but complete) containers for all the
23 /// calibration data types we have for tracker and trigger, and to write
24 /// them into OCDB.
25 ///
26 /// For more information, please see READMECDB
27 ///
28 // \author Laurent Aphecetche
29 //-----------------------------------------------------------------------------
30
31 #include "AliMUONCDB.h"
32
33 #include "AliMUON1DArray.h"
34 #include "AliMUON1DMap.h"
35 #include "AliMUON2DMap.h"
36 #include "AliMUON2DStoreValidator.h"
37 #include "AliMUONCalibParamNF.h"
38 #include "AliMUONCalibParamNI.h"
39 #include "AliMUONConstants.h"
40 #include "AliMUONTrackerIO.h"
41 #include "AliMUONTriggerEfficiencyCells.h"
42 #include "AliMUONTriggerLut.h"
43 #include "AliMUONVStore.h"
44 #include "AliMUONVCalibParam.h"
45 #include "AliMUONVCalibParam.h"
46 #include "AliMUONGlobalCrateConfig.h"
47 #include "AliMUONRegionalTriggerConfig.h"
48
49 #include "AliMpCDB.h"
50 #include "AliMpConstants.h"
51 #include "AliMpDDLStore.h"
52 #include "AliMpManuStore.h"
53 #include "AliMpDEManager.h"
54 #include "AliMpDetElement.h"
55 #include "AliMpFiles.h"
56 #include "AliMpHVNamer.h"
57 #include "AliMpManuIterator.h"
58 #include "AliMpSegmentation.h"
59 #include "AliMpStationType.h"
60 #include "AliMpVSegmentation.h"
61
62 #include "AliCodeTimer.h"
63 #include "AliCDBEntry.h"
64 #include "AliCDBManager.h"
65 #include "AliDCSValue.h"
66 #include "AliLog.h"
67
68 #include <Riostream.h>
69 #include <TArrayI.h>
70 #include <TClass.h>
71 #include <TH1F.h>
72 #include <TList.h>
73 #include <TMap.h>
74 #include <TObjString.h>
75 #include <TROOT.h>
76 #include <TRandom.h>
77 #include <TStopwatch.h>
78 #include <TSystem.h>
79 #include <TMath.h>
80
81
82 /// \cond CLASSIMP
83 ClassImp(AliMUONCDB)
84 /// \endcond
85
86 namespace
87 {
88   //_____________________________________________________________________________
89 AliMUONVStore* Create2DMap()
90 {
91   return new AliMUON2DMap(true);
92 }
93
94   //_____________________________________________________________________________
95 void getBoundaries(const AliMUONVStore& store, Int_t dim,
96                    Float_t* xmin, Float_t* xmax)
97 {
98   /// Assuming the store contains AliMUONVCalibParam objects, compute the
99   /// limits of the value contained in the VCalibParam, for each of its dimensions
100   /// xmin and xmax must be of dimension dim
101   
102   for ( Int_t i = 0; i < dim; ++i ) 
103   {
104     xmin[i]=1E30;
105     xmax[i]=-1E30;
106   }
107   
108   TIter next(store.CreateIterator());
109   AliMUONVCalibParam* value;
110   
111   while ( ( value = dynamic_cast<AliMUONVCalibParam*>(next() ) ) )
112   {
113     Int_t detElemId = value->ID0();
114     Int_t manuId = value->ID1();
115     
116     const AliMpVSegmentation* seg = 
117       AliMpSegmentation::Instance()->GetMpSegmentationByElectronics(detElemId,manuId);
118         
119     for ( Int_t manuChannel = 0; manuChannel < value->Size(); ++manuChannel )
120     {
121       AliMpPad pad = seg->PadByLocation(AliMpIntPair(manuId,manuChannel),kFALSE);
122       if (!pad.IsValid()) continue;
123       
124       for ( Int_t i = 0; i < dim; ++i ) 
125       {
126         Float_t x0 = value->ValueAsFloat(manuChannel,i);
127       
128         xmin[i] = TMath::Min(xmin[i],x0);
129         xmax[i] = TMath::Max(xmax[i],x0);
130       }
131     }
132   }
133
134   for ( Int_t i = 0; i < dim; ++i ) 
135   {
136     if ( TMath::Abs(xmin[i]-xmax[i]) < 1E-3 ) 
137     {
138       xmin[i] -= 1;
139       xmax[i] += 1;
140     }
141   }
142 }
143
144 //_____________________________________________________________________________
145 Double_t GetRandom(Double_t mean, Double_t sigma, Bool_t mustBePositive)
146 {
147   Double_t x(-1);
148   if ( mustBePositive ) 
149   {
150     while ( x < 0 ) 
151     {
152       x = gRandom->Gaus(mean,sigma);
153     }
154   }
155   else
156   {
157     x = gRandom->Gaus(mean,sigma);
158   }
159   return x;
160 }
161
162 }
163
164 //_____________________________________________________________________________
165 AliMUONCDB::AliMUONCDB(const char* cdbpath)
166 : TObject(),
167   fCDBPath(cdbpath),
168   fMaxNofChannelsToGenerate(-1)
169 {
170   /// ctor
171     // Load mapping
172     if ( ! AliMpCDB::LoadDDLStore() ) {
173       AliFatal("Could not access mapping from OCDB !");
174     }
175
176     if ( ! AliMpCDB::LoadManuStore() ) {
177       AliFatal("Could not access run-dependent mapping from OCDB !");
178     }
179 }
180
181 //_____________________________________________________________________________
182 AliMUONCDB::~AliMUONCDB()
183 {
184   /// dtor
185 }
186
187 //_____________________________________________________________________________
188 AliMUONVStore* 
189 AliMUONCDB::Diff(AliMUONVStore& store1, AliMUONVStore& store2, 
190                  const char* opt)
191 {
192   /// creates a store which contains store1-store2
193   /// if opt="abs" the difference is absolute one,
194   /// if opt="rel" then what is stored is (store1-store2)/store1
195   /// if opt="percent" then what is stored is rel*100
196   ///
197   /// WARNING Works only for stores which holds AliMUONVCalibParam objects
198   
199   TString sopt(opt);
200   sopt.ToUpper();
201   
202   if ( !sopt.Contains("ABS") && !sopt.Contains("REL") && !sopt.Contains("PERCENT") )
203   {
204     AliErrorClass(Form("opt %s not supported. Only ABS, REL, PERCENT are",opt));
205     return 0x0;
206   }
207   
208   AliMUONVStore* d = static_cast<AliMUONVStore*>(store1.Clone());
209   
210   TIter next(d->CreateIterator());
211   
212   AliMUONVCalibParam* param;
213   
214   while ( ( param = dynamic_cast<AliMUONVCalibParam*>(next() ) ) )
215   {
216     Int_t detElemId = param->ID0();
217     Int_t manuId = param->ID1();
218     
219     AliMUONVCalibParam* param2 = dynamic_cast<AliMUONVCalibParam*>(store2.FindObject(detElemId,manuId));
220     //FIXME: this might happen. Handle it.
221     if (!param2) 
222     {
223       cerr << "param2 is null : FIXME : this might happen !" << endl;
224       delete d;
225       return 0;
226     }
227     
228     for ( Int_t i = 0; i < param->Size(); ++i )
229     {
230       for ( Int_t j = 0; j < param->Dimension(); ++j )
231       {
232         Float_t value(0);
233         if ( sopt.Contains("ABS") )
234         {
235           value = param->ValueAsFloat(i,j) - param2->ValueAsFloat(i,j);
236         }
237         else if ( sopt.Contains("REL") || sopt.Contains("PERCENT") )
238         {
239           if ( param->ValueAsFloat(i,j) ) 
240           {
241             value = (param->ValueAsFloat(i,j) - param2->ValueAsFloat(i,j))/param->ValueAsFloat(i,j);
242           }
243           else 
244           {
245             continue;
246           }
247           if ( sopt.Contains("PERCENT") ) value *= 100.0;
248         }
249         param->SetValueAsFloat(i,j,value);
250       }      
251     }
252   }
253   return d;
254 }
255
256 //_____________________________________________________________________________
257 void 
258 AliMUONCDB::Plot(const AliMUONVStore& store, const char* name, Int_t nbins)
259 {
260   /// Make histograms of each dimension of the AliMUONVCalibParam
261   /// contained inside store.
262   /// It produces histograms named name_0, name_1, etc...
263   
264   TIter next(store.CreateIterator());
265   AliMUONVCalibParam* param;
266   Int_t n(0);
267   const Int_t kNStations = AliMpConstants::NofTrackingChambers()/2;
268   Int_t* nPerStation = new Int_t[kNStations];
269   TH1** h(0x0);
270   
271   for ( Int_t i = 0; i < kNStations; ++i ) nPerStation[i]=0;
272   
273   while ( ( param = static_cast<AliMUONVCalibParam*>(next()) ) )
274   {
275     if (!h)
276     {
277       Int_t dim = param->Dimension();
278       h = new TH1*[dim];
279       Float_t* xmin = new Float_t[dim];
280       Float_t* xmax = new Float_t[dim];
281       getBoundaries(store,dim,xmin,xmax);
282       
283       for ( Int_t i = 0; i < dim; ++i ) 
284       {
285         h[i] = new TH1F(Form("%s_%d",name,i),Form("%s_%d",name,i),
286                             nbins,xmin[i],xmax[i]);
287         AliInfo(Form("Created histogram %s",h[i]->GetName()));
288       }
289     }
290     
291     Int_t detElemId = param->ID0();
292     Int_t manuId = param->ID1();
293     Int_t station = AliMpDEManager::GetChamberId(detElemId)/2;
294     
295     const AliMpVSegmentation* seg = 
296       AliMpSegmentation::Instance()->GetMpSegmentationByElectronics(detElemId,manuId);
297     
298     for ( Int_t manuChannel = 0; manuChannel < param->Size(); ++manuChannel )
299     {
300       AliMpPad pad = seg->PadByLocation(AliMpIntPair(manuId,manuChannel),kFALSE);
301       if (!pad.IsValid()) continue;
302
303       ++n;
304       ++nPerStation[station];
305       
306       for ( Int_t dim = 0; dim < param->Dimension(); ++dim ) 
307       {
308         h[dim]->Fill(param->ValueAsFloat(manuChannel,dim));
309       }
310     }
311   } 
312   
313   for ( Int_t i = 0; i < kNStations; ++i )
314   {
315     AliInfo(Form("Station %d %d ",(i+1),nPerStation[i]));
316   }
317
318   AliInfo(Form("Number of channels = %d",n));
319   
320   delete[] nPerStation;
321 }
322
323 //_____________________________________________________________________________
324 Int_t 
325 AliMUONCDB::MakeHVStore(TMap& aliasMap, Bool_t defaultValues)
326 {
327   /// Create a HV store
328   
329   AliMpHVNamer hvNamer;
330   
331   TObjArray* aliases = hvNamer.GenerateAliases();
332   
333   Int_t nSwitch(0);
334   Int_t nChannels(0);
335   
336   for ( Int_t i = 0; i < aliases->GetEntries(); ++i ) 
337   {
338     TObjString* alias = static_cast<TObjString*>(aliases->At(i));
339     TString& aliasName = alias->String();
340     if ( aliasName.Contains("sw") ) 
341     {
342       // HV Switch (St345 only)
343       TObjArray* valueSet = new TObjArray;
344       valueSet->SetOwner(kTRUE);
345       
346       Bool_t value = kTRUE;
347       
348       if (!defaultValues)
349       {
350         Float_t r = gRandom->Uniform();
351         if ( r < 0.007 ) value = kFALSE;      
352       } 
353       
354       for ( UInt_t timeStamp = 0; timeStamp < 60*3; timeStamp += 60 )
355       {
356         AliDCSValue* dcsValue = new AliDCSValue(value,timeStamp);
357         valueSet->Add(dcsValue);
358       }
359       aliasMap.Add(new TObjString(*alias),valueSet);
360       ++nSwitch;
361     }
362     else
363     {
364       TObjArray* valueSet = new TObjArray;
365       valueSet->SetOwner(kTRUE);
366       for ( UInt_t timeStamp = 0; timeStamp < 60*15; timeStamp += 120 )
367       {
368         Float_t value = 1500;
369         if (!defaultValues) value = GetRandom(1750,62.5,true);
370         AliDCSValue* dcsValue = new AliDCSValue(value,timeStamp);
371         valueSet->Add(dcsValue);
372       }
373       aliasMap.Add(new TObjString(*alias),valueSet);
374       ++nChannels;
375     }
376   }
377   
378   delete aliases;
379   
380   AliInfo(Form("%d HV channels and %d switches",nChannels,nSwitch));
381   
382   return nChannels+nSwitch;
383 }
384
385 //_____________________________________________________________________________
386 Int_t 
387 AliMUONCDB::MakePedestalStore(AliMUONVStore& pedestalStore, Bool_t defaultValues)
388 {
389   /// Create a pedestal store. if defaultValues=true, ped.mean=ped.sigma=1,
390   /// otherwise mean and sigma are from a gaussian (with parameters
391   /// defined below by the kPedestal* constants)
392
393   AliCodeTimerAuto("");
394   
395   Int_t nchannels(0);
396   Int_t nmanus(0);
397   
398   const Int_t kChannels(AliMpConstants::ManuNofChannels());
399   const Float_t kPedestalMeanMean(200);
400   const Float_t kPedestalMeanSigma(10);
401   const Float_t kPedestalSigmaMean(1.0);
402   const Float_t kPedestalSigmaSigma(0.2);
403
404   Int_t detElemId;
405   Int_t manuId;
406     
407   AliMpManuIterator it;
408   
409   while ( it.Next(detElemId,manuId) )
410   {
411     ++nmanus;
412
413     AliMUONVCalibParam* ped = 
414       new AliMUONCalibParamNF(2,kChannels,detElemId,manuId,AliMUONVCalibParam::InvalidFloatValue());
415
416     AliMpDetElement* de = AliMpDDLStore::Instance()->GetDetElement(detElemId);
417     
418     for ( Int_t manuChannel = 0; manuChannel < kChannels; ++manuChannel )
419     {
420       if ( ! de->IsConnectedChannel(manuId,manuChannel) ) continue;
421       
422       ++nchannels;
423       
424       Float_t meanPedestal;
425       Float_t sigmaPedestal;
426       
427       if ( defaultValues ) 
428       {
429         meanPedestal = 0.0;
430         sigmaPedestal = 1.0;
431       }
432       else
433       {
434         Bool_t positive(kTRUE);
435         meanPedestal = 0.0;
436         while ( meanPedestal == 0.0 ) // avoid strict zero 
437         {
438           meanPedestal = GetRandom(kPedestalMeanMean,kPedestalMeanSigma,positive);
439         }
440         sigmaPedestal = GetRandom(kPedestalSigmaMean,kPedestalSigmaSigma,positive);
441       }
442       ped->SetValueAsFloat(manuChannel,0,meanPedestal);
443       ped->SetValueAsFloat(manuChannel,1,sigmaPedestal);
444       
445     }
446     Bool_t ok = pedestalStore.Add(ped);
447     if (!ok)
448     {
449       AliError(Form("Could not set DetElemId=%d manuId=%d",detElemId,manuId));
450     }
451     if ( fMaxNofChannelsToGenerate > 0 && nchannels >= fMaxNofChannelsToGenerate ) break;
452   }
453   
454   AliInfo(Form("%d Manus and %d channels.",nmanus,nchannels));
455   return nchannels;
456 }
457
458 //_____________________________________________________________________________
459 Int_t
460 AliMUONCDB::MakeCapacitanceStore(AliMUONVStore& capaStore, const char* file)
461 {
462   /// Read the capacitance values from file and append them to the capaStore
463   
464   return AliMUONTrackerIO::ReadCapacitances(file,capaStore);
465 }
466
467 //_____________________________________________________________________________
468 Int_t 
469 AliMUONCDB::MakeCapacitanceStore(AliMUONVStore& capaStore, Bool_t defaultValues)
470 {
471   /// Create a capacitance store. if defaultValues=true, all capa are 1.0,
472   /// otherwise they are from a gaussian with parameters defined in the
473   /// kCapa* constants below.
474
475   AliCodeTimerAuto("");
476   
477   Int_t nchannels(0);
478   Int_t nmanus(0);
479   Int_t nmanusOK(0); // manus for which we got the serial number
480     
481   const Float_t kCapaMean(0.3);
482   const Float_t kCapaSigma(0.1);
483   const Float_t kInjectionGainMean(3);
484   const Float_t kInjectionGainSigma(1);
485
486   Int_t detElemId;
487   Int_t manuId;
488   
489   AliMpManuIterator it;
490   
491   while ( it.Next(detElemId,manuId) )
492   {
493     ++nmanus;
494     
495     AliMpDetElement* de = AliMpDDLStore::Instance()->GetDetElement(detElemId); 
496     Int_t serialNumber = AliMpManuStore::Instance()->GetManuSerial(detElemId, manuId);
497       
498     if ( serialNumber <= 0 ) continue;
499     
500     ++nmanusOK;
501     
502     AliMUONVCalibParam* capa = static_cast<AliMUONVCalibParam*>(capaStore.FindObject(serialNumber));
503     
504     if (!capa)
505     {
506       capa = new AliMUONCalibParamNF(2,AliMpConstants::ManuNofChannels(),serialNumber,0,1.0);
507       Bool_t ok = capaStore.Add(capa);
508       if (!ok)
509       {
510         AliError(Form("Could not set serialNumber=%d manuId=%d",serialNumber,manuId));
511       }      
512     }
513     
514     for ( Int_t manuChannel = 0; manuChannel < capa->Size(); ++manuChannel )
515     {
516       if ( ! de->IsConnectedChannel(manuId,manuChannel) ) continue;
517       
518       ++nchannels;
519       
520       Float_t capaValue;
521       Float_t injectionGain;
522       
523       if ( defaultValues ) 
524       {
525         capaValue = 1.0;
526         injectionGain = 1.0;
527       }
528       else
529       {
530         capaValue = GetRandom(kCapaMean,kCapaSigma,kTRUE);
531         injectionGain = GetRandom(kInjectionGainMean,kInjectionGainSigma,kTRUE);
532       }
533       capa->SetValueAsFloat(manuChannel,0,capaValue);
534       capa->SetValueAsFloat(manuChannel,1,injectionGain);
535     }
536   }
537   
538   Float_t percent = 0;
539   if ( nmanus ) percent = 100*nmanusOK/nmanus;
540   AliInfo(Form("%5d manus with serial number (out of %5d manus = %3.0f%%)",
541                nmanusOK,nmanus,percent));
542   AliInfo(Form("%5d channels",nchannels));
543   if ( percent < 100 ) 
544   {
545     AliWarning("Did not get all serial numbers. capaStore is incomplete !!!!");
546   }
547   return nchannels;
548   
549 }
550
551 //_____________________________________________________________________________
552 Int_t 
553 AliMUONCDB::MakeGainStore(AliMUONVStore& gainStore, Bool_t defaultValues)
554 {  
555   /// Create a gain store. if defaultValues=true, all gains set so that
556   /// charge = (adc-ped)
557   ///
558   /// otherwise parameters are taken from gaussians with parameters 
559   /// defined in the k* constants below.
560   
561   AliCodeTimerAuto("");
562   
563   Int_t nchannels(0);
564   Int_t nmanus(0);
565     
566   const Int_t kSaturation(3000);
567   const Double_t kA0Mean(1.2);
568   const Double_t kA0Sigma(0.1);
569   const Double_t kA1Mean(1E-5);
570   const Double_t kA1Sigma(1E-6);
571   const Double_t kQualMean(0xFF);
572   const Double_t kQualSigma(0x10);
573   const Int_t kThresMean(1600);
574   const Int_t kThresSigma(100);
575   
576   Int_t detElemId;
577   Int_t manuId;
578   
579   AliMpManuIterator it;
580   
581   while ( it.Next(detElemId,manuId) )
582   {
583     ++nmanus;
584
585     AliMUONVCalibParam* gain = 
586       new AliMUONCalibParamNF(5,AliMpConstants::ManuNofChannels(),
587                               detElemId,
588                               manuId,
589                               AliMUONVCalibParam::InvalidFloatValue());
590
591     AliMpDetElement* de = AliMpDDLStore::Instance()->GetDetElement(detElemId);
592
593     for ( Int_t manuChannel = 0; manuChannel < gain->Size(); ++manuChannel )
594     {
595       if ( ! de->IsConnectedChannel(manuId,manuChannel) ) continue;
596       
597       ++nchannels;
598       
599       if ( defaultValues ) 
600       {
601         gain->SetValueAsFloat(manuChannel,0,1.0);
602         gain->SetValueAsFloat(manuChannel,1,0.0);
603         gain->SetValueAsInt(manuChannel,2,4095); 
604         gain->SetValueAsInt(manuChannel,3,1);
605         gain->SetValueAsInt(manuChannel,4,kSaturation);
606       }
607       else
608       {
609         Bool_t positive(kTRUE);
610         gain->SetValueAsFloat(manuChannel,0,GetRandom(kA0Mean,kA0Sigma,positive));
611         gain->SetValueAsFloat(manuChannel,1,GetRandom(kA1Mean,kA1Sigma,!positive));
612         gain->SetValueAsInt(manuChannel,2,(Int_t)TMath::Nint(GetRandom(kThresMean,kThresSigma,positive)));
613         gain->SetValueAsInt(manuChannel,3,(Int_t)TMath::Nint(GetRandom(kQualMean,kQualSigma,positive)));
614         gain->SetValueAsInt(manuChannel,4,kSaturation);        
615       }
616       
617     }
618     Bool_t ok = gainStore.Add(gain);
619     if (!ok)
620     {
621       AliError(Form("Could not set DetElemId=%d manuId=%d",detElemId,manuId));
622     }
623     if ( fMaxNofChannelsToGenerate > 0 && nchannels >= fMaxNofChannelsToGenerate ) break;
624   }
625   
626   AliInfo(Form("%d Manus and %d channels.",nmanus,nchannels));
627   return nchannels;
628 }
629
630 //_____________________________________________________________________________
631 Int_t
632 AliMUONCDB::MakeLocalTriggerMaskStore(AliMUONVStore& localBoardMasks) const
633 {
634   /// Generate local trigger masks store. All masks are set to FFFF
635   
636   AliCodeTimerAuto("");
637   
638   Int_t ngenerated(0);
639   // Generate fake mask values for all localboards and put that into
640   // one single container (localBoardMasks)
641   for ( Int_t i = 1; i <= AliMpConstants::TotalNofLocalBoards(); ++i )
642   {
643     AliMUONVCalibParam* localBoard = new AliMUONCalibParamNI(1,8,i,0,0);
644     for ( Int_t x = 0; x < 2; ++x )
645     {
646       for ( Int_t y = 0; y < 4; ++y )
647       {
648         Int_t index = x*4+y;
649         localBoard->SetValueAsInt(index,0,0xFFFF);
650         ++ngenerated;
651       }
652     }
653     localBoardMasks.Add(localBoard);
654   }
655   return ngenerated;
656 }
657
658 //_____________________________________________________________________________
659 Int_t
660 AliMUONCDB::MakeRegionalTriggerConfigStore(AliMUONRegionalTriggerConfig& rtm) const
661 {
662   /// Make a regional trigger config store. Mask is set to FFFF for each local board (Ch.F.)
663   
664   AliCodeTimerAuto("");
665   
666   if ( ! rtm.ReadData(AliMpFiles::LocalTriggerBoardMapping()) ) {
667     AliErrorStream() << "Error when reading from mapping file" << endl;
668     return 0;
669   }
670     
671   return rtm.GetNofTriggerCrates();  
672 }
673
674
675 //_____________________________________________________________________________
676 Int_t 
677 AliMUONCDB::MakeGlobalTriggerConfigStore(AliMUONGlobalCrateConfig& gtm) const
678 {
679   /// Make a global trigger config store. All masks (disable) set to 0x00 for each Darc board (Ch.F.)
680   
681   AliCodeTimerAuto("");
682
683     return gtm.ReadData(AliMpFiles::GlobalTriggerBoardMapping());
684 }
685
686
687 //_____________________________________________________________________________
688 AliMUONTriggerLut* 
689 AliMUONCDB::MakeTriggerLUT(const char* file) const
690 {
691   /// Make a triggerlut object, from a file.
692   
693   AliCodeTimerAuto("");
694   
695   AliMUONTriggerLut* lut = new AliMUONTriggerLut;
696   lut->ReadFromFile(file);
697   return lut;
698 }
699
700 //_____________________________________________________________________________
701 AliMUONTriggerEfficiencyCells*
702 AliMUONCDB::MakeTriggerEfficiency(const char* file) const
703 {
704   /// Make a trigger efficiency object from a file.
705   
706   AliCodeTimerAuto("");
707   
708   return new AliMUONTriggerEfficiencyCells(file);
709 }
710
711 //_____________________________________________________________________________
712 void 
713 AliMUONCDB::WriteToCDB(const char* calibpath, TObject* object, 
714                        Int_t startRun, Int_t endRun, 
715                        const char* filename)
716 {
717   /// Write a given object to OCDB
718   
719   AliCDBId id(calibpath,startRun,endRun);
720   AliCDBMetaData md;
721   md.SetAliRootVersion(gROOT->GetVersion());
722   md.SetComment(gSystem->ExpandPathName(filename));
723   md.SetResponsible("Uploaded using AliMUONCDB class");
724   AliCDBManager* man = AliCDBManager::Instance();
725   man->SetDefaultStorage(fCDBPath);
726   man->Put(object,id,&md);
727 }
728
729 //_____________________________________________________________________________
730 void 
731 AliMUONCDB::WriteToCDB(const char* calibpath, TObject* object, 
732                        Int_t startRun, Int_t endRun, Bool_t defaultValues)
733 {
734   /// Write a given object to OCDB
735   
736   AliCDBId id(calibpath,startRun,endRun);
737   AliCDBMetaData md;
738   md.SetAliRootVersion(gROOT->GetVersion());
739   if ( defaultValues )
740   {
741     md.SetComment("Test with default values");
742   }
743   else
744   {
745     md.SetComment("Test with random values");
746   }
747   md.SetResponsible("AliMUONCDB tester class");
748   
749   AliCDBManager* man = AliCDBManager::Instance();
750   man->SetDefaultStorage(fCDBPath);
751   man->Put(object,id,&md);
752 }
753
754 //_____________________________________________________________________________
755 Int_t 
756 AliMUONCDB::MakeNeighbourStore(AliMUONVStore& neighbourStore)
757 {
758   /// Fill the neighbours store with, for each channel, a TObjArray of its
759   /// neighbouring pads (including itself)
760   
761   AliCodeTimerAuto("");
762   
763   AliInfo("Generating NeighbourStore. This will take a while. Please be patient.");
764   
765   Int_t nchannels(0);
766   
767   TObjArray tmp;
768
769   Int_t detElemId;
770   Int_t manuId;
771   
772   AliMpManuIterator it;
773   
774   while ( it.Next(detElemId,manuId) )
775   {
776     const AliMpVSegmentation* seg = 
777       AliMpSegmentation::Instance()->GetMpSegmentationByElectronics(detElemId,manuId);
778     
779     AliMUONVCalibParam* calibParam = static_cast<AliMUONVCalibParam*>(neighbourStore.FindObject(detElemId,manuId));
780     if (!calibParam)
781     {
782       Int_t dimension(11);
783       Int_t size(AliMpConstants::ManuNofChannels());
784       Int_t defaultValue(-1);
785       Int_t packingFactor(size);
786       
787       calibParam = new AliMUONCalibParamNI(dimension,size,detElemId,manuId,defaultValue,packingFactor);
788       Bool_t ok = neighbourStore.Add(calibParam);
789       if (!ok)
790       {
791         AliError(Form("Could not set DetElemId=%d manuId=%d",detElemId,manuId));
792         return -1;
793       }      
794     }
795     
796     for ( Int_t manuChannel = 0; manuChannel < AliMpConstants::ManuNofChannels(); ++manuChannel )
797     {
798       AliMpPad pad = seg->PadByLocation(AliMpIntPair(manuId,manuChannel),kFALSE);
799       
800       if (pad.IsValid()) 
801       {
802         ++nchannels;
803
804         seg->GetNeighbours(pad,tmp,true,true);
805         Int_t nofPadNeighbours = tmp.GetEntriesFast();
806             
807         for ( Int_t i = 0; i < nofPadNeighbours; ++i )
808         {
809           AliMpPad* p = static_cast<AliMpPad*>(tmp.UncheckedAt(i));
810           Int_t x;
811 //          Bool_t ok =
812           calibParam->PackValues(p->GetLocation().GetFirst(),p->GetLocation().GetSecond(),x);
813 //          if (!ok)
814 //          {
815 //            AliError("Could not pack value. Something is seriously wrong. Please check");
816 //            StdoutToAliError(pad->Print(););
817 //            return -1;
818 //          }
819           calibParam->SetValueAsInt(manuChannel,i,x);
820         }
821       }
822     }
823     }
824   
825   return nchannels;
826 }
827
828 //_____________________________________________________________________________
829 void
830 AliMUONCDB::SetMaxNofChannelsToGenerate(Int_t n)
831 {
832   /// Set the maximum number of channels to generate (used for testing only)
833   /// n < 0 means no limit
834   fMaxNofChannelsToGenerate = n;
835 }
836
837 //_____________________________________________________________________________
838 void
839 AliMUONCDB::WriteLocalTriggerMasks(Int_t startRun, Int_t endRun)
840 {  
841   /// Write local trigger masks to OCDB
842   
843   AliMUONVStore* ltm = new AliMUON1DArray(AliMpConstants::TotalNofLocalBoards()+1);
844   Int_t ngenerated = MakeLocalTriggerMaskStore(*ltm);
845   AliInfo(Form("Ngenerated = %d",ngenerated));
846   if (ngenerated>0)
847   {
848     WriteToCDB("MUON/Calib/LocalTriggerBoardMasks",ltm,startRun,endRun,true);
849   }
850   delete ltm;
851 }
852
853 //_____________________________________________________________________________
854 void
855 AliMUONCDB::WriteRegionalTriggerConfig(Int_t startRun, Int_t endRun)
856 {  
857   /// Write regional trigger masks to OCDB
858   
859   AliMUONRegionalTriggerConfig* rtm = new AliMUONRegionalTriggerConfig();
860   Int_t ngenerated = MakeRegionalTriggerConfigStore(*rtm);
861   AliInfo(Form("Ngenerated = %d",ngenerated));
862   if (ngenerated>0)
863   {
864     WriteToCDB("MUON/Calib/RegionalTriggerConfig",rtm,startRun,endRun,true);
865   }
866   delete rtm;
867 }
868
869
870 //_____________________________________________________________________________
871 void
872 AliMUONCDB::WriteGlobalTriggerConfig(Int_t startRun, Int_t endRun)
873 {  
874   /// Write global trigger masks to OCDB
875   
876   AliMUONGlobalCrateConfig* gtm = new AliMUONGlobalCrateConfig();
877
878   Int_t ngenerated = MakeGlobalTriggerConfigStore(*gtm);
879   AliInfo(Form("Ngenerated = %d",ngenerated));
880   if (ngenerated>0)
881   {
882     WriteToCDB("MUON/Calib/GlobalTriggerCrateConfig",gtm,startRun,endRun,true);
883   }
884   delete gtm;
885 }
886
887
888 //_____________________________________________________________________________
889 void
890 AliMUONCDB::WriteTriggerLut(Int_t startRun, Int_t endRun)
891 {  
892   /// Write trigger LUT to OCDB
893   
894   AliMUONTriggerLut* lut = MakeTriggerLUT();
895   if (lut)
896   {
897     WriteToCDB("MUON/Calib/TriggerLut",lut,startRun,endRun,true);
898   }
899   delete lut;
900 }
901
902 //_____________________________________________________________________________
903 void
904 AliMUONCDB::WriteTriggerEfficiency(Int_t startRun, Int_t endRun)
905 {  
906   /// Write trigger efficiency to OCDB
907   
908   AliMUONTriggerEfficiencyCells* eff = MakeTriggerEfficiency();
909   if (eff)
910   {
911     WriteToCDB("MUON/Calib/TriggerEfficiency",eff,startRun,endRun,true);
912   }
913   delete eff;
914 }
915
916 //_____________________________________________________________________________
917 void 
918 AliMUONCDB::WriteNeighbours(Int_t startRun, Int_t endRun)
919 {
920   /// Write neighbours to OCDB
921   
922   AliMUONVStore* neighbours = Create2DMap();
923   Int_t ngenerated = MakeNeighbourStore(*neighbours);
924   AliInfo(Form("Ngenerated = %d",ngenerated));
925   if (ngenerated>0)
926   {
927     WriteToCDB("MUON/Calib/Neighbours",neighbours,startRun,endRun,true);
928   }
929   delete neighbours;
930 }
931
932 //_____________________________________________________________________________
933 void 
934 AliMUONCDB::WriteHV(Bool_t defaultValues,
935                     Int_t startRun, Int_t endRun)
936 {
937   /// generate HV values (either cste = 1500 V) if defaultValues=true or random
938   /// if defaultValues=false, see makeHVStore) and
939   /// store them into CDB located at cdbpath, with a validity period
940   /// ranging from startRun to endRun
941   
942   TMap* hvStore = new TMap;
943   Int_t ngenerated = MakeHVStore(*hvStore,defaultValues);
944   AliInfo(Form("Ngenerated = %d",ngenerated));
945   if (ngenerated>0)
946   {
947     WriteToCDB("MUON/Calib/HV",hvStore,startRun,endRun,defaultValues);
948   }
949   delete hvStore;
950 }
951
952 //_____________________________________________________________________________
953 void 
954 AliMUONCDB::WritePedestals(Bool_t defaultValues,
955                            Int_t startRun, Int_t endRun)
956 {
957   /// generate pedestal values (either 0 if defaultValues=true or random
958   /// if defaultValues=false, see makePedestalStore) and
959   /// store them into CDB located at cdbpath, with a validity period
960   /// ranging from startRun to endRun
961   
962   AliMUONVStore* pedestalStore = Create2DMap();
963   Int_t ngenerated = MakePedestalStore(*pedestalStore,defaultValues);
964   AliInfo(Form("Ngenerated = %d",ngenerated));
965   WriteToCDB("MUON/Calib/Pedestals",pedestalStore,startRun,endRun,defaultValues);
966   delete pedestalStore;
967 }
968
969
970 //_____________________________________________________________________________
971 void 
972 AliMUONCDB::WriteGains(Bool_t defaultValues,
973                        Int_t startRun, Int_t endRun)
974 {
975   /// generate gain values (either 1 if defaultValues=true or random
976   /// if defaultValues=false, see makeGainStore) and
977   /// store them into CDB located at cdbpath, with a validity period
978   /// ranging from startRun to endRun
979   
980   AliMUONVStore* gainStore = Create2DMap();
981   Int_t ngenerated = MakeGainStore(*gainStore,defaultValues);
982   AliInfo(Form("Ngenerated = %d",ngenerated));  
983   WriteToCDB("MUON/Calib/Gains",gainStore,startRun,endRun,defaultValues);
984   delete gainStore;
985 }
986
987 //_____________________________________________________________________________
988 void 
989 AliMUONCDB::WriteCapacitances(const char* filename,
990                               Int_t startRun, Int_t endRun)
991 {
992   /// read manu capacitance and injection gain values from file 
993   /// and store them into CDB located at cdbpath, with a validity period
994   /// ranging from startRun to endRun
995   
996   AliMUONVStore* capaStore = new AliMUON1DMap(16828);
997   Int_t ngenerated = MakeCapacitanceStore(*capaStore,filename);
998   AliInfo(Form("Ngenerated = %d",ngenerated));
999   if ( ngenerated > 0 ) 
1000   {
1001     WriteToCDB("MUON/Calib/Capacitances",capaStore,startRun,endRun,filename);
1002   }
1003   delete capaStore;
1004 }
1005
1006 //_____________________________________________________________________________
1007 void 
1008 AliMUONCDB::WriteCapacitances(Bool_t defaultValues,
1009                               Int_t startRun, Int_t endRun)
1010 {
1011   /// generate manu capacitance values (either 1 if defaultValues=true or random
1012   /// if defaultValues=false, see makeCapacitanceStore) and
1013   /// store them into CDB located at cdbpath, with a validity period
1014   /// ranging from startRun to endRun
1015   
1016   AliMUONVStore* capaStore = new AliMUON1DMap(16828);
1017   Int_t ngenerated = MakeCapacitanceStore(*capaStore,defaultValues);
1018   AliInfo(Form("Ngenerated = %d",ngenerated));
1019   WriteToCDB("MUON/Calib/Capacitances",capaStore,startRun,endRun,defaultValues);
1020   delete capaStore;
1021 }
1022
1023 //_____________________________________________________________________________
1024 void
1025 AliMUONCDB::WriteTrigger(Int_t startRun, Int_t endRun)
1026 {
1027   /// Writes all Trigger related calibration to CDB
1028   WriteLocalTriggerMasks(startRun,endRun);
1029   WriteRegionalTriggerConfig(startRun,endRun);
1030   WriteGlobalTriggerConfig(startRun,endRun);
1031   WriteTriggerLut(startRun,endRun);
1032   WriteTriggerEfficiency(startRun,endRun);
1033 }
1034
1035 //_____________________________________________________________________________
1036 void
1037 AliMUONCDB::WriteTracker(Bool_t defaultValues, Int_t startRun, Int_t endRun)
1038 {
1039   /// Writes all Tracker related calibration to CDB
1040   WriteHV(defaultValues,startRun,endRun);
1041   WritePedestals(defaultValues,startRun,endRun);
1042   WriteGains(defaultValues,startRun,endRun);
1043   WriteCapacitances(defaultValues,startRun,endRun);
1044   WriteNeighbours(startRun,endRun);
1045 }