REST-for-Physics  v2.3
Rare Event Searches ToolKit for Physics
Loading...
Searching...
No Matches
TRestAnalysisTree.cxx
1/*************************************************************************
2 * This file is part of the REST software framework. *
3 * *
4 * Copyright (C) 2016 GIFNA/TREX (University of Zaragoza) *
5 * For more information see http://gifna.unizar.es/trex *
6 * *
7 * REST is free software: you can redistribute it and/or modify *
8 * it under the terms of the GNU General Public License as published by *
9 * the Free Software Foundation, either version 3 of the License, or *
10 * (at your option) any later version. *
11 * *
12 * REST is distributed in the hope that it will be useful, *
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15 * GNU General Public License for more details. *
16 * *
17 * You should have a copy of the GNU General Public License along with *
18 * REST in $REST_PATH/LICENSE. *
19 * If not, see http://www.gnu.org/licenses/. *
20 * For the list of contributors see $REST_PATH/CREDITS. *
21 *************************************************************************/
22
85
86#include "TRestAnalysisTree.h"
87
88#include <TFile.h>
89#include <TH1F.h>
90#include <TLeaf.h>
91#include <TObjArray.h>
92
93#include "TRestStringHelper.h"
94#include "TRestStringOutput.h"
95#include "TRestTools.h"
96
97using namespace std;
98
99ClassImp(TRestAnalysisTree) using namespace std;
100
101TRestAnalysisTree::TRestAnalysisTree() : TTree() {
102 SetName("AnalysisTree");
103 SetTitle("REST Analysis tree");
104
105 Initialize();
106}
107
108TRestAnalysisTree::TRestAnalysisTree(TTree* tree) : TTree() {
109 SetName("AnalysisTree");
110 SetTitle("Linked to " + (TString)tree->GetName());
111
112 Initialize();
113
114 tree->GetEntry(0);
115
116 TObjArray* lfs = tree->GetListOfLeaves();
117 for (int i = 0; i < lfs->GetLast() + 1; i++) {
118 TLeaf* lf = (TLeaf*)lfs->UncheckedAt(i);
119 RESTValue obs;
120 ReadLeafValueToObservable(lf, obs);
121 obs.name = lf->GetName();
122 SetObservable(-1, obs);
123 }
124}
125
126TRestAnalysisTree* TRestAnalysisTree::ConvertFromTTree(TTree* tree) {
127 if (tree->ClassName() == (TString) "TRestAnalysisTree") {
128 return (TRestAnalysisTree*)tree;
129 }
130
131 return new TRestAnalysisTree(tree);
132}
133
134TRestAnalysisTree::TRestAnalysisTree(const TString& name, const TString& title) : TTree(name, title) {
135 SetName(name);
136 SetTitle(title);
137
138 Initialize();
139}
140
141void TRestAnalysisTree::Initialize() {
142 fRunOrigin = 0;
143 fSubRunOrigin = 0;
144 fEventID = 0;
145 fSubEventID = 0;
146 fSubEventTag = new TString();
147 fTimeStamp = 0;
148
149 fStatus = 0;
150 fNObservables = 0;
151 fChain = nullptr;
152
153 fObservableIdMap.clear();
154 fObservableIdSearchMap.clear();
155 fObservableDescriptions.clear();
156 fObservableNames.clear();
157 fObservables.clear();
158}
159
166Int_t TRestAnalysisTree::GetObservableID(const string& obsName) {
168 auto iter = fObservableIdMap.find(obsName);
169 if (iter != fObservableIdMap.end()) {
170 return iter->second;
171 } else {
172 return -1;
173 }
174}
175
182Int_t TRestAnalysisTree::GetMatchedObservableID(const string& obsName) {
183 // if (ObservableExists(obsName)) return GetObservableID(obsName);
184 auto iter = fObservableIdSearchMap.find(obsName);
185 if (iter != fObservableIdSearchMap.end()) {
186 return iter->second;
187 } else {
188 vector<int> diffs;
189 for (auto& fObservableName : fObservableNames) {
190 string obs = (string)fObservableName;
191 int diff1 = DiffString(obs, obsName);
192
193 obs = obs.substr(obs.find('_') + 1, -1);
194 int diff2 = DiffString(obs, obsName);
195
196 diffs.push_back(min(diff1, diff2));
197 }
198
199 int matchedCount = 0;
200 int minPos = 0;
201 int min = 1e5;
202 for (unsigned int i = 0; i < diffs.size(); i++) {
203 if (min > diffs[i]) {
204 min = diffs[i];
205 minPos = i;
206 }
207 if (diffs[i] == 0) {
208 matchedCount++;
209 }
210 }
211
212 if (matchedCount == 1) {
213 cout << "TRestAnalysisTree::GetObservableID(): Find observable " << fObservableNames[minPos]
214 << " for obs name: " << obsName << endl;
215 fObservableIdSearchMap[obsName] = minPos;
216 return minPos;
217 } else if (matchedCount == 0) {
218 RESTError << "TRestAnalysisTree::GetObservableID(): No Matching observable found" << RESTendl;
219 if (min <= 2) {
220 RESTError << "did you mean \"" << fObservableNames[minPos] << "\" ?" << RESTendl;
221 fObservableIdSearchMap[obsName] = -1;
222 return -1;
223 }
224 } else {
225 RESTWarning << "TRestAnalysisTree::GetObservableID(): Multiple observables found" << RESTendl;
226 RESTWarning
227 << "Please specify the full observable name (e.g, sAna_ThresholdIntegral) in your code. "
228 << RESTendl;
229 RESTWarning << "Returning the first matched observable : " << fObservableNames[minPos]
230 << RESTendl;
231 fObservableIdSearchMap[obsName] = minPos;
232 return minPos;
233 }
234 }
235 fObservableIdSearchMap[obsName] = -1;
236 return -1;
237}
238
244Bool_t TRestAnalysisTree::ObservableExists(const string& obsName) {
246 return fObservableIdMap.count(obsName) > 0;
247}
248
253// Status | Nbranches | NObservables | Entries | Description
254// 1. Created | 0 | 0 | 0 | The AnalysisTree is just created in code
255// 2. Retrieved | >=6 | 0 | >0 | The AnalysisTree is just retrieved from file
256// 3. EmptyCloned | >=6 | 0 | 0 | The AnalysisTree is cloned from another
257// tree, it is empty
258// 4. Connected | >=6 | >=Nbranches-6 | 0 | Local observables are created and connected
259// to the branches. We can still modify observables in this case.
260// 5. Filled | >=6 | =NObs | >0 | Local observables are created and connected
261// to the branches, and entry > 0. We cannot modify observables in this case. if Nbranches == 6, We regard the
262// tree as Connected/Filled
263//
264// Status | AddObs Logic | Fill Logic | GetEntry Logic
265// 1. Created | Allowed | ->4, ->5 | ->4
266// 2. Retrieved | Denied | ->5 | ->5
267// 3. EmptyCloned | ->4 | ->4, ->5 | ->4
268// 4. Connected | Allowed | ->5 | Allowed
269// 5. Filled | Denied | Allowed | Allowed
270//
272 int NBranches = GetListOfBranches()->GetEntriesFast();
273 int NObsInList = fObservables.size();
274 int Entries = GetEntriesFast();
275
276 // if (fROOTTree != nullptr) {
277 // return TRestAnalysisTree_Status::ROOTTree;
278 //}
279
280 if (NBranches == 0) {
282 }
283
284 if (NBranches > 6) {
285 if (NObsInList == 0) {
286 if (Entries > 0) {
288 } else {
290 }
291 } else {
292 if (Entries > 0) {
293 return TRestAnalysisTree_Status::Filled;
294 } else {
296 }
297 }
298 } else if (NBranches == 6) {
299 auto br = (TBranch*)GetListOfBranches()->UncheckedAt(0);
300 if ((int*)br->GetAddress() != &fRunOrigin) {
301 if (Entries > 0) {
303 } else {
305 }
306 } else {
307 if (Entries > 0) {
308 return TRestAnalysisTree_Status::Filled;
309 } else {
311 }
312 }
313 } else {
315 }
316
318}
319
329 // connect basic event branches
330 TBranch* br1 = GetBranch("runOrigin");
331 TBranch* br2 = GetBranch("subRunOrigin");
332 TBranch* br3 = GetBranch("eventID");
333 TBranch* br4 = GetBranch("subEventID");
334 TBranch* br5 = GetBranch("timeStamp");
335 TBranch* br6 = GetBranch("subEventTag");
336
337 if (br1 && br2 && br3 && br4 && br5 && br6) {
338 br1->SetAddress(&fRunOrigin);
339 br2->SetAddress(&fSubRunOrigin);
340 br3->SetAddress(&fEventID);
341 br4->SetAddress(&fSubEventID);
342 br5->SetAddress(&fTimeStamp);
343 br6->SetAddress(&fSubEventTag);
344 } else {
345 cout << "REST Error: TRestAnalysisTree::ConnectBranches(): event branches does not exist!" << endl;
346 exit(1);
347 }
348
349 // create observables(no assembly) from stored observable info.
350 fObservables = std::vector<RESTValue>(GetNumberOfObservables());
351 for (int i = 0; i < GetNumberOfObservables(); i++) {
352 fObservables[i] = REST_Reflection::WrapType((string)fObservableTypes[i]);
353 fObservables[i].name = fObservableNames[i];
354 }
356
357 if (fChain) {
358 fChain->GetEntry(0);
359 } else {
360 TTree::GetEntry(0);
361 }
362
363 for (int i = 0; i < GetNumberOfObservables(); i++) {
364 TBranch* branch = GetBranch(fObservableNames[i]);
365 if (branch != nullptr) {
366 if (branch->GetAddress() != nullptr) {
367 if ((string)branch->ClassName() != "TBranch") {
368 // for TBranchElement the saved address is char**
369 fObservables[i].address = *(char**)branch->GetAddress();
370 } else {
371 // for TBranch the saved address is char*
372 fObservables[i].address = branch->GetAddress();
373 }
374 } else {
375 fObservables[i].Assembly();
376 branch->SetAddress(fObservables[i].address);
377 }
378 }
379 }
380
381 fStatus = EvaluateStatus();
382}
383
393 if (!GetBranch("runOrigin")) Branch("runOrigin", &fRunOrigin);
394 if (!GetBranch("subRunOrigin")) Branch("subRunOrigin", &fSubRunOrigin);
395 if (!GetBranch("eventID")) Branch("eventID", &fEventID);
396 if (!GetBranch("subEventID")) Branch("subEventID", &fSubEventID);
397 if (!GetBranch("timeStamp")) Branch("timeStamp", &fTimeStamp);
398 if (!GetBranch("subEventTag")) Branch("subEventTag", fSubEventTag);
399
400 for (int n = 0; n < GetNumberOfObservables(); n++) {
401 TString typeName = fObservableTypes[n];
402 TString brName = fObservableNames[n];
403 char* ref = fObservables[n].address;
404
405 TBranch* branch = GetBranch(brName);
406 if (branch == nullptr) {
407 if (typeName == "double") {
408 this->Branch(brName, (double*)ref);
409 } else if (typeName == "float") {
410 this->Branch(brName, (float*)ref);
411 } else if (typeName == "long double") {
412 this->Branch(brName, (long double*)ref);
413 } else if (typeName == "bool") {
414 this->Branch(brName, (bool*)ref);
415 } else if (typeName == "char") {
416 this->Branch(brName, (char*)ref);
417 } else if (typeName == "int") {
418 this->Branch(brName, (int*)ref);
419 } else if (typeName == "short") {
420 this->Branch(brName, (short*)ref);
421 } else if (typeName == "unsigned char") {
422 this->Branch(brName, (unsigned char*)ref);
423 } else if (typeName == "unsigned int") {
424 this->Branch(brName, (unsigned int*)ref);
425 } else if (typeName == "unsigned short") {
426 this->Branch(brName, (unsigned short*)ref);
427 } else if (typeName == "long") {
428 this->Branch(brName, (long*)ref);
429 } else if (typeName == "long long") {
430 this->Branch(brName, (long long*)ref);
431 } else if (typeName == "unsigned long") {
432 this->Branch(brName, (unsigned long*)ref);
433 } else if (typeName == "unsigned long long") {
434 this->Branch(brName, (unsigned long long*)ref);
435 } else {
436 this->Branch(brName, typeName, ref);
437 }
438
439 this->GetBranch(brName)->SetTitle("(" + typeName + ") " + fObservableDescriptions[n]);
440 }
441 }
442
443 fStatus = EvaluateStatus();
444}
445
446void TRestAnalysisTree::InitObservables() {
447 fObservables = std::vector<RESTValue>(GetNumberOfObservables());
448 for (int i = 0; i < GetNumberOfObservables(); i++) {
449 fObservables[i] = REST_Reflection::WrapType((string)fObservableTypes[i]);
450 fObservables[i].name = fObservableNames[i];
451 }
453}
454
461 if (fObservableIdMap.size() != fObservableNames.size()) {
462 fObservableIdMap.clear();
463 for (unsigned int i = 0; i < fObservableNames.size(); i++) {
464 fObservableIdMap[(string)fObservableNames[i]] = i;
465 }
466 if (fObservableIdMap.size() != fObservableNames.size()) {
467 cout << "REST ERROR! duplicated or blank observable name!" << endl;
468 }
469 }
470}
471
472void TRestAnalysisTree::ReadLeafValueToObservable(TLeaf* lf, RESTValue& obs) {
473 if (lf == nullptr || lf->GetLen() == 0) return;
474
475 if (obs.IsZombie()) {
476 // this means we need to determine the observable type first
477 string type;
478 string leafdef(lf->GetBranch()->GetTitle());
479 if (leafdef.find("[") == string::npos) {
480 // there is no [] mark in the leaf. The leaf is a single values
481 switch (leafdef[leafdef.size() - 1]) {
482 case 'C':
483 type = "string";
484 break;
485 case 'B':
486 type = "char";
487 break;
488 case 'S':
489 type = "stort";
490 break;
491 case 'I':
492 type = "int";
493 break;
494 case 'F':
495 type = "float";
496 break;
497 case 'D':
498 type = "double";
499 break;
500 case 'L':
501 type = "long long";
502 break;
503 case 'O':
504 type = "bool";
505 break;
506 default:
507 RESTError << "Unsupported leaf definition: " << leafdef << "! Assuming int" << RESTendl;
508 type = "int";
509 }
510 } else {
511 switch (leafdef[leafdef.size() - 1]) {
512 case 'I':
513 type = "vector<int>";
514 break;
515 case 'F':
516 type = "vector<float>";
517 break;
518 case 'D':
519 type = "vector<double>";
520 break;
521 default:
522 RESTError << "Unsupported leaf definition: " << leafdef << "! Assuming vector<int>"
523 << RESTendl;
524 type = "vector<int>";
525 }
526 }
527 obs = REST_Reflection::Assembly(type);
528 }
529
530 // start to fill value
531 if (obs.is_data_type) {
532 // the observable is basic type, we directly set it address from leaf
533 obs.address = (char*)lf->GetValuePointer();
534 } else if (obs.type == "vector<double>") {
535 auto ptr = (double*)lf->GetValuePointer();
536 vector<double> val(ptr, ptr + lf->GetLen());
537 obs.SetValue(val);
538 } else if (obs.type == "vector<int>") {
539 int* ptr = (int*)lf->GetValuePointer();
540 vector<int> val(ptr, ptr + lf->GetLen());
541 obs.SetValue(val);
542 } else if (obs.type == "vector<float>") {
543 auto ptr = (float*)lf->GetValuePointer();
544 vector<float> val(ptr, ptr + lf->GetLen());
545 obs.SetValue(val);
546 } else if (obs.type == "string") {
547 char* ptr = (char*)lf->GetValuePointer();
548 string val(ptr, lf->GetLen());
549 obs.SetValue(val);
550 } else {
551 RESTWarning << "Unsupported observable type to convert from TLeaf!" << RESTendl;
552 }
553}
554
555RESTValue TRestAnalysisTree::GetObservable(const string& obsName) {
556 Int_t id = GetObservableID(obsName);
557 if (id == -1) return {};
558 return GetObservable(id);
559}
560
563RESTValue TRestAnalysisTree::GetObservable(Int_t n) {
564 if (n >= fNObservables) {
565 cout << "Error! TRestAnalysisTree::GetObservable(): index outside limits!" << endl;
566 return {};
567 }
568
569 if (fChain != nullptr) {
570 return ((TRestAnalysisTree*)fChain->GetTree())->GetObservable(n);
571 }
572
573 return fObservables[n];
574}
575
578 if (n >= fNObservables) {
579 cout << "Error! TRestAnalysisTree::GetObservableName(): index outside limits!" << endl;
580 return "";
581 }
582 return fObservableNames[n];
583}
584
587 if (n >= fNObservables) {
588 cout << "Error! TRestAnalysisTree::GetObservableDescription(): index outside limits!" << endl;
589 return "";
590 }
591 return fObservableDescriptions[n];
592}
593
596 if (n >= fNObservables) {
597 cout << "Error! TRestAnalysisTree::GetObservableType(): index outside limits!" << endl;
598 return "double";
599 }
600 return fObservableTypes[n];
601}
602
604TString TRestAnalysisTree::GetObservableType(const string& obsName) {
605 Int_t id = GetObservableID(obsName);
606 if (id == -1) return "NotFound";
607 return GetObservableType(id);
608}
609
613Double_t TRestAnalysisTree::GetDblObservableValue(const string& obsName) {
614 return GetDblObservableValue(GetObservableID(obsName));
615}
616
621 if (n >= fNObservables) {
622 cout << "Error! TRestAnalysisTree::GetDblObservableValue(): index outside limits!" << endl;
623 return 0;
624 }
625
626 if (GetObservableType(n) == "int") return GetObservableValue<int>(n);
627 if (GetObservableType(n) == "float") return GetObservableValue<float>(n);
628 if (GetObservableType(n) == "double") return GetObservableValue<double>(n);
629
630 cout << "TRestAnalysisTree::GetDblObservableValue. Type " << GetObservableType(n)
631 << " not supported! Returning zero" << endl;
632 return 0.;
633}
634
635RESTValue TRestAnalysisTree::AddObservable(const TString& observableName, const TString& observableType,
636 const TString& description) {
637 if (fStatus == None) fStatus = EvaluateStatus();
638
639 if (fStatus == Created) {
640 } else if (fStatus == Retrieved) {
641 cout << "REST_Warning: cannot add observable for retrieved tree with data!" << endl;
642 return -1;
643 } else if (fStatus == EmptyCloned) {
645 } else if (fStatus == Connected) {
646 } else if (fStatus == Filled) {
647 cout << "REST_Warning: cannot add observable! AnalysisTree is already filled" << endl;
648 return -1;
649 } else if (fChain != nullptr) {
650 cout << "Error! cannot add observable! AnalysisTree is in chain state" << endl;
651 return -1;
652 }
653
654 if (GetObservableID((string)observableName) == -1) {
655 RESTValue ptr = REST_Reflection::Assembly((string)observableType);
656 ptr.name = observableName;
657 if (!ptr.IsZombie()) {
658 fObservableNames.push_back(observableName);
659 fObservableIdMap[(string)observableName] = fObservableNames.size() - 1;
660 fObservableDescriptions.push_back(description);
661 fObservableTypes.push_back(observableType);
662 fObservables.push_back(ptr);
663
665 } else {
666 cout << "Error adding observable \"" << observableName << "\" with type \"" << observableType
667 << "\", type not found!" << endl;
668 return -1;
669 }
670 } else {
671 return GetObservableID((string)observableName);
672 }
673
674 return fObservables[fNObservables - 1];
675}
676
677void TRestAnalysisTree::PrintObservables() {
678 if (fStatus == None) fStatus = EvaluateStatus();
679
680 if (fStatus == Created) {
681 } else if (fStatus == Retrieved) {
682 cout << "TRestAnalysisTree::PrintObservables(): Reading entry 0" << endl;
683 GetEntry(0);
684 } else if (fStatus == EmptyCloned) {
685 cout << "REST_Warning: AnalysisTree is empty" << endl;
687 } else if (fStatus == Connected) {
688 cout << "REST_Warning: AnalysisTree is empty" << endl;
689 } else if (fStatus == Filled) {
690 }
691
692 cout.precision(15);
693 std::cout << "Entry : " << GetReadEntry() << std::endl;
694 std::cout << "> Event ID : " << GetEventID() << std::endl;
695 std::cout << "> Event Time : " << GetTimeStamp() << std::endl;
696 std::cout << "> Event Tag : " << GetSubEventTag() << std::endl;
697 std::cout << "-----------------------------------------" << std::endl;
698 cout.precision(6);
699
700 for (int n = 0; n < GetNumberOfObservables(); n++) {
701 PrintObservable(n);
702 }
703}
704
705// print the Nth observable in the observal list
706void TRestAnalysisTree::PrintObservable(int n) {
707 if (n < 0 || n >= fNObservables) {
708 return;
709 }
710 string obsVal = GetObservable(n).ToString();
711 int lengthRemaining = Console::GetWidth() - 14 - 45 - 13;
712
713 std::cout << "Observable : " << ToString(fObservableNames[n], 45)
714 << " Value : " << ToString(obsVal, lengthRemaining) << std::endl;
715}
716
717Int_t TRestAnalysisTree::GetEntry(Long64_t entry, Int_t getall) {
718 if (fStatus == None) fStatus = EvaluateStatus();
719
720 if (fStatus == Created) {
722 } else if (fStatus == Retrieved) {
724 } else if (fStatus == EmptyCloned) {
726 } else if (fStatus == Connected) {
727 } else if (fStatus == Filled) {
728 }
729
730 if (fChain != nullptr) {
731 return fChain->GetEntry(entry, getall);
732 } else {
733 return TTree::GetEntry(entry, getall);
734 }
735}
736
737void TRestAnalysisTree::SetEventInfo(TRestAnalysisTree* tree) {
738 if (fChain != nullptr) {
739 cout << "Error! cannot fill tree. AnalysisTree is in chain state" << endl;
740 return;
741 }
742
743 if (tree != nullptr) {
744 fEventID = tree->GetEventID();
745 fSubEventID = tree->GetSubEventID();
746 fTimeStamp = tree->GetTimeStamp();
747 *fSubEventTag = tree->GetSubEventTag();
748 fRunOrigin = tree->GetRunOrigin();
749 fSubRunOrigin = tree->GetSubRunOrigin();
750 }
751}
752
753void TRestAnalysisTree::SetEventInfo(TRestEvent* evt) {
754 if (fChain != nullptr) {
755 cout << "Error! cannot fill tree. AnalysisTree is in chain state" << endl;
756 return;
757 }
758
759 if (evt != nullptr) {
760 fEventID = evt->GetID();
761 fSubEventID = evt->GetSubID();
762 fTimeStamp = evt->GetTimeStamp().AsDouble();
763 *fSubEventTag = evt->GetSubEventTag();
764 fRunOrigin = evt->GetRunOrigin();
765 fSubRunOrigin = evt->GetSubRunOrigin();
766 }
767}
768
769Int_t TRestAnalysisTree::Fill() {
770 if (fStatus == None) fStatus = EvaluateStatus();
771
772 if (fChain != nullptr) {
773 cout << "Error! cannot fill tree. AnalysisTree is in chain state" << endl;
774 return -1;
775 }
776
777 fSetObservableIndex = 0;
778
779 if (fStatus == Filled) {
780 return TTree::Fill();
781 } else if (fStatus == Created) {
783 int a = TTree::Fill();
784 fStatus = EvaluateStatus();
785 return a;
786 } else if (fStatus == Retrieved) {
788 int a = TTree::Fill();
789 fStatus = EvaluateStatus();
790 return a;
791 } else if (fStatus == EmptyCloned) {
793 int a = TTree::Fill();
794 fStatus = EvaluateStatus();
795 return a;
796 } else if (fStatus == Connected) {
798 int a = TTree::Fill();
799 fStatus = EvaluateStatus();
800 return a;
801 }
802 return -1;
803}
804
808void TRestAnalysisTree::SetObservable(Int_t id, RESTValue obs) {
809 if (fChain != nullptr) {
810 cout << "Error! cannot set observable! AnalysisTree is in chain state" << endl;
811 return;
812 }
813 if (id == -1) {
814 // this means we want to find observable id by its name
815 id = GetObservableID(obs.name);
816 // if not found, we have a chance to create observable
817 if (id == -1) {
818 AddObservable(obs.name, obs.type);
819 id = GetObservableID(obs.name);
820 }
821 } else if (id == (int)fObservables.size()) {
822 // this means we want to add observable directly
823 AddObservable(obs.name, obs.type);
824 id = GetObservableID(obs.name);
825 }
826 if (id != -1) {
827 if (obs.type != fObservables[id].type) {
828 // if the observable branches are not created, and the type doesn't match,
829 // we still have the chance to fix. We reset fObservableTypes and fObservableMemory
830 // according to the input type value.
831 cout << "Warning: SetObservableValue(): setting value with different type. Observable : "
832 << obs.name << ", existing type: " << fObservables[id].type
833 << ", value to add is in type: " << obs.type << ", trying to update to the new type."
834 << endl;
835 fObservableTypes[id] = obs.type;
836 string name = fObservables[id].name;
837 fObservables[id].Destroy();
838 fObservables[id] = REST_Reflection::Assembly(obs.type);
839 fObservables[id].name = name;
840 }
841 obs >> fObservables[id];
842 }
843}
844
871void TRestAnalysisTree::SetObservable(string name, RESTValue value) {
872 value.name = name;
873 SetObservable(-1, value);
874}
875
883Bool_t TRestAnalysisTree::EvaluateCuts(const string& cut) {
884 std::vector<string> cuts = Split(cut, "&&", false, true);
885
886 for (auto& cut : cuts) {
887 if (!EvaluateCut(cut)) {
888 return false;
889 }
890 }
891
892 return true;
893}
894
901Bool_t TRestAnalysisTree::EvaluateCut(const string& cut) {
902 const std::vector<string> validOperators = {"==", "<=", ">=", "!=", "=", ">", "<"};
903
904 if (cut.find("&&") != string::npos) return EvaluateCuts(cut);
905
906 string operation, observable;
907 Double_t value = -1;
908 for (const auto& validOperator : validOperators) {
909 if (cut.find(validOperator) != string::npos) {
910 operation = validOperator;
911 observable = (string)cut.substr(0, cut.find(operation));
912 value = std::stod((string)cut.substr(cut.find(operation) + operation.length(), string::npos));
913 break;
914 }
915 }
916
917 if (operation.empty())
918 cout << "TRestAnalysisTree::EvaluateCut. Invalid operator in cut definition! " << cut << endl;
919
920 Double_t val = GetDblObservableValue(observable);
921 if (operation == "==" && value == val) return true;
922 if (operation == "!=" && value != val) return true;
923 if (operation == "<=" && val <= value) return true;
924 if (operation == ">=" && val >= value) return true;
925 if (operation == "=" && val == value) return true;
926 if (operation == ">" && val > value) return true;
927 if (operation == "<" && val < value) return true;
928
929 return false;
930}
931
936vector<string> TRestAnalysisTree::GetCutObservables(const string& cut_str) {
937 const std::vector<string> validOperators = {"==", "<=", ">=", "!=", "=", ">", "<"};
938
939 std::vector<string> cuts = Split(cut_str, "&&", false, true);
940
941 vector<string> obsNames;
942 for (auto& cut : cuts) {
943 string operation, observable;
944 for (const auto& validOperator : validOperators) {
945 if (cut.find(validOperator) != string::npos) {
946 obsNames.push_back((string)cut.substr(0, cut.find(validOperator)));
947 break;
948 }
949 }
950 }
951 return obsNames;
952}
953
957void TRestAnalysisTree::EnableBranches(vector<string> obsNames) {
958 for (auto& obsName : obsNames) this->SetBranchStatus(obsName.c_str(), true);
959}
960
964void TRestAnalysisTree::DisableBranches(vector<string> obsNames) {
965 for (auto& obsName : obsNames) this->SetBranchStatus(obsName.c_str(), false);
966}
967
971void TRestAnalysisTree::EnableAllBranches() { this->SetBranchStatus("*", true); }
972
976void TRestAnalysisTree::DisableAllBranches() { this->SetBranchStatus("*", false); }
977
985void TRestAnalysisTree::EnableQuickObservableValueSetting() { this->fQuickSetObservableValue = true; }
986
989void TRestAnalysisTree::DisableQuickObservableValueSetting() { this->fQuickSetObservableValue = false; }
990
995Double_t TRestAnalysisTree::GetObservableIntegral(const TString& obsName, Double_t xLow, Double_t xHigh) {
996 Int_t id = GetObservableID((std::string)obsName);
997
998 if (id < 0) {
999 RESTError << "TRestAnalysisTree::GetObservableIntegral. Observable not found! : " << obsName
1000 << RESTendl;
1001 return 0;
1002 }
1003
1004 Double_t sum = 0;
1005 for (Int_t n = 0; n < TTree::GetEntries(); n++) {
1006 TTree::GetEntry(n);
1007 Double_t value = GetDblObservableValue(id);
1008
1009 if (xLow != -1 && xHigh != -1 && (value < xLow || value > xHigh)) continue;
1010 sum += value;
1011 }
1012
1013 return sum;
1014}
1015
1020Double_t TRestAnalysisTree::GetObservableAverage(const TString& obsName, Double_t xLow, Double_t xHigh) {
1021 Int_t id = GetObservableID((std::string)obsName);
1022
1023 if (id < 0) {
1024 RESTError << "TRestAnalysisTree::GetObservableAverage. Observable not found! : " << obsName
1025 << RESTendl;
1026 return 0;
1027 }
1028
1029 Double_t sum = 0;
1030 Int_t N = 0;
1031 for (Int_t n = 0; n < TTree::GetEntries(); n++) {
1032 TTree::GetEntry(n);
1033 Double_t value = GetDblObservableValue(id);
1034
1035 if (xLow != -1 && xHigh != -1 && (value < xLow || value > xHigh)) continue;
1036 N++;
1037 sum += value;
1038 }
1039
1040 if (N <= 0) return 0;
1041
1042 return sum / N;
1043}
1044
1049Double_t TRestAnalysisTree::GetObservableRMS(const TString& obsName, Double_t xLow, Double_t xHigh) {
1050 Double_t mean = GetObservableAverage(obsName, xLow, xHigh);
1051
1052 Int_t id = GetObservableID((std::string)obsName);
1053
1054 Double_t sum = 0;
1055 Int_t N = 0;
1056 for (Int_t n = 0; n < TTree::GetEntries(); n++) {
1057 TTree::GetEntry(n);
1058 Double_t value = GetDblObservableValue(id);
1059
1060 if (xLow != -1 && xHigh != -1 && (value < xLow || value > xHigh)) continue;
1061 N++;
1062
1063 sum += (value - mean) * (value - mean);
1064 }
1065
1066 if (N <= 0) return 0;
1067
1068 return TMath::Sqrt(sum / N);
1069}
1070
1075Double_t TRestAnalysisTree::GetObservableMaximum(const TString& obsName, Double_t xLow, Double_t xHigh) {
1076 Int_t id = GetObservableID((std::string)obsName);
1077
1078 if (id < 0) {
1079 RESTError << "TRestAnalysisTree::GetObservableMaximum. Observable not found! : " << obsName
1080 << RESTendl;
1081 return 0;
1082 }
1083
1084 Double_t max = -DBL_MAX;
1085 for (Int_t n = 0; n < TTree::GetEntries(); n++) {
1086 TTree::GetEntry(n);
1087 Double_t value = GetDblObservableValue(id);
1088
1089 if (xLow != -1 && xHigh != -1 && (value < xLow || value > xHigh)) continue;
1090 if (value > max) max = value;
1091 }
1092
1093 return max;
1094}
1095
1100Double_t TRestAnalysisTree::GetObservableMinimum(const TString& obsName, Double_t xLow, Double_t xHigh) {
1101 Int_t id = GetObservableID((std::string)obsName);
1102
1103 if (id < 0) {
1104 RESTError << "TRestAnalysisTree::GetObservableMinimum. Observable not found! : " << obsName
1105 << RESTendl;
1106 return 0;
1107 }
1108
1109 Double_t min = DBL_MAX;
1110 for (Int_t n = 0; n < TTree::GetEntries(); n++) {
1111 TTree::GetEntry(n);
1112 Double_t value = GetDblObservableValue(id);
1113
1114 if (xLow != -1 && xHigh != -1 && (value < xLow || value > xHigh)) continue;
1115 if (value < min) min = value;
1116 }
1117
1118 return min;
1119}
1120
1145Double_t TRestAnalysisTree::GetObservableContour(const TString& obsName, const TString& obsWeight,
1146 Double_t level, Int_t nBins, Double_t xLow, Double_t xHigh) {
1147 if (level > 1 || level < 0) {
1148 RESTWarning << "Level is : " << level << RESTendl;
1149 RESTWarning << "Level must be between 0 and 1" << RESTendl;
1150 return 0;
1151 }
1152
1153 Double_t integral = this->GetIntegral(obsWeight, xLow, xHigh);
1154
1155 TString histDefinition = Form("hc(%5d,%lf,%lf)", nBins, xLow, xHigh);
1156 if (xHigh == -1)
1157 this->Draw(obsName + ">>hc", obsWeight);
1158 else
1159 this->Draw(obsName + ">>" + histDefinition, obsWeight);
1160
1161 TH1F* htemp = (TH1F*)gPad->GetPrimitive("hc");
1162
1163 Double_t sum = 0;
1164 for (int i = 0; i < htemp->GetNbinsX(); i++) {
1165 sum += htemp->GetBinContent(i + 1);
1166
1167 if (sum > level * integral) return htemp->GetBinCenter(i + 1);
1168 }
1169 return 0;
1170}
1171
1176
1177std::vector<std::string> TRestAnalysisTree::GetObservableNames() {
1178 std::vector<std::string> names;
1179
1180 auto branches = GetListOfBranches();
1181 for (int i = 0; i < branches->GetEntries(); i++) {
1182 names.push_back((string)branches->At(i)->GetName());
1183 }
1184
1185 return names;
1186}
1187
1191Int_t TRestAnalysisTree::WriteAsTTree(const char* name, Int_t option, Int_t bufsize) {
1192 TTree* tree = new TTree();
1193
1194 char* dest = (char*)tree + sizeof(TObject);
1195 char* from = (char*)this + sizeof(TObject);
1196
1197 constexpr size_t n = sizeof(TTree) - sizeof(TObject);
1198
1199 // copy the data of the created TTree to a temporary location
1200 char* temp = (char*)malloc(n);
1201 memcpy(temp, dest, n);
1202
1203 // copy the data of this TRestAnalysisTree to TTree, and call the new TTree to write
1204 memcpy(dest, from, n);
1205 int result = tree->Write(name, option, bufsize);
1206
1207 // restore the data of the created TTree, then we can free it!
1208 memcpy(dest, temp, n);
1209 free(temp);
1210 delete tree;
1211
1212 return result;
1213}
1214
1220Bool_t TRestAnalysisTree::AddChainFile(const string& _file) {
1221 auto file = TRestRootFileHandle::Open(_file, TRestRootFileMode::Read);
1222 if (!file) {
1223 RESTWarning << "TRestAnalysisTree::AddChainFile(): failed to open file " << _file << RESTendl;
1224 return false;
1225 }
1226
1227 if (this->GetRunOrigin() == 0) {
1228 this->GetEntry(0);
1229 }
1230
1231 auto tree = (TRestAnalysisTree*)file->Get("AnalysisTree");
1232 if (tree != nullptr && tree->GetEntry(0)) {
1233 if (tree->GetEntry(0) > 0) {
1234 if (tree->GetRunOrigin() == this->GetRunOrigin()) {
1235 // this is a valid tree
1236 delete tree;
1237
1238 if (fChain == nullptr) {
1239 fChain = new TChain("AnalysisTree", "Chained AnalysisTree");
1240 fChain->Add(this->GetCurrentFile()->GetName());
1241 }
1242 return fChain->Add(_file.c_str()) == 1;
1243 }
1244 RESTWarning
1245 << "TRestAnalysisTree::AddChainFile(): invalid file, AnalysisTree in file has different "
1246 "run id!"
1247 << RESTendl;
1248 }
1249 RESTWarning << "TRestAnalysisTree::AddChainFile(): invalid file, AnalysisTree in file is empty!"
1250 << RESTendl;
1251 delete tree;
1252 }
1253 RESTWarning << "TRestAnalysisTree::AddChainFile(): invalid file, file does not contain an AnalysisTree!"
1254 << RESTendl;
1255
1256 return false;
1257}
1258
1265 if (fChain == nullptr) {
1266 return TTree::GetTree();
1267 }
1268 return (TTree*)fChain;
1269}
1270
1277Long64_t TRestAnalysisTree::LoadTree(Long64_t entry) {
1278 if (fChain == nullptr) {
1279 return TTree::LoadTree(entry);
1280 } else {
1281 return fChain->LoadTree(entry);
1282 }
1283
1284 return -2;
1285}
1286
1287Long64_t TRestAnalysisTree::GetEntries() const {
1288 if (fChain == nullptr) {
1289 return TTree::GetEntries();
1290 }
1291 return fChain->GetEntries();
1292}
1293
1294Long64_t TRestAnalysisTree::GetEntries(const char* sel) {
1295 if (fChain == nullptr) {
1296 return TTree::GetEntries(sel);
1297 }
1298 return fChain->GetEntries(sel);
1299}
1300
1301TRestAnalysisTree::~TRestAnalysisTree() { delete fSubEventTag; }
void SetValue(const T &val)
Set the value of the wrapped type.
std::string type
Type of the wrapped object.
char * address
Address of the wrapped object.
bool is_data_type
Pointer to the corresponding TDataType helper, if the wrapped object is in data type.
bool IsZombie() const
If this object type wrapper is invalid.
std::string name
Name field.
REST core data-saving helper based on TTree.
TString GetObservableDescription(Int_t n)
Get the observable description according to id.
T GetObservableValue(Int_t n)
Get observable in a given type, according to its id.
void DisableQuickObservableValueSetting()
It will disable quick observable value setting.
std::vector< std::string > GetCutObservables(const std::string &cut_str)
It will return a list with the names found in a string with conditions, as given in methods as Evalua...
void UpdateObservables()
Update observables stored in the tree.
Double_t GetObservableContour(const TString &obsName, const TString &obsIndexer, Double_t level=0.5, Int_t nBins=-1, Double_t xLow=-1, Double_t xHigh=-1)
This method generates a histogram of the the observable obsName given in the argument weighting it wi...
void EnableAllBranches()
It will enable all branches in the tree.
void EnableQuickObservableValueSetting()
It will enable quick observable value setting.
Long64_t LoadTree(Long64_t entry)
Overrides TTree::LoadTree(), to set current tree according to the given entry number,...
Bool_t AddChainFile(const std::string &file)
Add a series output file like TChain.
TString GetObservableName(Int_t n)
Get the observable name according to id.
void UpdateBranches()
Update branches in the tree.
Double_t GetObservableIntegral(const TString &obsName, Double_t xLow=-1, Double_t xHigh=-1)
It returns the integral of the observable considering the given range. If no range is given the full ...
TChain * fChain
used for quick search of certain observables
Bool_t EvaluateCuts(const std::string &expression)
This method will receive a string with several analysis observables/cuts in the same fashion as used ...
TTree * GetTree() const
Overrides TTree::GetTree(), to get the actual tree used in case of chain operation(fCurrentTree !...
Double_t GetObservableMaximum(const TString &obsName, Double_t xLow=-1, Double_t xHigh=-1)
It returns the maximum value of obsName considering the given range. If no range is given the full hi...
Int_t GetObservableID(const std::string &obsName)
Get the index of the specified observable.
void MakeObservableIdMap()
Update the map of observable name to observable id.
Int_t GetMatchedObservableID(const std::string &obsName)
Get the index of the observable, erasing the prefix if exists.
Double_t GetObservableAverage(const TString &obsName, Double_t xLow=-1, Double_t xHigh=-1)
It returns the average of the observable considering the given range. If no range is given the full h...
void DisableBranches(std::vector< std::string > obsNames)
It will disable the branches given by argument.
Double_t GetObservableRMS(const TString &obsName, Double_t xLow=-1, Double_t xHigh=-1)
It returns the RMS of the observable considering the given range. If no range is given the full histo...
Double_t GetDblObservableValue(const std::string &obsName)
Get double value of the observable, according to the name.
TString GetObservableType(Int_t n)
Get the observable type according to id.
std::vector< std::string > GetObservableNames()
It returns a vector with strings containing all the observables that exist in the analysis tree.
void DisableAllBranches()
It will disable all branches in the tree.
Double_t GetObservableMinimum(const TString &obsName, Double_t xLow=-1, Double_t xHigh=-1)
It returns the minimum value of obsName considering the given range. If no range is given the full hi...
int EvaluateStatus()
Evaluate the Status of this tree.
Bool_t ObservableExists(const std::string &obsName)
Get if the specified observable exists.
Int_t fNObservables
in case multiple files for reading
void EnableBranches(std::vector< std::string > obsNames)
It will enable the branches given by argument.
Bool_t EvaluateCut(const std::string &expression)
This method will evaluate a condition on one analysis observable constructed as "observable>value"....
void SetObservable(Int_t id, RESTValue obs)
Set the value of observable whose id is as specified.
Int_t WriteAsTTree(const char *name=0, Int_t option=0, Int_t bufsize=0)
It writes TRestAnalysisTree as TTree, in order to migrate files to pure ROOT users.
A base class for any REST event.
Definition TRestEvent.h:38
static TRestRootFileHandle Open(const std::string &filename, TRestRootFileMode mode)
TRestReflector WrapType(const std::string &typeName)
Wrap information an object of type: typeName, memory is not allocated.
TRestReflector Assembly(const std::string &typeName)
Assembly an object of type: typeName, returning the allocated memory address and size.
std::vector< std::string > Split(std::string in, std::string separator, bool allowBlankString=false, bool removeWhiteSpaces=false, int startPos=-1)
Split the input string according to the given separator. Returning a vector of fragments.
Int_t DiffString(const std::string &source, const std::string &target)
Returns the number of different characters between two strings.