]> git.uio.no Git - u/mrichter/AliRoot.git/blob - MUON/AliMUONCDB.cxx
QA ref defaut storage setter in sim and rec
[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 "AliMpDCSNamer.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   AliMpDCSNamer hvNamer("TRACKER");
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::MakeTriggerDCSStore(TMap& aliasMap, Bool_t defaultValues)
388 {
389   /// Create a Trigger HV and Currents store
390   
391   AliMpDCSNamer triggerDCSNamer("TRIGGER");
392   
393   TObjArray* aliases = triggerDCSNamer.GenerateAliases();
394   
395   Int_t nChannels[2] = {0, 0};
396   
397   for ( Int_t i = 0; i < aliases->GetEntries(); ++i ) 
398   {
399     TObjString* alias = static_cast<TObjString*>(aliases->At(i));
400     TString& aliasName = alias->String();
401
402     TObjArray* valueSet = new TObjArray;
403     valueSet->SetOwner(kTRUE);
404     Int_t measureType = triggerDCSNamer.DCSvariableFromDCSAlias(aliasName.Data());
405     for ( UInt_t timeStamp = 0; timeStamp < 60*15; timeStamp += 120 )
406     {
407       Float_t value = 
408         (measureType == AliMpDCSNamer::kDCSI) ? 2. : 8000.;
409       if (!defaultValues) {
410         switch (measureType){
411         case AliMpDCSNamer::kDCSI:
412           value = GetRandom(2.,0.4,true);
413           break;
414         case AliMpDCSNamer::kDCSHV:
415           value = GetRandom(8000.,16.,true);
416           break;
417         }
418       }
419       AliDCSValue* dcsValue = new AliDCSValue(value,timeStamp);
420       valueSet->Add(dcsValue);
421     }
422     aliasMap.Add(new TObjString(*alias),valueSet);
423     ++nChannels[measureType];
424   }
425   
426   delete aliases;
427   
428   AliInfo(Form("Trigger channels I -> %i   HV -> %i",nChannels[0], nChannels[1]));
429   
430   return nChannels[0] + nChannels[1];
431 }
432
433 //_____________________________________________________________________________
434 Int_t 
435 AliMUONCDB::MakePedestalStore(AliMUONVStore& pedestalStore, Bool_t defaultValues)
436 {
437   /// Create a pedestal store. if defaultValues=true, ped.mean=ped.sigma=1,
438   /// otherwise mean and sigma are from a gaussian (with parameters
439   /// defined below by the kPedestal* constants)
440
441   AliCodeTimerAuto("");
442   
443   Int_t nchannels(0);
444   Int_t nmanus(0);
445   
446   const Int_t kChannels(AliMpConstants::ManuNofChannels());
447   
448   // bending
449   const Float_t kPedestalMeanMeanB(200.);
450   const Float_t kPedestalMeanSigmaB(10.);
451   const Float_t kPedestalSigmaMeanB(1.);
452   const Float_t kPedestalSigmaSigmaB(0.2);
453   
454   // non bending
455   const Float_t kPedestalMeanMeanNB(200.);
456   const Float_t kPedestalMeanSigmaNB(10.);
457   const Float_t kPedestalSigmaMeanNB(1.);
458   const Float_t kPedestalSigmaSigmaNB(0.2);
459   
460   const Float_t kFractionOfDeadManu(0.); // within [0.,1.]
461
462   Int_t detElemId;
463   Int_t manuId;
464     
465   AliMpManuIterator it;
466   
467   while ( it.Next(detElemId,manuId) )
468   {
469     // skip a given fraction of manus
470     if (kFractionOfDeadManu > 0. && gRandom->Uniform() < kFractionOfDeadManu) continue;
471     
472     ++nmanus;
473
474     AliMUONVCalibParam* ped = 
475       new AliMUONCalibParamNF(2,kChannels,detElemId,manuId,AliMUONVCalibParam::InvalidFloatValue());
476
477     AliMpDetElement* de = AliMpDDLStore::Instance()->GetDetElement(detElemId);
478     
479     for ( Int_t manuChannel = 0; manuChannel < kChannels; ++manuChannel )
480     {
481       if ( ! de->IsConnectedChannel(manuId,manuChannel) ) continue;
482       
483       ++nchannels;
484       
485       Float_t meanPedestal;
486       Float_t sigmaPedestal;
487       
488       if ( defaultValues ) 
489       {
490         meanPedestal = 0.0;
491         sigmaPedestal = 1.0;
492       }
493       else
494       {
495         Bool_t positive(kTRUE);
496         meanPedestal = 0.0;
497         
498         if ( manuId & AliMpConstants::ManuMask(AliMp::kNonBendingPlane) ) { // manu in non bending plane
499           
500           while ( meanPedestal == 0.0 ) // avoid strict zero 
501           {
502             meanPedestal = GetRandom(kPedestalMeanMeanNB,kPedestalMeanSigmaNB,positive);
503           }
504           sigmaPedestal = GetRandom(kPedestalSigmaMeanNB,kPedestalSigmaSigmaNB,positive);
505           
506         } else { // manu in bending plane
507           
508           while ( meanPedestal == 0.0 ) // avoid strict zero 
509           {
510             meanPedestal = GetRandom(kPedestalMeanMeanB,kPedestalMeanSigmaB,positive);
511           }
512           sigmaPedestal = GetRandom(kPedestalSigmaMeanB,kPedestalSigmaSigmaB,positive);
513           
514         }
515         
516       }
517       
518       ped->SetValueAsFloat(manuChannel,0,meanPedestal);
519       ped->SetValueAsFloat(manuChannel,1,sigmaPedestal);
520       
521     }
522     Bool_t ok = pedestalStore.Add(ped);
523     if (!ok)
524     {
525       AliError(Form("Could not set DetElemId=%d manuId=%d",detElemId,manuId));
526     }
527     if ( fMaxNofChannelsToGenerate > 0 && nchannels >= fMaxNofChannelsToGenerate ) break;
528   }
529   
530   AliInfo(Form("%d Manus and %d channels.",nmanus,nchannels));
531   return nchannels;
532 }
533
534 //_____________________________________________________________________________
535 Int_t
536 AliMUONCDB::MakeCapacitanceStore(AliMUONVStore& capaStore, const char* file)
537 {
538   /// Read the capacitance values from file and append them to the capaStore
539   
540   return AliMUONTrackerIO::ReadCapacitances(file,capaStore);
541 }
542
543 //_____________________________________________________________________________
544 Int_t 
545 AliMUONCDB::MakeCapacitanceStore(AliMUONVStore& capaStore, Bool_t defaultValues)
546 {
547   /// Create a capacitance store. if defaultValues=true, all capa are 1.0,
548   /// otherwise they are from a gaussian with parameters defined in the
549   /// kCapa* constants below.
550
551   AliCodeTimerAuto("");
552   
553   Int_t nchannels(0);
554   Int_t nmanus(0);
555   Int_t nmanusOK(0); // manus for which we got the serial number
556     
557   const Float_t kCapaMean(0.3);
558   const Float_t kCapaSigma(0.1);
559   const Float_t kInjectionGainMean(3);
560   const Float_t kInjectionGainSigma(1);
561
562   Int_t detElemId;
563   Int_t manuId;
564   
565   AliMpManuIterator it;
566   
567   while ( it.Next(detElemId,manuId) )
568   {
569     ++nmanus;
570     
571     AliMpDetElement* de = AliMpDDLStore::Instance()->GetDetElement(detElemId); 
572     Int_t serialNumber = AliMpManuStore::Instance()->GetManuSerial(detElemId, manuId);
573       
574     if ( serialNumber <= 0 ) continue;
575     
576     ++nmanusOK;
577     
578     AliMUONVCalibParam* capa = static_cast<AliMUONVCalibParam*>(capaStore.FindObject(serialNumber));
579     
580     if (!capa)
581     {
582       capa = new AliMUONCalibParamNF(2,AliMpConstants::ManuNofChannels(),serialNumber,0,1.0);
583       Bool_t ok = capaStore.Add(capa);
584       if (!ok)
585       {
586         AliError(Form("Could not set serialNumber=%d manuId=%d",serialNumber,manuId));
587       }      
588     }
589     
590     for ( Int_t manuChannel = 0; manuChannel < capa->Size(); ++manuChannel )
591     {
592       if ( ! de->IsConnectedChannel(manuId,manuChannel) ) continue;
593       
594       ++nchannels;
595       
596       Float_t capaValue;
597       Float_t injectionGain;
598       
599       if ( defaultValues ) 
600       {
601         capaValue = 1.0;
602         injectionGain = 1.0;
603       }
604       else
605       {
606         capaValue = GetRandom(kCapaMean,kCapaSigma,kTRUE);
607         injectionGain = GetRandom(kInjectionGainMean,kInjectionGainSigma,kTRUE);
608       }
609       capa->SetValueAsFloat(manuChannel,0,capaValue);
610       capa->SetValueAsFloat(manuChannel,1,injectionGain);
611     }
612   }
613   
614   Float_t percent = 0;
615   if ( nmanus ) percent = 100*nmanusOK/nmanus;
616   AliInfo(Form("%5d manus with serial number (out of %5d manus = %3.0f%%)",
617                nmanusOK,nmanus,percent));
618   AliInfo(Form("%5d channels",nchannels));
619   if ( percent < 100 ) 
620   {
621     AliWarning("Did not get all serial numbers. capaStore is incomplete !!!!");
622   }
623   return nchannels;
624   
625 }
626
627 //_____________________________________________________________________________
628 Int_t 
629 AliMUONCDB::MakeGainStore(AliMUONVStore& gainStore, Bool_t defaultValues)
630 {  
631   /// Create a gain store. if defaultValues=true, all gains set so that
632   /// charge = (adc-ped)
633   ///
634   /// otherwise parameters are taken from gaussians with parameters 
635   /// defined in the k* constants below.
636   
637   AliCodeTimerAuto("");
638   
639   Int_t nchannels(0);
640   Int_t nmanus(0);
641     
642   const Int_t kSaturation(3000);
643   const Double_t kA0Mean(1.2);
644   const Double_t kA0Sigma(0.1);
645   const Double_t kA1Mean(1E-5);
646   const Double_t kA1Sigma(1E-6);
647   const Double_t kQualMean(0xFF);
648   const Double_t kQualSigma(0x10);
649   const Int_t kThresMean(1600);
650   const Int_t kThresSigma(100);
651   
652   Int_t detElemId;
653   Int_t manuId;
654   
655   AliMpManuIterator it;
656   
657   while ( it.Next(detElemId,manuId) )
658   {
659     ++nmanus;
660
661     AliMUONVCalibParam* gain = 
662       new AliMUONCalibParamNF(5,AliMpConstants::ManuNofChannels(),
663                               detElemId,
664                               manuId,
665                               AliMUONVCalibParam::InvalidFloatValue());
666
667     AliMpDetElement* de = AliMpDDLStore::Instance()->GetDetElement(detElemId);
668
669     for ( Int_t manuChannel = 0; manuChannel < gain->Size(); ++manuChannel )
670     {
671       if ( ! de->IsConnectedChannel(manuId,manuChannel) ) continue;
672       
673       ++nchannels;
674       
675       if ( defaultValues ) 
676       {
677         gain->SetValueAsFloat(manuChannel,0,1.0);
678         gain->SetValueAsFloat(manuChannel,1,0.0);
679         gain->SetValueAsInt(manuChannel,2,4095); 
680         gain->SetValueAsInt(manuChannel,3,1);
681         gain->SetValueAsInt(manuChannel,4,kSaturation);
682       }
683       else
684       {
685         Bool_t positive(kTRUE);
686         gain->SetValueAsFloat(manuChannel,0,GetRandom(kA0Mean,kA0Sigma,positive));
687         gain->SetValueAsFloat(manuChannel,1,GetRandom(kA1Mean,kA1Sigma,!positive));
688         gain->SetValueAsInt(manuChannel,2,(Int_t)TMath::Nint(GetRandom(kThresMean,kThresSigma,positive)));
689         gain->SetValueAsInt(manuChannel,3,(Int_t)TMath::Nint(GetRandom(kQualMean,kQualSigma,positive)));
690         gain->SetValueAsInt(manuChannel,4,kSaturation);        
691       }
692       
693     }
694     Bool_t ok = gainStore.Add(gain);
695     if (!ok)
696     {
697       AliError(Form("Could not set DetElemId=%d manuId=%d",detElemId,manuId));
698     }
699     if ( fMaxNofChannelsToGenerate > 0 && nchannels >= fMaxNofChannelsToGenerate ) break;
700   }
701   
702   AliInfo(Form("%d Manus and %d channels.",nmanus,nchannels));
703   return nchannels;
704 }
705
706 //_____________________________________________________________________________
707 Int_t
708 AliMUONCDB::MakeLocalTriggerMaskStore(AliMUONVStore& localBoardMasks) const
709 {
710   /// Generate local trigger masks store. All masks are set to FFFF
711   
712   AliCodeTimerAuto("");
713   
714   Int_t ngenerated(0);
715   // Generate fake mask values for all localboards and put that into
716   // one single container (localBoardMasks)
717   for ( Int_t i = 1; i <= AliMpConstants::TotalNofLocalBoards(); ++i )
718   {
719     AliMUONVCalibParam* localBoard = new AliMUONCalibParamNI(1,8,i,0,0);
720     for ( Int_t x = 0; x < 2; ++x )
721     {
722       for ( Int_t y = 0; y < 4; ++y )
723       {
724         Int_t index = x*4+y;
725         localBoard->SetValueAsInt(index,0,0xFFFF);
726         ++ngenerated;
727       }
728     }
729     localBoardMasks.Add(localBoard);
730   }
731   return ngenerated;
732 }
733
734 //_____________________________________________________________________________
735 Int_t
736 AliMUONCDB::MakeRegionalTriggerConfigStore(AliMUONRegionalTriggerConfig& rtm) const
737 {
738   /// Make a regional trigger config store. Mask is set to FFFF for each local board (Ch.F.)
739   
740   AliCodeTimerAuto("");
741   
742   if ( ! rtm.ReadData(AliMpFiles::LocalTriggerBoardMapping()) ) {
743     AliErrorStream() << "Error when reading from mapping file" << endl;
744     return 0;
745   }
746     
747   return rtm.GetNofTriggerCrates();  
748 }
749
750
751 //_____________________________________________________________________________
752 Int_t 
753 AliMUONCDB::MakeGlobalTriggerConfigStore(AliMUONGlobalCrateConfig& gtm) const
754 {
755   /// Make a global trigger config store. All masks (disable) set to 0x00 for each Darc board (Ch.F.)
756   
757   AliCodeTimerAuto("");
758   
759   return gtm.ReadData(AliMpFiles::GlobalTriggerBoardMapping());
760 }
761
762
763 //_____________________________________________________________________________
764 AliMUONTriggerLut* 
765 AliMUONCDB::MakeTriggerLUT(const char* file) const
766 {
767   /// Make a triggerlut object, from a file.
768   
769   AliCodeTimerAuto("");
770   
771   AliMUONTriggerLut* lut = new AliMUONTriggerLut;
772   lut->ReadFromFile(file);
773   return lut;
774 }
775
776 //_____________________________________________________________________________
777 AliMUONTriggerEfficiencyCells*
778 AliMUONCDB::MakeTriggerEfficiency(const char* file) const
779 {
780   /// Make a trigger efficiency object from a file.
781   
782   AliCodeTimerAuto("");
783   
784   return new AliMUONTriggerEfficiencyCells(file);
785 }
786
787 //_____________________________________________________________________________
788 void 
789 AliMUONCDB::WriteToCDB(const char* calibpath, TObject* object, 
790                        Int_t startRun, Int_t endRun, 
791                        const char* filename)
792 {
793   /// Write a given object to OCDB
794   
795   TString comment(gSystem->ExpandPathName(filename));
796   
797   WriteToCDB(object, calibpath, startRun, endRun, comment.Data());
798 }
799
800 //_____________________________________________________________________________
801 void 
802 AliMUONCDB::WriteToCDB(const char* calibpath, TObject* object, 
803                        Int_t startRun, Int_t endRun, Bool_t defaultValues)
804 {
805   /// Write a given object to OCDB
806   
807   TString comment;
808   if ( defaultValues ) comment += "Test with default values";
809   else comment += "Test with random values";
810   
811   WriteToCDB(object, calibpath, startRun, endRun, comment.Data());
812 }
813
814 //_____________________________________________________________________________
815 void
816 AliMUONCDB::WriteToCDB(TObject* object, const char* calibpath, Int_t startRun, Int_t endRun,
817                        const char* comment, const char* responsible)
818 {
819   /// Write a given object to OCDB
820   
821   AliCDBId id(calibpath,startRun,endRun);
822   AliCDBMetaData md;
823   md.SetAliRootVersion(gROOT->GetVersion());
824   md.SetComment(comment);
825   md.SetResponsible(responsible);
826   AliCDBManager* man = AliCDBManager::Instance();
827   if (!man->IsDefaultStorageSet()) man->SetDefaultStorage(fCDBPath);
828   man->Put(object,id,&md);
829 }
830
831 //_____________________________________________________________________________
832 Int_t 
833 AliMUONCDB::MakeNeighbourStore(AliMUONVStore& neighbourStore)
834 {
835   /// Fill the neighbours store with, for each channel, a TObjArray of its
836   /// neighbouring pads (including itself)
837   
838   AliCodeTimerAuto("");
839   
840   AliInfo("Generating NeighbourStore. This will take a while. Please be patient.");
841   
842   Int_t nchannels(0);
843   
844   TObjArray tmp;
845
846   Int_t detElemId;
847   Int_t manuId;
848   
849   AliMpManuIterator it;
850   
851   while ( it.Next(detElemId,manuId) )
852   {
853     const AliMpVSegmentation* seg = 
854       AliMpSegmentation::Instance()->GetMpSegmentationByElectronics(detElemId,manuId);
855     
856     AliMUONVCalibParam* calibParam = static_cast<AliMUONVCalibParam*>(neighbourStore.FindObject(detElemId,manuId));
857     if (!calibParam)
858     {
859       Int_t dimension(11);
860       Int_t size(AliMpConstants::ManuNofChannels());
861       Int_t defaultValue(-1);
862       Int_t packingFactor(size);
863       
864       calibParam = new AliMUONCalibParamNI(dimension,size,detElemId,manuId,defaultValue,packingFactor);
865       Bool_t ok = neighbourStore.Add(calibParam);
866       if (!ok)
867       {
868         AliError(Form("Could not set DetElemId=%d manuId=%d",detElemId,manuId));
869         return -1;
870       }      
871     }
872     
873     for ( Int_t manuChannel = 0; manuChannel < AliMpConstants::ManuNofChannels(); ++manuChannel )
874     {
875       AliMpPad pad = seg->PadByLocation(AliMpIntPair(manuId,manuChannel),kFALSE);
876       
877       if (pad.IsValid()) 
878       {
879         ++nchannels;
880
881         seg->GetNeighbours(pad,tmp,true,true);
882         Int_t nofPadNeighbours = tmp.GetEntriesFast();
883             
884         for ( Int_t i = 0; i < nofPadNeighbours; ++i )
885         {
886           AliMpPad* p = static_cast<AliMpPad*>(tmp.UncheckedAt(i));
887           Int_t x;
888 //          Bool_t ok =
889           calibParam->PackValues(p->GetLocation().GetFirst(),p->GetLocation().GetSecond(),x);
890 //          if (!ok)
891 //          {
892 //            AliError("Could not pack value. Something is seriously wrong. Please check");
893 //            StdoutToAliError(pad->Print(););
894 //            return -1;
895 //          }
896           calibParam->SetValueAsInt(manuChannel,i,x);
897         }
898       }
899     }
900     }
901   
902   return nchannels;
903 }
904
905 //_____________________________________________________________________________
906 void
907 AliMUONCDB::SetMaxNofChannelsToGenerate(Int_t n)
908 {
909   /// Set the maximum number of channels to generate (used for testing only)
910   /// n < 0 means no limit
911   fMaxNofChannelsToGenerate = n;
912 }
913
914 //_____________________________________________________________________________
915 void
916 AliMUONCDB::WriteLocalTriggerMasks(Int_t startRun, Int_t endRun)
917 {  
918   /// Write local trigger masks to OCDB
919   
920   AliMUONVStore* ltm = new AliMUON1DArray(AliMpConstants::TotalNofLocalBoards()+1);
921   Int_t ngenerated = MakeLocalTriggerMaskStore(*ltm);
922   AliInfo(Form("Ngenerated = %d",ngenerated));
923   if (ngenerated>0)
924   {
925     WriteToCDB("MUON/Calib/LocalTriggerBoardMasks",ltm,startRun,endRun,true);
926   }
927   delete ltm;
928 }
929
930 //_____________________________________________________________________________
931 void
932 AliMUONCDB::WriteRegionalTriggerConfig(Int_t startRun, Int_t endRun)
933 {  
934   /// Write regional trigger masks to OCDB
935   
936   AliMUONRegionalTriggerConfig* rtm = new AliMUONRegionalTriggerConfig();
937   Int_t ngenerated = MakeRegionalTriggerConfigStore(*rtm);
938   AliInfo(Form("Ngenerated = %d",ngenerated));
939   if (ngenerated>0)
940   {
941     WriteToCDB("MUON/Calib/RegionalTriggerConfig",rtm,startRun,endRun,true);
942   }
943   delete rtm;
944 }
945
946
947 //_____________________________________________________________________________
948 void
949 AliMUONCDB::WriteGlobalTriggerConfig(Int_t startRun, Int_t endRun)
950 {  
951   /// Write global trigger masks to OCDB
952   
953   AliMUONGlobalCrateConfig* gtm = new AliMUONGlobalCrateConfig();
954
955   Int_t ngenerated = MakeGlobalTriggerConfigStore(*gtm);
956   AliInfo(Form("Ngenerated = %d",ngenerated));
957   if (ngenerated>0)
958   {
959     WriteToCDB("MUON/Calib/GlobalTriggerCrateConfig",gtm,startRun,endRun,true);
960   }
961   delete gtm;
962 }
963
964
965 //_____________________________________________________________________________
966 void
967 AliMUONCDB::WriteTriggerLut(Int_t startRun, Int_t endRun)
968 {  
969   /// Write trigger LUT to OCDB
970   
971   AliMUONTriggerLut* lut = MakeTriggerLUT();
972   if (lut)
973   {
974     WriteToCDB("MUON/Calib/TriggerLut",lut,startRun,endRun,true);
975   }
976   delete lut;
977 }
978
979 //_____________________________________________________________________________
980 void
981 AliMUONCDB::WriteTriggerEfficiency(Int_t startRun, Int_t endRun)
982 {  
983   /// Write trigger efficiency to OCDB
984   
985   AliMUONTriggerEfficiencyCells* eff = MakeTriggerEfficiency();
986   if (eff)
987   {
988     WriteToCDB("MUON/Calib/TriggerEfficiency",eff,startRun,endRun,true);
989   }
990   delete eff;
991 }
992
993 //_____________________________________________________________________________
994 void 
995 AliMUONCDB::WriteNeighbours(Int_t startRun, Int_t endRun)
996 {
997   /// Write neighbours to OCDB
998   
999   AliMUONVStore* neighbours = Create2DMap();
1000   Int_t ngenerated = MakeNeighbourStore(*neighbours);
1001   AliInfo(Form("Ngenerated = %d",ngenerated));
1002   if (ngenerated>0)
1003   {
1004     WriteToCDB("MUON/Calib/Neighbours",neighbours,startRun,endRun,true);
1005   }
1006   delete neighbours;
1007 }
1008
1009 //_____________________________________________________________________________
1010 void 
1011 AliMUONCDB::WriteHV(Bool_t defaultValues,
1012                     Int_t startRun, Int_t endRun)
1013 {
1014   /// generate HV values (either cste = 1500 V) if defaultValues=true or random
1015   /// if defaultValues=false, see makeHVStore) and
1016   /// store them into CDB located at cdbpath, with a validity period
1017   /// ranging from startRun to endRun
1018   
1019   TMap* hvStore = new TMap;
1020   Int_t ngenerated = MakeHVStore(*hvStore,defaultValues);
1021   AliInfo(Form("Ngenerated = %d",ngenerated));
1022   if (ngenerated>0)
1023   {
1024     WriteToCDB("MUON/Calib/HV",hvStore,startRun,endRun,defaultValues);
1025   }
1026   delete hvStore;
1027 }
1028
1029 //_____________________________________________________________________________
1030 void 
1031 AliMUONCDB::WriteTriggerDCS(Bool_t defaultValues,
1032                     Int_t startRun, Int_t endRun)
1033 {
1034   /// generate Trigger HV and current values (either const if defaultValues=true or random
1035   /// if defaultValues=false, see makeTriggerDCSStore) and
1036   /// store them into CDB located at cdbpath, with a validity period
1037   /// ranging from startRun to endRun
1038   
1039   TMap* triggerDCSStore = new TMap;
1040   Int_t ngenerated = MakeTriggerDCSStore(*triggerDCSStore,defaultValues);
1041   AliInfo(Form("Ngenerated = %d",ngenerated));
1042   if (ngenerated>0)
1043   {
1044     WriteToCDB("MUON/Calib/TriggerDCS",triggerDCSStore,startRun,endRun,defaultValues);
1045   }
1046   delete triggerDCSStore;
1047 }
1048
1049 //_____________________________________________________________________________
1050 void 
1051 AliMUONCDB::WritePedestals(Bool_t defaultValues,
1052                            Int_t startRun, Int_t endRun)
1053 {
1054   /// generate pedestal values (either 0 if defaultValues=true or random
1055   /// if defaultValues=false, see makePedestalStore) and
1056   /// store them into CDB located at cdbpath, with a validity period
1057   /// ranging from startRun to endRun
1058   
1059   AliMUONVStore* pedestalStore = Create2DMap();
1060   Int_t ngenerated = MakePedestalStore(*pedestalStore,defaultValues);
1061   AliInfo(Form("Ngenerated = %d",ngenerated));
1062   WriteToCDB("MUON/Calib/Pedestals",pedestalStore,startRun,endRun,defaultValues);
1063   delete pedestalStore;
1064 }
1065
1066
1067 //_____________________________________________________________________________
1068 void 
1069 AliMUONCDB::WriteGains(Bool_t defaultValues,
1070                        Int_t startRun, Int_t endRun)
1071 {
1072   /// generate gain values (either 1 if defaultValues=true or random
1073   /// if defaultValues=false, see makeGainStore) and
1074   /// store them into CDB located at cdbpath, with a validity period
1075   /// ranging from startRun to endRun
1076   
1077   AliMUONVStore* gainStore = Create2DMap();
1078   Int_t ngenerated = MakeGainStore(*gainStore,defaultValues);
1079   AliInfo(Form("Ngenerated = %d",ngenerated));  
1080   WriteToCDB("MUON/Calib/Gains",gainStore,startRun,endRun,defaultValues);
1081   delete gainStore;
1082 }
1083
1084 //_____________________________________________________________________________
1085 void 
1086 AliMUONCDB::WriteCapacitances(const char* filename,
1087                               Int_t startRun, Int_t endRun)
1088 {
1089   /// read manu capacitance and injection gain values from file 
1090   /// and store them into CDB located at cdbpath, with a validity period
1091   /// ranging from startRun to endRun
1092   
1093   AliMUONVStore* capaStore = new AliMUON1DMap(16828);
1094   Int_t ngenerated = MakeCapacitanceStore(*capaStore,filename);
1095   AliInfo(Form("Ngenerated = %d",ngenerated));
1096   if ( ngenerated > 0 ) 
1097   {
1098     WriteToCDB("MUON/Calib/Capacitances",capaStore,startRun,endRun,filename);
1099   }
1100   delete capaStore;
1101 }
1102
1103 //_____________________________________________________________________________
1104 void 
1105 AliMUONCDB::WriteCapacitances(Bool_t defaultValues,
1106                               Int_t startRun, Int_t endRun)
1107 {
1108   /// generate manu capacitance values (either 1 if defaultValues=true or random
1109   /// if defaultValues=false, see makeCapacitanceStore) and
1110   /// store them into CDB located at cdbpath, with a validity period
1111   /// ranging from startRun to endRun
1112   
1113   AliMUONVStore* capaStore = new AliMUON1DMap(16828);
1114   Int_t ngenerated = MakeCapacitanceStore(*capaStore,defaultValues);
1115   AliInfo(Form("Ngenerated = %d",ngenerated));
1116   WriteToCDB("MUON/Calib/Capacitances",capaStore,startRun,endRun,defaultValues);
1117   delete capaStore;
1118 }
1119
1120 //_____________________________________________________________________________
1121 void
1122 AliMUONCDB::WriteTrigger(Bool_t defaultValues, Int_t startRun, Int_t endRun)
1123 {
1124   /// Writes all Trigger related calibration to CDB
1125   WriteTriggerDCS(defaultValues,startRun,endRun);
1126   WriteLocalTriggerMasks(startRun,endRun);
1127   WriteRegionalTriggerConfig(startRun,endRun);
1128   WriteGlobalTriggerConfig(startRun,endRun);
1129   WriteTriggerLut(startRun,endRun);
1130   WriteTriggerEfficiency(startRun,endRun);
1131 }
1132
1133 //_____________________________________________________________________________
1134 void
1135 AliMUONCDB::WriteTracker(Bool_t defaultValues, Int_t startRun, Int_t endRun)
1136 {
1137   /// Writes all Tracker related calibration to CDB
1138   WriteHV(defaultValues,startRun,endRun);
1139   WritePedestals(defaultValues,startRun,endRun);
1140   WriteGains(defaultValues,startRun,endRun);
1141   WriteCapacitances(defaultValues,startRun,endRun);
1142   WriteNeighbours(startRun,endRun);
1143 }
1144