source: tags/Mars-V1.2/mbase/MTask.cc

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