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

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