]> git.uio.no Git - u/mrichter/AliRoot.git/blob - MUON/AliMUONCDB.cxx
Possibility to vary the cos(PA) cut
[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 /// \namespace AliMUONCDB
20 ///
21 /// Helper functions to experience the OCDB
22 ///
23 /// They allow to read magnetic field, mapping and recoParam from OCDB
24 ///
25 /// And also to generate dummy (but complete) containers for all the
26 /// calibration data types we have for tracker and trigger, and to write
27 /// them into OCDB.
28 ///
29 /// For more information, please see READMEcalib
30 ///
31 /// \author Laurent Aphecetche
32 //-----------------------------------------------------------------------------
33
34 #include "AliMUONCDB.h"
35
36 #include "AliMUON1DArray.h"
37 #include "AliMUON1DMap.h"
38 #include "AliMUON2DMap.h"
39 #include "AliMUON2DStoreValidator.h"
40 #include "AliMUONCalibParamND.h"
41 #include "AliMUONCalibParamNF.h"
42 #include "AliMUONCalibParamNI.h"
43 #include "AliMUONCalibrationData.h"
44 #include "AliMUONConstants.h"
45 #include "AliMUONGlobalCrateConfig.h"
46 #include "AliMUONLogger.h"
47 #include "AliMUONPadStatusMaker.h"
48 #include "AliMUONPadStatusMapMaker.h"
49 #include "AliMUONRecoParam.h"
50 #include "AliMUONRegionalTriggerConfig.h"
51 #include "AliMUONRejectList.h"
52 #include "AliMUONTrackerData.h"
53 #include "AliMUONTrackerIO.h"
54 #include "AliMUONTriggerEfficiencyCells.h"
55 #include "AliMUONTriggerLut.h"
56 #include "AliMUONVCalibParam.h"
57 #include "AliMUONVCalibParam.h"
58 #include "AliMUONVStore.h"
59
60 #include "AliMpCDB.h"
61 #include "AliMpConstants.h"
62 #include "AliMpDEStore.h"
63 #include "AliMpDDLStore.h"
64 #include "AliMpManuStore.h"
65 #include "AliMpDEManager.h"
66 #include "AliMpDetElement.h"
67 #include "AliMpFiles.h"
68 #include "AliMpDCSNamer.h"
69 #include "AliMpManuIterator.h"
70 #include "AliMpSegmentation.h"
71 #include "AliMpStationType.h"
72 #include "AliMpVSegmentation.h"
73
74 #include "AliCodeTimer.h"
75 #include "AliCDBEntry.h"
76 #include "AliCDBManager.h"
77 #include "AliGRPManager.h"
78 #include "AliDCSValue.h"
79 #include "AliLog.h"
80 #include "AliMpBusPatch.h"
81
82 #include <Riostream.h>
83 #include <TArrayI.h>
84 #include <TClass.h>
85 #include <TFile.h>
86 #include <TH1F.h>
87 #include <TList.h>
88 #include <TMap.h>
89 #include <TObjString.h>
90 #include <TROOT.h>
91 #include <TRandom.h>
92 #include <TStopwatch.h>
93 #include <TSystem.h>
94 #include <TMath.h>
95 #include <TGeoGlobalMagField.h>
96 #include <TClonesArray.h>
97 #include <sstream>
98 #include <set>
99
100 namespace
101 {
102   //_____________________________________________________________________________
103 AliMUONVStore* Create2DMap()
104 {
105   return new AliMUON2DMap(true);
106 }
107
108   //_____________________________________________________________________________
109 void getBoundaries(const AliMUONVStore& store, Int_t dim,
110                    Float_t* xmin, Float_t* xmax)
111 {
112   /// Assuming the store contains AliMUONVCalibParam objects, compute the
113   /// limits of the value contained in the VCalibParam, for each of its dimensions
114   /// xmin and xmax must be of dimension dim
115   
116   for ( Int_t i = 0; i < dim; ++i ) 
117   {
118     xmin[i]=1E30;
119     xmax[i]=-1E30;
120   }
121   
122   TIter next(store.CreateIterator());
123   AliMUONVCalibParam* value;
124   
125   while ( ( value = dynamic_cast<AliMUONVCalibParam*>(next() ) ) )
126   {
127     Int_t detElemId = value->ID0();
128     Int_t manuId = value->ID1();
129     
130     const AliMpVSegmentation* seg = 
131       AliMpSegmentation::Instance()->GetMpSegmentationByElectronics(detElemId,manuId);
132         
133     if (!seg) continue;
134     
135     for ( Int_t manuChannel = 0; manuChannel < value->Size(); ++manuChannel )
136     {
137       AliMpPad pad = seg->PadByLocation(manuId,manuChannel,kFALSE);
138       if (!pad.IsValid()) continue;
139       
140       for ( Int_t i = 0; i < dim; ++i ) 
141       {
142         Float_t x0 = value->ValueAsFloat(manuChannel,i);
143       
144         xmin[i] = TMath::Min(xmin[i],x0);
145         xmax[i] = TMath::Max(xmax[i],x0);
146       }
147     }
148   }
149
150   for ( Int_t i = 0; i < dim; ++i ) 
151   {
152     if ( TMath::Abs(xmin[i]-xmax[i]) < 1E-3 ) 
153     {
154       xmin[i] -= 1;
155       xmax[i] += 1;
156     }
157   }
158 }
159
160 //_____________________________________________________________________________
161 Double_t GetRandom(Double_t mean, Double_t sigma, Bool_t mustBePositive)
162 {
163   Double_t x(-1);
164   if ( mustBePositive ) 
165   {
166     while ( x < 0 ) 
167     {
168       x = gRandom->Gaus(mean,sigma);
169     }
170   }
171   else
172   {
173     x = gRandom->Gaus(mean,sigma);
174   }
175   return x;
176 }
177
178 }
179
180 //_____________________________________________________________________________
181 Bool_t AliMUONCDB::CheckOCDB(Bool_t pathOnly)
182 {
183   /// Check that OCDB path and run number are properly set
184   
185   AliCDBManager* man = AliCDBManager::Instance();
186   
187   // first OCDB path
188   if (!man->IsDefaultStorageSet()) {
189     AliErrorGeneral("AliMUONCDB", "OCDB path must be properly set");
190     return kFALSE;
191   }
192   
193   // then run number if required
194   if (pathOnly) return kTRUE;
195   if (man->GetRun() < 0) {
196     AliErrorGeneral("AliMUONCDB", "Run number must be properly set");
197     return kFALSE;
198   }
199   
200   return kTRUE;
201   
202 }
203
204 //_____________________________________________________________________________
205 Bool_t AliMUONCDB::CheckMapping(Bool_t segmentationOnly)
206 {
207   /// Check that the mapping has been loaded
208   
209   // first the segmentation
210   if (!AliMpSegmentation::Instance(false)) {
211     AliErrorGeneral("AliMUONCDB", "Mapping segmentation must be loaded first");
212     return kFALSE;
213   }
214   
215   // then the others if required
216   if (segmentationOnly) return kTRUE;
217   if (!AliMpDDLStore::Instance(false) || !AliMpDEStore::Instance(false) || !AliMpManuStore::Instance(false)) {
218     AliErrorGeneral("AliMUONCDB", "Full mapping must be loaded first");
219     return kFALSE;
220   }
221   
222   return kTRUE;
223   
224 }
225
226 //_____________________________________________________________________________
227 Bool_t AliMUONCDB::LoadField()
228 {
229   /// Load magnetic field (existing field will be deleted).
230   /// OCDB path and run number are supposed to be set.
231   
232   AliInfoGeneral("AliMUONCDB","Loading field map from GRP...");
233   
234   if (!AliMUONCDB::CheckOCDB()) return kFALSE;
235   
236   AliGRPManager grpMan;
237   
238   // make sure the old field is deleted even if it is locked
239   if(TGeoGlobalMagField::Instance()->IsLocked()) delete TGeoGlobalMagField::Instance();
240   
241   if (!grpMan.ReadGRPEntry() || !grpMan.SetMagField()) {
242     AliErrorGeneral("AliMUONCDB", "failed to load magnetic field from OCDB");
243     return kFALSE;
244   }
245   
246   return kTRUE;
247   
248 }
249
250 //_____________________________________________________________________________
251 Bool_t AliMUONCDB::LoadMapping(Bool_t segmentationOnly)
252 {
253   /// Load mapping (existing mapping will be unloaded).
254   /// OCDB path and run number are supposed to be set.
255   
256   AliInfoGeneral("AliMUONCDB", "Loading mapping from OCDB...");
257   
258   if (!AliMUONCDB::CheckOCDB()) return kFALSE;
259   
260   // in case it has already been set
261   AliMpCDB::UnloadAll();
262   
263   if (segmentationOnly) {
264     
265     if (!AliMpCDB::LoadMpSegmentation(kTRUE)){
266       AliErrorGeneral("AliMUONCDB", "failed to load segmentation from OCDB");
267       return kFALSE;
268     }
269     
270   } else {
271     
272     if (!AliMpCDB::LoadAll(kTRUE)) {
273       AliErrorGeneral("AliMUONCDB", "failed to load mapping from OCDB");
274       return kFALSE;
275     }
276     
277   }
278   
279   return kTRUE;
280   
281 }
282
283 //_____________________________________________________________________________
284 AliMUONRecoParam* AliMUONCDB::LoadRecoParam()
285 {
286   /// Load and return reconstruction parameters.
287   /// OCDB path is supposed to be set.
288   
289   AliInfoGeneral("AliMUONCDB", "Loading RecoParam from OCDB...");
290   
291   if (!AliMUONCDB::CheckOCDB()) return 0x0;
292   
293   AliMUONRecoParam* recoParam = 0x0;
294   AliCDBEntry* entry = AliCDBManager::Instance()->Get("MUON/Calib/RecoParam");
295   
296   if(entry) {
297     
298     // load recoParam according OCDB content (single or array)
299     if (!(recoParam = dynamic_cast<AliMUONRecoParam*>(entry->GetObject()))) {
300       
301       TObjArray* recoParamArray = static_cast<TObjArray*>(entry->GetObject());
302 //      recoParamArray->SetOwner(kTRUE); // FIXME: this should be done, but is causing a problem at the end of the reco... investigate why...
303       
304       for(Int_t i = 0; i < recoParamArray->GetEntriesFast(); i++) {
305         recoParam = static_cast<AliMUONRecoParam*>(recoParamArray->UncheckedAt(i));
306         if (recoParam->IsDefault()) break;
307         recoParam = 0x0;
308       }
309       
310     }
311     
312   }
313   
314   if (!recoParam) AliErrorGeneral("AliMUONCDB", "failed to load RecoParam from OCDB");
315   
316   return recoParam;
317   
318 }
319
320 //_____________________________________________________________________________
321 TClonesArray* AliMUONCDB::LoadAlignmentData()
322 {
323   /// Load and return the array of alignment objects.
324   
325   AliInfoGeneral("AliMUONCDB", "Loading Alignemnt from OCDB...");
326   
327   if (!AliMUONCDB::CheckOCDB()) return 0x0;
328   
329   TClonesArray* alignmentArray = 0x0;
330   AliCDBEntry* entry = AliCDBManager::Instance()->Get("MUON/Align/Data");
331   
332   if (entry) {
333     // load alignement array
334     alignmentArray = dynamic_cast<TClonesArray*>(entry->GetObject());
335   }
336   
337   if (!alignmentArray) { 
338     AliErrorGeneral("AliMUONCDB", "failed to load Alignemnt from OCDB");
339   }  
340   
341   return alignmentArray;
342 }
343
344 //_____________________________________________________________________________
345 AliMUONVStore* 
346 AliMUONCDB::Diff(AliMUONVStore& store1, AliMUONVStore& store2, 
347                  const char* opt)
348 {
349   /// creates a store which contains store1-store2
350   /// if opt="abs" the difference is absolute one,
351   /// if opt="rel" then what is stored is (store1-store2)/store1
352   /// if opt="percent" then what is stored is rel*100
353   ///
354   /// WARNING Works only for stores which holds AliMUONVCalibParam objects
355   
356   TString sopt(opt);
357   sopt.ToUpper();
358   
359   if ( !sopt.Contains("ABS") && !sopt.Contains("REL") && !sopt.Contains("PERCENT") )
360   {
361     AliErrorGeneral("AliMUONCDB", Form("opt %s not supported. Only ABS, REL, PERCENT are",opt));
362     return 0x0;
363   }
364   
365   AliMUONVStore* d = static_cast<AliMUONVStore*>(store1.Clone());
366   
367   TIter next(d->CreateIterator());
368   
369   AliMUONVCalibParam* param;
370   
371   while ( ( param = dynamic_cast<AliMUONVCalibParam*>(next() ) ) )
372   {
373     Int_t detElemId = param->ID0();
374     Int_t manuId = param->ID1();
375     
376     AliMUONVCalibParam* param2 = dynamic_cast<AliMUONVCalibParam*>(store2.FindObject(detElemId,manuId));
377     //FIXME: this might happen. Handle it.
378     if (!param2) 
379     {
380       cerr << "param2 is null : FIXME : this might happen !" << endl;
381       delete d;
382       return 0;
383     }
384     
385     for ( Int_t i = 0; i < param->Size(); ++i )
386     {
387       for ( Int_t j = 0; j < param->Dimension(); ++j )
388       {
389         Float_t value(0);
390         if ( sopt.Contains("ABS") )
391         {
392           value = param->ValueAsFloat(i,j) - param2->ValueAsFloat(i,j);
393         }
394         else if ( sopt.Contains("REL") || sopt.Contains("PERCENT") )
395         {
396           if ( param->ValueAsFloat(i,j) ) 
397           {
398             value = (param->ValueAsFloat(i,j) - param2->ValueAsFloat(i,j))/param->ValueAsFloat(i,j);
399           }
400           else 
401           {
402             continue;
403           }
404           if ( sopt.Contains("PERCENT") ) value *= 100.0;
405         }
406         param->SetValueAsFloat(i,j,value);
407       }      
408     }
409   }
410   return d;
411 }
412
413 //_____________________________________________________________________________
414 TH1** 
415 AliMUONCDB::Plot(const AliMUONVStore& store, const char* name, Int_t nbins)
416 {
417   /// Make histograms of each dimension of the AliMUONVCalibParam
418   /// contained inside store.
419   /// It produces histograms named name_0, name_1, etc...
420   
421   if (!AliMUONCDB::CheckMapping(kTRUE)) return 0x0;
422   
423   TIter next(store.CreateIterator());
424   AliMUONVCalibParam* param;
425   Int_t n(0);
426   const Int_t kNStations = AliMpConstants::NofTrackingChambers()/2;
427   Int_t* nPerStation = new Int_t[kNStations];
428   TH1** h(0x0);
429   
430   for ( Int_t i = 0; i < kNStations; ++i ) nPerStation[i]=0;
431   
432   while ( ( param = static_cast<AliMUONVCalibParam*>(next()) ) )
433   {
434     if (!h)
435     {
436       Int_t dim = param->Dimension();
437       h = new TH1*[dim];
438       Float_t* xmin = new Float_t[dim];
439       Float_t* xmax = new Float_t[dim];
440       getBoundaries(store,dim,xmin,xmax);
441       
442       for ( Int_t i = 0; i < dim; ++i ) 
443       {
444         h[i] = new TH1F(Form("%s_%d",name,i),Form("%s_%d",name,i),
445                             nbins,xmin[i],xmax[i]);
446         AliInfoGeneral("AliMUONCDB", Form("Created histogram %s",h[i]->GetName()));
447       }
448       delete [] xmin;
449       delete [] xmax;
450     }
451     
452     Int_t detElemId = param->ID0();
453     Int_t manuId = param->ID1();
454     Int_t station = AliMpDEManager::GetChamberId(detElemId)/2;
455     
456     const AliMpVSegmentation* seg = 
457       AliMpSegmentation::Instance()->GetMpSegmentationByElectronics(detElemId,manuId);
458     
459     if (!seg) continue;
460     
461     for ( Int_t manuChannel = 0; manuChannel < param->Size(); ++manuChannel )
462     {
463       AliMpPad pad = seg->PadByLocation(manuId,manuChannel,kFALSE);
464       if (!pad.IsValid()) continue;
465
466       ++n;
467       ++nPerStation[station];
468       
469       for ( Int_t dim = 0; dim < param->Dimension(); ++dim ) 
470       {
471         h[dim]->Fill(param->ValueAsFloat(manuChannel,dim));
472       }
473     }
474   } 
475   
476   for ( Int_t i = 0; i < kNStations; ++i )
477   {
478     AliInfoGeneral("AliMUONCDB", Form("Station %d %d ",(i+1),nPerStation[i]));
479   }
480
481   AliInfoGeneral("AliMUONCDB", Form("Number of channels = %d",n));
482   
483   delete[] nPerStation;
484   
485   return h;
486 }
487
488 //_____________________________________________________________________________
489 Int_t 
490 AliMUONCDB::MakeHVStore(TMap& aliasMap, Bool_t defaultValues)
491 {
492   /// Create a HV store
493   
494   if (!AliMUONCDB::CheckMapping()) return 0;
495   
496   AliMpDCSNamer hvNamer("TRACKER");
497   
498   TObjArray* aliases = hvNamer.GenerateAliases();
499   
500   Int_t nSwitch(0);
501   Int_t nChannels(0);
502   
503   for ( Int_t i = 0; i < aliases->GetEntries(); ++i ) 
504   {
505     TObjString* alias = static_cast<TObjString*>(aliases->At(i));
506     TString& aliasName = alias->String();
507     if ( aliasName.Contains("sw") ) 
508     {
509       // HV Switch (St345 only)
510       TObjArray* valueSet = new TObjArray;
511       valueSet->SetOwner(kTRUE);
512       
513       Bool_t value = kTRUE;
514       
515       if (!defaultValues)
516       {
517         Float_t r = gRandom->Uniform();
518         if ( r < 0.007 ) value = kFALSE;      
519       } 
520       
521       for ( UInt_t timeStamp = 0; timeStamp < 60*3; timeStamp += 60 )
522       {
523         AliDCSValue* dcsValue = new AliDCSValue(value,timeStamp);
524         valueSet->Add(dcsValue);
525       }
526       aliasMap.Add(new TObjString(*alias),valueSet);
527       ++nSwitch;
528     }
529     else
530     {
531       TObjArray* valueSet = new TObjArray;
532       valueSet->SetOwner(kTRUE);
533       for ( UInt_t timeStamp = 0; timeStamp < 60*15; timeStamp += 120 )
534       {
535         Float_t value = 1500;
536         if (!defaultValues) value = GetRandom(1750,62.5,true);
537         AliDCSValue* dcsValue = new AliDCSValue(value,timeStamp);
538         valueSet->Add(dcsValue);
539       }
540       aliasMap.Add(new TObjString(*alias),valueSet);
541       ++nChannels;
542     }
543   }
544   
545   delete aliases;
546   
547   AliInfoGeneral("AliMUONCDB", Form("%d HV channels and %d switches",nChannels,nSwitch));
548   
549   return nChannels+nSwitch;
550 }
551
552 //_____________________________________________________________________________
553 Int_t 
554 AliMUONCDB::MakeTriggerDCSStore(TMap& aliasMap, Bool_t defaultValues)
555 {
556   /// Create a Trigger HV and Currents store
557   
558   if (!AliMUONCDB::CheckMapping()) return 0;
559   
560   AliMpDCSNamer triggerDCSNamer("TRIGGER");
561   
562   TObjArray* aliases = triggerDCSNamer.GenerateAliases();
563   
564   Int_t nChannels[2] = {0, 0};
565   
566   for ( Int_t i = 0; i < aliases->GetEntries(); ++i ) 
567   {
568     TObjString* alias = static_cast<TObjString*>(aliases->At(i));
569     TString& aliasName = alias->String();
570
571     TObjArray* valueSet = new TObjArray;
572     valueSet->SetOwner(kTRUE);
573
574     Int_t measureType = triggerDCSNamer.DCSvariableFromDCSAlias(aliasName.Data());
575     if ( measureType < 0 ) {
576       AliErrorGeneralStream("AliMUONCDB") 
577         << "Failed to get DCS variable from an alias (trigger): "
578         << aliasName.Data() << endl;
579       return 0;
580     }
581         
582     for ( UInt_t timeStamp = 0; timeStamp < 60*15; timeStamp += 120 )
583     {
584       Float_t value = 
585         (measureType == AliMpDCSNamer::kDCSI) ? 2. : 8000.;
586       if (!defaultValues) {
587         switch (measureType){
588         case AliMpDCSNamer::kDCSI:
589           value = GetRandom(2.,0.4,true);
590           break;
591         case AliMpDCSNamer::kDCSHV:
592           value = GetRandom(8000.,16.,true);
593           break;
594         }
595       }
596       AliDCSValue* dcsValue = new AliDCSValue(value,timeStamp);
597       valueSet->Add(dcsValue);
598     }
599     aliasMap.Add(new TObjString(*alias),valueSet);
600     ++nChannels[measureType];
601   }
602   
603   delete aliases;
604   
605   AliInfoGeneral("AliMUONCDB", Form("Trigger channels I -> %i   HV -> %i",nChannels[0], nChannels[1]));
606   
607   return nChannels[0] + nChannels[1];
608 }
609
610 //_____________________________________________________________________________
611 Int_t 
612 AliMUONCDB::MakePedestalStore(AliMUONVStore& pedestalStore, Bool_t defaultValues)
613 {
614   /// Create a pedestal store. if defaultValues=true, ped.mean=ped.sigma=1,
615   /// otherwise mean and sigma are from a gaussian (with parameters
616   /// defined below by the kPedestal* constants)
617
618   AliCodeTimerAutoGeneral("",0);
619   
620   if (!AliMUONCDB::CheckMapping()) return 0;
621   
622   Int_t nchannels(0);
623   Int_t nmanus(0);
624   
625   const Int_t kChannels(AliMpConstants::ManuNofChannels());
626   
627   // bending
628   const Float_t kPedestalMeanMeanB(200.);
629   const Float_t kPedestalMeanSigmaB(10.);
630   const Float_t kPedestalSigmaMeanB(1.);
631   const Float_t kPedestalSigmaSigmaB(0.2);
632   
633   // non bending
634   const Float_t kPedestalMeanMeanNB(200.);
635   const Float_t kPedestalMeanSigmaNB(10.);
636   const Float_t kPedestalSigmaMeanNB(1.);
637   const Float_t kPedestalSigmaSigmaNB(0.2);
638   
639   const Float_t kFractionOfDeadManu(0.); // within [0.,1.]
640
641   Int_t detElemId;
642   Int_t manuId;
643     
644   AliMpManuIterator it;
645   
646   while ( it.Next(detElemId,manuId) )
647   {
648     // skip a given fraction of manus
649     if (kFractionOfDeadManu > 0. && gRandom->Uniform() < kFractionOfDeadManu) continue;
650     
651     ++nmanus;
652
653     AliMUONVCalibParam* ped = 
654       new AliMUONCalibParamNF(2,kChannels,detElemId,manuId,AliMUONVCalibParam::InvalidFloatValue());
655
656     AliMpDetElement* de = AliMpDDLStore::Instance()->GetDetElement(detElemId);
657     
658     for ( Int_t manuChannel = 0; manuChannel < kChannels; ++manuChannel )
659     {
660       if ( ! de->IsConnectedChannel(manuId,manuChannel) ) continue;
661       
662       ++nchannels;
663       
664       Float_t meanPedestal;
665       Float_t sigmaPedestal;
666       
667       if ( defaultValues ) 
668       {
669         meanPedestal = 0.0;
670         sigmaPedestal = 1.0;
671       }
672       else
673       {
674         Bool_t positive(kTRUE);
675         meanPedestal = 0.0;
676         
677         if ( manuId & AliMpConstants::ManuMask(AliMp::kNonBendingPlane) ) { // manu in non bending plane
678           
679           while ( meanPedestal == 0.0 ) // avoid strict zero 
680           {
681             meanPedestal = GetRandom(kPedestalMeanMeanNB,kPedestalMeanSigmaNB,positive);
682           }
683           sigmaPedestal = GetRandom(kPedestalSigmaMeanNB,kPedestalSigmaSigmaNB,positive);
684           
685         } else { // manu in bending plane
686           
687           while ( meanPedestal == 0.0 ) // avoid strict zero 
688           {
689             meanPedestal = GetRandom(kPedestalMeanMeanB,kPedestalMeanSigmaB,positive);
690           }
691           sigmaPedestal = GetRandom(kPedestalSigmaMeanB,kPedestalSigmaSigmaB,positive);
692           
693         }
694         
695       }
696       
697       ped->SetValueAsFloat(manuChannel,0,meanPedestal);
698       ped->SetValueAsFloat(manuChannel,1,sigmaPedestal);
699       
700     }
701     Bool_t ok = pedestalStore.Add(ped);
702     if (!ok)
703     {
704       AliErrorGeneral("AliMUONCDB", Form("Could not set DetElemId=%d manuId=%d",detElemId,manuId));
705     }
706   }
707   
708   AliInfoGeneral("AliMUONCDB", Form("%d Manus and %d channels.",nmanus,nchannels));
709   return nchannels;
710 }
711
712 //_____________________________________________________________________________
713 AliMUONRejectList* 
714 AliMUONCDB::MakeRejectListStore(Bool_t defaultValues)
715 {
716   /// Create a reject list
717   
718   AliCodeTimerAutoGeneral("",0);
719
720   AliMUONRejectList* rl = new AliMUONRejectList;
721   
722   if (!defaultValues)
723   {
724     rl->SetDetectionElementProbability(510);
725     rl->SetDetectionElementProbability(508);
726     return rl;
727   }
728   
729   return rl;
730 }
731
732 //_____________________________________________________________________________
733 Int_t 
734 AliMUONCDB::MakeOccupancyMapStore(AliMUONVStore& occupancyMapStore, Bool_t defaultValues)
735 {
736   /// Create an occupancy map.
737   
738   AliCodeTimerAutoGeneral("",0);
739   
740   if (!AliMUONCDB::CheckMapping()) return 0;
741   
742   Int_t nmanus(0);
743   
744   Int_t detElemId;
745   Int_t manuId;
746   
747   AliMpManuIterator it;
748   
749   Int_t nevents(1000);
750   
751   while ( it.Next(detElemId,manuId) )
752   {
753     ++nmanus;
754     
755     AliMUONVCalibParam* occupancy = new AliMUONCalibParamND(5,1,detElemId,manuId,0);
756     
757     Double_t occ = 0.0;
758
759     AliMpDetElement* de = AliMpDDLStore::Instance()->GetDetElement(detElemId);
760     
761     Int_t numberOfChannelsInManu = de->NofChannelsInManu(manuId);
762     
763     if (!defaultValues) occ = gRandom->Rndm(1);
764
765     Double_t sumn = occ*nevents;
766     
767     occupancy->SetValueAsFloat(0,0,sumn); 
768     occupancy->SetValueAsFloat(0,1,sumn);
769     occupancy->SetValueAsFloat(0,2,sumn);
770     occupancy->SetValueAsInt(0,3,numberOfChannelsInManu);
771     occupancy->SetValueAsInt(0,4,nevents);
772     
773     Bool_t ok = occupancyMapStore.Add(occupancy);
774     if (!ok)
775     {
776       AliErrorGeneral("AliMUONCDB", Form("Could not set DetElemId=%d manuId=%d",detElemId,manuId));
777     }
778   }
779   
780   return nmanus;
781 }
782
783 //_____________________________________________________________________________
784 Int_t
785 AliMUONCDB::MakeCapacitanceStore(AliMUONVStore& capaStore, const char* file)
786 {
787   /// Read the capacitance values from file and append them to the capaStore
788   
789   if (!AliMUONCDB::CheckMapping()) return 0;
790   
791   return AliMUONTrackerIO::ReadCapacitances(file,capaStore);
792 }
793
794 //_____________________________________________________________________________
795 Int_t 
796 AliMUONCDB::MakeCapacitanceStore(AliMUONVStore& capaStore, Bool_t defaultValues)
797 {
798   /// Create a capacitance store. if defaultValues=true, all capa are 1.0,
799   /// otherwise they are from a gaussian with parameters defined in the
800   /// kCapa* constants below.
801
802   AliCodeTimerAutoGeneral("",0);
803   
804   if (!AliMUONCDB::CheckMapping()) return 0;
805   
806   Int_t nchannels(0);
807   Int_t nmanus(0);
808   Int_t nmanusOK(0); // manus for which we got the serial number
809     
810   const Float_t kCapaMean(0.3);
811   const Float_t kCapaSigma(0.1);
812   const Float_t kInjectionGainMean(3);
813   const Float_t kInjectionGainSigma(1);
814
815   Int_t detElemId;
816   Int_t manuId;
817   
818   AliMpManuIterator it;
819   
820   while ( it.Next(detElemId,manuId) )
821   {
822     ++nmanus;
823     
824     AliMpDetElement* de = AliMpDDLStore::Instance()->GetDetElement(detElemId); 
825     Int_t serialNumber = AliMpManuStore::Instance()->GetManuSerial(detElemId, manuId);
826       
827     if ( serialNumber <= 0 ) continue;
828     
829     ++nmanusOK;
830     
831     AliMUONVCalibParam* capa = static_cast<AliMUONVCalibParam*>(capaStore.FindObject(serialNumber));
832     
833     if (!capa)
834     {
835       capa = new AliMUONCalibParamNF(2,AliMpConstants::ManuNofChannels(),serialNumber,0,1.0);
836       Bool_t ok = capaStore.Add(capa);
837       if (!ok)
838       {
839         AliErrorGeneral("AliMUONCDB", Form("Could not set serialNumber=%d manuId=%d",serialNumber,manuId));
840       }      
841     }
842     
843     for ( Int_t manuChannel = 0; manuChannel < capa->Size(); ++manuChannel )
844     {
845       if ( ! de->IsConnectedChannel(manuId,manuChannel) ) continue;
846       
847       ++nchannels;
848       
849       Float_t capaValue;
850       Float_t injectionGain;
851       
852       if ( defaultValues ) 
853       {
854         capaValue = 1.0;
855         injectionGain = 1.0;
856       }
857       else
858       {
859         capaValue = GetRandom(kCapaMean,kCapaSigma,kTRUE);
860         injectionGain = GetRandom(kInjectionGainMean,kInjectionGainSigma,kTRUE);
861       }
862       capa->SetValueAsFloat(manuChannel,0,capaValue);
863       capa->SetValueAsFloat(manuChannel,1,injectionGain);
864     }
865   }
866   
867   Float_t percent = 0;
868   if ( nmanus ) percent = 100*nmanusOK/nmanus;
869   AliInfoGeneral("AliMUONCDB", Form("%5d manus with serial number (out of %5d manus = %3.0f%%)",
870                nmanusOK,nmanus,percent));
871   AliInfoGeneral("AliMUONCDB", Form("%5d channels",nchannels));
872   if ( percent < 100 ) 
873   {
874     AliWarningGeneral("AliMUONCDB", "Did not get all serial numbers. capaStore is incomplete !!!!");
875   }
876   return nchannels;
877   
878 }
879
880 //_____________________________________________________________________________
881 Int_t 
882 AliMUONCDB::MakeGainStore(AliMUONVStore& gainStore, Bool_t defaultValues)
883 {  
884   /// Create a gain store. if defaultValues=true, all gains set so that
885   /// charge = (adc-ped)
886   ///
887   /// otherwise parameters are taken from gaussians with parameters 
888   /// defined in the k* constants below.
889   
890   AliCodeTimerAutoGeneral("",0);
891   
892   if (!AliMUONCDB::CheckMapping()) return 0;
893   
894   Int_t nchannels(0);
895   Int_t nmanus(0);
896     
897   const Int_t kSaturation(3000);
898   const Double_t kA0Mean(1.2);
899   const Double_t kA0Sigma(0.1);
900   const Double_t kA1Mean(1E-5);
901   const Double_t kA1Sigma(1E-6);
902   const Double_t kQualMean(0xFF);
903   const Double_t kQualSigma(0x10);
904   const Int_t kThresMean(1600);
905   const Int_t kThresSigma(100);
906   
907   Int_t detElemId;
908   Int_t manuId;
909   
910   AliMpManuIterator it;
911   
912   while ( it.Next(detElemId,manuId) )
913   {
914     ++nmanus;
915
916     AliMUONVCalibParam* gain = 
917       new AliMUONCalibParamNF(5,AliMpConstants::ManuNofChannels(),
918                               detElemId,
919                               manuId,
920                               AliMUONVCalibParam::InvalidFloatValue());
921
922     AliMpDetElement* de = AliMpDDLStore::Instance()->GetDetElement(detElemId);
923
924     for ( Int_t manuChannel = 0; manuChannel < gain->Size(); ++manuChannel )
925     {
926       if ( ! de->IsConnectedChannel(manuId,manuChannel) ) continue;
927       
928       ++nchannels;
929       
930       if ( defaultValues ) 
931       {
932         gain->SetValueAsFloat(manuChannel,0,1.0);
933         gain->SetValueAsFloat(manuChannel,1,0.0);
934         gain->SetValueAsInt(manuChannel,2,4095); 
935         gain->SetValueAsInt(manuChannel,3,1);
936         gain->SetValueAsInt(manuChannel,4,kSaturation);
937       }
938       else
939       {
940         Bool_t positive(kTRUE);
941         gain->SetValueAsFloat(manuChannel,0,GetRandom(kA0Mean,kA0Sigma,positive));
942         gain->SetValueAsFloat(manuChannel,1,GetRandom(kA1Mean,kA1Sigma,!positive));
943         gain->SetValueAsInt(manuChannel,2,(Int_t)TMath::Nint(GetRandom(kThresMean,kThresSigma,positive)));
944         gain->SetValueAsInt(manuChannel,3,(Int_t)TMath::Nint(GetRandom(kQualMean,kQualSigma,positive)));
945         gain->SetValueAsInt(manuChannel,4,kSaturation);        
946       }
947       
948     }
949     Bool_t ok = gainStore.Add(gain);
950     if (!ok)
951     {
952       AliErrorGeneral("AliMUONCDB", Form("Could not set DetElemId=%d manuId=%d",detElemId,manuId));
953     }
954   }
955   
956   AliInfoGeneral("AliMUONCDB", Form("%d Manus and %d channels.",nmanus,nchannels));
957   return nchannels;
958 }
959
960 //_____________________________________________________________________________
961 Int_t
962 AliMUONCDB::MakeLocalTriggerMaskStore(AliMUONVStore& localBoardMasks)
963 {
964   /// Generate local trigger masks store. All masks are set to FFFF
965   
966   AliCodeTimerAutoGeneral("",0);
967   
968   Int_t ngenerated(0);
969   // Generate fake mask values for all localboards and put that into
970   // one single container (localBoardMasks)
971   for ( Int_t i = 1; i <= AliMpConstants::TotalNofLocalBoards(); ++i )
972   {
973     AliMUONVCalibParam* localBoard = new AliMUONCalibParamNI(1,8,i,0,0);
974     for ( Int_t x = 0; x < 2; ++x )
975     {
976       for ( Int_t y = 0; y < 4; ++y )
977       {
978         Int_t index = x*4+y;
979         localBoard->SetValueAsInt(index,0,0xFFFF);
980         ++ngenerated;
981       }
982     }
983     localBoardMasks.Add(localBoard);
984   }
985   return ngenerated;
986 }
987
988 //_____________________________________________________________________________
989 Int_t
990 AliMUONCDB::MakeRegionalTriggerConfigStore(AliMUONRegionalTriggerConfig& rtm)
991 {
992   /// Make a regional trigger config store. Mask is set to FFFF for each local board (Ch.F.)
993   
994   AliCodeTimerAutoGeneral("",0);
995   
996   if ( ! rtm.ReadData(AliMpFiles::LocalTriggerBoardMapping()) ) {
997     AliErrorGeneral("AliMUONCDB", "Error when reading from mapping file");
998     return 0;
999   }
1000     
1001   return rtm.GetNofTriggerCrates();  
1002 }
1003
1004
1005 //_____________________________________________________________________________
1006 Int_t 
1007 AliMUONCDB::MakeGlobalTriggerConfigStore(AliMUONGlobalCrateConfig& gtm)
1008 {
1009   /// Make a global trigger config store. All masks (disable) set to 0x00 for each Darc board (Ch.F.)
1010   
1011   AliCodeTimerAutoGeneral("",0);
1012   
1013   return gtm.ReadData(AliMpFiles::GlobalTriggerBoardMapping());
1014 }
1015
1016
1017 //_____________________________________________________________________________
1018 AliMUONTriggerLut* 
1019 AliMUONCDB::MakeTriggerLUT(const char* file)
1020 {
1021   /// Make a triggerlut object, from a file.
1022   
1023   AliCodeTimerAutoGeneral("",0);
1024   
1025   AliMUONTriggerLut* lut = new AliMUONTriggerLut;
1026   lut->ReadFromFile(file);
1027   return lut;
1028 }
1029
1030 //_____________________________________________________________________________
1031 AliMUONTriggerEfficiencyCells*
1032 AliMUONCDB::MakeTriggerEfficiency(const char* file)
1033 {
1034   /// Make a trigger efficiency object from a file.
1035   
1036   AliCodeTimerAutoGeneral("",0);
1037   
1038   return new AliMUONTriggerEfficiencyCells(file);
1039 }
1040
1041 //_____________________________________________________________________________
1042 void 
1043 AliMUONCDB::WriteToCDB(const char* calibpath, TObject* object, 
1044                        Int_t startRun, Int_t endRun, 
1045                        const char* filename)
1046 {
1047   /// Write a given object to OCDB
1048   
1049   TString comment(gSystem->ExpandPathName(filename));
1050   
1051   WriteToCDB(object, calibpath, startRun, endRun, comment.Data());
1052 }
1053
1054 //_____________________________________________________________________________
1055 void 
1056 AliMUONCDB::WriteToCDB(const char* calibpath, TObject* object, 
1057                        Int_t startRun, Int_t endRun, Bool_t defaultValues)
1058 {
1059   /// Write a given object to OCDB
1060   
1061   TString comment;
1062   if ( defaultValues ) comment += "Test with default values";
1063   else comment += "Test with random values";
1064   
1065   WriteToCDB(object, calibpath, startRun, endRun, comment.Data());
1066 }
1067
1068 //_____________________________________________________________________________
1069 void
1070 AliMUONCDB::WriteToCDB(TObject* object, const char* calibpath, Int_t startRun, Int_t endRun,
1071                        const char* comment, const char* responsible)
1072 {
1073   /// Write a given object to OCDB
1074   
1075   if (!AliMUONCDB::CheckOCDB(kTRUE)) return;
1076   
1077   AliCDBId id(calibpath,startRun,endRun);
1078   AliCDBMetaData md;
1079   md.SetAliRootVersion(gROOT->GetVersion());
1080   md.SetComment(comment);
1081   md.SetResponsible(responsible);
1082   AliCDBManager::Instance()->Put(object,id,&md);
1083 }
1084
1085 //_____________________________________________________________________________
1086 Int_t 
1087 AliMUONCDB::MakeNeighbourStore(AliMUONVStore& neighbourStore)
1088 {
1089   /// Fill the neighbours store with, for each channel, a TObjArray of its
1090   /// neighbouring pads (including itself)
1091   
1092   AliCodeTimerAutoGeneral("",0);
1093   
1094   if (!AliMUONCDB::CheckMapping()) return 0;
1095   
1096   AliInfoGeneral("AliMUONCDB", "Generating NeighbourStore. This will take a while. Please be patient.");
1097   
1098   Int_t nchannels(0);
1099   
1100   TObjArray tmp;
1101
1102   Int_t detElemId;
1103   Int_t manuId;
1104   
1105   AliMpManuIterator it;
1106   
1107   while ( it.Next(detElemId,manuId) )
1108   {
1109     const AliMpVSegmentation* seg = 
1110       AliMpSegmentation::Instance()->GetMpSegmentationByElectronics(detElemId,manuId);
1111     
1112     AliMUONVCalibParam* calibParam = static_cast<AliMUONVCalibParam*>(neighbourStore.FindObject(detElemId,manuId));
1113     if (!calibParam)
1114     {
1115       Int_t dimension(11);
1116       Int_t size(AliMpConstants::ManuNofChannels());
1117       Int_t defaultValue(-1);
1118       Int_t packingFactor(size);
1119       
1120       calibParam = new AliMUONCalibParamNI(dimension,size,detElemId,manuId,defaultValue,packingFactor);
1121       Bool_t ok = neighbourStore.Add(calibParam);
1122       if (!ok)
1123       {
1124         AliErrorGeneral("AliMUONCDB", Form("Could not set DetElemId=%d manuId=%d",detElemId,manuId));
1125         return -1;
1126       }      
1127     }
1128     
1129     for ( Int_t manuChannel = 0; manuChannel < AliMpConstants::ManuNofChannels(); ++manuChannel )
1130     {
1131       AliMpPad pad = seg->PadByLocation(manuId,manuChannel,kFALSE);
1132       
1133       if (pad.IsValid()) 
1134       {
1135         ++nchannels;
1136
1137         seg->GetNeighbours(pad,tmp,true,true);
1138         Int_t nofPadNeighbours = tmp.GetEntriesFast();
1139             
1140         for ( Int_t i = 0; i < nofPadNeighbours; ++i )
1141         {
1142           AliMpPad* p = static_cast<AliMpPad*>(tmp.UncheckedAt(i));
1143           Int_t x;
1144 //          Bool_t ok =
1145               calibParam->PackValues(p->GetManuId(),p->GetManuChannel(),x);
1146 //          if (!ok)
1147 //          {
1148 //            AliError("Could not pack value. Something is seriously wrong. Please check");
1149 //            StdoutToAliError(pad->Print(););
1150 //            return -1;
1151 //          }
1152           calibParam->SetValueAsInt(manuChannel,i,x);
1153         }
1154       }
1155     }
1156     }
1157   
1158   return nchannels;
1159 }
1160
1161 //_____________________________________________________________________________
1162 void
1163 AliMUONCDB::WriteLocalTriggerMasks(Int_t startRun, Int_t endRun)
1164 {  
1165   /// Write local trigger masks to OCDB
1166   
1167   AliMUONVStore* ltm = new AliMUON1DArray(AliMpConstants::TotalNofLocalBoards()+1);
1168   Int_t ngenerated = MakeLocalTriggerMaskStore(*ltm);
1169   AliInfoGeneral("AliMUONCDB", Form("Ngenerated = %d",ngenerated));
1170   if (ngenerated>0)
1171   {
1172     WriteToCDB("MUON/Calib/LocalTriggerBoardMasks",ltm,startRun,endRun,true);
1173   }
1174   delete ltm;
1175 }
1176
1177 //_____________________________________________________________________________
1178 void
1179 AliMUONCDB::WriteRegionalTriggerConfig(Int_t startRun, Int_t endRun)
1180 {  
1181   /// Write regional trigger masks to OCDB
1182   
1183   AliMUONRegionalTriggerConfig* rtm = new AliMUONRegionalTriggerConfig();
1184   Int_t ngenerated = MakeRegionalTriggerConfigStore(*rtm);
1185   AliInfoGeneral("AliMUONCDB", Form("Ngenerated = %d",ngenerated));
1186   if (ngenerated>0)
1187   {
1188     WriteToCDB("MUON/Calib/RegionalTriggerConfig",rtm,startRun,endRun,true);
1189   }
1190   delete rtm;
1191 }
1192
1193
1194 //_____________________________________________________________________________
1195 void
1196 AliMUONCDB::WriteGlobalTriggerConfig(Int_t startRun, Int_t endRun)
1197 {  
1198   /// Write global trigger masks to OCDB
1199   
1200   AliMUONGlobalCrateConfig* gtm = new AliMUONGlobalCrateConfig();
1201
1202   Int_t ngenerated = MakeGlobalTriggerConfigStore(*gtm);
1203   AliInfoGeneral("AliMUONCDB", Form("Ngenerated = %d",ngenerated));
1204   if (ngenerated>0)
1205   {
1206     WriteToCDB("MUON/Calib/GlobalTriggerCrateConfig",gtm,startRun,endRun,true);
1207   }
1208   delete gtm;
1209 }
1210
1211
1212 //_____________________________________________________________________________
1213 void
1214 AliMUONCDB::WriteTriggerLut(Int_t startRun, Int_t endRun)
1215 {  
1216   /// Write trigger LUT to OCDB
1217   
1218   AliMUONTriggerLut* lut = MakeTriggerLUT();
1219   if (lut)
1220   {
1221     WriteToCDB("MUON/Calib/TriggerLut",lut,startRun,endRun,true);
1222   }
1223   delete lut;
1224 }
1225
1226 //_____________________________________________________________________________
1227 void
1228 AliMUONCDB::WriteTriggerEfficiency(Int_t startRun, Int_t endRun)
1229 {  
1230   /// Write trigger efficiency to OCDB
1231   
1232   AliMUONTriggerEfficiencyCells* eff = MakeTriggerEfficiency();
1233   if (eff)
1234   {
1235     WriteToCDB("MUON/Calib/TriggerEfficiency",eff,startRun,endRun,true);
1236   }
1237   delete eff;
1238 }
1239
1240 //_____________________________________________________________________________
1241 void 
1242 AliMUONCDB::WriteNeighbours(Int_t startRun, Int_t endRun)
1243 {
1244   /// Write neighbours to OCDB
1245   
1246   AliMUONVStore* neighbours = Create2DMap();
1247   Int_t ngenerated = MakeNeighbourStore(*neighbours);
1248   AliInfoGeneral("AliMUONCDB", Form("Ngenerated = %d",ngenerated));
1249   if (ngenerated>0)
1250   {
1251     WriteToCDB("MUON/Calib/Neighbours",neighbours,startRun,endRun,true);
1252   }
1253   delete neighbours;
1254 }
1255
1256 //_____________________________________________________________________________
1257 void 
1258 AliMUONCDB::WriteHV(Bool_t defaultValues,
1259                     Int_t startRun, Int_t endRun)
1260 {
1261   /// generate HV values (either cste = 1500 V) if defaultValues=true or random
1262   /// if defaultValues=false, see makeHVStore) and
1263   /// store them into CDB located at cdbpath, with a validity period
1264   /// ranging from startRun to endRun
1265   
1266   TMap* hvStore = new TMap;
1267   Int_t ngenerated = MakeHVStore(*hvStore,defaultValues);
1268   AliInfoGeneral("AliMUONCDB", Form("Ngenerated = %d",ngenerated));
1269   if (ngenerated>0)
1270   {
1271     WriteToCDB("MUON/Calib/HV",hvStore,startRun,endRun,defaultValues);
1272   }
1273   delete hvStore;
1274 }
1275
1276 //_____________________________________________________________________________
1277 void 
1278 AliMUONCDB::WriteTriggerDCS(Bool_t defaultValues,
1279                     Int_t startRun, Int_t endRun)
1280 {
1281   /// generate Trigger HV and current values (either const if defaultValues=true or random
1282   /// if defaultValues=false, see makeTriggerDCSStore) and
1283   /// store them into CDB located at cdbpath, with a validity period
1284   /// ranging from startRun to endRun
1285   
1286   TMap* triggerDCSStore = new TMap;
1287   Int_t ngenerated = MakeTriggerDCSStore(*triggerDCSStore,defaultValues);
1288   AliInfoGeneral("AliMUONCDB", Form("Ngenerated = %d",ngenerated));
1289   if (ngenerated>0)
1290   {
1291     WriteToCDB("MUON/Calib/TriggerDCS",triggerDCSStore,startRun,endRun,defaultValues);
1292   }
1293   delete triggerDCSStore;
1294 }
1295
1296 //_____________________________________________________________________________
1297 void 
1298 AliMUONCDB::WritePedestals(Bool_t defaultValues,
1299                            Int_t startRun, Int_t endRun)
1300 {
1301   /// generate pedestal values (either 0 if defaultValues=true or random
1302   /// if defaultValues=false, see makePedestalStore) and
1303   /// store them into CDB located at cdbpath, with a validity period
1304   /// ranging from startRun to endRun
1305   
1306   AliMUONVStore* pedestalStore = Create2DMap();
1307   Int_t ngenerated = MakePedestalStore(*pedestalStore,defaultValues);
1308   AliInfoGeneral("AliMUONCDB", Form("Ngenerated = %d",ngenerated));
1309   WriteToCDB("MUON/Calib/Pedestals",pedestalStore,startRun,endRun,defaultValues);
1310   delete pedestalStore;
1311 }
1312
1313 //_____________________________________________________________________________
1314 void 
1315 AliMUONCDB::WriteOccupancyMap(Bool_t defaultValues,
1316                               Int_t startRun, Int_t endRun)
1317 {
1318   /// generate occupancy map values (either empty one if defaultValues=true, or
1319   /// random one, see MakeOccupancyMapStore) and
1320   /// store them into CDB located at cdbpath, with a validity period
1321   /// ranging from startRun to endRun
1322   
1323   AliMUONVStore* occupancyMapStore = Create2DMap();
1324   Int_t ngenerated = MakeOccupancyMapStore(*occupancyMapStore,defaultValues);
1325   AliInfoGeneral("AliMUONCDB", Form("Ngenerated = %d",ngenerated));
1326   WriteToCDB("MUON/Calib/OccupancyMap",occupancyMapStore,startRun,endRun,defaultValues);
1327   delete occupancyMapStore;
1328 }
1329
1330 //_____________________________________________________________________________
1331 void 
1332 AliMUONCDB::WriteRejectList(Bool_t defaultValues,
1333                               Int_t startRun, Int_t endRun)
1334 {
1335   /// generate reject list values (either empty one if defaultValues=true, or
1336   /// random one, see MakeRejectListStore) and
1337   /// store them into CDB located at cdbpath, with a validity period
1338   /// ranging from startRun to endRun
1339   
1340   AliMUONRejectList* rl = MakeRejectListStore(defaultValues);
1341   WriteToCDB("MUON/Calib/RejectList",rl,startRun,endRun,defaultValues);
1342   delete rl;
1343 }
1344
1345
1346 //_____________________________________________________________________________
1347 void 
1348 AliMUONCDB::WriteGains(Bool_t defaultValues,
1349                        Int_t startRun, Int_t endRun)
1350 {
1351   /// generate gain values (either 1 if defaultValues=true or random
1352   /// if defaultValues=false, see makeGainStore) and
1353   /// store them into CDB located at cdbpath, with a validity period
1354   /// ranging from startRun to endRun
1355   
1356   AliMUONVStore* gainStore = Create2DMap();
1357   Int_t ngenerated = MakeGainStore(*gainStore,defaultValues);
1358   AliInfoGeneral("AliMUONCDB", Form("Ngenerated = %d",ngenerated));  
1359   WriteToCDB("MUON/Calib/Gains",gainStore,startRun,endRun,defaultValues);
1360   delete gainStore;
1361 }
1362
1363 //_____________________________________________________________________________
1364 void 
1365 AliMUONCDB::WriteCapacitances(const char* filename,
1366                               Int_t startRun, Int_t endRun)
1367 {
1368   /// read manu capacitance and injection gain values from file 
1369   /// and store them into CDB located at cdbpath, with a validity period
1370   /// ranging from startRun to endRun
1371   
1372   AliMUONVStore* capaStore = new AliMUON1DMap(16828);
1373   Int_t ngenerated = MakeCapacitanceStore(*capaStore,filename);
1374   AliInfoGeneral("AliMUONCDB", Form("Ngenerated = %d",ngenerated));
1375   if ( ngenerated > 0 ) 
1376   {
1377     WriteToCDB("MUON/Calib/Capacitances",capaStore,startRun,endRun,filename);
1378   }
1379   delete capaStore;
1380 }
1381
1382 //_____________________________________________________________________________
1383 void 
1384 AliMUONCDB::WriteCapacitances(Bool_t defaultValues,
1385                               Int_t startRun, Int_t endRun)
1386 {
1387   /// generate manu capacitance values (either 1 if defaultValues=true or random
1388   /// if defaultValues=false, see makeCapacitanceStore) and
1389   /// store them into CDB located at cdbpath, with a validity period
1390   /// ranging from startRun to endRun
1391   
1392   AliMUONVStore* capaStore = new AliMUON1DMap(16828);
1393   Int_t ngenerated = MakeCapacitanceStore(*capaStore,defaultValues);
1394   AliInfoGeneral("AliMUONCDB", Form("Ngenerated = %d",ngenerated));
1395   WriteToCDB("MUON/Calib/Capacitances",capaStore,startRun,endRun,defaultValues);
1396   delete capaStore;
1397 }
1398
1399 //_____________________________________________________________________________
1400 void
1401 AliMUONCDB::WriteTrigger(Bool_t defaultValues, Int_t startRun, Int_t endRun)
1402 {
1403   /// Writes all Trigger related calibration to CDB
1404   WriteTriggerDCS(defaultValues,startRun,endRun);
1405   WriteLocalTriggerMasks(startRun,endRun);
1406   WriteRegionalTriggerConfig(startRun,endRun);
1407   WriteGlobalTriggerConfig(startRun,endRun);
1408   WriteTriggerLut(startRun,endRun);
1409   WriteTriggerEfficiency(startRun,endRun);
1410 }
1411
1412 //_____________________________________________________________________________
1413 void
1414 AliMUONCDB::WriteConfig(Int_t startRun, Int_t endRun)
1415 {
1416   /// Write complete tracker configuration to OCDB
1417   ostringstream lines;
1418   TIter next(AliMpDDLStore::Instance()->CreateBusPatchIterator());
1419   AliMpBusPatch* bp;
1420   while ( ( bp = static_cast<AliMpBusPatch*>(next()) ) )
1421   {
1422     for (Int_t imanu = 0; imanu < bp->GetNofManus(); ++imanu) 
1423     {
1424       lines << bp->GetId() << " " << bp->GetManuId(imanu) << endl;
1425     }
1426   }
1427   
1428   AliMUON2DMap config(kTRUE);
1429   
1430   AliMUONTrackerIO::DecodeConfig(lines.str().c_str(),config);
1431   
1432   WriteToCDB("MUON/Calib/Config",&config,startRun,endRun,kTRUE);
1433 }
1434
1435 //_____________________________________________________________________________
1436 void
1437 AliMUONCDB::WriteTracker(Bool_t defaultValues, Int_t startRun, Int_t endRun)
1438 {
1439   /// Writes all Tracker related calibration to CDB
1440   WriteHV(defaultValues,startRun,endRun);
1441   WritePedestals(defaultValues,startRun,endRun);
1442   WriteGains(defaultValues,startRun,endRun);
1443   WriteCapacitances(defaultValues,startRun,endRun);
1444   WriteNeighbours(startRun,endRun);
1445   WriteOccupancyMap(defaultValues,startRun,endRun);
1446   WriteRejectList(defaultValues,startRun,endRun);
1447   WriteConfig(startRun,endRun);
1448 }
1449
1450 //_____________________________________________________________________________
1451 void 
1452 AliMUONCDB::ShowCapacitances()
1453 {
1454   /// Show briefly the number of capa values we have in the OCDB,
1455   /// and the list of manu that are actually in the config and for which
1456   /// we miss the capa (if any).
1457   
1458   if (!AliMUONCDB::CheckOCDB()) return;
1459   
1460   AliMUONCDB::LoadMapping();
1461   
1462   if (!AliMUONCDB::CheckMapping()) return;
1463   
1464   AliCDBEntry* e = AliCDBManager::Instance()->Get("MUON/Calib/Config");
1465   
1466   if (!e) return ;
1467   
1468   AliMUONVStore* config = static_cast<AliMUONVStore*>(e->GetObject());
1469   
1470   e = AliCDBManager::Instance()->Get("MUON/Calib/Capacitances");
1471   
1472   if (!e) return;
1473   
1474   AliMUONVStore* capacitances = static_cast<AliMUONVStore*>(e->GetObject());
1475   
1476   AliInfoGeneral("ShowCapacitances",Form("%d capacitances are in OCDB",capacitances->GetSize()));
1477   
1478   TIter nextManu(config->CreateIterator());
1479   AliMUONVCalibParam* param;
1480   
1481   while ( ( param = static_cast<AliMUONVCalibParam*>(nextManu()) ) )
1482   {
1483     Int_t detElemId = param->ID0();
1484     Int_t manuId = param->ID1();
1485     
1486     Int_t serialNumber 
1487     = AliMpManuStore::Instance()->GetManuSerial(detElemId, manuId);
1488     
1489     if (serialNumber<0)
1490     {
1491       AliErrorGeneral("ShowCapacitances",Form("Did not find serial for DE %04d MANUID %04d",detElemId,manuId));
1492     }
1493     else
1494     {
1495       AliMUONVCalibParam* capa = static_cast<AliMUONVCalibParam*>(capacitances->FindObject(serialNumber));
1496       if (!capa)
1497       {
1498         AliErrorGeneral("ShowCapacitances",Form("Did not find capacitance for DE %04d MANUID %04d SERIAL %d",detElemId,manuId,serialNumber));
1499       }
1500     }
1501   }
1502   
1503 }
1504
1505 //_____________________________________________________________________________
1506 void 
1507 AliMUONCDB::ShowConfig(Bool_t withStatusMap)
1508 {  
1509   /// Dumps the current tracker configuration, i.e. number and identity of missing buspatches
1510   /// If statusMap is true, will also take into account the status map to report the number
1511   /// of good channels
1512   
1513   if (!AliMUONCDB::CheckOCDB()) return;
1514   
1515   AliMUONCDB::LoadMapping();
1516   
1517   if (!AliMUONCDB::CheckMapping()) return;
1518   
1519   AliCDBEntry* e = AliCDBManager::Instance()->Get("MUON/Calib/Config");
1520   
1521   if (!e) return ;
1522   
1523   AliMUONVStore* config = static_cast<AliMUONVStore*>(e->GetObject());
1524   
1525   AliMUONPadStatusMapMaker* statusMapMaker(0x0);
1526   AliMUONCalibrationData* cd(0x0);
1527   AliMUONPadStatusMaker* statusMaker(0x0);
1528
1529   if ( withStatusMap ) 
1530   {
1531     cd = new AliMUONCalibrationData(AliCDBManager::Instance()->GetRun());
1532   
1533     statusMaker = new AliMUONPadStatusMaker(*cd);
1534
1535     AliMUONRecoParam* recoParam = AliMUONCDB::LoadRecoParam();
1536   
1537     statusMaker->SetLimits(*recoParam);
1538   
1539     UInt_t mask = recoParam->PadGoodnessMask();
1540
1541     delete recoParam;
1542     
1543     const Bool_t deferredInitialization = kFALSE;
1544   
1545     statusMapMaker = new AliMUONPadStatusMapMaker(*cd,mask,deferredInitialization);
1546   }
1547   
1548   TIter nextManu(config->CreateIterator());
1549   AliMUONVCalibParam* param;
1550   
1551   AliMpExMap buspatches;
1552   
1553   while ( ( param = static_cast<AliMUONVCalibParam*>(nextManu()) ) )
1554   {
1555     Int_t detElemId = param->ID0();
1556     Int_t manuId = param->ID1();
1557     Int_t busPatchId = AliMpDDLStore::Instance()->GetBusPatchId(detElemId,manuId);
1558     if ( buspatches.GetValue(busPatchId) == 0x0 ) 
1559     {      
1560       buspatches.Add(busPatchId,new TObjString(Form("BP%04d",busPatchId)));
1561     }
1562   }
1563
1564   TArrayI removed(buspatches.GetSize());
1565
1566   TIter next(AliMpDDLStore::Instance()->CreateBusPatchIterator());
1567   AliMpBusPatch* bp;
1568   Int_t n(0);
1569   Int_t nok(0);
1570   Int_t nremoved(0);
1571   
1572   // accounting of bus patches first
1573   
1574   while ( ( bp = static_cast<AliMpBusPatch*>(next())))
1575   {
1576     if ( buspatches.GetValue(bp->GetId()) )
1577     {
1578       ++nok;
1579     }
1580     else
1581     {
1582       removed.SetAt(bp->GetId(),nremoved++);
1583     }
1584   }
1585   
1586   // accounting of channels
1587   
1588   AliMpManuIterator it;
1589
1590   Int_t totalNumberOfChannels(0);
1591   Int_t removedChannels(0);
1592   Int_t badChannels(0);
1593   Int_t badAndRemovedChannels(0);
1594   Int_t badOrRemovedChannels(0);
1595   
1596   Int_t detElemId, manuId;
1597   
1598   while ( it.Next(detElemId,manuId) )
1599   {
1600     AliMpDetElement* de = AliMpDDLStore::Instance()->GetDetElement(detElemId);
1601     for ( Int_t i = 0; i < AliMpConstants::ManuNofChannels(); ++i )
1602     {
1603       Int_t busPatchId = AliMpDDLStore::Instance()->GetBusPatchId(detElemId,manuId);
1604       
1605       if ( de->IsConnectedChannel(manuId,i) )
1606       {
1607         ++totalNumberOfChannels;
1608         Bool_t badBusPatch = ( buspatches.GetValue(busPatchId) == 0x0 );
1609         
1610         if ( withStatusMap ) 
1611         {
1612           Bool_t badChannel = ( ( statusMapMaker->StatusMap(detElemId,manuId,i) & AliMUONPadStatusMapMaker::SelfDeadMask() ) != 0);
1613           if ( badChannel ) ++badChannels;
1614           if ( badBusPatch && badChannel ) ++badAndRemovedChannels;
1615           if ( badBusPatch || badChannel ) ++badOrRemovedChannels;          
1616         }
1617       
1618         if ( badBusPatch) ++removedChannels;
1619       }
1620     }
1621   }
1622   
1623   
1624   Int_t* indices = new Int_t[nremoved];
1625   
1626   TMath::Sort(nremoved,removed.GetArray(),indices,kFALSE);
1627   
1628   for ( Int_t i = 0; i < nremoved; ++i ) 
1629   {
1630     Int_t busPatchId = removed[indices[i]];
1631     bp = AliMpDDLStore::Instance()->GetBusPatch(busPatchId);
1632     bp->Print();
1633   }
1634   
1635   delete[] indices;  
1636   
1637   cout << endl;
1638   cout << Form("Bus patches n=%3d nok=%3d nremoved=%3d",n,nok,nremoved) << endl;
1639
1640   cout << Form("Channels n=%6d nremoved=%6d bad=%6d bad and removed=%6d bad or removed=%6d",
1641                totalNumberOfChannels,removedChannels,badChannels,badAndRemovedChannels,badOrRemovedChannels) << endl;
1642   
1643   if (totalNumberOfChannels>0)
1644   {
1645     cout << Form("Percentage of readout channels %5.1f %%",removedChannels*100.0/totalNumberOfChannels) << endl;
1646     if ( withStatusMap )
1647     {
1648       cout << Form("Percentage of non useable channels (bad or removed) %5.1f %%",
1649                    badOrRemovedChannels*100.0/totalNumberOfChannels) << endl;
1650     }
1651   }
1652   
1653   
1654   delete statusMapMaker;
1655   delete cd;
1656   delete statusMaker;  
1657 }
1658
1659 //______________________________________________________________________________
1660 void AliMUONCDB::ReadIntegers(const char* filename, std::vector<int>& integers)
1661 {
1662   /// Read integers from filename, where integers are either
1663   /// separated by "," or by return carriage
1664   ifstream in(gSystem->ExpandPathName(filename));
1665   int i;
1666   
1667   std::set<int> runset;
1668   
1669   char line[10000];
1670   
1671   in.getline(line,10000,'\n');
1672   
1673   TString sline(line);
1674   
1675   if (sline.Contains(","))
1676   {
1677     TObjArray* a = sline.Tokenize(",");
1678     TIter next(a);
1679     TObjString* s;
1680     while ( ( s = static_cast<TObjString*>(next()) ) )
1681     {
1682       runset.insert(s->String().Atoi());
1683     }
1684     delete a;
1685   }
1686   else
1687   {
1688     runset.insert(sline.Atoi());
1689     
1690     while ( in >> i )
1691     {
1692       runset.insert(i);
1693     }
1694   }
1695   
1696   for ( std::set<int>::const_iterator it = runset.begin(); it != runset.end(); ++it ) 
1697   {
1698     integers.push_back((*it)); 
1699   }
1700   
1701   std::sort(integers.begin(),integers.end());
1702 }
1703
1704 //______________________________________________________________________________
1705 void AliMUONCDB::ShowFaultyBusPatches(const char* runlist, double occLimit,
1706                                       const char* outputBaseName,
1707                                       const char* ocdbPath)
1708 {
1709   /// Shows the list of bus patches above a given occupancy limit,
1710   /// for each run in the runlist
1711   
1712   AliLog::GetRootLogger()->SetGlobalLogLevel(AliLog::kError);
1713   
1714   //  AliLog::SetPrintType(AliLog::kInfo,kFALSE);
1715   //  AliLog::SetPrintType(AliLog::kWarning,kFALSE);
1716   //  gErrorIgnoreLevel=kError; // to avoid all the TAlienFile::Open messages...
1717   
1718   AliCDBManager* man = AliCDBManager::Instance();
1719   
1720   man->SetDefaultStorage(ocdbPath);
1721   
1722   Bool_t first(kTRUE);
1723   
1724   std::vector<int> runnumbers;
1725   
1726   ReadIntegers(runlist,runnumbers);
1727   
1728   AliMUON2DMap bpValues(kFALSE);
1729   
1730   std::ofstream outfile(Form("%s.txt",outputBaseName));
1731   
1732   for ( unsigned int i = 0 ; i < runnumbers.size(); ++i )
1733   {
1734     int runNumber = runnumbers[i];
1735     
1736     man->SetRun(runNumber);
1737     
1738     if ( first ) 
1739     {
1740       AliMpCDB::LoadAll();  
1741       first = kFALSE;
1742     }
1743     
1744     AliCDBEntry* e = man->Get("MUON/Calib/OccupancyMap",runNumber);
1745     
1746     if (!e)
1747     {
1748       AliErrorGeneral("AliMUONCDB::ShowFaultyBusPatches",
1749                       Form("Could not get OccupancyMap for run %09d",runNumber));
1750       continue;
1751     }
1752     
1753     AliMUONVStore* occmap = static_cast<AliMUONVStore*>(e->GetObject());
1754     
1755     AliMUONTrackerData td("occ","occ",*occmap);
1756     
1757     TIter nextBP(AliMpDDLStore::Instance()->CreateBusPatchIterator());
1758     AliMpBusPatch* bp;
1759     std::set<int> buspatches;
1760     Double_t sumn = 1000.0;
1761     
1762     while ( ( bp = static_cast<AliMpBusPatch*>(nextBP()) ) )
1763     {      
1764       Double_t occ = td.BusPatch(bp->GetId(),2);
1765       
1766       if (occ>occLimit) 
1767       {
1768         buspatches.insert(bp->GetId());
1769         
1770         AliMUONVCalibParam* param = static_cast<AliMUONVCalibParam*>(bpValues.FindObject(bp->GetId()));
1771         
1772         if (!param)
1773         {
1774           param = new AliMUONCalibParamND(5, 1, bp->GetId(), 0);
1775           bpValues.Add(param);
1776           
1777           Int_t detElemId = AliMpDDLStore::Instance()->GetDEfromBus(bp->GetId());
1778           AliMpDetElement* de = AliMpDDLStore::Instance()->GetDetElement(detElemId);
1779           
1780           Int_t nchannels(0);
1781           
1782           for ( Int_t imanu = 0; imanu < bp->GetNofManus(); ++imanu ) 
1783           {
1784             Int_t manuId = bp->GetManuId(imanu);
1785             nchannels += de->NofChannelsInManu(manuId);
1786           }
1787           
1788           param->SetValueAsDouble(0,2,sumn);
1789           param->SetValueAsDouble(0,3,nchannels);
1790           param->SetValueAsDouble(0,4,1);          
1791         }
1792         
1793         Double_t sumw = sumn*(param->ValueAsDouble(0)/sumn+1.0/runnumbers.size());
1794         Double_t sumw2 = 0.0; //(sumn-1)*ey*ey+sumw*sumw/sumn;
1795         
1796         param->SetValueAsDouble(0,0,sumw);
1797         param->SetValueAsDouble(0,1,sumw2);
1798         
1799       }
1800     }
1801     
1802     outfile << Form("RUN %09d",runNumber);
1803     
1804     for ( std::set<int>::const_iterator bit = buspatches.begin(); bit != buspatches.end(); ++bit )
1805     {
1806       outfile << Form(" %4d",*bit);
1807     }
1808     outfile << endl;
1809   }
1810   
1811   outfile.close();
1812   
1813   const char* name = "BPfailureRate";
1814   
1815   AliMUONTrackerData* mpData = new AliMUONTrackerData(name,name,bpValues,2);
1816   mpData->SetDimensionName(0,name);
1817   
1818   TFile f(Form("%s.root",outputBaseName),"recreate");
1819   mpData->Write();
1820   f.Close();
1821   
1822   cout << Form("Results are in %s.txt and %s.root",outputBaseName,outputBaseName) << endl;
1823   
1824   gSystem->Exec(Form("cat %s.txt",outputBaseName));
1825   
1826 }
1827
1828 //______________________________________________________________________________
1829 void AliMUONCDB::CheckHV(Int_t runNumber, Int_t verbose)
1830 {
1831   /// Check the HV values in OCDB for a given run
1832   
1833   TList messages;
1834   messages.SetOwner(kTRUE);
1835   
1836   Bool_t patched(kTRUE);
1837   
1838   if (!AliCDBManager::Instance()->IsDefaultStorageSet())
1839   {
1840     AliCDBManager::Instance()->SetDefaultStorage("raw://");
1841   }
1842
1843   AliCDBManager::Instance()->SetRun(runNumber);
1844
1845   LoadMapping();
1846   
1847   AliMUONCalibrationData::CreateHV(runNumber,0,patched,&messages);
1848   
1849   AliMUONCalibrationData cd(runNumber,true);
1850   
1851   AliMUONPadStatusMaker statusMaker(cd);
1852   
1853   AliMUONRecoParam* rp = AliMUONCDB::LoadRecoParam();
1854   
1855   if (!rp)
1856   {
1857     AliErrorGeneral("AliMUONCDB::CheckHV","Could not get RecoParam !!!");
1858     return;
1859   }
1860   
1861   statusMaker.SetLimits(*rp);
1862   
1863   TIter next(&messages);
1864   TObjString* s;
1865   AliMpDCSNamer hvNamer("TRACKER");
1866   AliMUONLogger log;
1867   
1868   while ( ( s = static_cast<TObjString*>(next()) ) )
1869   {
1870     TObjArray* a = s->String().Tokenize(":");
1871     
1872     TString name(static_cast<TObjString*>(a->At(0))->String());
1873     
1874     if ( name.Contains("sw") || name.Contains("SUMMARY") ) continue;
1875     
1876     Int_t index = hvNamer.DCSIndexFromDCSAlias(name.Data());
1877     
1878     Int_t detElemId = hvNamer.DetElemIdFromDCSAlias(name.Data());
1879     
1880     AliMpDetElement* de = AliMpDDLStore::Instance()->GetDetElement(detElemId);
1881     
1882     if (!de)
1883     {
1884       AliErrorGeneral("AliMUONCDB::CheckHV",Form("Could not get detElemId from dcsAlias %s",name.Data()));
1885       continue;
1886     }
1887     
1888     Int_t manuId;
1889     
1890     if ( index >= 0 )
1891     {
1892       const AliMpArrayI* array = de->ManusForHV(index);
1893       manuId = array->GetValue(0);
1894     }
1895     else
1896       
1897     {
1898       AliMpBusPatch* bp = AliMpDDLStore::Instance()->GetBusPatch(de->GetBusPatchId(0));
1899       
1900       manuId = bp->GetManuId(0);
1901     }
1902     
1903     Int_t status = statusMaker.HVStatus(detElemId,manuId);
1904     
1905     log.Log(AliMUONPadStatusMaker::AsString(status).Data());
1906     
1907     s->String() += Form(" (DE %4d) ",detElemId);
1908     s->String() += AliMUONPadStatusMaker::AsString(status).Data();
1909     
1910     delete a;
1911   }    
1912   
1913   TIter nextMessage(&messages);
1914   TObjString* msg;
1915   
1916   while ( ( msg = static_cast<TObjString*>(nextMessage()) ) )
1917   {
1918     if ( verbose > 0 || msg->String().Contains("SUMMARY") )
1919     {
1920       AliInfoGeneral("AliMUONCDB::CheckHV",Form("RUN %09d HVchannel %s",runNumber,msg->String().Data()));
1921     }
1922   }
1923   
1924   TString lmsg;
1925   Int_t occurance;
1926   TString totalLog;
1927   
1928   while (log.Next(lmsg,occurance))
1929   {
1930     totalLog += Form("%s(%d)",lmsg.Data(),occurance);
1931     totalLog += " | ";
1932   }
1933
1934   AliInfoGeneral("AliMUONCDB::CheckHV",Form("RUN %09d %s",runNumber,totalLog.Data()));
1935
1936   // one last loop to get the list of problematic HV channels
1937   nextMessage.Reset();
1938   
1939   while ( ( msg = static_cast<TObjString*>(nextMessage()) ) )
1940   {
1941     if ( msg->String().Contains("HV ") )
1942     {
1943       AliInfoGeneral("AliMUONCDB::CheckHV",Form("     Problem at %s",msg->String().Data()));      
1944     }
1945   }
1946    
1947   AliCDBManager::Instance()->ClearCache();
1948 }
1949
1950