source: trunk/MagicSoft/Mars/mbase/MReadTree.cc@ 1192

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