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

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