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

Last change on this file since 5832 was 5713, checked in by tbretz, 20 years ago
*** empty log message ***
File size: 15.9 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-2003
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
111ClassImp(MTask);
112
113using namespace std;
114
115MTask::MTask(const char *name, const char *title)
116 : fFilter(NULL), fSerialNumber(0), fIsPreprocessed(kFALSE),
117 fStopwatch(0)
118{
119 fName = name ? name : "MTask";
120 fTitle = title ? title : "Base class for all tasks (dummy task).";
121
122 fListOfBranches = new TList;
123 fListOfBranches->SetOwner();
124
125 fStopwatch = new TStopwatch;
126}
127
128MTask::~MTask()
129{
130 delete fStopwatch;
131 delete fListOfBranches;
132}
133
134// --------------------------------------------------------------------------
135//
136// This adds a branch to the list for the auto enabeling schmeme.
137// This makes it possible for MReadTree to decide which branches
138// are really needed for the eventloop. Only the necessary branches
139// are read from disk which speeds up the calculation enormously.
140//
141// You can use TRegExp expressions like "*.fEnergy", but the
142// recommended method is to call this function for exactly all
143// branches you want to have, eg:
144// AddToBranchList("MMcTrig.fNumFirstLevel");
145// AddToBranchList("MMcTrig;1.fNumFirstLevel");
146// AddToBranchList("MMcTrig;2.fNumFirstLevel");
147//
148// We agreed on the convetion, that all branches are stored with
149// a trailing dot '.' so that always the Master Branch name
150// (eg. MMcTrig) is part of the branch name.
151//
152// Remark: The common place to call AddToBranchList is the
153// constructor of the derived classes (tasks)
154//
155void MTask::AddToBranchList(const char *b)
156{
157 if (fListOfBranches->FindObject(b))
158 return;
159
160 fListOfBranches->Add(new TNamed(b, ""));
161}
162
163// --------------------------------------------------------------------------
164//
165// Using this overloaded member function you may cascade several branches
166// in acomma seperated list, eg: "MMcEvt.fTheta,MMcEvt.fEnergy"
167//
168// For moredetailed information see AddToBranchList(const char *b);
169//
170void MTask::AddToBranchList(const TString &str)
171{
172 TString s = str;
173
174 while (!s.IsNull())
175 {
176 Int_t fst = s.First(',');
177
178 if (fst<0)
179 fst = s.Length();
180
181 AddToBranchList((const char*)TString(s(0, fst)));
182
183 s.Remove(0, fst+1);
184 }
185}
186
187// --------------------------------------------------------------------------
188//
189// Copy constructor.
190//
191MTask::MTask(MTask &t)
192{
193 fFilter = t.fFilter;
194 fListOfBranches->AddAll(t.fListOfBranches);
195}
196
197// --------------------------------------------------------------------------
198//
199// Mapper function for PreProcess.
200// Sets the preprocessed flag dependend on the return value of PreProcess.
201// Resets number of executions and cpu consumtion timer.
202//
203Int_t MTask::CallPreProcess(MParList *plist)
204{
205 // This does not reset the counter!
206 fStopwatch->Reset();
207 fNumExec0 = GetNumExecutionsTotal();
208
209 *fLog << all << fName << "... " << flush;
210 if (fDisplay)
211 fDisplay->SetStatusLine2(*this);
212
213 switch (PreProcess(plist))
214 {
215 case kFALSE:
216 return kFALSE;
217
218 case kTRUE:
219 fIsPreprocessed = kTRUE;
220 return kTRUE;
221
222 case kSKIP:
223 return kSKIP;
224 }
225
226 *fLog << err << dbginf << "PreProcess of " << GetDescriptor();
227 *fLog << " returned an unknown value... aborting." << endl;
228
229 return kFALSE;
230}
231
232// --------------------------------------------------------------------------
233//
234// Mapper function for Process.
235// Executes Process dependent on the existance of a filter and its possible
236// return value.
237// If Process is executed, the execution counter is increased.
238// Count cpu consumtion time.
239//
240Int_t MTask::CallProcess()
241{
242 //
243 // Check for the existance of a filter. If a filter is existing
244 // check for its value. If the value is kFALSE don't execute
245 // this task.
246 //
247 const Bool_t exec = fFilter ? fFilter->IsConditionTrue() : kTRUE;
248
249 if (!exec)
250 return kTRUE;
251
252 fStopwatch->Start(kFALSE);
253 const Int_t rc = Process();
254 fStopwatch->Stop();
255
256 return rc;
257}
258
259// --------------------------------------------------------------------------
260//
261// Mapper function for PreProcess.
262// Calls Postprocess dependent on the state of the preprocessed flag,
263// resets this flag.
264//
265Int_t MTask::CallPostProcess()
266{
267 if (!fIsPreprocessed)
268 return kTRUE;
269
270 fIsPreprocessed = kFALSE;
271
272 *fLog << all << fName << "... " << flush;
273 if (fDisplay)
274 fDisplay->SetStatusLine2(*this);
275
276 return PostProcess();
277}
278
279// --------------------------------------------------------------------------
280//
281// This is reinit function
282//
283// This function is called asynchronously if the tasks in the tasklist need
284// reinitialization. This for example happens when the eventloop switches
285// from one group of events to another one (eg. switching between events
286// of different runs means reading a new run header and a new run header
287// may mean that some value must be reinitialized)
288//
289// the virtual implementation returns kTRUE
290//
291Bool_t MTask::ReInit(MParList *pList)
292{
293 return kTRUE;
294}
295
296// --------------------------------------------------------------------------
297//
298// This is processed before the eventloop starts
299//
300// It is the job of the PreProcess to connect the tasks
301// with the right container in the parameter list.
302//
303// the virtual implementation returns kTRUE
304//
305Int_t MTask::PreProcess(MParList *pList)
306{
307 return kTRUE;
308}
309
310// --------------------------------------------------------------------------
311//
312// This is processed for every event in the eventloop
313//
314// the virtual implementation returns kTRUE
315//
316Int_t MTask::Process()
317{
318 return kTRUE;
319}
320
321// --------------------------------------------------------------------------
322//
323// This is processed after the eventloop starts
324//
325// the virtual implementation returns kTRUE
326//
327Int_t MTask::PostProcess()
328{
329 return kTRUE;
330}
331
332// --------------------------------------------------------------------------
333//
334// Returns the name of the object. If the name of the object is not the
335// class name it returns the object name and in []-brackets the class name.
336// If a serial number is set (!=0) the serial number is added to the
337// name (eg. ;1)
338//
339const TString MTask::GetDescriptor() const
340{
341 //
342 // Because it returns a (const char*) we cannot return a casted
343 // local TString. The pointer would - immediatly after return -
344 // point to a random memory segment, because the TString has gone.
345 //
346 if (fName==ClassName())
347 return fSerialNumber==0 ? ClassName() : MString::Form("%s;%d", ClassName(), fSerialNumber);
348
349 return fSerialNumber>0 ?
350 MString::Form("%s;%d [%s]", fName.Data(), fSerialNumber, ClassName()) :
351 MString::Form("%s [%s]", fName.Data(), ClassName());
352}
353
354// --------------------------------------------------------------------------
355//
356// Return the total number of calls to since PreProcess(). If Process() was
357// not called due to a set filter this is not counted.
358//
359UInt_t MTask::GetNumExecutions() const
360{
361 return GetNumExecutionsTotal()-fNumExec0;
362}
363
364// --------------------------------------------------------------------------
365//
366// Return the total number of calls to Process(). If Process() was not
367// called due to a set filter this is not counted.
368//
369UInt_t MTask::GetNumExecutionsTotal() const
370{
371 return (UInt_t)fStopwatch->Counter()-1;
372}
373
374// --------------------------------------------------------------------------
375//
376// Return total CPU execution time in seconds of calls to Process().
377// If Process() was not called due to a set filter this is not counted.
378//
379Double_t MTask::GetCpuTime() const
380{
381 return fStopwatch->CpuTime();
382}
383
384// --------------------------------------------------------------------------
385//
386// Return total real execution time in seconds of calls to Process().
387// If Process() was not called due to a set filter this is not counted.
388//
389Double_t MTask::GetRealTime() const
390{
391 return fStopwatch->RealTime();
392}
393
394// --------------------------------------------------------------------------
395//
396// Prints the relative time spent in Process() (relative means relative to
397// its parent Tasklist) and the number of times Process() was executed.
398// Don't wonder if the sum of the tasks in a tasklist is not 100%,
399// because only the call to Process() of the task is measured. The
400// time of the support structure is ignored. The faster your analysis is
401// the more time is 'wasted' in the support structure.
402// Only the CPU time is displayed. This means that exspecially task
403// which have a huge part of file i/o will be underestimated in their
404// relative wasted time.
405// For convinience the lvl argument results in a number of spaces at the
406// beginning of the line. So that the structur of a tasklist can be
407// identified. If a Tasklist or task has filter applied the name of the
408// filter is printer in <>-brackets behind the number of executions.
409// Use MTaskList::PrintStatistics without an argument.
410// For tasks which don't overwrite Process() no action is perfomed.
411//
412void MTask::PrintStatistics(const Int_t lvl, Bool_t title, Double_t time) const
413{
414 if (!OverwritesProcess() && IsA()!=MTask::Class())
415 return;
416
417 *fLog << all << setfill(' ') << setw(lvl) << " ";
418
419 if (GetCpuTime()>0 && time>0 && GetCpuTime()>=0.001*time)
420 *fLog << Form("%5.1f", GetCpuTime()/time*100) << "% ";
421 else
422 *fLog << " ";
423 *fLog << GetDescriptor() << "\t";
424 *fLog << dec << GetNumExecutions();
425 if (fFilter)
426 *fLog << " <" << fFilter->GetName() << ">";
427 if (title)
428 *fLog << "\t" << fTitle;
429 *fLog << endl;
430}
431
432// --------------------------------------------------------------------------
433//
434// First call MParContainer::SavePrimitive which should stream the primitive
435// to the output stream. Then, if a filter is set, stream first the filter
436// and afterwards set the filter for this task.
437//
438void MTask::SavePrimitive(ofstream &out, Option_t *o)
439{
440 MParContainer::SavePrimitive(out);
441 if (!fFilter)
442 return;
443
444 /*
445 If we don't stream filter which are not in the task list itself
446 (which means: already streamed) we may be able to use
447 SavePrimitive as some kind of validity check for the macros
448
449 fFilter->SavePrimitive(out);
450 */
451 out << " " << GetUniqueName() << ".SetFilter(&" << fFilter->GetUniqueName() <<");" << endl;
452 if (fSerialNumber>0)
453 out << " " << GetUniqueName() << ".SetSerialNumber(" << fSerialNumber <<");" << endl;
454}
455
456// --------------------------------------------------------------------------
457//
458// Check whether the class given in the argument overwrites MTask::Process.
459// This function calls itself recursively. If you want to call it,
460// leave out the argument.
461//
462Bool_t MTask::OverwritesProcess(TClass *cls) const
463{
464 if (!cls)
465 cls = IsA();
466
467 //
468 // Check whether we reached the base class MTask
469 //
470 if (cls==MTask::Class())
471 return kFALSE;
472
473 //
474 // Check whether the class cls overwrites Process
475 //
476 if (cls->GetMethodAny("Process"))
477 return kTRUE;
478
479 //
480 // If the class itself doesn't overload it check all it's base classes
481 //
482 TBaseClass *base=NULL;
483 TIter NextBase(cls->GetListOfBases());
484 while ((base=(TBaseClass*)NextBase()))
485 {
486 if (OverwritesProcess(base->GetClassPointer()))
487 return kTRUE;
488 }
489
490 return kFALSE;
491}
492
493void MTask::SetDisplay(MStatusDisplay *d)
494{
495 if (fFilter)
496 fFilter->SetDisplay(d);
497 MParContainer::SetDisplay(d);
498}
499
500// --------------------------------------------------------------------------
501//
502// This is used to print the output in the PostProcess/Finalize.
503// Or everywhere else in a nice fashioned and unified way.
504//
505void MTask::PrintSkipped(UInt_t n, const char *str)
506{
507 *fLog << " " << setw(7) << n << " (";
508 *fLog << Form("%5.1f", 100.*n/GetNumExecutions());
509 *fLog << "%) Evts skipped: " << str << endl;
510}
Note: See TracBrowser for help on using the repository browser.