source: trunk/MagicSoft/Mars/mfileio/MReadTree.cc@ 1521

Last change on this file since 1521 was 1483, checked in by tbretz, 22 years ago
*** empty log message ***
File size: 24.4 KB
Line 
1/* ======================================================================== *\
2!
3! *
4! * This file is part of MARS, the MAGIC Analysis and Reconstruction
5! * Software. It is distributed to you in the hope that it can be a useful
6! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
7! * It is distributed WITHOUT ANY WARRANTY.
8! *
9! * Permission to use, copy, modify and distribute this software and its
10! * documentation for any purpose is hereby granted without fee,
11! * provided that the above copyright notice appear in all copies and
12! * that both that copyright notice and this permission notice appear
13! * in supporting documentation. It is provided "as is" without express
14! * or implied warranty.
15! *
16!
17!
18! Author(s): Thomas Bretz 12/2000 <mailto:tbretz@uni-sw.gwdg.de>
19!
20! Copyright: MAGIC Software Development, 2000-2002
21!
22!
23\* ======================================================================== */
24
25/////////////////////////////////////////////////////////////////////////////
26// //
27// MReadTree //
28// //
29// This tasks opens all branches in a specified tree and creates the //
30// corresponding parameter containers if not already existing in the //
31// parameter list. //
32// //
33// The Process function reads one events from the tree. To go through the //
34// events of one tree make sure that the event number is increased from //
35// outside. It makes also possible to go back by decreasing the number. //
36// //
37// If you don't want to start reading the first event you have to call //
38// MReadTree::SetEventNum after instantiating your MReadTree-object. //
39// //
40// To make reading much faster (up to a factor of 10 to 20) you can //
41// ensure that only the data you are really processing is enabled by //
42// calling MReadTree::UseLeaf. //
43// //
44// If the chain switches from one file to another file all //
45// TObject::Notify() functions are called of TObject objects which were //
46// added to the Notifier list view MReadTree::AddNotify. If MReadTree //
47// is the owner (viw MReadTree::SetOwner) all this objects are deleted //
48// by the destructor of MReadTree //
49// //
50/////////////////////////////////////////////////////////////////////////////
51#include "MReadTree.h"
52
53#include <fstream.h>
54
55#include <TFile.h> // TFile::GetName
56#include <TSystem.h> // gSystem->ExpandPath
57#include <TGProgressBar.h>
58#include <TChainElement.h>
59#include <TOrdCollection.h>
60
61#include "MLog.h"
62#include "MLogManip.h"
63
64#include "MChain.h"
65#include "MFilter.h"
66#include "MParList.h"
67#include "MTaskList.h"
68
69ClassImp(MReadTree);
70
71// --------------------------------------------------------------------------
72//
73// Default constructor. Don't use it.
74//
75MReadTree::MReadTree()
76 : fNumEntry(0), fBranchChoosing(kFALSE), fAutoEnable(kTRUE), fProgress(NULL)
77{
78 fName = "MReadTree";
79 fTitle = "Task to loop over all events in one single tree";
80
81 fVetoList = NULL;
82 fNotify = NULL;
83
84 fChain = NULL;
85}
86
87// --------------------------------------------------------------------------
88//
89// Constructor. It creates an TChain instance which represents the
90// the Tree you want to read and adds the given file (if you gave one).
91// More files can be added using MReadTree::AddFile.
92// Also an empty veto list is created. This list is used if you want to
93// veto (disable or "don't enable") a branch in the tree, it vetos also
94// the creation of the corresponding object.
95// An empty list of TObjects are also created. This objects are called
96// at any time the TChain starts to read from another file.
97//
98MReadTree::MReadTree(const char *tname, const char *fname,
99 const char *name, const char *title)
100 : fNumEntry(0), fBranchChoosing(kFALSE), fAutoEnable(kTRUE), fProgress(NULL)
101{
102 fName = name ? name : "MReadTree";
103 fTitle = title ? title : "Task to loop over all events in one single tree";
104
105 fVetoList = new TList;
106 fVetoList->SetOwner();
107
108 fNotify = new TList;
109
110 //
111 // open the input stream
112 //
113 fChain = new MChain(tname);
114
115 // root 3.02:
116 // In TChain::Addfile remove the limitation that the file name must contain
117 // the string ".root". ".root" is necessary only in case one wants to specify
118 // a Tree in a subdirectory of a Root file with eg, the format:
119
120 if (fname)
121 fChain->Add(fname);
122}
123
124// --------------------------------------------------------------------------
125//
126// Destructor. It deletes the TChain and veto list object
127//
128MReadTree::~MReadTree()
129{
130 //
131 // Delete all the pointers to pointers to the objects where the
132 // branche data gets stored.
133 //
134 TIter Next(fChain->GetStatus());
135
136 TChainElement *element = NULL;
137 while ((element=(TChainElement*)Next()))
138 delete (MParContainer**)element->GetBaddress();
139
140 //
141 // Delete the chain and the veto list
142 //
143#if ROOT_VERSION_CODE < ROOT_VERSION(3,03,00)
144 if (fChain->GetFile())
145 delete fChain->GetFile();
146#endif
147 delete fChain;
148
149 delete fNotify;
150 delete fVetoList;
151}
152
153// --------------------------------------------------------------------------
154//
155// If the owner flag is set all TObjects which are scheduled via
156// AddNotify are deleted by the destructor of MReadTree
157//
158void MReadTree::SetOwner(Bool_t flag)
159{
160 flag ? fNotify->SetBit(kIsOwner) : fNotify->ResetBit(kIsOwner);
161}
162
163// --------------------------------------------------------------------------
164//
165// This function is called each time MReadTree changes the file to read
166// from. It calls all TObject::Notify() functions which are scheduled
167// via AddNotify.
168//
169Bool_t MReadTree::Notify()
170{
171 *fLog << inf << GetDescriptor() << ": Notify '" << fChain->GetName();
172 *fLog << "' (before processing event #" << GetEventNum()-1 << ")" << endl;
173
174 //fNotify->Notify();
175
176 return kTRUE;
177}
178
179// --------------------------------------------------------------------------
180//
181// If you want to read the given tree over several files you must add
182// the files here before PreProcess is called. Be careful: If the tree
183// doesn't have the same contents (branches) it may confuse your
184// program (trees which are are not existing in later files are not read
185// anymore, tree wich are not existing in the first file are never read)
186//
187// Name may use the wildcarding notation, eg "xxx*.root" means all files
188// starting with xxx in the current file system directory.
189//
190// AddFile returns the number of files added to the chain.
191//
192Int_t MReadTree::AddFile(const char *fname)
193{
194 //
195 // FIXME! A check is missing whether the file already exists or not.
196 //
197 //
198 // returns the number of file which were added
199 //
200 return fChain->Add(fname);
201}
202
203// --------------------------------------------------------------------------
204//
205// This function is called if Branch choosing method should get enabled.
206// Branch choosing means, that only the enabled branches are read into
207// memory. To use an enableing scheme we have to disable all branches first.
208// This is done, if this function is called the first time.
209//
210void MReadTree::EnableBranchChoosing()
211{
212 if (fBranchChoosing)
213 return;
214
215 *fLog << inf << GetDescriptor() << ": Branch choosing method enabled (only enabled branches are read)." << endl;
216 fChain->SetBranchStatus("*", kFALSE);
217 fBranchChoosing = kTRUE;
218}
219
220// --------------------------------------------------------------------------
221//
222// The first time this function is called all branches are disabled.
223// The given branch is enabled. By enabling only the branches you
224// are processing you can speed up your calculation many times (up to
225// a factor of 10 or 20)
226//
227void MReadTree::EnableBranch(const char *name)
228{
229 EnableBranchChoosing();
230
231 TNamed branch(name, "");
232 SetBranchStatus(&branch, kTRUE);
233}
234
235// --------------------------------------------------------------------------
236//
237// Set branch status of branch name
238//
239void MReadTree::SetBranchStatus(const char *name, Bool_t status)
240{
241 fChain->SetBranchStatus(name, status);
242
243 *fLog << inf << (status ? "Enabled" : "Disabled");
244 *fLog << " subbranch '" << name << "'." << endl;
245}
246
247// --------------------------------------------------------------------------
248//
249// Checks whether a branch with the given name exists in the chain
250// and sets the branch status of this branch corresponding to status.
251//
252void MReadTree::SetBranchStatus(TObject *branch, Bool_t status)
253{
254 //
255 // Get branch name
256 //
257 const char *name = branch->GetName();
258
259 //
260 // Check whether this branch really exists
261 //
262 if (fChain->GetBranch(name))
263 SetBranchStatus(name, status);
264
265 //
266 // Remove trailing '.' if one and try to enable the subbranch without
267 // the master branch name. This is to be compatible with older mars
268 // and camera files.
269 //
270 const char *dot = strrchr(name, '.');
271 if (!dot)
272 return;
273
274 if (fChain->GetBranch(dot+1))
275 SetBranchStatus(dot+1, status);
276}
277
278// --------------------------------------------------------------------------
279//
280// Set the status of all branches in the list to status.
281//
282void MReadTree::SetBranchStatus(const TList *list, Bool_t status)
283{
284 //
285 // Loop over all subbranches in this master branch
286 //
287 TIter Next(list);
288
289 TObject *obj;
290 while ((obj=Next()))
291 SetBranchStatus(obj, status);
292}
293
294// --------------------------------------------------------------------------
295//
296// This is the implementation of the Auto Enabling Scheme.
297// For more information see MTask::AddBranchToList.
298// This function loops over all tasks and its filters in the tasklist
299// and enables all branches which are requested by the tasks and its
300// filters.
301//
302// To enable 'unknown' branches which are not in the branchlist of
303// the tasks you can call EnableBranch
304//
305void MReadTree::EnableBranches(MParList *plist)
306{
307 //
308 // check whether branch choosing must be switched on
309 //
310 EnableBranchChoosing();
311
312 //
313 // request the tasklist from the parameter list.
314 // FIXME: Tasklist can have a different name
315 //
316 const MTaskList *tlist = (MTaskList*)plist->FindObject("MTaskList");
317 if (!tlist)
318 {
319 *fLog << warn << GetDescriptor() << "Cannot use auto enabeling scheme for branches. 'MTaskList' not found." << endl;
320 return;
321 }
322
323 //
324 // This loop is not necessary. We could do it like in the commented
325 // loop below. But this loop makes sure, that we don't try to enable
326 // one branch several times. This would not harm, but we would get
327 // an output for each attempt. To have several outputs for one subbranch
328 // may confuse the user, this we don't want.
329 // This loop creates a new list of subbranches and for each branch
330 // which is added we check before whether it already exists or not.
331 //
332 TList list;
333
334 MTask *task;
335 TIter NextTask(tlist->GetList());
336 while ((task=(MTask*)NextTask()))
337 {
338 TObject *obj;
339
340 TIter NextTBranch(task->GetListOfBranches());
341 while ((obj=NextTBranch()))
342 if (!list.FindObject(obj->GetName()))
343 list.Add(obj);
344
345 const MFilter *filter = task->GetFilter();
346
347 if (!filter)
348 continue;
349
350 TIter NextFBranch(filter->GetListOfBranches());
351 while ((obj=NextFBranch()))
352 if (!list.FindObject(obj->GetName()))
353 list.Add(obj);
354 }
355
356 SetBranchStatus(&list, kTRUE);
357/*
358 //
359 // Loop over all tasks iand its filters n the task list.
360 //
361 MTask *task;
362 TIter NextTask(tlist->GetList());
363 while ((task=(MTask*)NextTask()))
364 {
365 SetBranchStatus(task->GetListOfBranches(), kTRUE);
366
367 const MFilter *filter = task->GetFilter();
368 if (!filter)
369 continue;
370
371 SetBranchStatus(filter->GetListOfBranches(), kTRUE);
372
373 }
374*/
375}
376
377// --------------------------------------------------------------------------
378//
379// The disables all subbranches of the given master branch.
380//
381void MReadTree::DisableSubBranches(TBranch *branch)
382{
383 //
384 // This is not necessary, it would work without. But the output
385 // may confuse the user...
386 //
387 if (fAutoEnable || fBranchChoosing)
388 return;
389
390 SetBranchStatus(branch->GetListOfBranches(), kFALSE);
391}
392
393// --------------------------------------------------------------------------
394//
395// The PreProcess loops (till now) over the branches in the given tree.
396// It checks if the corresponding containers (containers with the same
397// name than the branch name) are existing in the Parameter Container List.
398// If not, a container of objec type 'branch-name' is created (everything
399// after the last semicolon in the branch name is stripped). Only
400// branches which don't have a veto (see VetoBranch) are enabled If the
401// object isn't found in the root dictionary (a list of classes known by the
402// root environment) the branch is skipped and an error message is printed
403// out.
404//
405Bool_t MReadTree::PreProcess(MParList *pList)
406{
407 //
408 // Make sure, that all the following calls doesn't result in
409 // Notifications. This may be dangerous, because the notified
410 // tasks are not preprocessed.
411 //
412 fChain->SetNotify(NULL);
413
414 //
415 // get number of events in this tree
416 //
417 fNumEntries = (UInt_t)fChain->GetEntries();
418
419 if (!fNumEntries)
420 {
421 *fLog << warn << dbginf << "No entries found in file(s)" << endl;
422 return kFALSE;
423 }
424
425 //
426 // output logging information
427 //
428 *fLog << inf << fNumEntries << " entries found in file(s)." << endl;
429
430 //
431 // Get all branches of this tree and
432 // create the Iterator to loop over all branches
433 //
434 TIter Next(fChain->GetListOfBranches());
435 TBranch *branch=NULL;
436
437 Int_t num=0;
438 //
439 // loop over all tasks for processing
440 //
441 while ( (branch=(TBranch*)Next()) )
442 {
443 //
444 // Get Name of Branch and Object
445 //
446 const char *bname = branch->GetName();
447
448 TString oname(bname);
449 if (oname.EndsWith("."))
450 oname.Remove(oname.Length()-1);
451
452 //
453 // Check if enabeling the branch is allowed
454 //
455 if (fVetoList->FindObject(oname))
456 {
457 *fLog << inf << "Master branch " << bname << " has veto... skipped." << endl;
458 DisableSubBranches(branch);
459 continue;
460 }
461
462 //
463 // Create a pointer to the pointer to the object in which the
464 // branch data is stored. The pointers are stored in the TChain
465 // object and we get the pointers from there to delete it.
466 //
467 MParContainer **pcont= new MParContainer*;
468
469#if ROOT_VERSION_CODE < ROOT_VERSION(3,02,06)
470 const char *classname = oname;
471#else
472 const char *classname = branch->GetClassName();
473#endif
474
475 //
476 // check if object is existing in the list
477 //
478 *pcont=pList->FindCreateObj(classname, oname);
479
480 if (!*pcont)
481 {
482 //
483 // if class is not existing in the (root) environment
484 // we cannot proceed reading this branch
485 //
486 *fLog << warn << dbginf << "Warning: Class '" << classname;
487 *fLog << "' for " << oname << " not existing in dictionary. Branch skipped." << endl;
488 DisableSubBranches(branch);
489 continue;
490 }
491
492 //
493 // Check whether a Pointer to a pointer already exists, if
494 // we created one already delete it.
495 //
496 TChainElement *element = (TChainElement*)fChain->GetStatus()->FindObject(bname);
497 if (element)
498 delete (MParContainer**)element->GetBaddress();
499
500 //
501 // here pcont is a pointer the to container in which the data from
502 // the actual branch should be stored - enable branch.
503 //
504 fChain->SetBranchAddress(bname, pcont);
505
506 *fLog << inf << "Master branch address " << bname << " [";
507 *fLog << classname << "] setup for reading." << endl;
508
509 //*fLog << "Branch " << bname << " autodel: " << (int)branch->IsAutoDelete() << endl;
510 //branch->SetAutoDelete();
511
512 num++;
513 }
514
515 *fLog << inf << GetDescriptor() << " setup " << num << " master branches addresses." << endl;
516
517 //
518 // If auto enabling scheme isn't disabled, do auto enabling
519 //
520 if (fAutoEnable)
521 EnableBranches(pList);
522
523 //
524 // If a progress bar is given set its range.
525 //
526 if (fProgress)
527 fProgress->SetRange(0, fNumEntries);
528
529 //
530 // Now we can start notifying. Reset tree makes sure, that TChain thinks
531 // that the correct file is not yet initialized and reinitilizes it
532 // as soon as the first event is read. This is necessary to call
533 // the notifiers when the first event is read, but after the
534 // PreProcess-function.
535 //
536 fChain->ResetTree();
537 fChain->SetNotify(this);
538
539 return kTRUE;
540}
541
542// --------------------------------------------------------------------------
543//
544// Set the ready to save flag of all containers which branchaddresses are
545// set for. This is necessary to copy data.
546//
547void MReadTree::SetReadyToSave(Bool_t flag)
548{
549 TIter Next(fChain->GetStatus());
550
551 TChainElement *element = NULL;
552 while ((element=(TChainElement*)Next()))
553 {
554 //
555 // Check whether the branch is enabled
556 //
557 if (!element->GetStatus())
558 continue;
559
560 //
561 // Get the pointer to the pointer of the corresponding container
562 //
563 MParContainer **pcont = (MParContainer**)element->GetBaddress();
564
565 //
566 // Check whether the pointer is not NULL
567 //
568 if (!pcont || !*pcont)
569 continue;
570
571 //
572 // Set the ready to save status of the container.
573 //
574 (*pcont)->SetReadyToSave(flag);
575 }
576
577 //
578 // Set the ready to save status of this task (used?), too
579 //
580 MTask::SetReadyToSave(flag);
581}
582
583// --------------------------------------------------------------------------
584//
585// The Process-function reads one event from the tree (this contains all
586// enabled branches) and increases the position in the file by one event.
587// (Remark: The position can also be set by some member functions
588// If the end of the file is reached the Eventloop is stopped.
589//
590#if ROOT_VERSION_CODE < ROOT_VERSION(3,02,06)
591#include "MRawEvtData.h"
592#endif
593Bool_t MReadTree::Process()
594{
595 //
596 // This is necessary due to a bug in TChain::LoadTree in root.
597 // will be fixed in 3.03
598 //
599#if ROOT_VERSION_CODE < ROOT_VERSION(3,03,01)
600 if (fNumEntry >= fNumEntries)
601 return kFALSE;
602#endif
603
604#if ROOT_VERSION_CODE < ROOT_VERSION(3,02,06)
605 //
606 // This fixes 99.9% of a memory leak using a root version prior
607 // to 3.02/??
608 //
609 TChainElement *element=NULL;
610 TIter Next(fChain->GetStatus());
611 while ((element=(TChainElement*)Next()))
612 {
613 MParContainer **c = (MParContainer**)element->GetBaddress();
614 if (!c) continue;
615 if ((*c)->InheritsFrom(MRawEvtData::Class()))
616 ((MRawEvtData*)(*c))->DeletePixels(kFALSE);
617
618 }
619#endif
620
621 Bool_t rc = fChain->GetEntry(fNumEntry++) != 0;
622
623 if (rc)
624 SetReadyToSave();
625
626 return rc;
627}
628
629// --------------------------------------------------------------------------
630//
631// Get the Event with the current EventNumber fNumEntry
632//
633Bool_t MReadTree::GetEvent()
634{
635 Bool_t rc = fChain->GetEntry(fNumEntry) != 0;
636
637 if (rc)
638 SetReadyToSave();
639
640 return rc;
641}
642
643// --------------------------------------------------------------------------
644//
645// Decrease the number of the event which is read by Process() next
646// by one or more
647//
648Bool_t MReadTree::DecEventNum(UInt_t dec)
649{
650 if (fNumEntry-dec >= fNumEntries)
651 {
652 *fLog << warn << GetDescriptor() << ": DecEventNum, WARNING - Event " << fNumEntry << "-";
653 *fLog << dec << "=" << (Int_t)fNumEntry-dec << " out of Range." << endl;
654 return kFALSE;
655 }
656
657 fNumEntry -= dec;
658 return kTRUE;
659}
660
661// --------------------------------------------------------------------------
662//
663// Increase the number of the event which is read by Process() next
664// by one or more
665//
666Bool_t MReadTree::IncEventNum(UInt_t inc)
667{
668 if (fNumEntry+inc >= fNumEntries)
669 {
670 *fLog << warn << GetDescriptor() << ": IncEventNum, WARNING - Event " << fNumEntry << "+";
671 *fLog << inc << "=" << (Int_t)fNumEntry+inc << " out of Range." << endl;
672 return kFALSE;
673 }
674
675 fNumEntry += inc;
676 return kTRUE;
677}
678
679// --------------------------------------------------------------------------
680//
681// This function makes Process() read event number nr next
682//
683// Remark: You can use this function after instatiating you MReadTree-object
684// to set the event number from which you want to start reading.
685//
686Bool_t MReadTree::SetEventNum(UInt_t nr)
687{
688 if (nr >= fNumEntries)
689 {
690 *fLog << warn << GetDescriptor() << ": SetEventNum, WARNING - " << nr << " out of Range." << endl;
691 return kFALSE;
692 }
693
694 fNumEntry = nr;
695 return kTRUE;
696}
697
698// --------------------------------------------------------------------------
699//
700// For the branch with the given name:
701// 1) no object is automatically created
702// 2) the branch address for this branch is not set
703// (because we lack the object, see 1)
704// 3) The whole branch (exactly: all its subbranches) are disabled
705// this means are not read in memory by TTree:GetEntry
706//
707void MReadTree::VetoBranch(const char *name)
708{
709 fVetoList->Add(new TNamed(name, ""));
710}
711
712// --------------------------------------------------------------------------
713//
714// Return the name of the file we are actually reading from.
715//
716TString MReadTree::GetFileName() const
717{
718 const TFile *file = fChain->GetFile();
719
720 if (!file)
721 return TString("<unknown>");
722
723 TString name(file->GetName());
724 name.Remove(0, name.Last('/')+1);
725 return name;
726}
727
728// --------------------------------------------------------------------------
729//
730// Return the number of the file in the chain, -1 in case of an error
731//
732Int_t MReadTree::GetFileIndex() const
733{
734 return fChain->GetTreeNumber();
735 /*
736 const TString filename = fChain->GetFile()->GetName();
737
738 int i=0;
739 TObject *file = NULL;
740
741 TIter Next(fChain->GetListOfFiles());
742 while ((file=Next()))
743 {
744 if (filename==gSystem->ExpandPathName(file->GetTitle()))
745 return i;
746 i++;
747 }
748 return -1;
749 */
750}
751
752// --------------------------------------------------------------------------
753//
754// This schedules a TObject which Notify(9 function is called in case
755// of MReadTree (TChain) switches from one file in the chain to another
756// one.
757//
758void MReadTree::AddNotify(TObject *obj)
759{
760 fNotify->Add(obj);
761}
762
763void MReadTree::Print(Option_t *o) const
764{
765 *fLog << all << GetDescriptor() << dec << endl;
766 *fLog << setfill('-') << setw(strlen(GetDescriptor())) << "" << endl;
767 *fLog << " Files [Tree]:" << endl;
768
769 int i = 0;
770 TIter Next(fChain->GetListOfFiles());
771 TObject *obj = NULL;
772 while ((obj=Next()))
773 *fLog << " " << i++ << ") " << obj->GetTitle() << " [" << obj->GetName() << "]" << endl;
774
775 *fLog << " Total Number of Entries: " << fNumEntries << endl;
776 *fLog << " Next Entry to read: " << fNumEntry << endl;
777}
778
779// --------------------------------------------------------------------------
780//
781// Implementation of SavePrimitive. Used to write the call to a constructor
782// to a macro. In the original root implementation it is used to write
783// gui elements to a macro-file.
784//
785void MReadTree::StreamPrimitive(ofstream &out) const
786{
787 out << " " << ClassName() << " " << GetUniqueName() << "(\"";
788 out << fChain->GetName() << "\", \"" << fName << "\", \"" << fTitle << "\");" << endl;
789
790 TIter Next(fChain->GetListOfFiles());
791 TObject *obj = NULL;
792 while ((obj=Next()))
793 out << " " << GetUniqueName() << ".AddFile(\"" << obj->GetTitle() << "\");" << endl;
794
795 if (!fAutoEnable)
796 out << " " << GetUniqueName() << ".DisableAutoScheme();" << endl;
797
798 if (fNumEntry!=0)
799 out << " " << GetUniqueName() << ".SetEventNum(" << fNumEntry << ");" << endl;
800
801
802}
Note: See TracBrowser for help on using the repository browser.