source: trunk/MagicSoft/Mars/mbase/MTask.cc@ 8795

Last change on this file since 8795 was 8642, checked in by tbretz, 17 years ago
*** empty log message ***
File size: 17.6 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@astro.uni-wuerzburg.de>
19!
20! Copyright: MAGIC Software Development, 2000-2007
21!
22!
23\* ======================================================================== */
24
25/////////////////////////////////////////////////////////////////////////////
26//
27// MTask
28//
29// Base class for all tasks which can perfomed in a tasklist
30// For each event processed in the eventloop all the different
31// tasks in the tasklist will be processed.
32//
33// So all tasks must inherit from this baseclass.
34//
35// The inheritance from MInputStreamID is used to indicate the
36// type of event that this task is for. If it is "All" it is executed
37// independantly of the actual ID of the task list.
38//
39// Inside this abstract class, there are three fundamental function:
40//
41// - PreProcess(): executed before the eventloop starts. Here you
42// can initiate different things, open files, etc.
43// As an argument this function gets a pointer to the
44// parameter list. You can stop the execution by
45// returning kFALSE instead of kTRUE. If an error
46// occured and you return kFALSE make sure, that
47// any action is closed correctly and all newly
48// created object are deleted. The PostProcess in
49// such a case won't be executed by the Tasklist or
50// Eventloop.
51//
52// - Process(): executed for each event in the eventloop. Do it
53// one task after the other (as they occur in the
54// tasklist). Only the tasks with a Stream ID
55// which matches the actual ID of the tasklist
56// are executed. A task can return kFALSE to
57// stop the execuition of the tasklist or
58// kCONTINUE to skip the pending tasks. If you want
59// to stop the eventloop and wants the eventloop to
60// return the status 'failed' return kERROR.
61//
62// - ReInit() The idea is, that
63// a) we have one file per run
64// b) each file contains so called run-headers which
65// stores information 'per run', eg MRawRunHeader
66// or the bad pixels
67// c) this information must be evaluated somehow each
68// time a new file is opened.
69//
70// If you use MReadMarsFile or MCT1ReadPreProc it is
71// called each time a new file has been opened and the
72// new run headers have been read before the first
73// event of these file is preprocessed.
74//
75// - PostProcess(): executed after the eventloop. Here you can close
76// output files, start display of the run parameter,
77// etc. PostProcess is only executed in case of
78// PreProcess was successfull (returned kTRUE)
79//
80//
81// Remark: Using a MTask in your tasklist doesn't make much sense,
82// because it is doing nothing. However it is a nice tool
83// to count something (exspecially if used together with a
84// filter)
85//
86//
87// Version 1:
88// ----------
89// - first version
90//
91// Version 2:
92// ----------
93// - added fSerialNumber
94//
95/////////////////////////////////////////////////////////////////////////////
96#include "MTask.h"
97
98#include <fstream>
99
100#include <TBaseClass.h> // OverwritesProcess
101#include <TStopwatch.h> // TStopwatch
102
103#include "MString.h"
104
105#include "MLog.h"
106#include "MLogManip.h"
107
108#include "MFilter.h"
109#include "MStatusDisplay.h"
110
111#undef DEBUG_PROCESS
112//#define DEBUG_PROCESS
113
114ClassImp(MTask);
115
116using namespace std;
117
118MTask::MTask(const char *name, const char *title)
119 : fFilter(NULL), fSerialNumber(0), fIsPreprocessed(kFALSE),
120 fStopwatch(0), fNumExecutions(0), fNumExec0(0), fAccelerator(0)
121{
122 fName = name ? name : "MTask";
123 fTitle = title ? title : "Base class for all tasks (dummy task).";
124
125 fListOfBranches = new TList;
126 fListOfBranches->SetOwner();
127
128 fStopwatch = new TStopwatch;
129}
130
131// --------------------------------------------------------------------------
132//
133// Destructor. Delete fStopwatch and fListOfBranches
134//
135MTask::~MTask()
136{
137 delete fStopwatch;
138 delete fListOfBranches;
139}
140
141// --------------------------------------------------------------------------
142//
143// Initialize fFilter with filter and if not null add the result of
144// GetDataMember from the filter to the branch list.
145//
146void MTask::SetFilter(MFilter *filter)
147{
148 fFilter=filter;
149 if (!filter)
150 return;
151
152 fFilter->SetBit(kMustCleanup); // Better is better ;-)
153 AddToBranchList(filter->GetDataMember());
154}
155
156// --------------------------------------------------------------------------
157//
158// This adds a branch to the list for the auto enabeling schmeme.
159// This makes it possible for MReadTree to decide which branches
160// are really needed for the eventloop. Only the necessary branches
161// are read from disk which speeds up the calculation enormously.
162//
163// You can use TRegExp expressions like "*.fEnergy", but the
164// recommended method is to call this function for exactly all
165// branches you want to have, eg:
166// AddToBranchList("MMcTrig.fNumFirstLevel");
167// AddToBranchList("MMcTrig;1.fNumFirstLevel");
168// AddToBranchList("MMcTrig;2.fNumFirstLevel");
169//
170// We agreed on the convetion, that all branches are stored with
171// a trailing dot '.' so that always the Master Branch name
172// (eg. MMcTrig) is part of the branch name.
173//
174// Remark: The common place to call AddToBranchList is the
175// constructor of the derived classes (tasks)
176//
177void MTask::AddToBranchList(const char *b)
178{
179 if (fListOfBranches->FindObject(b))
180 return;
181
182 fListOfBranches->Add(new TNamed(b, ""));
183}
184
185// --------------------------------------------------------------------------
186//
187// Using this overloaded member function you may cascade several branches
188// in acomma seperated list, eg: "MMcEvt.fTheta,MMcEvt.fEnergy"
189//
190// For moredetailed information see AddToBranchList(const char *b);
191//
192void MTask::AddToBranchList(const TString &str)
193{
194 TString s = str;
195
196 while (!s.IsNull())
197 {
198 Int_t fst = s.First(',');
199
200 if (fst<0)
201 fst = s.Length();
202
203 AddToBranchList((const char*)TString(s(0, fst)));
204
205 s.Remove(0, fst+1);
206 }
207}
208
209// --------------------------------------------------------------------------
210//
211// Copy constructor. Reset MInputStreamID, copy pointer to fFilter and
212// copy the contents of fListOfBranches
213//
214MTask::MTask(MTask &t) : MInputStreamID()
215{
216 fFilter = t.fFilter;
217 fListOfBranches->AddAll(t.fListOfBranches);
218}
219
220// --------------------------------------------------------------------------
221//
222// Mapper function for PreProcess.
223// Sets the preprocessed flag dependend on the return value of PreProcess.
224// Resets number of executions and cpu consumtion timer.
225// If task has already been preprocessed return kTRUE.
226//
227Int_t MTask::CallPreProcess(MParList *plist)
228{
229 if (fIsPreprocessed)
230 return kTRUE;
231
232 // This does not reset the counter!
233 fStopwatch->Reset();
234 fNumExecutions = 0;
235 fNumExec0 = GetNumExecutionsTotal();
236
237 *fLog << all << GetDescriptor() << "... " << flush;
238 if (fDisplay)
239 fDisplay->SetStatusLine2(*this);
240
241 switch (PreProcess(plist))
242 {
243 case kFALSE:
244 return kFALSE;
245
246 case kTRUE:
247 fIsPreprocessed = kTRUE;
248 return kTRUE;
249
250 case kSKIP:
251 return kSKIP;
252 }
253
254 *fLog << err << dbginf << "PreProcess of " << GetDescriptor();
255 *fLog << " returned an unknown value... aborting." << endl;
256
257 return kFALSE;
258}
259
260// --------------------------------------------------------------------------
261//
262// Mapper function for Process.
263// Executes Process dependent on the existance of a filter and its possible
264// return value.
265// If Process is executed, the execution counter is increased.
266// Count cpu consumption time.
267//
268Int_t MTask::CallProcess()
269{
270 //
271 // Check for the existance of a filter. If a filter is existing
272 // check for its value. If the value is kFALSE don't execute
273 // this task.
274 //
275 if (fFilter && !fFilter->IsConditionTrue())
276 return kTRUE;
277
278 if (!HasAccelerator(kAccDontTime))
279 fStopwatch->Start(kFALSE);
280
281 fNumExecutions++;
282
283#ifdef DEBUG_PROCESS
284 *fLog << all << flush << GetName() << "..." << flush;
285#endif
286
287 const Int_t rc = Process();
288
289#ifdef DEBUG_PROCESS
290 *fLog << all << flush << "done." << endl;
291#endif
292
293 if (!HasAccelerator(kAccDontTime))
294 fStopwatch->Stop();
295
296 return rc;
297}
298
299// --------------------------------------------------------------------------
300//
301// Mapper function for PreProcess.
302// Calls Postprocess dependent on the state of the preprocessed flag,
303// resets this flag.
304//
305Int_t MTask::CallPostProcess()
306{
307 if (!fIsPreprocessed)
308 return kTRUE;
309
310 fIsPreprocessed = kFALSE;
311
312 *fLog << all << GetDescriptor() << "... " << flush;
313 if (fDisplay)
314 fDisplay->SetStatusLine2(*this);
315
316 return PostProcess();
317}
318
319// --------------------------------------------------------------------------
320//
321// This is reinit function
322//
323// This function is called asynchronously if the tasks in the tasklist need
324// reinitialization. This for example happens when the eventloop switches
325// from one group of events to another one (eg. switching between events
326// of different runs means reading a new run header and a new run header
327// may mean that some value must be reinitialized)
328//
329// the virtual implementation returns kTRUE
330//
331Bool_t MTask::ReInit(MParList *)
332{
333 return kTRUE;
334}
335
336// --------------------------------------------------------------------------
337//
338// This is processed before the eventloop starts
339//
340// It is the job of the PreProcess to connect the tasks
341// with the right container in the parameter list.
342//
343// the virtual implementation returns kTRUE
344//
345Int_t MTask::PreProcess(MParList *)
346{
347 return kTRUE;
348}
349
350// --------------------------------------------------------------------------
351//
352// This is processed for every event in the eventloop
353//
354// the virtual implementation returns kTRUE
355//
356Int_t MTask::Process()
357{
358 return kTRUE;
359}
360
361// --------------------------------------------------------------------------
362//
363// This is processed after the eventloop starts
364//
365// the virtual implementation returns kTRUE
366//
367Int_t MTask::PostProcess()
368{
369 return kTRUE;
370}
371
372// --------------------------------------------------------------------------
373//
374// Returns the name of the object. If the name of the object is not the
375// class name it returns the object name and in []-brackets the class name.
376// If a serial number is set (!=0) the serial number is added to the
377// name (eg. ;1)
378//
379const TString MTask::GetDescriptor() const
380{
381 //
382 // Because it returns a (const char*) we cannot return a casted
383 // local TString. The pointer would - immediatly after return -
384 // point to a random memory segment, because the TString has gone.
385 //
386 if (fName==ClassName())
387 return fSerialNumber==0 ? (TString)ClassName() : MString::Format("%s;%d", ClassName(), fSerialNumber);
388
389 return fSerialNumber>0 ?
390 MString::Format("%s;%d [%s]", fName.Data(), fSerialNumber, ClassName()) :
391 MString::Format("%s [%s]", fName.Data(), ClassName());
392}
393
394// --------------------------------------------------------------------------
395//
396// Return the total number of calls to since PreProcess(). If Process() was
397// not called due to a set filter this is not counted.
398//
399UInt_t MTask::GetNumExecutions() const
400{
401 return GetNumExecutionsTotal()-fNumExec0;
402}
403
404// --------------------------------------------------------------------------
405//
406// Return the total number of calls to Process(). If Process() was not
407// called due to a set filter this is not counted.
408//
409UInt_t MTask::GetNumExecutionsTotal() const
410{
411 return fNumExecutions-1;
412}
413
414// --------------------------------------------------------------------------
415//
416// Return total CPU execution time in seconds of calls to Process().
417// If Process() was not called due to a set filter this is not counted.
418//
419Double_t MTask::GetCpuTime() const
420{
421 return fStopwatch->CpuTime();
422}
423
424// --------------------------------------------------------------------------
425//
426// Return total real execution time in seconds of calls to Process().
427// If Process() was not called due to a set filter this is not counted.
428//
429Double_t MTask::GetRealTime() const
430{
431 return fStopwatch->RealTime();
432}
433
434// --------------------------------------------------------------------------
435//
436// Prints the relative time spent in Process() (relative means relative to
437// its parent Tasklist) and the number of times Process() was executed.
438// Don't wonder if the sum of the tasks in a tasklist is not 100%,
439// because only the call to Process() of the task is measured. The
440// time of the support structure is ignored. The faster your analysis is
441// the more time is 'wasted' in the support structure.
442// Only the CPU time is displayed. This means that exspecially task
443// which have a huge part of file i/o will be underestimated in their
444// relative wasted time.
445// For convinience the lvl argument results in a number of spaces at the
446// beginning of the line. So that the structur of a tasklist can be
447// identified. If a Tasklist or task has filter applied the name of the
448// filter is printer in <>-brackets behind the number of executions.
449// Use MTaskList::PrintStatistics without an argument.
450// For tasks which don't overwrite Process() no action is perfomed.
451//
452void MTask::PrintStatistics(const Int_t lvl, Bool_t title, Double_t time) const
453{
454 if (!OverwritesProcess() && IsA()!=MTask::Class())
455 return;
456
457 *fLog << all << setfill(' ') << setw(lvl) << " ";
458
459 if (GetCpuTime()>0 && time>0 && GetCpuTime()>=0.001*time && !HasAccelerator(kAccDontTime))
460 *fLog << Form("%5.1f", GetCpuTime()/time*100) << "% ";
461 else
462 *fLog << " ";
463
464 if (HasStreamId())
465 *fLog << GetStreamId() << ":";
466 *fLog << GetDescriptor();
467
468 if (GetNumExecutions()!=(UInt_t)-1)
469 *fLog << "\t" << dec << GetNumExecutions();
470
471 if (fFilter)
472 *fLog << " <" << fFilter->GetName() << ">";
473 if (title)
474 *fLog << "\t" << fTitle;
475 *fLog << endl;
476}
477
478// --------------------------------------------------------------------------
479//
480// First call MParContainer::SavePrimitive which should stream the primitive
481// to the output stream. Then, if a filter is set, stream first the filter
482// and afterwards set the filter for this task.
483//
484void MTask::SavePrimitive(ostream &out, Option_t *)
485{
486 MParContainer::SavePrimitive(out);
487 if (!fFilter)
488 return;
489
490 /*
491 If we don't stream filter which are not in the task list itself
492 (which means: already streamed) we may be able to use
493 SavePrimitive as some kind of validity check for the macros
494
495 fFilter->SavePrimitive(out);
496 */
497 out << " " << GetUniqueName() << ".SetFilter(&" << fFilter->GetUniqueName() <<");" << endl;
498 if (fSerialNumber>0)
499 out << " " << GetUniqueName() << ".SetSerialNumber(" << fSerialNumber <<");" << endl;
500}
501
502void MTask::SavePrimitive(ofstream &out, Option_t *o)
503{
504 SavePrimitive(static_cast<ostream&>(out), o);
505}
506
507// --------------------------------------------------------------------------
508//
509// Check whether the class given in the argument overwrites MTask::Process.
510// This function calls itself recursively. If you want to call it,
511// leave out the argument.
512//
513Bool_t MTask::OverwritesProcess(TClass *cls) const
514{
515 if (!cls)
516 cls = IsA();
517
518 //
519 // Check whether we reached the base class MTask
520 //
521 if (cls==MTask::Class())
522 return kFALSE;
523
524 //
525 // Check whether the class cls overwrites Process
526 //
527 if (cls->GetMethodAny("Process"))
528 return kTRUE;
529
530 //
531 // If the class itself doesn't overload it check all it's base classes
532 //
533 TBaseClass *base=NULL;
534 TIter NextBase(cls->GetListOfBases());
535 while ((base=(TBaseClass*)NextBase()))
536 {
537 if (OverwritesProcess(base->GetClassPointer()))
538 return kTRUE;
539 }
540
541 return kFALSE;
542}
543
544void MTask::SetDisplay(MStatusDisplay *d)
545{
546 if (fFilter)
547 fFilter->SetDisplay(d);
548 MParContainer::SetDisplay(d);
549}
550
551// --------------------------------------------------------------------------
552//
553// This is used to print the output in the PostProcess/Finalize.
554// Or everywhere else in a nice fashioned and unified way.
555//
556void MTask::PrintSkipped(UInt_t n, const char *str)
557{
558 *fLog << " " << setw(7) << n << " (";
559 *fLog << Form("%5.1f", 100.*n/GetNumExecutions());
560 *fLog << "%) Evts skipped: " << str << endl;
561}
562
563// --------------------------------------------------------------------------
564//
565// If obj==fFilter set fFilter to NULL
566// Call MParcontainer::RecursiveRemove
567//
568void MTask::RecursiveRemove(TObject *obj)
569{
570 if (obj==fFilter)
571 fFilter=NULL;
572
573 if (fFilter)
574 fFilter->RecursiveRemove(obj);
575
576 MParContainer::RecursiveRemove(obj);
577}
Note: See TracBrowser for help on using the repository browser.