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