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