1 /**************************************************************************
2 * Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. *
4 * Author: The ALICE Off-line Project. *
5 * Contributors are mentioned in the code where appropriate. *
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 **************************************************************************/
18 //-----------------------------------------------------------------------------
19 /// \class AliCounterCollection
21 /// generic class to handle a collection of counters
23 /// \author Philippe Pillot
24 //-----------------------------------------------------------------------------
26 #include "AliCounterCollection.h"
31 #include <TObjString.h>
32 #include <TObjArray.h>
33 #include <THnSparse.h>
34 #include <THashList.h>
38 #include <TCollection.h>
40 ClassImp(AliCounterCollection)
42 //-----------------------------------------------------------------------
43 AliCounterCollection::AliCounterCollection(const char* name) :
45 fRubrics(new THashList(10)),
46 fRubricsSize(new TArrayI(10)),
48 fWeightedCounters(kFALSE)
54 //-----------------------------------------------------------------------
55 AliCounterCollection::~AliCounterCollection()
63 //-----------------------------------------------------------------------
64 void AliCounterCollection::Clear(Option_t*)
68 fRubricsSize->Reset();
69 delete fCounters; fCounters = 0x0;
70 fWeightedCounters = kFALSE;
73 //-----------------------------------------------------------------------
74 void AliCounterCollection::AddRubric(TString name, TString listOfKeyWords)
76 /// Add a new rubric with the complete list of related key words separated by "/".
77 /// If the key word "any" is not defined, the overall statistics is
78 /// assumed to be the sum of the statistics under each key word.
81 listOfKeyWords.ToUpper();
83 if (fRubrics->Contains(name.Data())) {
84 AliError(Form("rubric named %s already exist",name.Data()));
88 // add the list of autorized key words
89 TObjArray* rubric = listOfKeyWords.Tokenize("/");
90 CleanListOfStrings(rubric);
91 rubric->SetName(name.Data());
92 Int_t nRubrics = fRubrics->GetSize();
93 rubric->SetUniqueID(nRubrics);
94 fRubrics->AddLast(rubric);
96 // save the number of autorized key words (expand the array if needed)
97 if (nRubrics+1 > fRubricsSize->GetSize()) fRubricsSize->Set(2*fRubricsSize->GetSize());
98 (*fRubricsSize)[nRubrics] = rubric->GetEntriesFast();
101 //-----------------------------------------------------------------------
102 void AliCounterCollection::AddRubric(TString name, Int_t maxNKeyWords)
104 /// Add a new rubric containing at maximum maxNKeyWords key words.
105 /// Key words will be added as the counters get filled until the maximum is reached.
106 /// If the key word "any" is never defined, the overall statistics is
107 /// assumed to be the sum of the statistics under each key word.
111 if (fRubrics->Contains(name.Data())) {
112 AliError(Form("rubric named %s already exist",name.Data()));
116 // create the empty rubric
117 TObjString* rubric = new TObjString(name.Data());
118 Int_t nRubrics = fRubrics->GetSize();
119 rubric->SetUniqueID(nRubrics);
120 fRubrics->AddLast(rubric);
122 // save the maximum number of autorized key words
123 if (nRubrics+1 > fRubricsSize->GetSize()) fRubricsSize->Set(2*fRubricsSize->GetSize());
124 (*fRubricsSize)[nRubrics] = maxNKeyWords;
127 //-----------------------------------------------------------------------
128 void AliCounterCollection::Init(Bool_t weightedCounters)
130 /// Initialize the internal counters from the added rubrics.
132 // create the counters
134 fWeightedCounters = weightedCounters;
135 if (fWeightedCounters)
136 fCounters = new THnSparseT<TArrayF>("hCounters", "hCounters", fRubrics->GetSize(), fRubricsSize->GetArray(), 0x0, 0x0);
138 fCounters = new THnSparseT<TArrayI>("hCounters", "hCounters", fRubrics->GetSize(), fRubricsSize->GetArray(), 0x0, 0x0);
141 TObject* rubric = 0x0;
142 TIter nextRubric(fRubrics);
143 while ((rubric = nextRubric())) {
144 TAxis* axis = fCounters->GetAxis((Int_t)rubric->GetUniqueID());
147 axis->SetName(rubric->GetName());
149 // set labels if already known
150 TObjArray* keyWords = dynamic_cast<TObjArray*>(rubric);
152 TObjString* label = 0x0;
154 TIter nextLabel(keyWords);
155 while ((label = static_cast<TObjString*>(nextLabel()))) axis->SetBinLabel(bin++, label->String().Data());
162 //-----------------------------------------------------------------------
163 Int_t AliCounterCollection::GetNActiveBins(Int_t dim)
165 /// return the number of labels in that rubric.
166 THashList* labels = fCounters->GetAxis(dim)->GetLabels();
167 return (labels) ? labels->GetSize() : 0;
170 //-----------------------------------------------------------------------
171 Bool_t AliCounterCollection::ContainsAny(Int_t dim)
173 /// return kTRUE if that rubric contains the keyWord "ANY".
174 THashList* labels = fCounters->GetAxis(dim)->GetLabels();
175 return (labels && labels->Contains("ANY"));
178 //-----------------------------------------------------------------------
179 const Int_t* AliCounterCollection::FindBins(const TString& externalKey, Bool_t allocate, Int_t& nEmptySlots)
181 /// Return the corresponding bins ordered by rubric or 0x0 if externalKey is not valid.
182 /// The externalKey format must be rubric:keyWord/rubric:keyWord/rubric:keyWord/...
183 /// If allocate = kTRUE, new key words are added to the corresponding rubric if possible.
184 /// If a rubric is not filled in, the coresponding slot contain -1 in the array.
185 /// It is the responsability of the user to delete the returned array.
187 // produce an empty array of keys
188 Int_t nRubrics = fRubrics->GetSize();
189 Int_t* bins = new Int_t[nRubrics];
190 for (Int_t i=0; i<nRubrics; i++) bins[i] = -1;
191 nEmptySlots = nRubrics;
192 Bool_t isValid = kTRUE;
194 // get the list of rubric:keyWord pairs
195 TObjArray* rubricKeyPairs = externalKey.Tokenize("/");
197 // loop over each rubric:keyWord pair
198 TObjString* pair = 0x0;
199 TIter next(rubricKeyPairs);
200 while ((pair = static_cast<TObjString*>(next()))) {
202 // get both rubric and associated key word
203 TObjArray* rubricKeyPair = pair->String().Tokenize(":");
205 // check the format of the pair
206 if (rubricKeyPair->GetEntriesFast() != 2) {
207 AliError("invalid key format");
209 delete rubricKeyPair;
213 // get the axis corresponding to that rubric
214 Int_t dim = FindDim(static_cast<TObjString*>(rubricKeyPair->UncheckedAt(0))->String());
217 delete rubricKeyPair;
221 // find the bin corresponding to that key word
222 Int_t bin = FindBin(dim, static_cast<TObjString*>(rubricKeyPair->UncheckedAt(1))->String(), allocate);
225 delete rubricKeyPair;
229 // check if the array of keys already contains something for that rubric
230 if (bins[dim] >= 0) {
231 AliWarning("key already given for that rubric --> ignored");
232 delete rubricKeyPair;
236 // store the corresponding bin for that slot
241 delete rubricKeyPair;
244 // delete the array in case of problem
248 nEmptySlots = nRubrics;
252 delete rubricKeyPairs;
257 //-----------------------------------------------------------------------
258 Int_t AliCounterCollection::FindDim(const TString& rubricName) const
260 /// Return the dimension corresponding to that rubric (or -1 in case of failure).
261 TObject* rubric = fRubrics->FindObject(rubricName.Data());
263 AliError(Form("invalid rubric: %s",rubricName.Data()));
266 return (Int_t) rubric->GetUniqueID();
269 //-----------------------------------------------------------------------
270 Int_t AliCounterCollection::FindBin(Int_t dim, const TString& keyWord, Bool_t allocate)
272 /// Return the bin number corresponding to that key word (or -1 in case of failure).
273 /// If allocate = kTRUE, try to add the key word if possible.
275 TAxis* axis = fCounters->GetAxis(dim);
277 // look for the bin corresponding to keyWord
278 THashList* labels = axis->GetLabels();
279 TObjString* label = (labels) ? static_cast<TObjString*>(labels->FindObject(keyWord.Data())) : 0x0;
280 Int_t bin = (label) ? (Int_t)label->GetUniqueID() : -1;
282 // in case the keyWord does not exist, try to add it if required
283 if (bin<0 && allocate) {
284 Int_t nLabels = (labels) ? labels->GetSize() : 0;
285 if (nLabels < axis->GetNbins()) {
287 axis->SetBinLabel(bin, keyWord.Data());
291 if (bin<0) AliError(Form("invalid key word: %s:%s",axis->GetName(),keyWord.Data()));
296 //-----------------------------------------------------------------------
297 Short_t** AliCounterCollection::DecodeSelection(const TString& selections, const TObjArray& displayedRubrics)
299 /// Tag the selected keywords in each rubric (-1=subtract; 0=discard; 1=add). Format:
300 /// "rubric:[any-]keyWord,keyWord,../rubric:[any-]keyWord,.." (order does not matter).
301 /// It is the responsability of the user to delete the returned array.
303 // produce an empty array of selected keys
304 Int_t nRubrics = fCounters->GetNdimensions();
305 Short_t** selects = new Short_t*[nRubrics];
306 for (Int_t i=0; i<nRubrics; i++) selects[i] = 0x0;
308 // get the list of rubric:LisOfKeyWord pairs
309 TObjArray* rubricKeyPairs = selections.Tokenize("/");
311 // loop over each rubric:keyWord pair
312 TObjString* pair = 0x0;
313 TIter next(rubricKeyPairs);
314 while ((pair = static_cast<TObjString*>(next()))) {
316 // get both rubric and associated list of key words
317 TObjArray* rubricKeyPair = pair->String().Tokenize(":");
319 // check the format of the pair
320 if (rubricKeyPair->GetEntriesFast() != 2) {
321 AliError("invalid key format");
322 delete rubricKeyPair;
323 delete rubricKeyPairs;
324 for (Int_t i=0; i<nRubrics; i++) if (selects[i]) delete[] selects[i];
329 // check wether to select or to discard the keyWords
330 Int_t include = kTRUE;
331 TString ListOfKeyWords(static_cast<TObjString*>(rubricKeyPair->UncheckedAt(1))->String());
332 if (ListOfKeyWords.BeginsWith("ANY-")) {
333 ListOfKeyWords.Remove(0,4);
337 // select the key words
338 const TString& rubric = static_cast<TObjString*>(rubricKeyPair->UncheckedAt(0))->String();
339 if (!Select(include, rubric, ListOfKeyWords, displayedRubrics.Contains(rubric.Data()), selects)) {
340 delete rubricKeyPair;
341 delete rubricKeyPairs;
342 for (Int_t i=0; i<nRubrics; i++) if (selects[i]) delete[] selects[i];
348 delete rubricKeyPair;
352 delete rubricKeyPairs;
354 // complete the selection of other rubrics
355 for (Int_t i=0; i<nRubrics; i++) {
357 // skip already processed rubrics
358 if (selects[i]) continue;
360 // create the list of bins
361 Int_t nBins = GetNActiveBins(i) + 1;
362 selects[i] = new Short_t[nBins];
364 // select all key words or only the key work "ANY"
365 if (ContainsAny(i) && !displayedRubrics.Contains(fCounters->GetAxis(i)->GetName())) {
366 memset(selects[i], 0, sizeof(Short_t) * nBins);
367 selects[i][FindBin(i, "ANY", kFALSE)] = 1;
368 } else for (Int_t j=0; j<nBins; j++) selects[i][j] = 1;
375 //-----------------------------------------------------------------------
376 Bool_t AliCounterCollection::Select(Bool_t include, const TString& rubric, const TString& keywords,
377 Bool_t displayed, Short_t* selectBins[])
379 /// Tag the selected keywords (separated by ',') in that rubric (-1=subtract; 0=discard; 1=add).
381 Int_t dim = FindDim(rubric);
382 if (dim < 0) return kFALSE;
384 if (selectBins[dim]) {
385 AliWarning(Form("selection already made for rubric %s --> ignored",rubric.Data()));
389 // get list of key words to select
390 TObjArray* keys = keywords.Tokenize(",");
391 if (keys->GetEntriesFast() == 0) {
392 AliError(Form("no key word specified for rubric %s",rubric.Data()));
397 // create the list of bins
398 Int_t nBins = GetNActiveBins(dim) + 1;
399 selectBins[dim] = new Short_t[nBins];
401 // select/unselect all bins
402 Bool_t containsAny = ContainsAny(dim);
403 if (include || (containsAny && !displayed)) {
404 memset(selectBins[dim], 0, sizeof(Short_t) * nBins);
405 if (!include) selectBins[dim][FindBin(dim, "ANY", kFALSE)] = 1;
406 } else for (Int_t j=0; j<nBins; j++) selectBins[dim][j] = 1;
408 // select/unselect specific key words
409 TObjString* key = 0x0;
411 while ((key = static_cast<TObjString*>(nextKey()))) {
413 // special case of key word "ANY"
414 if (key->String() == "ANY") {
418 Int_t binAny = FindBin(dim, "ANY", kFALSE);
419 if (include) selectBins[dim][binAny] = 1;
420 else selectBins[dim][binAny] = 0;
424 if (include) for (Int_t j=0; j<nBins; j++) selectBins[dim][j] = 1;
425 else memset(selectBins[dim], 0, sizeof(Short_t) * nBins);
429 } else { // other cases
431 // find the corresponding bin
432 Int_t bin = FindBin(dim, key->String().Data(), kFALSE);
438 // select/unselect it
439 if (include) selectBins[dim][bin] = 1;
440 else if (containsAny && !displayed) selectBins[dim][bin] = -1;
441 else selectBins[dim][bin] = 0;
453 //-----------------------------------------------------------------------
454 void AliCounterCollection::CleanListOfStrings(TObjArray* list)
456 /// Make sure all strings appear only once in this list
458 // remove multiple-occurrence
459 Int_t nEntries = list->GetEntriesFast();
460 for (Int_t i = 0; i < nEntries; i++) {
461 TObjString* entry1 = static_cast<TObjString*>(list->UncheckedAt(i));
462 if (!entry1) continue;
463 for (Int_t j = i+1; j < nEntries; j++) {
464 TObjString* entry2 = static_cast<TObjString*>(list->UncheckedAt(j));
465 if (entry2 && entry2->IsEqual(entry1)) {
466 AliWarning(Form("multiple-occurence of string \"%s\" --> removed",entry2->String().Data()));
472 // remove empty slots
476 //-----------------------------------------------------------------------
477 void AliCounterCollection::Count(TString externalKey, Int_t value)
479 /// Add "value" to the counter referenced by "externalKey".
480 /// The externalKey format must be rubric:keyWord/rubric:keyWord/rubric:keyWord/...
481 if (value > 0) CountAsDouble(externalKey, (Double_t)value);
482 else if (value < 0) AliError("cannot count negative values");
485 //-----------------------------------------------------------------------
486 void AliCounterCollection::Count(TString externalKey, Double_t value)
488 /// Add "value" to the counter referenced by "externalKey".
489 /// The externalKey format must be rubric:keyWord/rubric:keyWord/rubric:keyWord/...
490 if (fWeightedCounters) CountAsDouble(externalKey, value);
491 else AliError("non-weighted counters can only be filled with intergers");
494 //-----------------------------------------------------------------------
495 void AliCounterCollection::CountAsDouble(TString externalKey, Double_t value)
497 /// Add "value" to the counter referenced by "externalKey".
498 /// The externalKey format must be rubric:keyWord/rubric:keyWord/rubric:keyWord/...
501 AliError("counters are not initialized");
505 externalKey.ToUpper();
507 // convert external to internal key
508 Int_t nEmptySlots = 0;
509 const Int_t* bins = FindBins(externalKey, kTRUE, nEmptySlots);
512 // check for empty slots
513 if (nEmptySlots > 0) {
514 AliError("incomplete key");
519 // increment the corresponding counter
520 fCounters->AddBinContent(bins, value);
526 //-----------------------------------------------------------------------
527 void AliCounterCollection::Print(const Option_t* opt) const
529 /// Print every individual counters if opt=="" or call "Print(opt, "")".
531 if (strcmp(opt,"")) {
532 const_cast<AliCounterCollection*>(this)->Print(opt, "");
537 AliError("counters are not initialized");
541 if (fCounters->GetNbins() == 0) {
542 printf("\nall counters are empty\n\n");
546 Int_t nRubrics = fCounters->GetNdimensions();
547 Int_t* bins = new Int_t[nRubrics];
549 // loop over every filled counters
550 for (Long64_t i=0; i<fCounters->GetNbins(); ++i) {
552 // get the content of the bin
553 Double_t value = fCounters->GetBinContent(i, bins);
555 // build the corresponding counter name
557 for (Int_t j=0; j<nRubrics; j++) counter += Form("/%s",fCounters->GetAxis(j)->GetBinLabel(bins[j]));
561 if (fWeightedCounters) printf("\n%s %g", counter.Data(), value);
562 else printf("\n%s %d", counter.Data(), (Int_t)value);
570 //-----------------------------------------------------------------------
571 TString AliCounterCollection::GetKeyWords(TString rubric) const
573 /// return the list of key words for the given rubric.
575 TString keyWords = "";
578 AliError("counters are not initialized");
584 // get the dimension corresponding to that rubric
585 Int_t dim = FindDim(rubric);
586 if (dim < 0) return keyWords;
588 // build list of key words
589 TObjString* label = 0x0;
590 TIter nextLabel(fCounters->GetAxis(dim)->GetLabels());
591 while ((label = static_cast<TObjString*>(nextLabel()))) keyWords += Form("%s,",label->String().Data());
592 keyWords.Remove(TString::kTrailing, ',');
597 //-----------------------------------------------------------------------
598 Double_t AliCounterCollection::GetSum(TString selections)
600 /// Get the overall statistics for the given selection (result is integrated over not specified rubrics):
601 /// - format of "selections" is rubric:[any-]keyWord,keyWord,../rubric:[any-]keyWord,.. (order does not matter).
604 AliError("counters are not initialized");
608 selections.ToUpper();
610 // decode the selections
611 Short_t** select = DecodeSelection(selections, TObjArray());
612 if (!select) return 0.;
614 // loop over every filled counters and compute integral
616 Int_t nDims = fCounters->GetNdimensions();
617 Int_t* coord = new Int_t[nDims];
618 for (Long64_t i=0; i<fCounters->GetNbins(); ++i) {
620 // get the content of the counter
621 Double_t value = fCounters->GetBinContent(i, coord);
623 // discard not selected counters and compute the selection factor
624 Int_t selectionFactor = 1;
625 for (Int_t dim = 0; dim < nDims && selectionFactor != 0; dim++) selectionFactor *= select[dim][coord[dim]];
626 if (selectionFactor == 0) continue;
629 sum += selectionFactor * value;
633 for (Int_t iDim=0; iDim<nDims; iDim++) delete[] select[iDim];
640 //-----------------------------------------------------------------------
641 void AliCounterCollection::PrintKeyWords() const
643 /// Print the full list of key words.
646 AliError("counters are not initialized");
651 Int_t nRubrics = fCounters->GetNdimensions();
652 for (Int_t iDim=0; iDim<nRubrics; iDim++) {
653 TAxis* axis = fCounters->GetAxis(iDim);
655 // print rubric's name
656 printf("\n%s:", axis->GetName());
658 // loop over key words
659 Bool_t first = kTRUE;
660 TObjString* label = 0x0;
661 TIter nextLabel(axis->GetLabels());
662 while ((label = static_cast<TObjString*>(nextLabel()))) {
664 //print key word's name
666 printf("%s", label->String().Data());
668 } else printf(",%s", label->String().Data());
675 //-----------------------------------------------------------------------
676 void AliCounterCollection::PrintValue(TString selections)
678 /// Print value of selected counter.
679 /// format of "selections" is rubric:keyWord/rubric:keyWord/rubric:keyWord/...
682 AliError("counters are not initialized");
686 selections.ToUpper();
688 // convert external to internal key
689 Int_t nEmptySlots = 0;
690 const Int_t* selectedBins = FindBins(selections, kFALSE, nEmptySlots);
691 if (!selectedBins) return;
693 // check for empty slots
694 if (nEmptySlots > 0) {
695 AliError("incomplete key");
696 delete[] selectedBins;
701 if (fWeightedCounters) printf("\n%g\n\n", fCounters->GetBinContent(selectedBins));
702 else printf("\n%d\n\n", (Int_t) fCounters->GetBinContent(selectedBins));
705 delete[] selectedBins;
708 //-----------------------------------------------------------------------
709 void AliCounterCollection::Print(TString rubrics, TString selections, Bool_t removeEmpty)
711 /// Print desired rubrics for the given selection:
712 /// - format of "rubrics" is rubric1/rubric2/.. (order matters only for output).
713 /// - format of "selections" is rubric:[any-]keyWord,keyWord,../rubric:[any-]keyWord,.. (order does not matter).
714 /// If "data" contains 1 rubric, the output will be one counter for each element of that rubric.
715 /// If "data" contains 2 rubrics, the output will be an array of counters, rubric1 vs rubric2.
716 /// If "data" contains 3 rubrics, the output will be an array rubric1 vs rubric2 for each element in rubric3.
718 /// Results are integrated over rubrics not specified neither in "rubrics" nor in "selections".
721 AliError("counters are not initialized");
726 selections.ToUpper();
728 // get the rubrics to print
729 TObjArray* rubricsToPrint = rubrics.Tokenize("/");
730 if (rubricsToPrint->GetEntriesFast() == 0) {
731 delete rubricsToPrint;
735 // remove rubrics called twice
736 CleanListOfStrings(rubricsToPrint);
738 // project counters in the rubrics to print according to the selections
739 TObject* hist = Projection(*rubricsToPrint, selections);
741 delete rubricsToPrint;
746 Int_t nRubricsToPrint = rubricsToPrint->GetEntriesFast();
747 if (nRubricsToPrint == 1 && (static_cast<TH1D*>(hist))->GetEntries() > 0)
748 PrintList(static_cast<TH1D*>(hist), removeEmpty);
749 else if (nRubricsToPrint == 2 && (static_cast<TH2D*>(hist))->GetEntries() > 0)
750 PrintArray(static_cast<TH2D*>(hist), removeEmpty);
751 else if (nRubricsToPrint > 2 && (static_cast<THnSparse*>(hist))->GetEntries() > 0)
752 PrintListOfArrays(static_cast<THnSparse*>(hist), removeEmpty);
754 printf("\nselected counters are empty\n\n");
757 delete rubricsToPrint;
761 //-----------------------------------------------------------------------
762 void AliCounterCollection::PrintSum(TString selections)
764 /// Print the overall statistics for the given selection (result is integrated over not specified rubrics):
765 /// - format of "selections" is rubric:[any-]keyWord,keyWord,../rubric:[any-]keyWord,.. (order does not matter).
766 Double_t sum = GetSum(selections);
767 if (fWeightedCounters) printf("\n%g\n\n", sum);
768 else printf("\n%d\n\n", (Int_t)sum);
771 //-----------------------------------------------------------------------
772 void AliCounterCollection::PrintList(const TH1D* hist, Bool_t removeEmpty) const
774 /// Print the content of 1D histogram as a list.
776 // set the format to print labels
777 THashList* labels = hist->GetXaxis()->GetLabels();
779 if (fWeightedCounters) format = Form("\n%%%ds %%9g",GetMaxLabelSize(labels));
780 else format = Form("\n%%%ds %%9d",GetMaxLabelSize(labels));
782 // print value for each label
783 TObjString* label = 0x0;
784 TIter nextLabel(labels);
785 while ((label = static_cast<TObjString*>(nextLabel()))) {
786 Int_t bin = (Int_t) label->GetUniqueID();
787 Double_t value = hist->GetBinContent(bin);
788 if (removeEmpty && value == 0.) continue;
789 if (fWeightedCounters) printf(format.Data(), label->String().Data(), value);
790 else printf(format.Data(), label->String().Data(), (Int_t) value);
795 //-----------------------------------------------------------------------
796 void AliCounterCollection::PrintArray(const TH2D* hist, Bool_t removeEmpty) const
798 /// Print the content of 2D histogram as an array.
800 // set the format to print labels in X direction
801 THashList* labelsX = hist->GetXaxis()->GetLabels();
802 TString formatX(Form("\n%%%ds ",GetMaxLabelSize(labelsX)));
804 // set the format to print labels in Y direction and values
805 THashList* labelsY = hist->GetYaxis()->GetLabels();
806 Int_t maxLabelSizeY = TMath::Max(9, GetMaxLabelSize(labelsY));
807 TString formatYs(Form("%%%ds ",maxLabelSizeY));
808 TString formatYd(Form("%%%dd ",maxLabelSizeY));
809 TString formatYg(Form("%%%dg ",maxLabelSizeY));
811 // if required, set the list of labels for which all counters are not empty
812 Bool_t *useLabelX = 0x0, *useLabelY = 0x0;
813 TObjString *labelX = 0x0, *labelY = 0x0;
814 TIter nextLabelX(labelsX);
815 TIter nextLabelY(labelsY);
818 // create label flags and set them as unused
819 useLabelX = new Bool_t[labelsX->GetSize()+1];
820 memset(useLabelX, kFALSE, sizeof(Bool_t) * (labelsX->GetSize()+1));
821 useLabelY = new Bool_t[labelsY->GetSize()+1];
822 memset(useLabelY, kFALSE, sizeof(Bool_t) * (labelsY->GetSize()+1));
824 // loop over labels in X direction
825 while ((labelX = static_cast<TObjString*>(nextLabelX()))) {
826 Int_t binX = (Int_t) labelX->GetUniqueID();
828 // loop over labels in Y direction
830 while ((labelY = static_cast<TObjString*>(nextLabelY()))) {
831 Int_t binY = (Int_t) labelY->GetUniqueID();
833 // both labels already set as used
834 if (useLabelX[binX] && useLabelY[binY]) continue;
837 if (hist->GetBinContent(binX, binY) == 0.) continue;
840 useLabelX[binX] = kTRUE;
841 useLabelY[binY] = kTRUE;
849 // print labels in Y axis
850 printf(formatX.Data()," ");
852 while ((labelY = static_cast<TObjString*>(nextLabelY()))) {
853 if (removeEmpty && !useLabelY[labelY->GetUniqueID()]) continue;
854 printf(formatYs.Data(), labelY->String().Data());
857 // fill array for each label in X axis
859 while ((labelX = static_cast<TObjString*>(nextLabelX()))) {
860 Int_t binX = (Int_t) labelX->GetUniqueID();
862 if (removeEmpty && !useLabelX[binX]) continue;
865 printf(formatX.Data(), labelX->String().Data());
867 // print value for each label in Y axis
869 while ((labelY = static_cast<TObjString*>(nextLabelY()))) {
870 Int_t binY = (Int_t) labelY->GetUniqueID();
871 if (removeEmpty && !useLabelY[binY]) continue;
872 if (fWeightedCounters) printf(formatYg.Data(), hist->GetBinContent(binX, binY));
873 else printf(formatYd.Data(), (Int_t) hist->GetBinContent(binX, binY));
885 //-----------------------------------------------------------------------
886 void AliCounterCollection::PrintListOfArrays(const THnSparse* hist, Bool_t removeEmpty) const
888 /// Print the content of nD histogram as a list of arrays.
890 // set the format to print labels in X direction
891 THashList* labelsX = hist->GetAxis(0)->GetLabels();
892 TString formatX(Form("\n%%%ds ",GetMaxLabelSize(labelsX)));
894 // set the format to print labels in Y direction and values
895 THashList* labelsY = hist->GetAxis(1)->GetLabels();
896 Int_t maxLabelSizeY = TMath::Max(9, GetMaxLabelSize(labelsY));
897 TString formatYs(Form("%%%ds ",maxLabelSizeY));
898 TString formatYd(Form("%%%dd ",maxLabelSizeY));
899 TString formatYg(Form("%%%dg ",maxLabelSizeY));
901 // create a list containing each combination of labels refering the arrays to be printout
903 listOfCombis.SetOwner();
905 // add a first empty combination
906 Int_t nDim = hist->GetNdimensions();
907 listOfCombis.AddLast(new TObjArray(nDim-2));
909 // loop over the nDim-2 other rubrics
910 for (Int_t i=2; i<nDim; i++) {
912 // save the last label of that rubic
913 THashList* labels = hist->GetAxis(i)->GetLabels();
914 TObjString* lastLabel = (labels) ? static_cast<TObjString*>(labels->Last()) : 0x0;
915 if (!lastLabel) return;
917 // prepare iteration over the list of labels
918 TIter nextLabel(labels);
920 // loop over existing combinations
921 TObjLink* lnk = listOfCombis.FirstLink();
924 // get the current combination
925 TObjArray* currentCombi = static_cast<TObjArray*>(lnk->GetObject());
927 // loop over labels in the current rubric
929 TObjString* label = 0x0;
930 while ((label = static_cast<TObjString*>(nextLabel()))) {
932 // stop at the last one
933 if (label == lastLabel) break;
935 // copy the current combination, add the current label to it and add it to the list of combinations
936 TObjArray* combi = new TObjArray(*currentCombi);
937 combi->AddLast(label);
938 listOfCombis.AddBefore(lnk, combi);
941 // add the last label to the current combination
942 currentCombi->AddLast(lastLabel);
949 // create bin coordinates to access individual counters
950 Int_t* bins = new Int_t[nDim];
952 // create label flags
953 Bool_t *useLabelX = 0x0, *useLabelY = 0x0;
955 useLabelX = new Bool_t[labelsX->GetSize()+1];
956 useLabelY = new Bool_t[labelsY->GetSize()+1];
959 // loop over each combination of labels
960 TObjArray* combi = 0x0;
961 TIter nextCombi(&listOfCombis);
962 while ((combi = static_cast<TObjArray*>(nextCombi()))) {
964 // make the name of the combination and fill the corresponding bin coordinates
965 TString combiName = "/";
966 for (Int_t i=2; i<nDim; i++) {
967 TObjString* label = static_cast<TObjString*>(combi->UncheckedAt(i-2));
968 combiName += Form("%s/",label->String().Data());
969 bins[i] = (Int_t)label->GetUniqueID();
972 // reset the list of labels for which all counters are not empty
974 memset(useLabelX, kFALSE, sizeof(Bool_t) * (labelsX->GetSize()+1));
975 memset(useLabelY, kFALSE, sizeof(Bool_t) * (labelsY->GetSize()+1));
978 Bool_t empty = kTRUE;
979 TObjString* labelX = 0x0;
980 TObjString* labelY = 0x0;
981 TIter nextLabelX(labelsX);
982 TIter nextLabelY(labelsY);
983 // loop over labels in X direction
984 while ((labelX = static_cast<TObjString*>(nextLabelX()))) {
985 bins[0] = (Int_t) labelX->GetUniqueID();
987 // loop over labels in Y direction
989 while ((labelY = static_cast<TObjString*>(nextLabelY()))) {
990 bins[1] = (Int_t) labelY->GetUniqueID();
992 // both labels already set as used
993 if (removeEmpty && useLabelX[bins[0]] && useLabelY[bins[1]]) continue;
996 if (hist->GetBinContent(bins) == 0.) continue;
998 // set label as used and array as not empty
1001 useLabelX[bins[0]] = kTRUE;
1002 useLabelY[bins[1]] = kTRUE;
1007 if (!removeEmpty && !empty) break;
1011 // skip empty arrays
1012 if (empty) continue;
1014 // print the name of the combination of labels refering the incoming array
1015 printf("\n%s:\n",combiName.Data());
1017 // print labels in Y axis
1018 printf(formatX.Data()," ");
1020 while ((labelY = static_cast<TObjString*>(nextLabelY()))) {
1021 if (removeEmpty && !useLabelY[labelY->GetUniqueID()]) continue;
1022 printf(formatYs.Data(), labelY->String().Data());
1025 // fill array for each label in X axis
1027 while ((labelX = static_cast<TObjString*>(nextLabelX()))) {
1028 bins[0] = (Int_t) labelX->GetUniqueID();
1030 if (removeEmpty && !useLabelX[bins[0]]) continue;
1033 printf(formatX.Data(), labelX->String().Data());
1035 // print value for each label in Y axis
1037 while ((labelY = static_cast<TObjString*>(nextLabelY()))) {
1038 bins[1] = (Int_t) labelY->GetUniqueID();
1039 if (removeEmpty && !useLabelY[bins[1]]) continue;
1040 if (fWeightedCounters) printf(formatYg.Data(), hist->GetBinContent(bins));
1041 else printf(formatYd.Data(), (Int_t) hist->GetBinContent(bins));
1055 //-----------------------------------------------------------------------
1056 Int_t AliCounterCollection::GetMaxLabelSize(THashList* labels) const
1058 /// Return the number of characters of the longest label.
1059 Int_t maxLabelSize = 0;
1060 TObjString* label = 0x0;
1061 TIter nextLabel(labels);
1062 while ((label = static_cast<TObjString*>(nextLabel())))
1063 maxLabelSize = TMath::Max(maxLabelSize, label->String().Length());
1064 return maxLabelSize;
1067 //-----------------------------------------------------------------------
1068 TH1D* AliCounterCollection::Get(TString rubric, TString selections)
1070 /// Get counters of the rubric "rubric" for the given "selection".
1071 /// Format of "selections" is rubric:[any-]keyWord,keyWord,../rubric:[any-]keyWord,.. (order does not matter).
1072 /// Results are integrated over rubrics not specified neither in "rubric1" nor in "selections".
1073 /// It is the responsability of the user to delete the returned histogram.
1076 AliError("counters are not initialized");
1081 selections.ToUpper();
1083 // fill the rubrics to print
1084 TObjArray rubricsToPrint(1);
1085 rubricsToPrint.SetOwner();
1086 rubricsToPrint.AddLast(new TObjString(rubric.Data()));
1088 // project counters in the rubrics to print according to the selections
1089 TH1D* hist = static_cast<TH1D*>(Projection(rubricsToPrint, selections));
1091 // make it ready to display
1094 // remove statistic box
1095 hist->SetStats(kFALSE);
1098 TAxis* axis = hist->GetXaxis();
1099 THashList* labels = axis->GetLabels();
1100 Int_t nLabels = (labels) ? labels->GetSize() : 1;
1101 axis->SetRange(1,nLabels);
1102 axis->SetNdivisions(1,kFALSE);
1103 axis->SetTitle(rubric.Data());
1106 hist->GetYaxis()->SetTitle("Counts");
1112 //-----------------------------------------------------------------------
1113 TH2D* AliCounterCollection::Get(TString rubric1, TString rubric2, TString selections)
1115 /// Get counters of the "rubric1" vs "rubric2" for the given "selection".
1116 /// Format of "selections" is rubric:[any-]keyWord,keyWord,../rubric:[any-]keyWord,.. (order does not matter).
1117 /// Results are integrated over rubrics not specified neither in "rubric1", "rubric2" nor in "selections".
1118 /// It is the responsability of the user to delete the returned histogram.
1121 AliError("counters are not initialized");
1127 selections.ToUpper();
1129 // fill the rubrics to print
1130 TObjArray rubricsToPrint(2);
1131 rubricsToPrint.SetOwner();
1132 rubricsToPrint.AddLast(new TObjString(rubric2.Data()));
1133 rubricsToPrint.AddLast(new TObjString(rubric1.Data()));
1135 // project counters in the rubrics to print according to the selections
1136 TH2D* hist = static_cast<TH2D*>(Projection(rubricsToPrint, selections));
1141 // remove statistic box
1142 hist->SetStats(kFALSE);
1145 TAxis* axisX = hist->GetXaxis();
1146 THashList* labelsX = axisX->GetLabels();
1147 Int_t nLabelsX = (labelsX) ? labelsX->GetSize() : 1;
1148 axisX->SetRange(1,nLabelsX);
1149 axisX->SetNdivisions(1,kFALSE);
1150 axisX->SetTitle(rubric2.Data());
1153 TAxis* axisY = hist->GetYaxis();
1154 THashList* labelsY = axisY->GetLabels();
1155 Int_t nLabelsY = (labelsY) ? labelsY->GetSize() : 1;
1156 axisY->SetRange(1,nLabelsY);
1157 axisY->SetNdivisions(1,kFALSE);
1158 axisY->SetTitle(rubric1.Data());
1164 //-----------------------------------------------------------------------
1165 TH1D* AliCounterCollection::Draw(TString rubric, TString selections)
1167 /// Draw counters of the rubric "rubric" for the given "selection".
1168 /// Format of "selections" is rubric:[any-]keyWord,keyWord,../rubric:[any-]keyWord,.. (order does not matter).
1169 /// Results are integrated over rubrics not specified neither in "rubric1" nor in "selections".
1170 /// It is the responsability of the user to delete the returned histogram.
1171 TH1D* hist = Get(rubric, selections);
1172 if (hist) hist->Draw("htext");
1176 //-----------------------------------------------------------------------
1177 TH2D* AliCounterCollection::Draw(TString rubric1, TString rubric2, TString selections)
1179 /// Draw counters of the "rubric1" vs "rubric2" for the given "selection".
1180 /// Format of "selections" is rubric:[any-]keyWord,keyWord,../rubric:[any-]keyWord,.. (order does not matter).
1181 /// Results are integrated over rubrics not specified neither in "rubric1", "rubric2" nor in "selections".
1182 /// It is the responsability of the user to delete the returned histogram.
1183 TH2D* hist = Get(rubric1, rubric2, selections);
1184 if (hist) hist->Draw("text");
1188 //-----------------------------------------------------------------------
1189 TObject* AliCounterCollection::Projection(const TObjArray& data, const TString& selections)
1191 /// Return desired "data" for the given "selection" stored in a new histogram or 0x0 in case of failure.
1192 /// The type of the histogram (TH1D, TH2D or THnSparse) depend on the number of data.
1193 /// It is the responsability of the user to delete the returned histogram.
1195 // decode the selections
1196 Short_t** select = DecodeSelection(selections, data);
1197 if (!select) return 0x0;
1199 // define name and dimensions of projection histo
1200 TString name(fCounters->GetName());
1201 Int_t nDims = fCounters->GetNdimensions();
1202 Int_t nTargetDims = data.GetEntriesFast();
1203 TArrayI targetDims(nTargetDims);
1204 TArrayI nNewBins(nTargetDims);
1205 TArrayI* OldToNewCoord = new TArrayI[nTargetDims];
1206 for (Int_t i=0; i<nTargetDims; i++) {
1209 name += Form("_%s",static_cast<TObjString*>(data.UncheckedAt(i))->String().Data());
1212 targetDims[i] = FindDim(static_cast<TObjString*>(data.UncheckedAt(i))->String());
1214 // set number of selected bins in the target dims and make the correspondence between old and new coordinates
1216 if (targetDims[i] > -1) {
1217 Int_t nBins = GetNActiveBins(targetDims[i]) + 1;
1218 OldToNewCoord[i].Set(nBins);
1219 for (Int_t j=1; j<nBins; j++) if (select[targetDims[i]][j] > 0) OldToNewCoord[i][j] = ++nNewBins[i];
1222 // clean memory and return 0x0 in case of problem
1223 if (nNewBins[i] == 0) {
1224 for (Int_t iDim=0; iDim<nDims; iDim++) delete[] select[iDim];
1226 delete[] OldToNewCoord;
1232 // define title of projection histo
1233 TString title = "Selections: ";
1234 TString selectionString(selections);
1235 selectionString.Remove(TString::kBoth, '/');
1236 if (selectionString.Length() > 0) title += Form("%s/", selectionString.Data());
1238 TIter nextRubric(fRubrics);
1239 while ((rub = nextRubric())) {
1240 if (selectionString.Contains(Form("%s:",rub->GetName()))) continue;
1241 if (data.Contains(rub->GetName())) continue;
1242 title += Form("%s:ANY/", rub->GetName());
1244 title.ReplaceAll("/", " ");
1246 // Create new histograms
1248 if (nTargetDims == 1) hist = new TH1D(name.Data(), title.Data(), nNewBins[0], 0., 1.);
1249 else if (nTargetDims == 2) hist = new TH2D(name.Data(), title.Data(), nNewBins[0], 0., 1., nNewBins[1], 0., 1.);
1250 else if (fWeightedCounters) hist = new THnSparseT<TArrayF>(name.Data(), title.Data(), nTargetDims, nNewBins.GetArray(), 0x0, 0x0);
1251 else hist = new THnSparseT<TArrayI>(name.Data(), title.Data(), nTargetDims, nNewBins.GetArray(), 0x0, 0x0);
1253 // Set new axis labels
1255 if (nTargetDims < 3) {
1258 TIter nextLabelX(fCounters->GetAxis(targetDims[0])->GetLabels());
1259 while ((label = static_cast<TObjString*>(nextLabelX()))) {
1260 if (select[targetDims[0]][label->GetUniqueID()] > 0) {
1261 static_cast<TH1*>(hist)->GetXaxis()->SetBinLabel(OldToNewCoord[0][label->GetUniqueID()], label->String().Data());
1266 if (nTargetDims == 2) {
1267 TIter nextLabelY(fCounters->GetAxis(targetDims[1])->GetLabels());
1268 while ((label = static_cast<TObjString*>(nextLabelY()))) {
1269 if (select[targetDims[1]][label->GetUniqueID()] > 0) {
1270 static_cast<TH1*>(hist)->GetYaxis()->SetBinLabel(OldToNewCoord[1][label->GetUniqueID()], label->String().Data());
1278 for (Int_t i=0; i<nTargetDims; i++) {
1279 TIter nextLabel(fCounters->GetAxis(targetDims[i])->GetLabels());
1280 while ((label = static_cast<TObjString*>(nextLabel()))) {
1281 if (select[targetDims[i]][label->GetUniqueID()] > 0) {
1282 static_cast<THnSparse*>(hist)->GetAxis(i)->SetBinLabel(OldToNewCoord[i][label->GetUniqueID()], label->String().Data());
1289 // loop over every filled counters
1290 Int_t* coord = new Int_t[nDims];
1291 Int_t* newCoord = new Int_t[nTargetDims];
1293 for (Long64_t i=0; i<fCounters->GetNbins(); ++i) {
1295 // get the content of the counter
1296 Double_t value = fCounters->GetBinContent(i, coord);
1298 // discard not selected counters and compute the selection factor
1299 Int_t selectionFactor = 1;
1300 for (Int_t dim = 0; dim < nDims && selectionFactor != 0; dim++) selectionFactor *= select[dim][coord[dim]];
1301 if (selectionFactor == 0) continue;
1303 // find new coordinates in the projection histo
1304 for (Int_t d = 0; d < nTargetDims; ++d) newCoord[d] = OldToNewCoord[d][coord[targetDims[d]]];
1306 // fill projection histo
1307 if (nTargetDims < 3) {
1308 Int_t linBin = (nTargetDims == 1) ? newCoord[0] : static_cast<TH1*>(hist)->GetBin(newCoord[0], newCoord[1]);
1309 static_cast<TH1*>(hist)->AddBinContent(linBin, selectionFactor*value);
1310 } else static_cast<THnSparse*>(hist)->AddBinContent(newCoord, selectionFactor*value);
1315 // update the number of entries
1316 if (nTargetDims < 3) static_cast<TH1*>(hist)->SetEntries(nEntries);
1317 else static_cast<THnSparse*>(hist)->SetEntries(nEntries);
1320 for (Int_t iDim=0; iDim<nDims; iDim++) delete[] select[iDim];
1324 delete[] OldToNewCoord;
1329 //-----------------------------------------------------------------------
1330 Int_t* AliCounterCollection::CheckConsistency(const AliCounterCollection* c)
1332 /// Consistency check of the two counter collections. To be consistent, both counters
1333 /// must have the same rubrics with the same list of authorized key words if any.
1334 /// Return the correspondence between the local rubric ordering and the one of the other counter,
1335 /// or 0x0 in case of problem. It is the responsability of the user to delete the returned array.
1337 if (!fCounters || !c->fCounters) {
1338 AliError("counters are not initialized");
1342 // check if both counters are weighted or not
1343 if (c->fWeightedCounters != fWeightedCounters) AliWarning("merging non-weighted with weigthed counters");
1345 // check if the number of rubrics is the same
1346 Int_t nRubrics = fRubrics->GetSize();
1347 if (c->fRubrics->GetSize() != nRubrics) {
1348 AliError("both counters do not contain the same number of rubrics");
1352 Int_t* otherDims = new Int_t[nRubrics];
1354 // loop over local rubrics
1355 TObject* rubric1 = 0x0;
1356 TIter nextRubric(fRubrics);
1357 while ((rubric1 = nextRubric())) {
1359 // find that rubric in the other counter
1360 TObject* rubric2 = c->fRubrics->FindObject(rubric1->GetName());
1362 AliError(Form("the other counter does not contain the rubric %s", rubric1->GetName()));
1367 // check the list of authorized key words if any
1368 TObjArray* keyWords1 = dynamic_cast<TObjArray*>(rubric1);
1369 TObjArray* keyWords2 = dynamic_cast<TObjArray*>(rubric2);
1370 if (keyWords1 && keyWords2) {
1372 // check if the number of key words is the same
1373 if (keyWords1->GetEntriesFast() != keyWords2->GetEntriesFast()) {
1374 AliError("that rubric does not contain the same number of authorized key words in both counters");
1379 // loop over local key words
1380 TObjString* keyWord = 0x0;
1381 TIter nextKeyWord(keyWords1);
1382 while ((keyWord = static_cast<TObjString*>(nextKeyWord()))) {
1384 // find that key word in the corresponding rubric of the other counter
1385 if (!keyWords2->FindObject(keyWord->String().Data())) {
1386 AliError(Form("rubric %s does not contain the key word %s in the other counter", rubric1->GetName(), keyWord->String().Data()));
1393 } else if (keyWords1 || keyWords2) {
1395 // that rubric has not been initialized the same way in both counter
1397 AliError(Form("rubric %s of the other counter does not contain a list of authorized key words while this does", rubric1->GetName()));
1399 AliError(Form("rubric %s of this counter does not contain a list of authorized key words while the other does", rubric1->GetName()));
1406 // save the correspondence of rubric IDs in both counters
1407 otherDims[rubric1->GetUniqueID()] = rubric2->GetUniqueID();
1414 //-----------------------------------------------------------------------
1415 void AliCounterCollection::Add(const AliCounterCollection* counter)
1417 /// Add the given AliCounterCollections to this. They must have the
1418 /// same rubrics with the same list of authorized key words if any.
1420 // check the consistency between the other counter and this and get the correspondences between rubric IDs.
1421 Int_t* otherDims = CheckConsistency(counter);
1422 if (!otherDims) return;
1424 Int_t nRubrics = fCounters->GetNdimensions();
1425 Int_t* thisBins = new Int_t[nRubrics];
1426 Int_t* otherBins = new Int_t[nRubrics];
1428 // loop over every filled bins inside the other counter
1429 for (Long64_t i = 0; i < counter->fCounters->GetNbins(); i++) {
1431 // get the content of the bin
1432 Double_t value = counter->fCounters->GetBinContent(i, otherBins);
1434 // convert "other" bin coordinates to "this" bin coordinates
1436 for (Int_t dim = 0; dim < nRubrics; dim++) {
1437 TString label = counter->fCounters->GetAxis(otherDims[dim])->GetBinLabel(otherBins[otherDims[dim]]);
1438 thisBins[dim] = FindBin(dim, label, kTRUE);
1439 if (thisBins[dim] < 0) {
1440 AliError("this counter is full, unable to add that key word");
1447 // increment the corresponding local counter
1448 fCounters->AddBinContent(thisBins, value);
1457 //-----------------------------------------------------------------------
1458 Long64_t AliCounterCollection::Merge(TCollection* list)
1460 /// Merge this with a list of AliCounterCollections. All AliCounterCollections provided
1461 /// must have the same rubrics with the same list of authorized key words if any.
1463 if (!list || !fCounters) return 0;
1464 if (list->IsEmpty()) return (Long64_t)fCounters->GetEntries();
1467 const TObject* obj = 0x0;
1468 while ((obj = next())) {
1470 // check that "obj" is an object of the class AliCounterCollection
1471 const AliCounterCollection* counter = dynamic_cast<const AliCounterCollection*>(obj);
1473 AliFatal(Form("object named \"%s\" is a %s instead of an AliCounterCollection!", obj->GetName(), obj->ClassName()));
1477 // merge counter to this one
1482 return (Long64_t)fCounters->GetEntries();
1485 //-----------------------------------------------------------------------
1486 void AliCounterCollection::Sort(Option_t* opt, Bool_t asInt)
1488 /// Sort rubrics defined without a list of authorized key words or all rubrics if opt=="all".
1489 /// If asInt=kTRUE, key words are ordered as interger instead of alphabetically.
1492 AliError("counters are not initialized");
1496 Bool_t all = (!strcasecmp(opt, "all"));
1498 Bool_t somethingToSort = kFALSE;
1499 Int_t nRubrics = fRubrics->GetSize();
1500 Bool_t* rubricsToSort = new Bool_t[nRubrics];
1501 memset(rubricsToSort, kFALSE, sizeof(Bool_t) * nRubrics);
1503 // choose rubrics to sort
1504 TObject* rubric = 0x0;
1505 TIter nextRubric(fRubrics);
1506 while ((rubric = nextRubric())) {
1508 if (all || dynamic_cast<TObjString*>(rubric)) {
1510 // check if something to sort
1511 THashList* labels = fCounters->GetAxis((Int_t)rubric->GetUniqueID())->GetLabels();
1512 if (!labels || labels->GetSize() < 2) continue;
1514 // select that rubric
1515 rubricsToSort[(Int_t)rubric->GetUniqueID()] = kTRUE;
1516 somethingToSort = kTRUE;
1522 // sort selected rubrics if any
1523 if (somethingToSort) Sort(rubricsToSort, asInt);
1526 delete[] rubricsToSort;
1529 //-----------------------------------------------------------------------
1530 void AliCounterCollection::SortRubric(TString rubric, Bool_t asInt)
1532 /// Sort only that rubric. If asInt=kTRUE, key words are ordered as interger instead of alphabetically.
1535 AliError("counters are not initialized");
1541 // find the rubric to sort
1542 Int_t dim = FindDim(rubric);
1543 if (dim < 0) return;
1545 // check if something to sort
1546 THashList* labels = fCounters->GetAxis(dim)->GetLabels();
1547 if (!labels || labels->GetSize() < 2) return;
1549 // select that rubric
1550 Int_t nRubrics = fRubrics->GetSize();
1551 Bool_t* rubricsToSort = new Bool_t[nRubrics];
1552 memset(rubricsToSort, kFALSE, sizeof(Bool_t) * nRubrics);
1553 rubricsToSort[dim] = kTRUE;
1556 Sort(rubricsToSort, asInt);
1559 delete[] rubricsToSort;
1562 //-----------------------------------------------------------------------
1563 void AliCounterCollection::Sort(const Bool_t* rubricsToSort, Bool_t asInt)
1565 /// Sort labels (alphabetically or as integer) in each rubric flagged in "rubricsToSort".
1567 // create a new counter
1568 THnSparse* oldCounters = fCounters;
1569 Int_t nRubrics = fRubrics->GetSize();
1570 if (fWeightedCounters)
1571 fCounters = new THnSparseT<TArrayF>("hCounters", "hCounters", nRubrics, fRubricsSize->GetArray(), 0x0, 0x0);
1573 fCounters = new THnSparseT<TArrayI>("hCounters", "hCounters", nRubrics, fRubricsSize->GetArray(), 0x0, 0x0);
1574 Int_t** newBins = new Int_t*[nRubrics];
1575 Bool_t newBinsFilled = kTRUE;
1577 // define the new axes
1578 for (Int_t i=0; i<nRubrics; i++) {
1579 TAxis* oldAxis = oldCounters->GetAxis(i);
1580 TAxis* newAxis = fCounters->GetAxis(i);
1582 // set the name of the new axis
1583 newAxis->SetName(oldAxis->GetName());
1586 THashList* oldLabels = oldAxis->GetLabels();
1589 newBinsFilled = kFALSE;
1593 // sort them if required
1594 if (rubricsToSort[i]) {
1595 if (asInt) { oldLabels = SortAsInt(oldLabels); }
1596 else { oldLabels->Sort(); }
1599 // set labels in the new axis and save the correspondence between new and old bins
1600 newBins[i] = new Int_t[oldLabels->GetSize()+1];
1601 TObjString* label = 0x0;
1603 TIter nextLabel(oldLabels);
1604 while ((label = static_cast<TObjString*>(nextLabel()))) {
1605 newAxis->SetBinLabel(bin, label->String().Data());
1606 newBins[i][(Int_t)label->GetUniqueID()] = bin;
1611 if (rubricsToSort[i] && asInt) delete oldLabels;
1614 // fill the new fCounters only if all axes have label(s) defined (otherwise it is empty)
1615 if (newBinsFilled) {
1617 // fill the new counters
1618 Int_t* oldCoor = new Int_t[nRubrics];
1619 Int_t* newCoor = new Int_t[nRubrics];
1620 for (Long64_t i = 0; i < oldCounters->GetNbins(); i++) {
1621 Double_t value = oldCounters->GetBinContent(i, oldCoor);
1622 for (Int_t dim = 0; dim < nRubrics; dim++) newCoor[dim] = newBins[dim][oldCoor[dim]];
1623 fCounters->AddBinContent(newCoor, value);
1632 for (Int_t i=0; i<nRubrics; i++) delete[] newBins[i];
1637 //-----------------------------------------------------------------------
1638 THashList* AliCounterCollection::SortAsInt(const THashList* labels)
1640 /// Return a list (not owner) of labels sorted assuming they are integers.
1641 /// It is the responsability of user to delete the returned list.
1643 THashList* sortedLabels = new THashList(labels->GetSize());
1644 TIter nextSortedLabel(sortedLabels);
1647 TObjString* label = 0x0;
1648 TIter nextLabel(labels);
1649 while ((label = static_cast<TObjString*>(nextLabel()))) {
1651 // find where to add it
1652 TObjString* sortedLabel = 0x0;
1653 nextSortedLabel.Reset();
1654 while ((sortedLabel = static_cast<TObjString*>(nextSortedLabel())) &&
1655 (sortedLabel->String().Atoi() <= label->String().Atoi())) {}
1658 if (sortedLabel) sortedLabels->AddBefore(sortedLabel, label);
1659 else sortedLabels->AddLast(label);
1662 return sortedLabels;