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

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